LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - SelectionDAGBuilder.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 4325 4461 97.0 %
Date: 2018-06-17 00:07:59 Functions: 177 182 97.3 %
Legend: Lines: hit not hit

          Line data    Source code
       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/APFloat.h"
      17             : #include "llvm/ADT/APInt.h"
      18             : #include "llvm/ADT/ArrayRef.h"
      19             : #include "llvm/ADT/BitVector.h"
      20             : #include "llvm/ADT/DenseMap.h"
      21             : #include "llvm/ADT/None.h"
      22             : #include "llvm/ADT/Optional.h"
      23             : #include "llvm/ADT/STLExtras.h"
      24             : #include "llvm/ADT/SmallPtrSet.h"
      25             : #include "llvm/ADT/SmallSet.h"
      26             : #include "llvm/ADT/SmallVector.h"
      27             : #include "llvm/ADT/StringRef.h"
      28             : #include "llvm/ADT/Triple.h"
      29             : #include "llvm/ADT/Twine.h"
      30             : #include "llvm/Analysis/AliasAnalysis.h"
      31             : #include "llvm/Analysis/BranchProbabilityInfo.h"
      32             : #include "llvm/Analysis/ConstantFolding.h"
      33             : #include "llvm/Analysis/EHPersonalities.h"
      34             : #include "llvm/Analysis/Loads.h"
      35             : #include "llvm/Analysis/MemoryLocation.h"
      36             : #include "llvm/Analysis/TargetLibraryInfo.h"
      37             : #include "llvm/Analysis/ValueTracking.h"
      38             : #include "llvm/Analysis/VectorUtils.h"
      39             : #include "llvm/CodeGen/Analysis.h"
      40             : #include "llvm/CodeGen/FunctionLoweringInfo.h"
      41             : #include "llvm/CodeGen/GCMetadata.h"
      42             : #include "llvm/CodeGen/ISDOpcodes.h"
      43             : #include "llvm/CodeGen/MachineBasicBlock.h"
      44             : #include "llvm/CodeGen/MachineFrameInfo.h"
      45             : #include "llvm/CodeGen/MachineFunction.h"
      46             : #include "llvm/CodeGen/MachineInstr.h"
      47             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      48             : #include "llvm/CodeGen/MachineJumpTableInfo.h"
      49             : #include "llvm/CodeGen/MachineMemOperand.h"
      50             : #include "llvm/CodeGen/MachineModuleInfo.h"
      51             : #include "llvm/CodeGen/MachineOperand.h"
      52             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      53             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      54             : #include "llvm/CodeGen/SelectionDAG.h"
      55             : #include "llvm/CodeGen/SelectionDAGNodes.h"
      56             : #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
      57             : #include "llvm/CodeGen/StackMaps.h"
      58             : #include "llvm/CodeGen/TargetFrameLowering.h"
      59             : #include "llvm/CodeGen/TargetInstrInfo.h"
      60             : #include "llvm/CodeGen/TargetLowering.h"
      61             : #include "llvm/CodeGen/TargetOpcodes.h"
      62             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      63             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      64             : #include "llvm/CodeGen/ValueTypes.h"
      65             : #include "llvm/CodeGen/WinEHFuncInfo.h"
      66             : #include "llvm/IR/Argument.h"
      67             : #include "llvm/IR/Attributes.h"
      68             : #include "llvm/IR/BasicBlock.h"
      69             : #include "llvm/IR/CFG.h"
      70             : #include "llvm/IR/CallSite.h"
      71             : #include "llvm/IR/CallingConv.h"
      72             : #include "llvm/IR/Constant.h"
      73             : #include "llvm/IR/ConstantRange.h"
      74             : #include "llvm/IR/Constants.h"
      75             : #include "llvm/IR/DataLayout.h"
      76             : #include "llvm/IR/DebugInfoMetadata.h"
      77             : #include "llvm/IR/DebugLoc.h"
      78             : #include "llvm/IR/DerivedTypes.h"
      79             : #include "llvm/IR/Function.h"
      80             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      81             : #include "llvm/IR/InlineAsm.h"
      82             : #include "llvm/IR/InstrTypes.h"
      83             : #include "llvm/IR/Instruction.h"
      84             : #include "llvm/IR/Instructions.h"
      85             : #include "llvm/IR/IntrinsicInst.h"
      86             : #include "llvm/IR/Intrinsics.h"
      87             : #include "llvm/IR/LLVMContext.h"
      88             : #include "llvm/IR/Metadata.h"
      89             : #include "llvm/IR/Module.h"
      90             : #include "llvm/IR/Operator.h"
      91             : #include "llvm/IR/Statepoint.h"
      92             : #include "llvm/IR/Type.h"
      93             : #include "llvm/IR/User.h"
      94             : #include "llvm/IR/Value.h"
      95             : #include "llvm/MC/MCContext.h"
      96             : #include "llvm/MC/MCSymbol.h"
      97             : #include "llvm/Support/AtomicOrdering.h"
      98             : #include "llvm/Support/BranchProbability.h"
      99             : #include "llvm/Support/Casting.h"
     100             : #include "llvm/Support/CodeGen.h"
     101             : #include "llvm/Support/CommandLine.h"
     102             : #include "llvm/Support/Compiler.h"
     103             : #include "llvm/Support/Debug.h"
     104             : #include "llvm/Support/ErrorHandling.h"
     105             : #include "llvm/Support/MachineValueType.h"
     106             : #include "llvm/Support/MathExtras.h"
     107             : #include "llvm/Support/raw_ostream.h"
     108             : #include "llvm/Target/TargetIntrinsicInfo.h"
     109             : #include "llvm/Target/TargetMachine.h"
     110             : #include "llvm/Target/TargetOptions.h"
     111             : #include <algorithm>
     112             : #include <cassert>
     113             : #include <cstddef>
     114             : #include <cstdint>
     115             : #include <cstring>
     116             : #include <iterator>
     117             : #include <limits>
     118             : #include <numeric>
     119             : #include <tuple>
     120             : #include <utility>
     121             : #include <vector>
     122             : 
     123             : using namespace llvm;
     124             : 
     125             : #define DEBUG_TYPE "isel"
     126             : 
     127             : /// LimitFloatPrecision - Generate low-precision inline sequences for
     128             : /// some float libcalls (6, 8 or 12 bits).
     129             : static unsigned LimitFloatPrecision;
     130             : 
     131             : static cl::opt<unsigned, true>
     132      101169 :     LimitFPPrecision("limit-float-precision",
     133      101169 :                      cl::desc("Generate low-precision inline sequences "
     134             :                               "for some float libcalls"),
     135      202338 :                      cl::location(LimitFloatPrecision), cl::Hidden,
     136      303507 :                      cl::init(0));
     137             : 
     138      101169 : static cl::opt<unsigned> SwitchPeelThreshold(
     139      202338 :     "switch-peel-threshold", cl::Hidden, cl::init(66),
     140      101169 :     cl::desc("Set the case probability threshold for peeling the case from a "
     141             :              "switch statement. A value greater than 100 will void this "
     142      101169 :              "optimization"));
     143             : 
     144             : // Limit the width of DAG chains. This is important in general to prevent
     145             : // DAG-based analysis from blowing up. For example, alias analysis and
     146             : // load clustering may not complete in reasonable time. It is difficult to
     147             : // recognize and avoid this situation within each individual analysis, and
     148             : // future analyses are likely to have the same behavior. Limiting DAG width is
     149             : // the safe approach and will be especially important with global DAGs.
     150             : //
     151             : // MaxParallelChains default is arbitrarily high to avoid affecting
     152             : // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
     153             : // sequence over this should have been converted to llvm.memcpy by the
     154             : // frontend. It is easy to induce this behavior with .ll code such as:
     155             : // %buffer = alloca [4096 x i8]
     156             : // %data = load [4096 x i8]* %argPtr
     157             : // store [4096 x i8] %data, [4096 x i8]* %buffer
     158             : static const unsigned MaxParallelChains = 64;
     159             : 
     160             : // True if the Value passed requires ABI mangling as it is a parameter to a
     161             : // function or a return value from a function which is not an intrinsic.
     162      301751 : static bool isABIRegCopy(const Value *V) {
     163      301751 :   const bool IsRetInst = V && isa<ReturnInst>(V);
     164      301751 :   const bool IsCallInst = V && isa<CallInst>(V);
     165             :   const bool IsInLineAsm =
     166       12731 :       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
     167             :   const bool IsIndirectFunctionCall =
     168      301751 :       IsCallInst && !IsInLineAsm &&
     169             :       !static_cast<const CallInst *>(V)->getCalledFunction();
     170             :   // It is possible that the call instruction is an inline asm statement or an
     171             :   // indirect function call in which case the return value of
     172             :   // getCalledFunction() would be nullptr.
     173             :   const bool IsInstrinsicCall =
     174      313962 :       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
     175       12211 :       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
     176             :           Intrinsic::not_intrinsic;
     177             : 
     178      301751 :   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
     179             : }
     180             : 
     181             : static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     182             :                                       const SDValue *Parts, unsigned NumParts,
     183             :                                       MVT PartVT, EVT ValueVT, const Value *V,
     184             :                                       bool IsABIRegCopy);
     185             : 
     186             : /// getCopyFromParts - Create a value that contains the specified legal parts
     187             : /// combined into the value they represent.  If the parts combine to a type
     188             : /// larger than ValueVT then AssertOp can be used to specify whether the extra
     189             : /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
     190             : /// (ISD::AssertSext).
     191      565458 : static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
     192             :                                 const SDValue *Parts, unsigned NumParts,
     193             :                                 MVT PartVT, EVT ValueVT, const Value *V,
     194             :                                 Optional<ISD::NodeType> AssertOp = None,
     195             :                                 bool IsABIRegCopy = false) {
     196      565458 :   if (ValueVT.isVector())
     197             :     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
     198      167367 :                                   PartVT, ValueVT, V, IsABIRegCopy);
     199             : 
     200             :   assert(NumParts > 0 && "No parts to assemble!");
     201             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     202      398091 :   SDValue Val = Parts[0];
     203             : 
     204      398091 :   if (NumParts > 1) {
     205             :     // Assemble the value from multiple parts.
     206       15132 :     if (ValueVT.isInteger()) {
     207       13989 :       unsigned PartBits = PartVT.getSizeInBits();
     208       13989 :       unsigned ValueBits = ValueVT.getSizeInBits();
     209             : 
     210             :       // Assemble the power of 2 part.
     211       14206 :       unsigned RoundParts = NumParts & (NumParts - 1) ?
     212         217 :         1 << Log2_32(NumParts) : NumParts;
     213       13989 :       unsigned RoundBits = PartBits * RoundParts;
     214             :       EVT RoundVT = RoundBits == ValueBits ?
     215       13989 :         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
     216       13989 :       SDValue Lo, Hi;
     217             : 
     218       13989 :       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
     219             : 
     220       13989 :       if (RoundParts > 2) {
     221        1751 :         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
     222        3502 :                               PartVT, HalfVT, V);
     223        3502 :         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
     224        3502 :                               RoundParts / 2, PartVT, HalfVT, V);
     225             :       } else {
     226       12238 :         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
     227       12238 :         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
     228             :       }
     229             : 
     230       27978 :       if (DAG.getDataLayout().isBigEndian())
     231             :         std::swap(Lo, Hi);
     232             : 
     233       13989 :       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
     234             : 
     235       13989 :       if (RoundParts < NumParts) {
     236             :         // Assemble the trailing non-power-of-2 part.
     237         217 :         unsigned OddParts = NumParts - RoundParts;
     238         217 :         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
     239         217 :         Hi = getCopyFromParts(DAG, DL,
     240         434 :                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
     241             : 
     242             :         // Combine the round and odd parts.
     243         217 :         Lo = Val;
     244         434 :         if (DAG.getDataLayout().isBigEndian())
     245             :           std::swap(Lo, Hi);
     246         217 :         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     247         217 :         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
     248         217 :         Hi =
     249         434 :             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
     250         217 :                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
     251         651 :                                         TLI.getPointerTy(DAG.getDataLayout())));
     252         217 :         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
     253         217 :         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
     254             :       }
     255        1143 :     } else if (PartVT.isFloatingPoint()) {
     256             :       // FP split into multiple FP parts (for ppcf128)
     257             :       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
     258             :              "Unexpected split");
     259             :       SDValue Lo, Hi;
     260         168 :       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
     261         336 :       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
     262         336 :       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
     263             :         std::swap(Lo, Hi);
     264         168 :       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
     265             :     } else {
     266             :       // FP split into integer parts (soft fp)
     267             :       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
     268             :              !PartVT.isVector() && "Unexpected split");
     269         975 :       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
     270         975 :       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
     271             :     }
     272             :   }
     273             : 
     274             :   // There is now one part, held in Val.  Correct it to match ValueVT.
     275             :   // PartEVT is the type of the register class that holds the value.
     276             :   // ValueVT is the type of the inline asm operation.
     277      398091 :   EVT PartEVT = Val.getValueType();
     278             : 
     279      398925 :   if (PartEVT == ValueVT)
     280      370940 :     return Val;
     281             : 
     282       28823 :   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
     283        1672 :       ValueVT.bitsLT(PartEVT)) {
     284             :     // For an FP value in an integer part, we need to truncate to the right
     285             :     // width first.
     286          28 :     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
     287          28 :     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
     288             :   }
     289             : 
     290             :   // Handle types that have the same size.
     291       27151 :   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
     292        1740 :     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     293             : 
     294             :   // Handle types with different sizes.
     295       25411 :   if (PartEVT.isInteger() && ValueVT.isInteger()) {
     296       24851 :     if (ValueVT.bitsLT(PartEVT)) {
     297             :       // For a truncate, see if we have any information to
     298             :       // indicate whether the truncated bits will always be
     299             :       // zero or sign-extension.
     300       24828 :       if (AssertOp.hasValue())
     301        9934 :         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
     302       19868 :                           DAG.getValueType(ValueVT));
     303       24828 :       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     304             :     }
     305          23 :     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
     306             :   }
     307             : 
     308        1120 :   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
     309             :     // FP_ROUND's are always exact here.
     310         560 :     if (ValueVT.bitsLT(Val.getValueType()))
     311             :       return DAG.getNode(
     312             :           ISD::FP_ROUND, DL, ValueVT, Val,
     313        1120 :           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
     314             : 
     315           0 :     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
     316             :   }
     317             : 
     318           0 :   llvm_unreachable("Unknown mismatch!");
     319             : }
     320             : 
     321          12 : static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
     322             :                                               const Twine &ErrMsg) {
     323             :   const Instruction *I = dyn_cast_or_null<Instruction>(V);
     324          12 :   if (!V)
     325           0 :     return Ctx.emitError(ErrMsg);
     326             : 
     327             :   const char *AsmError = ", possible invalid constraint for vector type";
     328             :   if (const CallInst *CI = dyn_cast<CallInst>(I))
     329          12 :     if (isa<InlineAsm>(CI->getCalledValue()))
     330          12 :       return Ctx.emitError(I, ErrMsg + AsmError);
     331             : 
     332           0 :   return Ctx.emitError(I, ErrMsg);
     333             : }
     334             : 
     335             : /// getCopyFromPartsVector - Create a value that contains the specified legal
     336             : /// parts combined into the value they represent.  If the parts combine to a
     337             : /// type larger than ValueVT then AssertOp can be used to specify whether the
     338             : /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
     339             : /// ValueVT (ISD::AssertSext).
     340      167367 : static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     341             :                                       const SDValue *Parts, unsigned NumParts,
     342             :                                       MVT PartVT, EVT ValueVT, const Value *V,
     343             :                                       bool IsABIRegCopy) {
     344             :   assert(ValueVT.isVector() && "Not a vector value");
     345             :   assert(NumParts > 0 && "No parts to assemble!");
     346      167367 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     347      167367 :   SDValue Val = Parts[0];
     348             : 
     349             :   // Handle a multi-element vector.
     350      167367 :   if (NumParts > 1) {
     351        9091 :     EVT IntermediateVT;
     352        9091 :     MVT RegisterVT;
     353             :     unsigned NumIntermediates;
     354             :     unsigned NumRegs;
     355             : 
     356        9091 :     if (IsABIRegCopy) {
     357       16366 :       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
     358        8183 :           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
     359        8183 :           RegisterVT);
     360             :     } else {
     361         908 :       NumRegs =
     362         908 :           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
     363             :                                      NumIntermediates, RegisterVT);
     364             :     }
     365             : 
     366             :     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
     367             :     NumParts = NumRegs; // Silence a compiler warning.
     368             :     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
     369             :     assert(RegisterVT.getSizeInBits() ==
     370             :            Parts[0].getSimpleValueType().getSizeInBits() &&
     371             :            "Part type sizes don't match!");
     372             : 
     373             :     // Assemble the parts into intermediate operands.
     374       18182 :     SmallVector<SDValue, 8> Ops(NumIntermediates);
     375        9091 :     if (NumIntermediates == NumParts) {
     376             :       // If the register was not expanded, truncate or copy the value,
     377             :       // as appropriate.
     378       64549 :       for (unsigned i = 0; i != NumParts; ++i)
     379       84159 :         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
     380       56106 :                                   PartVT, IntermediateVT, V);
     381         648 :     } else if (NumParts > 0) {
     382             :       // If the intermediate type was expanded, build the intermediate
     383             :       // operands from the parts.
     384             :       assert(NumParts % NumIntermediates == 0 &&
     385             :              "Must expand into a divisible number of parts!");
     386         648 :       unsigned Factor = NumParts / NumIntermediates;
     387        3556 :       for (unsigned i = 0; i != NumIntermediates; ++i)
     388        4362 :         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
     389        2908 :                                   PartVT, IntermediateVT, V);
     390             :     }
     391             : 
     392             :     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
     393             :     // intermediate operands.
     394             :     EVT BuiltVectorTy =
     395        9091 :         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
     396             :                          (IntermediateVT.isVector()
     397        6914 :                               ? IntermediateVT.getVectorNumElements() * NumParts
     398       25096 :                               : NumIntermediates));
     399        9091 :     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
     400             :                                                 : ISD::BUILD_VECTOR,
     401       18182 :                       DL, BuiltVectorTy, Ops);
     402             :   }
     403             : 
     404             :   // There is now one part, held in Val.  Correct it to match ValueVT.
     405      334734 :   EVT PartEVT = Val.getValueType();
     406             : 
     407      168080 :   if (PartEVT == ValueVT)
     408      161962 :     return Val;
     409             : 
     410        5405 :   if (PartEVT.isVector()) {
     411             :     // If the element type of the source/dest vectors are the same, but the
     412             :     // parts vector has more elements than the value vector, then we have a
     413             :     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
     414             :     // elements we want.
     415        9058 :     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
     416             :       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
     417             :              "Cannot narrow, it would be a lossy transformation");
     418             :       return DAG.getNode(
     419             :           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
     420        3564 :           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     421             :     }
     422             : 
     423             :     // Vector/Vector bitcast.
     424        3341 :     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
     425        1841 :       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     426             : 
     427             :     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
     428             :       "Cannot handle this kind of promotion");
     429             :     // Promoted vector extract
     430        1500 :     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
     431             : 
     432             :   }
     433             : 
     434             :   // Trivial bitcast if the types are the same size and the destination
     435             :   // vector type is legal.
     436         876 :   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
     437             :       TLI.isTypeLegal(ValueVT))
     438          21 :     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     439             : 
     440         855 :   if (ValueVT.getVectorNumElements() != 1) {
     441             :      // Certain ABIs require that vectors are passed as integers. For vectors
     442             :      // are the same size, this is an obvious bitcast.
     443         194 :      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
     444         106 :        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     445          88 :      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
     446             :        // Bitcast Val back the original type and extract the corresponding
     447             :        // vector we want.
     448          80 :        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
     449          80 :        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
     450         160 :                                            ValueVT.getVectorElementType(), Elts);
     451          80 :        Val = DAG.getBitcast(WiderVecType, Val);
     452             :        return DAG.getNode(
     453             :            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
     454         240 :            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     455             :      }
     456             : 
     457           8 :      diagnosePossiblyInvalidConstraint(
     458           8 :          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
     459           8 :      return DAG.getUNDEF(ValueVT);
     460             :   }
     461             : 
     462             :   // Handle cases such as i8 -> <1 x i1>
     463         661 :   EVT ValueSVT = ValueVT.getVectorElementType();
     464         661 :   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
     465          83 :     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
     466             :                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
     467             : 
     468         661 :   return DAG.getBuildVector(ValueVT, DL, Val);
     469             : }
     470             : 
     471             : static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
     472             :                                  SDValue Val, SDValue *Parts, unsigned NumParts,
     473             :                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
     474             : 
     475             : /// getCopyToParts - Create a series of nodes that contain the specified value
     476             : /// split into legal parts.  If the parts contain more bits than Val, then, for
     477             : /// integers, ExtendKind can be used to specify how to generate the extra bits.
     478      627224 : static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
     479             :                            SDValue *Parts, unsigned NumParts, MVT PartVT,
     480             :                            const Value *V,
     481             :                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
     482             :                            bool IsABIRegCopy = false) {
     483      627224 :   EVT ValueVT = Val.getValueType();
     484             : 
     485             :   // Handle the vector case separately.
     486      627224 :   if (ValueVT.isVector())
     487      100062 :     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
     488      100062 :                                 IsABIRegCopy);
     489             : 
     490      527162 :   unsigned PartBits = PartVT.getSizeInBits();
     491             :   unsigned OrigNumParts = NumParts;
     492             :   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
     493             :          "Copying to an illegal type!");
     494             : 
     495      527162 :   if (NumParts == 0)
     496             :     return;
     497             : 
     498             :   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
     499             :   EVT PartEVT = PartVT;
     500           0 :   if (PartEVT == ValueVT) {
     501             :     assert(NumParts == 1 && "No-op copy with multiple parts!");
     502      496709 :     Parts[0] = Val;
     503      496709 :     return;
     504             :   }
     505             : 
     506       30453 :   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
     507             :     // If the parts cover more bits than the value has, promote the value.
     508       18962 :     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
     509             :       assert(NumParts == 1 && "Do not know what to promote to!");
     510         206 :       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
     511             :     } else {
     512       18756 :       if (ValueVT.isFloatingPoint()) {
     513             :         // FP values need to be bitcast, then extended if they are being put
     514             :         // into a larger container.
     515          43 :         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
     516          43 :         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     517             :       }
     518             :       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
     519             :              ValueVT.isInteger() &&
     520             :              "Unknown mismatch!");
     521       18756 :       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     522       18756 :       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
     523       18756 :       if (PartVT == MVT::x86mmx)
     524           1 :         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     525             :     }
     526       11491 :   } else if (PartBits == ValueVT.getSizeInBits()) {
     527             :     // Different types of the same size.
     528             :     assert(NumParts == 1 && PartEVT != ValueVT);
     529         658 :     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     530       10833 :   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
     531             :     // If the parts cover less bits than value has, truncate the value.
     532             :     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
     533             :            ValueVT.isInteger() &&
     534             :            "Unknown mismatch!");
     535         382 :     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     536         382 :     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     537         382 :     if (PartVT == MVT::x86mmx)
     538           0 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     539             :   }
     540             : 
     541             :   // The value may have changed - recompute ValueVT.
     542       30453 :   ValueVT = Val.getValueType();
     543             :   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
     544             :          "Failed to tile the value with PartVT!");
     545             : 
     546       30453 :   if (NumParts == 1) {
     547           0 :     if (PartEVT != ValueVT) {
     548           4 :       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
     549             :                                         "scalar-to-vector conversion failed");
     550           4 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     551             :     }
     552             : 
     553       19965 :     Parts[0] = Val;
     554       19965 :     return;
     555             :   }
     556             : 
     557             :   // Expand the value into multiple parts.
     558       10488 :   if (NumParts & (NumParts - 1)) {
     559             :     // The number of parts is not a power of 2.  Split off and copy the tail.
     560             :     assert(PartVT.isInteger() && ValueVT.isInteger() &&
     561             :            "Do not know what to expand to!");
     562          25 :     unsigned RoundParts = 1 << Log2_32(NumParts);
     563          25 :     unsigned RoundBits = RoundParts * PartBits;
     564          25 :     unsigned OddParts = NumParts - RoundParts;
     565             :     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
     566          25 :                                  DAG.getIntPtrConstant(RoundBits, DL));
     567          25 :     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
     568             : 
     569          50 :     if (DAG.getDataLayout().isBigEndian())
     570             :       // The odd parts were reversed by getCopyToParts - unreverse them.
     571           3 :       std::reverse(Parts + RoundParts, Parts + NumParts);
     572             : 
     573             :     NumParts = RoundParts;
     574          25 :     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     575          25 :     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     576             :   }
     577             : 
     578             :   // The number of parts is a power of 2.  Repeatedly bisect the value using
     579             :   // EXTRACT_ELEMENT.
     580       10488 :   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
     581       10488 :                          EVT::getIntegerVT(*DAG.getContext(),
     582             :                                            ValueVT.getSizeInBits()),
     583       31464 :                          Val);
     584             : 
     585       33496 :   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
     586       37768 :     for (unsigned i = 0; i < NumParts; i += StepSize) {
     587       13132 :       unsigned ThisBits = StepSize * PartBits / 2;
     588       13132 :       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
     589       13132 :       SDValue &Part0 = Parts[i];
     590       13132 :       SDValue &Part1 = Parts[i+StepSize/2];
     591             : 
     592       13132 :       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
     593       26264 :                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
     594       13132 :       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
     595       26264 :                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
     596             : 
     597       13132 :       if (ThisBits == PartBits && ThisVT != PartVT) {
     598         172 :         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
     599         172 :         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
     600             :       }
     601             :     }
     602             :   }
     603             : 
     604       20976 :   if (DAG.getDataLayout().isBigEndian())
     605        2398 :     std::reverse(Parts, Parts + OrigNumParts);
     606             : }
     607             : 
     608             : 
     609             : /// getCopyToPartsVector - Create a series of nodes that contain the specified
     610             : /// value split into legal parts.
     611      100062 : static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     612             :                                  SDValue Val, SDValue *Parts, unsigned NumParts,
     613             :                                  MVT PartVT, const Value *V,
     614             :                                  bool IsABIRegCopy) {
     615      100062 :   EVT ValueVT = Val.getValueType();
     616             :   assert(ValueVT.isVector() && "Not a vector");
     617      100062 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     618             : 
     619      100062 :   if (NumParts == 1) {
     620             :     EVT PartEVT = PartVT;
     621           0 :     if (PartEVT == ValueVT) {
     622             :       // Nothing to do.
     623        3142 :     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
     624             :       // Bitconvert vector->vector case.
     625        1468 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     626           0 :     } else if (PartVT.isVector() &&
     627        2876 :                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
     628         601 :                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
     629         601 :       EVT ElementVT = PartVT.getVectorElementType();
     630             :       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
     631             :       // undef elements.
     632             :       SmallVector<SDValue, 16> Ops;
     633        2169 :       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
     634        1568 :         Ops.push_back(DAG.getNode(
     635             :             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
     636        6272 :             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
     637             : 
     638        2711 :       for (unsigned i = ValueVT.getVectorNumElements(),
     639         601 :            e = PartVT.getVectorNumElements(); i != e; ++i)
     640        2110 :         Ops.push_back(DAG.getUNDEF(ElementVT));
     641             : 
     642         601 :       Val = DAG.getBuildVector(PartVT, DL, Ops);
     643             : 
     644             :       // FIXME: Use CONCAT for 2x -> 4x.
     645             : 
     646             :       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
     647             :       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
     648         979 :     } else if (PartVT.isVector() &&
     649        2052 :                PartEVT.getVectorElementType().bitsGE(
     650        2052 :                  ValueVT.getVectorElementType()) &&
     651         979 :                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
     652             : 
     653             :       // Promoted vector extract
     654         979 :       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
     655             :     } else {
     656          94 :       if (ValueVT.getVectorNumElements() == 1) {
     657          54 :         Val = DAG.getNode(
     658             :             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
     659         216 :             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     660             :       } else {
     661             :         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
     662             :                "lossy conversion of vector to scalar type");
     663             :         EVT IntermediateType =
     664          40 :             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
     665          40 :         Val = DAG.getBitcast(IntermediateType, Val);
     666          40 :         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
     667             :       }
     668             :     }
     669             : 
     670             :     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
     671       95467 :     Parts[0] = Val;
     672             :     return;
     673             :   }
     674             : 
     675             :   // Handle a multi-element vector.
     676        4595 :   EVT IntermediateVT;
     677        4595 :   MVT RegisterVT;
     678             :   unsigned NumIntermediates;
     679             :   unsigned NumRegs;
     680        4595 :   if (IsABIRegCopy) {
     681        7808 :     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
     682        3904 :         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
     683        3904 :         RegisterVT);
     684             :   } else {
     685         691 :     NumRegs =
     686         691 :         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
     687             :                                    NumIntermediates, RegisterVT);
     688             :   }
     689        4595 :   unsigned NumElements = ValueVT.getVectorNumElements();
     690             : 
     691             :   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
     692             :   NumParts = NumRegs; // Silence a compiler warning.
     693             :   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
     694             : 
     695             :   // Convert the vector to the appropiate type if necessary.
     696             :   unsigned DestVectorNoElts =
     697        4595 :       NumIntermediates *
     698        9190 :       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
     699             :   EVT BuiltVectorTy = EVT::getVectorVT(
     700        4595 :       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
     701        4876 :   if (Val.getValueType() != BuiltVectorTy)
     702         189 :     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
     703             : 
     704             :   // Split the vector into intermediate operands.
     705        9190 :   SmallVector<SDValue, 8> Ops(NumIntermediates);
     706       28499 :   for (unsigned i = 0; i != NumIntermediates; ++i) {
     707       11952 :     if (IntermediateVT.isVector())
     708       17214 :       Ops[i] =
     709       17214 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
     710        8607 :                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
     711       34428 :                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
     712             :     else
     713        6690 :       Ops[i] = DAG.getNode(
     714             :           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
     715       13380 :           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     716             :   }
     717             : 
     718             :   // Split the intermediate operands into legal parts.
     719        4595 :   if (NumParts == NumIntermediates) {
     720             :     // If the register was not expanded, promote or copy the value,
     721             :     // as appropriate.
     722       27474 :     for (unsigned i = 0; i != NumParts; ++i)
     723       23008 :       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
     724         129 :   } else if (NumParts > 0) {
     725             :     // If the intermediate type was expanded, split each the value into
     726             :     // legal parts.
     727             :     assert(NumIntermediates != 0 && "division by zero");
     728             :     assert(NumParts % NumIntermediates == 0 &&
     729             :            "Must expand into a divisible number of parts!");
     730         129 :     unsigned Factor = NumParts / NumIntermediates;
     731        1025 :     for (unsigned i = 0; i != NumIntermediates; ++i)
     732         896 :       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
     733             :   }
     734             : }
     735             : 
     736       58896 : RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
     737       58896 :                            EVT valuevt, bool IsABIMangledValue)
     738             :     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
     739      117792 :       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
     740             : 
     741      305550 : RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
     742             :                            const DataLayout &DL, unsigned Reg, Type *Ty,
     743      611100 :                            bool IsABIMangledValue) {
     744      305550 :   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
     745             : 
     746      305550 :   IsABIMangled = IsABIMangledValue;
     747             : 
     748      934018 :   for (EVT ValueVT : ValueVTs) {
     749             :     unsigned NumRegs = IsABIMangledValue
     750      620224 :                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
     751      620224 :                            : TLI.getNumRegisters(Context, ValueVT);
     752             :     MVT RegisterVT = IsABIMangledValue
     753        8244 :                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
     754      322478 :                          : TLI.getRegisterType(Context, ValueVT);
     755      965376 :     for (unsigned i = 0; i != NumRegs; ++i)
     756      325571 :       Regs.push_back(Reg + i);
     757      314234 :     RegVTs.push_back(RegisterVT);
     758      314234 :     RegCount.push_back(NumRegs);
     759      314234 :     Reg += NumRegs;
     760             :   }
     761      305550 : }
     762             : 
     763      160169 : SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
     764             :                                       FunctionLoweringInfo &FuncInfo,
     765             :                                       const SDLoc &dl, SDValue &Chain,
     766             :                                       SDValue *Flag, const Value *V) const {
     767             :   // A Value with type {} or [0 x %t] needs no registers.
     768      160169 :   if (ValueVTs.empty())
     769           0 :     return SDValue();
     770             : 
     771      160169 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     772             : 
     773             :   // Assemble the legal parts into the final values.
     774      320338 :   SmallVector<SDValue, 4> Values(ValueVTs.size());
     775             :   SmallVector<SDValue, 8> Parts;
     776      322391 :   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
     777             :     // Copy the legal parts from the registers.
     778      324444 :     EVT ValueVT = ValueVTs[Value];
     779      162222 :     unsigned NumRegs = RegCount[Value];
     780      162222 :     MVT RegisterVT = IsABIMangled
     781      172802 :       ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value])
     782      324444 :       : RegVTs[Value];
     783             : 
     784      162222 :     Parts.resize(NumRegs);
     785      499172 :     for (unsigned i = 0; i != NumRegs; ++i) {
     786             :       SDValue P;
     787      168475 :       if (!Flag) {
     788      328998 :         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
     789             :       } else {
     790        7952 :         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
     791        3976 :         *Flag = P.getValue(2);
     792             :       }
     793             : 
     794      168475 :       Chain = P.getValue(1);
     795      336950 :       Parts[i] = P;
     796             : 
     797             :       // If the source register was virtual and if we know something about it,
     798             :       // add an assert node.
     799      529847 :       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
     800      322527 :           !RegisterVT.isInteger() || RegisterVT.isVector())
     801      157525 :         continue;
     802             : 
     803             :       const FunctionLoweringInfo::LiveOutInfo *LOI =
     804             :         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
     805       79508 :       if (!LOI)
     806       79508 :         continue;
     807             : 
     808       63844 :       unsigned RegSize = RegisterVT.getSizeInBits();
     809       63844 :       unsigned NumSignBits = LOI->NumSignBits;
     810             :       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
     811             : 
     812       65703 :       if (NumZeroBits == RegSize) {
     813             :         // The current value is a zero.
     814             :         // Explicitly express that as it would be easier for
     815             :         // optimizations to kick in.
     816        3718 :         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
     817        1859 :         continue;
     818             :       }
     819             : 
     820             :       // FIXME: We capture more information than the dag can represent.  For
     821             :       // now, just use the tightest assertzext/assertsext possible.
     822             :       bool isSExt = true;
     823       61985 :       EVT FromVT(MVT::Other);
     824       61985 :       if (NumSignBits == RegSize) {
     825             :         isSExt = true;   // ASSERT SEXT 1
     826         602 :         FromVT = MVT::i1;
     827       61383 :       } else if (NumZeroBits >= RegSize - 1) {
     828             :         isSExt = false;  // ASSERT ZEXT 1
     829        7573 :         FromVT = MVT::i1;
     830       53810 :       } else if (NumSignBits > RegSize - 8) {
     831             :         isSExt = true;   // ASSERT SEXT 8
     832        1226 :         FromVT = MVT::i8;
     833       52584 :       } else if (NumZeroBits >= RegSize - 8) {
     834             :         isSExt = false;  // ASSERT ZEXT 8
     835        1392 :         FromVT = MVT::i8;
     836       51192 :       } else if (NumSignBits > RegSize - 16) {
     837             :         isSExt = true;   // ASSERT SEXT 16
     838         574 :         FromVT = MVT::i16;
     839       50618 :       } else if (NumZeroBits >= RegSize - 16) {
     840             :         isSExt = false;  // ASSERT ZEXT 16
     841         480 :         FromVT = MVT::i16;
     842       50138 :       } else if (NumSignBits > RegSize - 32) {
     843             :         isSExt = true;   // ASSERT SEXT 32
     844        3185 :         FromVT = MVT::i32;
     845       72865 :       } else if (NumZeroBits >= RegSize - 32) {
     846             :         isSExt = false;  // ASSERT ZEXT 32
     847       21041 :         FromVT = MVT::i32;
     848             :       } else {
     849       25912 :         continue;
     850             :       }
     851             :       // Add an assertion node.
     852             :       assert(FromVT != MVT::Other);
     853       72146 :       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
     854      108219 :                              RegisterVT, P, DAG.getValueType(FromVT));
     855             :     }
     856             : 
     857      324444 :     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
     858      162222 :                                      NumRegs, RegisterVT, ValueVT, V);
     859      162222 :     Part += NumRegs;
     860             :     Parts.clear();
     861             :   }
     862             : 
     863      160169 :   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
     864             : }
     865             : 
     866      151482 : void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
     867             :                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
     868             :                                  const Value *V,
     869             :                                  ISD::NodeType PreferredExtendType) const {
     870      151482 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     871             :   ISD::NodeType ExtendKind = PreferredExtendType;
     872             : 
     873             :   // Get the list of the values's legal parts.
     874      151482 :   unsigned NumRegs = Regs.size();
     875      302964 :   SmallVector<SDValue, 8> Parts(NumRegs);
     876      309981 :   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
     877      316998 :     unsigned NumParts = RegCount[Value];
     878             : 
     879      158499 :     MVT RegisterVT = IsABIMangled
     880      164407 :       ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value])
     881      316998 :       : RegVTs[Value];
     882             : 
     883      315971 :     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
     884             :       ExtendKind = ISD::ZERO_EXTEND;
     885             : 
     886      158499 :     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
     887      158499 :                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
     888      158499 :     Part += NumParts;
     889             :   }
     890             : 
     891             :   // Copy the parts into the registers.
     892      302964 :   SmallVector<SDValue, 8> Chains(NumRegs);
     893      478918 :   for (unsigned i = 0; i != NumRegs; ++i) {
     894             :     SDValue Part;
     895      163718 :     if (!Flag) {
     896      314316 :       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
     897             :     } else {
     898       13120 :       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
     899        6560 :       *Flag = Part.getValue(1);
     900             :     }
     901             : 
     902      327436 :     Chains[i] = Part.getValue(0);
     903             :   }
     904             : 
     905      151482 :   if (NumRegs == 1 || Flag)
     906             :     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
     907             :     // flagged to it. That is the CopyToReg nodes and the user are considered
     908             :     // a single scheduling unit. If we create a TokenFactor and return it as
     909             :     // chain, then the TokenFactor is both a predecessor (operand) of the
     910             :     // user as well as a successor (the TF operands are flagged to the user).
     911             :     // c1, f1 = CopyToReg
     912             :     // c2, f2 = CopyToReg
     913             :     // c3     = TokenFactor c1, c2
     914             :     // ...
     915             :     //        = op c3, ..., f2
     916      284944 :     Chain = Chains[NumRegs-1];
     917             :   else
     918        9010 :     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
     919      151482 : }
     920             : 
     921       58880 : void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
     922             :                                         unsigned MatchingIdx, const SDLoc &dl,
     923             :                                         SelectionDAG &DAG,
     924             :                                         std::vector<SDValue> &Ops) const {
     925       58880 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     926             : 
     927       58880 :   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
     928       58880 :   if (HasMatching)
     929             :     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
     930      117216 :   else if (!Regs.empty() &&
     931       58608 :            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
     932             :     // Put the register class of the virtual registers in the flag word.  That
     933             :     // way, later passes can recompute register class constraints for inline
     934             :     // assembly as well as normal instructions.
     935             :     // Don't do this for tied operands that can use the regclass information
     936             :     // from the def.
     937        8745 :     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
     938             :     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
     939        8745 :     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
     940             :   }
     941             : 
     942      117760 :   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
     943       58880 :   Ops.push_back(Res);
     944             : 
     945       58880 :   if (Code == InlineAsm::Kind_Clobber) {
     946             :     // Clobbers should always have a 1:1 mapping with registers, and may
     947             :     // reference registers that have illegal (e.g. vector) types. Hence, we
     948             :     // shouldn't try to apply any sort of splitting logic to them.
     949             :     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
     950             :            "No 1:1 mapping from clobbers to regs?");
     951             :     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
     952             :     (void)SP;
     953       96948 :     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
     954      145422 :       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
     955             :       assert(
     956             :           (Regs[I] != SP ||
     957             :            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
     958             :           "If we clobbered the stack pointer, MFI should know about it.");
     959             :     }
     960       48474 :     return;
     961             :   }
     962             : 
     963       20812 :   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
     964       20812 :     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
     965       10406 :     MVT RegisterVT = RegVTs[Value];
     966       31522 :     for (unsigned i = 0; i != NumRegs; ++i) {
     967             :       assert(Reg < Regs.size() && "Mismatch in # registers expected");
     968       21116 :       unsigned TheReg = Regs[Reg++];
     969       21116 :       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
     970             :     }
     971             :   }
     972             : }
     973             : 
     974             : SmallVector<std::pair<unsigned, unsigned>, 4>
     975          10 : RegsForValue::getRegsAndSizes() const {
     976             :   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
     977             :   unsigned I = 0;
     978          34 :   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
     979          14 :     unsigned RegCount = std::get<0>(CountAndVT);
     980          14 :     MVT RegisterVT = std::get<1>(CountAndVT);
     981          14 :     unsigned RegisterSize = RegisterVT.getSizeInBits();
     982          39 :     for (unsigned E = I + RegCount; I != E; ++I)
     983          50 :       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
     984             :   }
     985          10 :   return OutVec;
     986             : }
     987             : 
     988      226495 : void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
     989             :                                const TargetLibraryInfo *li) {
     990      226495 :   AA = aa;
     991      226495 :   GFI = gfi;
     992      226495 :   LibInfo = li;
     993      452990 :   DL = &DAG.getDataLayout();
     994      226495 :   Context = DAG.getContext();
     995      226495 :   LPadToCallSiteMap.clear();
     996      226495 : }
     997             : 
     998      364595 : void SelectionDAGBuilder::clear() {
     999      364595 :   NodeMap.clear();
    1000      364595 :   UnusedArgNodeMap.clear();
    1001             :   PendingLoads.clear();
    1002             :   PendingExports.clear();
    1003      364595 :   CurInst = nullptr;
    1004      364595 :   HasTailCall = false;
    1005      364595 :   SDNodeOrder = LowestSDNodeOrder;
    1006      364595 :   StatepointLowering.clear();
    1007      364595 : }
    1008             : 
    1009      226419 : void SelectionDAGBuilder::clearDanglingDebugInfo() {
    1010      226419 :   DanglingDebugInfoMap.clear();
    1011      226419 : }
    1012             : 
    1013      737869 : SDValue SelectionDAGBuilder::getRoot() {
    1014      737869 :   if (PendingLoads.empty())
    1015      503456 :     return DAG.getRoot();
    1016             : 
    1017      234413 :   if (PendingLoads.size() == 1) {
    1018      199503 :     SDValue Root = PendingLoads[0];
    1019      199503 :     DAG.setRoot(Root);
    1020             :     PendingLoads.clear();
    1021      199503 :     return Root;
    1022             :   }
    1023             : 
    1024             :   // Otherwise, we have to make a token factor node.
    1025      104730 :   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
    1026       69820 :                              PendingLoads);
    1027             :   PendingLoads.clear();
    1028       34910 :   DAG.setRoot(Root);
    1029       34910 :   return Root;
    1030             : }
    1031             : 
    1032      700625 : SDValue SelectionDAGBuilder::getControlRoot() {
    1033      700625 :   SDValue Root = DAG.getRoot();
    1034             : 
    1035      700625 :   if (PendingExports.empty())
    1036      609338 :     return Root;
    1037             : 
    1038             :   // Turn all of the CopyToReg chains into one factored node.
    1039      182574 :   if (Root.getOpcode() != ISD::EntryToken) {
    1040       59870 :     unsigned i = 0, e = PendingExports.size();
    1041      246626 :     for (; i != e; ++i) {
    1042             :       assert(PendingExports[i].getNode()->getNumOperands() > 1);
    1043      186756 :       if (PendingExports[i].getNode()->getOperand(0) == Root)
    1044             :         break;  // Don't add the root if we already indirectly depend on it.
    1045             :     }
    1046             : 
    1047       59870 :     if (i == e)
    1048       59870 :       PendingExports.push_back(Root);
    1049             :   }
    1050             : 
    1051      365148 :   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
    1052       91287 :                      PendingExports);
    1053             :   PendingExports.clear();
    1054       91287 :   DAG.setRoot(Root);
    1055       91287 :   return Root;
    1056             : }
    1057             : 
    1058     2363994 : void SelectionDAGBuilder::visit(const Instruction &I) {
    1059             :   // Set up outgoing PHI node register values before emitting the terminator.
    1060     2363994 :   if (isa<TerminatorInst>(&I)) {
    1061      337168 :     HandlePHINodesInSuccessorBlocks(I.getParent());
    1062             :   }
    1063             : 
    1064             :   // Increase the SDNodeOrder if dealing with a non-debug instruction.
    1065             :   if (!isa<DbgInfoIntrinsic>(I))
    1066     2312832 :     ++SDNodeOrder;
    1067             : 
    1068     2363994 :   CurInst = &I;
    1069             : 
    1070     4727988 :   visit(I.getOpcode(), I);
    1071             : 
    1072             :   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
    1073             :     // Propagate the fast-math-flags of this IR instruction to the DAG node that
    1074             :     // maps to this instruction.
    1075             :     // TODO: We could handle all flags (nsw, etc) here.
    1076             :     // TODO: If an IR instruction maps to >1 node, only the final node will have
    1077             :     //       flags set.
    1078      138724 :     if (SDNode *Node = getNodeForIRValue(&I)) {
    1079             :       SDNodeFlags IncomingFlags;
    1080      138652 :       IncomingFlags.copyFMF(*FPMO);
    1081      138652 :       if (!Node->getFlags().isDefined())
    1082             :         Node->setFlags(IncomingFlags);
    1083             :       else
    1084        2145 :         Node->intersectFlagsWith(IncomingFlags);
    1085             :     }
    1086             :   }
    1087             : 
    1088     4388026 :   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
    1089     2024038 :       !isStatepoint(&I)) // statepoints handle their exports internally
    1090     2023979 :     CopyToExportRegsIfNeeded(&I);
    1091             : 
    1092     2363988 :   CurInst = nullptr;
    1093     2363988 : }
    1094             : 
    1095           0 : void SelectionDAGBuilder::visitPHI(const PHINode &) {
    1096           0 :   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
    1097             : }
    1098             : 
    1099     2646879 : void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
    1100             :   // Note: this doesn't use InstVisitor, because it has to work with
    1101             :   // ConstantExpr's in addition to instructions.
    1102     2646879 :   switch (Opcode) {
    1103           0 :   default: llvm_unreachable("Unknown instruction type encountered!");
    1104             :     // Build the switch statement using the Instruction.def file.
    1105             : #define HANDLE_INST(NUM, OPCODE, CLASS) \
    1106             :     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
    1107             : #include "llvm/IR/Instruction.def"
    1108             :   }
    1109     2646873 : }
    1110             : 
    1111       51162 : void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
    1112             :                                                 const DIExpression *Expr) {
    1113     2737442 :   for (auto &DDIMI : DanglingDebugInfoMap)
    1114     2744626 :     for (auto &DDI : DDIMI.second)
    1115      109508 :       if (DDI.getDI()) {
    1116             :         const DbgValueInst *DI = DDI.getDI();
    1117             :         DIVariable *DanglingVariable = DI->getVariable();
    1118             :         DIExpression *DanglingExpr = DI->getExpression();
    1119       78902 :         if (DanglingVariable == Variable &&
    1120         890 :             Expr->fragmentsOverlap(DanglingExpr)) {
    1121             :           LLVM_DEBUG(dbgs()
    1122             :                      << "Dropping dangling debug info for " << *DI << "\n");
    1123        1756 :           DDI = DanglingDebugInfo();
    1124             :         }
    1125             :       }
    1126       51162 : }
    1127             : 
    1128             : // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
    1129             : // generate the debug data structures now that we've seen its definition.
    1130     1629797 : void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
    1131             :                                                    SDValue Val) {
    1132     1629797 :   DanglingDebugInfoVector &DDIV = DanglingDebugInfoMap[V];
    1133     1638442 :   for (auto &DDI : DDIV) {
    1134        8645 :     if (!DDI.getDI())
    1135         764 :       continue;
    1136             :     const DbgValueInst *DI = DDI.getDI();
    1137             :     DebugLoc dl = DDI.getdl();
    1138        7881 :     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
    1139        7881 :     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
    1140             :     DILocalVariable *Variable = DI->getVariable();
    1141             :     DIExpression *Expr = DI->getExpression();
    1142             :     assert(Variable->isValidLocationForIntrinsic(dl) &&
    1143             :            "Expected inlined-at fields to agree");
    1144             :     SDDbgValue *SDV;
    1145             :     if (Val.getNode()) {
    1146        7881 :       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
    1147             :         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
    1148             :                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
    1149             :         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
    1150             :         // Increase the SDNodeOrder for the DbgValue here to make sure it is
    1151             :         // inserted after the definition of Val when emitting the instructions
    1152             :         // after ISel. An alternative could be to teach
    1153             :         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
    1154             :         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
    1155             :                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
    1156             :                    << ValSDNodeOrder << "\n");
    1157        5206 :         SDV = getDbgValue(Val, Variable, Expr, dl,
    1158             :                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
    1159        5206 :         DAG.AddDbgValue(SDV, Val.getNode(), false);
    1160             :       } else
    1161             :         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
    1162             :                           << "in EmitFuncArgumentDbgValue\n");
    1163             :     } else
    1164             :       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1165             :   }
    1166     1629797 :   DanglingDebugInfoMap[V].clear();
    1167     1629797 : }
    1168             : 
    1169             : /// getCopyFromRegs - If there was virtual register allocated for the value V
    1170             : /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
    1171     1619606 : SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
    1172     1619606 :   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
    1173             :   SDValue Result;
    1174             : 
    1175     3239212 :   if (It != FuncInfo.ValueMap.end()) {
    1176      153681 :     unsigned InReg = It->second;
    1177             : 
    1178      307362 :     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
    1179      614724 :                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
    1180      307362 :     SDValue Chain = DAG.getEntryNode();
    1181      461043 :     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
    1182      153681 :                                  V);
    1183      153681 :     resolveDanglingDebugInfo(V, Result);
    1184             :   }
    1185             : 
    1186     1619606 :   return Result;
    1187             : }
    1188             : 
    1189             : /// getValue - Return an SDValue for the given Value.
    1190     4061232 : SDValue SelectionDAGBuilder::getValue(const Value *V) {
    1191             :   // If we already have an SDValue for this value, use it. It's important
    1192             :   // to do this first, so that we don't create a CopyFromReg if we already
    1193             :   // have a regular SDValue.
    1194     4061232 :   SDValue &N = NodeMap[V];
    1195     4061232 :   if (N.getNode()) return N;
    1196             : 
    1197             :   // If there's a virtual register allocated and initialized for this
    1198             :   // value, use it.
    1199     1619604 :   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
    1200      153679 :     return copyFromReg;
    1201             : 
    1202             :   // Otherwise create a new SDValue and remember it.
    1203     1465925 :   SDValue Val = getValueImpl(V);
    1204     1465925 :   NodeMap[V] = Val;
    1205     1465925 :   resolveDanglingDebugInfo(V, Val);
    1206     1465925 :   return Val;
    1207             : }
    1208             : 
    1209             : // Return true if SDValue exists for the given Value
    1210         395 : bool SelectionDAGBuilder::findValue(const Value *V) const {
    1211         839 :   return (NodeMap.find(V) != NodeMap.end()) ||
    1212         888 :     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
    1213             : }
    1214             : 
    1215             : /// getNonRegisterValue - Return an SDValue for the given Value, but
    1216             : /// don't look in FuncInfo.ValueMap for a virtual register.
    1217      145001 : SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
    1218             :   // If we already have an SDValue for this value, use it.
    1219      145001 :   SDValue &N = NodeMap[V];
    1220      145001 :   if (N.getNode()) {
    1221             :     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
    1222             :       // Remove the debug location from the node as the node is about to be used
    1223             :       // in a location which may differ from the original debug location.  This
    1224             :       // is relevant to Constant and ConstantFP nodes because they can appear
    1225             :       // as constant expressions inside PHI nodes.
    1226        3254 :       N->setDebugLoc(DebugLoc());
    1227             :     }
    1228      134810 :     return N;
    1229             :   }
    1230             : 
    1231             :   // Otherwise create a new SDValue and remember it.
    1232       10191 :   SDValue Val = getValueImpl(V);
    1233       10191 :   NodeMap[V] = Val;
    1234       10191 :   resolveDanglingDebugInfo(V, Val);
    1235       10191 :   return Val;
    1236             : }
    1237             : 
    1238             : /// getValueImpl - Helper function for getValue and getNonRegisterValue.
    1239             : /// Create an SDValue for the given value.
    1240     1476116 : SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
    1241     1476116 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    1242             : 
    1243     1476116 :   if (const Constant *C = dyn_cast<Constant>(V)) {
    1244     2670096 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
    1245             : 
    1246             :     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
    1247     1134174 :       return DAG.getConstant(*CI, getCurSDLoc(), VT);
    1248             : 
    1249             :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
    1250     1620678 :       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
    1251             : 
    1252      416764 :     if (isa<ConstantPointerNull>(C)) {
    1253       19974 :       unsigned AS = V->getType()->getPointerAddressSpace();
    1254       59922 :       return DAG.getConstant(0, getCurSDLoc(),
    1255       59922 :                              TLI.getPointerTy(DAG.getDataLayout(), AS));
    1256             :     }
    1257             : 
    1258             :     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
    1259       51885 :       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
    1260             : 
    1261      379495 :     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
    1262       29353 :       return DAG.getUNDEF(VT);
    1263             : 
    1264             :     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
    1265      565770 :       visit(CE->getOpcode(), *CE);
    1266      565770 :       SDValue N1 = NodeMap[V];
    1267             :       assert(N1.getNode() && "visit didn't populate the NodeMap!");
    1268      282885 :       return N1;
    1269             :     }
    1270             : 
    1271       67257 :     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
    1272             :       SmallVector<SDValue, 4> Constants;
    1273         184 :       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
    1274         184 :            OI != OE; ++OI) {
    1275         134 :         SDNode *Val = getValue(*OI).getNode();
    1276             :         // If the operand is an empty aggregate, there are no values.
    1277         134 :         if (!Val) continue;
    1278             :         // Add each leaf value from the operand to the Constants list
    1279             :         // to form a flattened list of all the values.
    1280         546 :         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
    1281         140 :           Constants.push_back(SDValue(Val, i));
    1282             :       }
    1283             : 
    1284         150 :       return DAG.getMergeValues(Constants, getCurSDLoc());
    1285             :     }
    1286             : 
    1287             :     if (const ConstantDataSequential *CDS =
    1288             :           dyn_cast<ConstantDataSequential>(C)) {
    1289             :       SmallVector<SDValue, 4> Ops;
    1290      259735 :       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    1291      210160 :         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
    1292             :         // Add each leaf value from the operand to the Constants list
    1293             :         // to form a flattened list of all the values.
    1294      840640 :         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
    1295      210160 :           Ops.push_back(SDValue(Val, i));
    1296             :       }
    1297             : 
    1298       49575 :       if (isa<ArrayType>(CDS->getType()))
    1299           9 :         return DAG.getMergeValues(Ops, getCurSDLoc());
    1300      247860 :       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
    1301             :     }
    1302             : 
    1303       35264 :     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
    1304             :       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
    1305             :              "Unknown struct or array constant!");
    1306             : 
    1307             :       SmallVector<EVT, 4> ValueVTs;
    1308        1168 :       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
    1309         584 :       unsigned NumElts = ValueVTs.size();
    1310         584 :       if (NumElts == 0)
    1311           1 :         return SDValue(); // empty struct
    1312        1166 :       SmallVector<SDValue, 4> Constants(NumElts);
    1313        5005 :       for (unsigned i = 0; i != NumElts; ++i) {
    1314        4422 :         EVT EltVT = ValueVTs[i];
    1315        2211 :         if (isa<UndefValue>(C))
    1316        3758 :           Constants[i] = DAG.getUNDEF(EltVT);
    1317         332 :         else if (EltVT.isFloatingPoint())
    1318         120 :           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
    1319             :         else
    1320        1208 :           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
    1321             :       }
    1322             : 
    1323        1749 :       return DAG.getMergeValues(Constants, getCurSDLoc());
    1324             :     }
    1325             : 
    1326             :     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
    1327         122 :       return DAG.getBlockAddress(BA, VT);
    1328             : 
    1329       16926 :     VectorType *VecTy = cast<VectorType>(V->getType());
    1330       16926 :     unsigned NumElements = VecTy->getNumElements();
    1331             : 
    1332             :     // Now that we know the number and type of the elements, get that number of
    1333             :     // elements into the Ops array based on what kind of constant it is.
    1334             :     SmallVector<SDValue, 16> Ops;
    1335             :     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
    1336       40211 :       for (unsigned i = 0; i != NumElements; ++i)
    1337       38466 :         Ops.push_back(getValue(CV->getOperand(i)));
    1338             :     } else {
    1339             :       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
    1340             :       EVT EltVT =
    1341       30362 :           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
    1342             : 
    1343       15181 :       SDValue Op;
    1344       15181 :       if (EltVT.isFloatingPoint())
    1345       10710 :         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
    1346             :       else
    1347       34833 :         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
    1348       15181 :       Ops.assign(NumElements, Op);
    1349             :     }
    1350             : 
    1351             :     // Create a BUILD_VECTOR node.
    1352       84630 :     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
    1353             :   }
    1354             : 
    1355             :   // If this is a static alloca, generate it as the frameindex instead of
    1356             :   // computation.
    1357             :   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
    1358             :     DenseMap<const AllocaInst*, int>::iterator SI =
    1359      138101 :       FuncInfo.StaticAllocaMap.find(AI);
    1360      276202 :     if (SI != FuncInfo.StaticAllocaMap.end())
    1361      138101 :       return DAG.getFrameIndex(SI->second,
    1362      414303 :                                TLI.getFrameIndexTy(DAG.getDataLayout()));
    1363             :   }
    1364             : 
    1365             :   // If this is an instruction which fast-isel has deferred, select it now.
    1366        2967 :   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
    1367        2967 :     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
    1368             : 
    1369        5934 :     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
    1370       11868 :                      Inst->getType(), isABIRegCopy(V));
    1371        5934 :     SDValue Chain = DAG.getEntryNode();
    1372        8901 :     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
    1373             :   }
    1374             : 
    1375           0 :   llvm_unreachable("Can't get register for value!");
    1376             : }
    1377             : 
    1378         106 : void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
    1379         106 :   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1380         106 :   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
    1381         106 :   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
    1382             :   bool IsSEH = isAsynchronousEHPersonality(Pers);
    1383             :   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
    1384         106 :   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
    1385         106 :   if (!IsSEH)
    1386             :     CatchPadMBB->setIsEHScopeEntry();
    1387             :   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
    1388         106 :   if (IsMSVCCXX || IsCoreCLR)
    1389             :     CatchPadMBB->setIsEHFuncletEntry();
    1390             :   // Wasm does not need catchpads anymore
    1391         106 :   if (!IsWasmCXX)
    1392         420 :     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
    1393         315 :                             getControlRoot()));
    1394         106 : }
    1395             : 
    1396          89 : void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
    1397             :   // Update machine-CFG edge.
    1398         178 :   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
    1399          89 :   FuncInfo.MBB->addSuccessor(TargetMBB);
    1400             : 
    1401          89 :   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1402             :   bool IsSEH = isAsynchronousEHPersonality(Pers);
    1403             :   if (IsSEH) {
    1404             :     // If this is not a fall-through branch or optimizations are switched off,
    1405             :     // emit the branch.
    1406          43 :     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
    1407          17 :         TM.getOptLevel() == CodeGenOpt::None)
    1408          40 :       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
    1409          30 :                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
    1410          26 :     return;
    1411             :   }
    1412             : 
    1413             :   // Figure out the funclet membership for the catchret's successor.
    1414             :   // This will be used by the FuncletLayout pass to determine how to order the
    1415             :   // BB's.
    1416             :   // A 'catchret' returns to the outer scope's color.
    1417             :   Value *ParentPad = I.getCatchSwitchParentPad();
    1418             :   const BasicBlock *SuccessorColor;
    1419          63 :   if (isa<ConstantTokenNone>(ParentPad))
    1420         114 :     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
    1421             :   else
    1422           6 :     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
    1423             :   assert(SuccessorColor && "No parent funclet for catchret!");
    1424         126 :   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
    1425             :   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
    1426             : 
    1427             :   // Create the terminator node.
    1428         189 :   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
    1429          63 :                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
    1430         252 :                             DAG.getBasicBlock(SuccessorColorMBB));
    1431          63 :   DAG.setRoot(Ret);
    1432             : }
    1433             : 
    1434          41 : void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
    1435             :   // Don't emit any special code for the cleanuppad instruction. It just marks
    1436             :   // the start of an EH scope/funclet.
    1437          41 :   FuncInfo.MBB->setIsEHScopeEntry();
    1438          41 :   FuncInfo.MBB->setIsEHFuncletEntry();
    1439          41 :   FuncInfo.MBB->setIsCleanupFuncletEntry();
    1440          41 : }
    1441             : 
    1442             : /// When an invoke or a cleanupret unwinds to the next EH pad, there are
    1443             : /// many places it could ultimately go. In the IR, we have a single unwind
    1444             : /// destination, but in the machine CFG, we enumerate all the possible blocks.
    1445             : /// This function skips over imaginary basic blocks that hold catchswitch
    1446             : /// instructions, and finds all the "real" machine
    1447             : /// basic block destinations. As those destinations may not be successors of
    1448             : /// EHPadBB, here we also calculate the edge probability to those destinations.
    1449             : /// The passed-in Prob is the edge probability to EHPadBB.
    1450       42775 : static void findUnwindDestinations(
    1451             :     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
    1452             :     BranchProbability Prob,
    1453             :     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
    1454             :         &UnwindDests) {
    1455             :   EHPersonality Personality =
    1456       42775 :     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1457       42775 :   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
    1458       42775 :   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
    1459             :   bool IsSEH = isAsynchronousEHPersonality(Personality);
    1460             : 
    1461       42894 :   while (EHPadBB) {
    1462       42780 :     const Instruction *Pad = EHPadBB->getFirstNonPHI();
    1463             :     BasicBlock *NewEHPadBB = nullptr;
    1464       42780 :     if (isa<LandingPadInst>(Pad)) {
    1465             :       // Stop on landingpads. They are not funclets.
    1466       85192 :       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
    1467       42596 :       break;
    1468         184 :     } else if (isa<CleanupPadInst>(Pad)) {
    1469             :       // Stop on cleanup pads. Cleanups are always funclet entries for all known
    1470             :       // personalities.
    1471         130 :       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
    1472          65 :       UnwindDests.back().first->setIsEHScopeEntry();
    1473          65 :       UnwindDests.back().first->setIsEHFuncletEntry();
    1474             :       break;
    1475           0 :     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
    1476             :       // Add the catchpad handlers to the possible destinations.
    1477         379 :       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
    1478         260 :         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
    1479             :         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
    1480         130 :         if (IsMSVCCXX || IsCoreCLR)
    1481          91 :           UnwindDests.back().first->setIsEHFuncletEntry();
    1482         130 :         if (!IsSEH)
    1483          92 :           UnwindDests.back().first->setIsEHScopeEntry();
    1484             :       }
    1485             :       NewEHPadBB = CatchSwitch->getUnwindDest();
    1486             :     } else {
    1487             :       continue;
    1488             :     }
    1489             : 
    1490         119 :     BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1491         119 :     if (BPI && NewEHPadBB)
    1492          28 :       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
    1493         119 :     EHPadBB = NewEHPadBB;
    1494             :   }
    1495       42775 : }
    1496             : 
    1497          33 : void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
    1498             :   // Update successor info.
    1499             :   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
    1500             :   auto UnwindDest = I.getUnwindDest();
    1501          33 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1502             :   BranchProbability UnwindDestProb =
    1503          33 :       (BPI && UnwindDest)
    1504          10 :           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
    1505          43 :           : BranchProbability::getZero();
    1506          33 :   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
    1507          55 :   for (auto &UnwindDest : UnwindDests) {
    1508          11 :     UnwindDest.first->setIsEHPad();
    1509          11 :     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
    1510             :   }
    1511          33 :   FuncInfo.MBB->normalizeSuccProbs();
    1512             : 
    1513             :   // Create the terminator node.
    1514             :   SDValue Ret =
    1515         165 :       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
    1516          33 :   DAG.setRoot(Ret);
    1517          33 : }
    1518             : 
    1519           0 : void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
    1520           0 :   report_fatal_error("visitCatchSwitch not yet implemented!");
    1521             : }
    1522             : 
    1523      176408 : void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
    1524      176408 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    1525      176408 :   auto &DL = DAG.getDataLayout();
    1526      176408 :   SDValue Chain = getControlRoot();
    1527             :   SmallVector<ISD::OutputArg, 8> Outs;
    1528             :   SmallVector<SDValue, 8> OutVals;
    1529             : 
    1530             :   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
    1531             :   // lower
    1532             :   //
    1533             :   //   %val = call <ty> @llvm.experimental.deoptimize()
    1534             :   //   ret <ty> %val
    1535             :   //
    1536             :   // differently.
    1537      176408 :   if (I.getParent()->getTerminatingDeoptimizeCall()) {
    1538           0 :     LowerDeoptimizingReturn();
    1539             :     return;
    1540             :   }
    1541             : 
    1542      176408 :   if (!FuncInfo.CanLowerReturn) {
    1543         881 :     unsigned DemoteReg = FuncInfo.DemoteRegister;
    1544         881 :     const Function *F = I.getParent()->getParent();
    1545             : 
    1546             :     // Emit a store of the return value through the virtual register.
    1547             :     // Leave Outs empty so that LowerReturn won't try to load return
    1548             :     // registers the usual way.
    1549             :     SmallVector<EVT, 1> PtrValueVTs;
    1550         881 :     ComputeValueVTs(TLI, DL,
    1551         881 :                     F->getReturnType()->getPointerTo(
    1552         881 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    1553             :                     PtrValueVTs);
    1554             : 
    1555        3524 :     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
    1556         881 :                                         DemoteReg, PtrValueVTs[0]);
    1557         881 :     SDValue RetOp = getValue(I.getOperand(0));
    1558             : 
    1559             :     SmallVector<EVT, 4> ValueVTs;
    1560             :     SmallVector<uint64_t, 4> Offsets;
    1561         881 :     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
    1562         881 :     unsigned NumValues = ValueVTs.size();
    1563             : 
    1564        1762 :     SmallVector<SDValue, 4> Chains(NumValues);
    1565        3197 :     for (unsigned i = 0; i != NumValues; ++i) {
    1566             :       // An aggregate return value cannot wrap around the address space, so
    1567             :       // offsets to its parts don't wrap either.
    1568        4632 :       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
    1569        3474 :       Chains[i] = DAG.getStore(
    1570        3474 :           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
    1571             :           // FIXME: better loc info would be nice.
    1572        3474 :           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
    1573             :     }
    1574             : 
    1575        3524 :     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
    1576         881 :                         MVT::Other, Chains);
    1577      175527 :   } else if (I.getNumOperands() != 0) {
    1578             :     SmallVector<EVT, 4> ValueVTs;
    1579      121805 :     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
    1580      121805 :     unsigned NumValues = ValueVTs.size();
    1581      121805 :     if (NumValues) {
    1582      121804 :       SDValue RetOp = getValue(I.getOperand(0));
    1583             : 
    1584      121804 :       const Function *F = I.getParent()->getParent();
    1585             : 
    1586             :       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
    1587      121804 :       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
    1588             :                                           Attribute::SExt))
    1589             :         ExtendKind = ISD::SIGN_EXTEND;
    1590      118044 :       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
    1591             :                                                Attribute::ZExt))
    1592             :         ExtendKind = ISD::ZERO_EXTEND;
    1593             : 
    1594      121804 :       LLVMContext &Context = F->getContext();
    1595      243608 :       bool RetInReg = F->getAttributes().hasAttribute(
    1596      121804 :           AttributeList::ReturnIndex, Attribute::InReg);
    1597             : 
    1598      369602 :       for (unsigned j = 0; j != NumValues; ++j) {
    1599      247798 :         EVT VT = ValueVTs[j];
    1600             : 
    1601      123899 :         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
    1602        7261 :           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
    1603             : 
    1604      123899 :         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
    1605      123899 :         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
    1606      247798 :         SmallVector<SDValue, 4> Parts(NumParts);
    1607      619495 :         getCopyToParts(DAG, getCurSDLoc(),
    1608      123899 :                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
    1609             :                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
    1610             : 
    1611             :         // 'inreg' on function refers to return value
    1612             :         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
    1613      123899 :         if (RetInReg)
    1614             :           Flags.setInReg();
    1615             : 
    1616             :         // Propagate extension type if any
    1617      123899 :         if (ExtendKind == ISD::SIGN_EXTEND)
    1618             :           Flags.setSExt();
    1619      120139 :         else if (ExtendKind == ISD::ZERO_EXTEND)
    1620             :           Flags.setZExt();
    1621             : 
    1622      389499 :         for (unsigned i = 0; i < NumParts; ++i) {
    1623      398400 :           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
    1624             :                                         VT, /*isfixed=*/true, 0, 0));
    1625      132800 :           OutVals.push_back(Parts[i]);
    1626             :         }
    1627             :       }
    1628             :     }
    1629             :   }
    1630             : 
    1631             :   // Push in swifterror virtual register as the last element of Outs. This makes
    1632             :   // sure swifterror virtual register will be returned in the swifterror
    1633             :   // physical register.
    1634      176408 :   const Function *F = I.getParent()->getParent();
    1635      284583 :   if (TLI.supportSwiftError() &&
    1636      284471 :       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
    1637             :     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
    1638             :     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
    1639             :     Flags.setSwiftError();
    1640         112 :     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
    1641             :                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
    1642             :                                   true /*isfixed*/, 1 /*origidx*/,
    1643             :                                   0 /*partOffs*/));
    1644             :     // Create SDNode for the swifterror virtual register.
    1645         112 :     OutVals.push_back(
    1646         560 :         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
    1647         112 :                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
    1648         224 :                         EVT(TLI.getPointerTy(DL))));
    1649             :   }
    1650             : 
    1651      176408 :   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
    1652             :   CallingConv::ID CallConv =
    1653             :     DAG.getMachineFunction().getFunction().getCallingConv();
    1654      352816 :   Chain = DAG.getTargetLoweringInfo().LowerReturn(
    1655      529224 :       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
    1656             : 
    1657             :   // Verify that the target's LowerReturn behaved as expected.
    1658             :   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
    1659             :          "LowerReturn didn't return a valid chain!");
    1660             : 
    1661             :   // Update the DAG with the new chain value resulting from return lowering.
    1662      176408 :   DAG.setRoot(Chain);
    1663             : }
    1664             : 
    1665             : /// CopyToExportRegsIfNeeded - If the given value has virtual registers
    1666             : /// created for it, emit nodes to copy the value into the virtual
    1667             : /// registers.
    1668     2094231 : void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
    1669             :   // Skip empty types
    1670     2094231 :   if (V->getType()->isEmptyTy())
    1671          16 :     return;
    1672             : 
    1673     2094215 :   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
    1674     4188430 :   if (VMI != FuncInfo.ValueMap.end()) {
    1675             :     assert(!V->use_empty() && "Unused value assigned virtual registers!");
    1676      132909 :     CopyValueToVirtualRegister(V, VMI->second);
    1677             :   }
    1678             : }
    1679             : 
    1680             : /// ExportFromCurrentBlock - If this condition isn't known to be exported from
    1681             : /// the current basic block, add it to ValueMap now so that we'll get a
    1682             : /// CopyTo/FromReg.
    1683        2140 : void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
    1684             :   // No need to export constants.
    1685        2140 :   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
    1686             : 
    1687             :   // Already exported?
    1688        1676 :   if (FuncInfo.isExportedInst(V)) return;
    1689             : 
    1690         780 :   unsigned Reg = FuncInfo.InitializeRegForValue(V);
    1691         780 :   CopyValueToVirtualRegister(V, Reg);
    1692             : }
    1693             : 
    1694         712 : bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
    1695             :                                                      const BasicBlock *FromBB) {
    1696             :   // The operands of the setcc have to be in this block.  We don't know
    1697             :   // how to export them from some other block.
    1698             :   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
    1699             :     // Can export from current BB.
    1700         322 :     if (VI->getParent() == FromBB)
    1701             :       return true;
    1702             : 
    1703             :     // Is already exported, noop.
    1704         160 :     return FuncInfo.isExportedInst(V);
    1705             :   }
    1706             : 
    1707             :   // If this is an argument, we can export it if the BB is the entry block or
    1708             :   // if it is already exported.
    1709         390 :   if (isa<Argument>(V)) {
    1710         218 :     if (FromBB == &FromBB->getParent()->getEntryBlock())
    1711             :       return true;
    1712             : 
    1713             :     // Otherwise, can only export this if it is already exported.
    1714          88 :     return FuncInfo.isExportedInst(V);
    1715             :   }
    1716             : 
    1717             :   // Otherwise, constants can always be exported.
    1718             :   return true;
    1719             : }
    1720             : 
    1721             : /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
    1722             : BranchProbability
    1723      111935 : SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
    1724             :                                         const MachineBasicBlock *Dst) const {
    1725      111935 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1726      111935 :   const BasicBlock *SrcBB = Src->getBasicBlock();
    1727      111935 :   const BasicBlock *DstBB = Dst->getBasicBlock();
    1728      111935 :   if (!BPI) {
    1729             :     // If BPI is not available, set the default probability as 1 / N, where N is
    1730             :     // the number of successors.
    1731        1785 :     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
    1732         595 :     return BranchProbability(1, SuccSize);
    1733             :   }
    1734      111340 :   return BPI->getEdgeProbability(SrcBB, DstBB);
    1735             : }
    1736             : 
    1737      176367 : void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
    1738             :                                                MachineBasicBlock *Dst,
    1739             :                                                BranchProbability Prob) {
    1740      176367 :   if (!FuncInfo.BPI)
    1741       32728 :     Src->addSuccessorWithoutProb(Dst);
    1742             :   else {
    1743      143639 :     if (Prob.isUnknown())
    1744      109999 :       Prob = getEdgeProbability(Src, Dst);
    1745      143639 :     Src->addSuccessor(Dst, Prob);
    1746             :   }
    1747      176367 : }
    1748             : 
    1749             : static bool InBlock(const Value *V, const BasicBlock *BB) {
    1750             :   if (const Instruction *I = dyn_cast<Instruction>(V))
    1751         812 :     return I->getParent() == BB;
    1752             :   return true;
    1753             : }
    1754             : 
    1755             : /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
    1756             : /// This function emits a branch and is used at the leaves of an OR or an
    1757             : /// AND operator tree.
    1758             : void
    1759         814 : SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
    1760             :                                                   MachineBasicBlock *TBB,
    1761             :                                                   MachineBasicBlock *FBB,
    1762             :                                                   MachineBasicBlock *CurBB,
    1763             :                                                   MachineBasicBlock *SwitchBB,
    1764             :                                                   BranchProbability TProb,
    1765             :                                                   BranchProbability FProb,
    1766             :                                                   bool InvertCond) {
    1767         814 :   const BasicBlock *BB = CurBB->getBasicBlock();
    1768             : 
    1769             :   // If the leaf of the tree is a comparison, merge the condition into
    1770             :   // the caseblock.
    1771             :   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
    1772             :     // The operands of the cmp have to be in this block.  We don't know
    1773             :     // how to export them from some other block.  If this is the first block
    1774             :     // of the sequence, no exporting is needed.
    1775        1050 :     if (CurBB == SwitchBB ||
    1776         712 :         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
    1777         356 :          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
    1778             :       ISD::CondCode Condition;
    1779             :       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
    1780             :         ICmpInst::Predicate Pred =
    1781         647 :             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
    1782         647 :         Condition = getICmpCondCode(Pred);
    1783             :       } else {
    1784             :         const FCmpInst *FC = cast<FCmpInst>(Cond);
    1785             :         FCmpInst::Predicate Pred =
    1786          47 :             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
    1787          47 :         Condition = getFCmpCondCode(Pred);
    1788          47 :         if (TM.Options.NoNaNsFPMath)
    1789           0 :           Condition = getFCmpCodeWithoutNaN(Condition);
    1790             :       }
    1791             : 
    1792             :       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
    1793        1388 :                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
    1794         694 :       SwitchCases.push_back(CB);
    1795             :       return;
    1796             :     }
    1797             :   }
    1798             : 
    1799             :   // Create a CaseBlock record representing this branch.
    1800         120 :   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
    1801         120 :   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
    1802         240 :                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
    1803         120 :   SwitchCases.push_back(CB);
    1804             : }
    1805             : 
    1806             : /// FindMergedConditions - If Cond is an expression like
    1807        1262 : void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
    1808             :                                                MachineBasicBlock *TBB,
    1809             :                                                MachineBasicBlock *FBB,
    1810             :                                                MachineBasicBlock *CurBB,
    1811             :                                                MachineBasicBlock *SwitchBB,
    1812             :                                                Instruction::BinaryOps Opc,
    1813             :                                                BranchProbability TProb,
    1814             :                                                BranchProbability FProb,
    1815             :                                                bool InvertCond) {
    1816             :   // Skip over not part of the tree and remember to invert op and operands at
    1817             :   // next level.
    1818        1287 :   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
    1819          22 :     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
    1820          41 :     if (InBlock(CondOp, CurBB->getBasicBlock())) {
    1821          21 :       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
    1822          21 :                            !InvertCond);
    1823          21 :       return;
    1824             :     }
    1825             :   }
    1826             : 
    1827             :   const Instruction *BOp = dyn_cast<Instruction>(Cond);
    1828             :   // Compute the effective opcode for Cond, taking into account whether it needs
    1829             :   // to be inverted, e.g.
    1830             :   //   and (not (or A, B)), C
    1831             :   // gets lowered as
    1832             :   //   and (and (not A, not B), C)
    1833             :   unsigned BOpc = 0;
    1834             :   if (BOp) {
    1835             :     BOpc = BOp->getOpcode();
    1836        1162 :     if (InvertCond) {
    1837          33 :       if (BOpc == Instruction::And)
    1838             :         BOpc = Instruction::Or;
    1839          29 :       else if (BOpc == Instruction::Or)
    1840             :         BOpc = Instruction::And;
    1841             :     }
    1842             :   }
    1843             : 
    1844             :   // If this node is not part of the or/and tree, emit it as a branch.
    1845        2313 :   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
    1846         880 :       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
    1847         847 :       BOp->getParent() != CurBB->getBasicBlock() ||
    1848        2063 :       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
    1849             :       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
    1850         814 :     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
    1851             :                                  TProb, FProb, InvertCond);
    1852         814 :     return;
    1853             :   }
    1854             : 
    1855             :   //  Create TmpBB after CurBB.
    1856             :   MachineFunction::iterator BBI(CurBB);
    1857         427 :   MachineFunction &MF = DAG.getMachineFunction();
    1858         427 :   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
    1859         427 :   CurBB->getParent()->insert(++BBI, TmpBB);
    1860             : 
    1861         427 :   if (Opc == Instruction::Or) {
    1862             :     // Codegen X | Y as:
    1863             :     // BB1:
    1864             :     //   jmp_if_X TBB
    1865             :     //   jmp TmpBB
    1866             :     // TmpBB:
    1867             :     //   jmp_if_Y TBB
    1868             :     //   jmp FBB
    1869             :     //
    1870             : 
    1871             :     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
    1872             :     // The requirement is that
    1873             :     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
    1874             :     //     = TrueProb for original BB.
    1875             :     // Assuming the original probabilities are A and B, one choice is to set
    1876             :     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
    1877             :     // A/(1+B) and 2B/(1+B). This choice assumes that
    1878             :     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
    1879             :     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
    1880             :     // TmpBB, but the math is more complicated.
    1881             : 
    1882         203 :     auto NewTrueProb = TProb / 2;
    1883         203 :     auto NewFalseProb = TProb / 2 + FProb;
    1884             :     // Emit the LHS condition.
    1885         406 :     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
    1886             :                          NewTrueProb, NewFalseProb, InvertCond);
    1887             : 
    1888             :     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
    1889         406 :     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
    1890         203 :     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
    1891             :     // Emit the RHS condition into TmpBB.
    1892         203 :     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
    1893             :                          Probs[0], Probs[1], InvertCond);
    1894             :   } else {
    1895             :     assert(Opc == Instruction::And && "Unknown merge op!");
    1896             :     // Codegen X & Y as:
    1897             :     // BB1:
    1898             :     //   jmp_if_X TmpBB
    1899             :     //   jmp FBB
    1900             :     // TmpBB:
    1901             :     //   jmp_if_Y TBB
    1902             :     //   jmp FBB
    1903             :     //
    1904             :     //  This requires creation of TmpBB after CurBB.
    1905             : 
    1906             :     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
    1907             :     // The requirement is that
    1908             :     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
    1909             :     //     = FalseProb for original BB.
    1910             :     // Assuming the original probabilities are A and B, one choice is to set
    1911             :     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
    1912             :     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
    1913             :     // TrueProb for BB1 * FalseProb for TmpBB.
    1914             : 
    1915         224 :     auto NewTrueProb = TProb + FProb / 2;
    1916         224 :     auto NewFalseProb = FProb / 2;
    1917             :     // Emit the LHS condition.
    1918         448 :     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
    1919             :                          NewTrueProb, NewFalseProb, InvertCond);
    1920             : 
    1921             :     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
    1922         448 :     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
    1923         224 :     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
    1924             :     // Emit the RHS condition into TmpBB.
    1925         224 :     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
    1926             :                          Probs[0], Probs[1], InvertCond);
    1927             :   }
    1928             : }
    1929             : 
    1930             : /// If the set of cases should be emitted as a series of branches, return true.
    1931             : /// If we should emit this as a bunch of and/or'd together conditions, return
    1932             : /// false.
    1933             : bool
    1934         387 : SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
    1935         774 :   if (Cases.size() != 2) return true;
    1936             : 
    1937             :   // If this is two comparisons of the same values or'd or and'd together, they
    1938             :   // will get folded into a single comparison, so don't emit two blocks.
    1939         370 :   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
    1940         689 :        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
    1941         341 :       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
    1942           1 :        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
    1943             :     return false;
    1944             :   }
    1945             : 
    1946             :   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
    1947             :   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
    1948         410 :   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
    1949         124 :       Cases[0].CC == Cases[1].CC &&
    1950         393 :       isa<Constant>(Cases[0].CmpRHS) &&
    1951          53 :       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
    1952          31 :     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
    1953             :       return false;
    1954          30 :     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
    1955             :       return false;
    1956             :   }
    1957             : 
    1958             :   return true;
    1959             : }
    1960             : 
    1961      103213 : void SelectionDAGBuilder::visitBr(const BranchInst &I) {
    1962      103213 :   MachineBasicBlock *BrMBB = FuncInfo.MBB;
    1963             : 
    1964             :   // Update machine-CFG edges.
    1965      206426 :   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
    1966             : 
    1967      103213 :   if (I.isUnconditional()) {
    1968             :     // Update machine-CFG edges.
    1969       61683 :     BrMBB->addSuccessor(Succ0MBB);
    1970             : 
    1971             :     // If this is not a fall-through branch or optimizations are switched off,
    1972             :     // emit the branch.
    1973       61683 :     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
    1974      126700 :       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
    1975             :                               MVT::Other, getControlRoot(),
    1976       95025 :                               DAG.getBasicBlock(Succ0MBB)));
    1977             : 
    1978       62059 :     return;
    1979             :   }
    1980             : 
    1981             :   // If this condition is one of the special cases we handle, do special stuff
    1982             :   // now.
    1983             :   const Value *CondVal = I.getCondition();
    1984       83060 :   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
    1985             : 
    1986             :   // If this is a series of conditions that are or'd or and'd together, emit
    1987             :   // this as a sequence of branches instead of setcc's with and/or operations.
    1988             :   // As long as jumps are not expensive, this should improve performance.
    1989             :   // For example, instead of something like:
    1990             :   //     cmp A, B
    1991             :   //     C = seteq
    1992             :   //     cmp D, E
    1993             :   //     F = setle
    1994             :   //     or C, F
    1995             :   //     jnz foo
    1996             :   // Emit:
    1997             :   //     cmp A, B
    1998             :   //     je foo
    1999             :   //     cmp D, E
    2000             :   //     jle foo
    2001             :   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
    2002             :     Instruction::BinaryOps Opcode = BOp->getOpcode();
    2003        1341 :     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
    2004        1421 :         !I.getMetadata(LLVMContext::MD_unpredictable) &&
    2005         403 :         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
    2006         387 :       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
    2007             :                            Opcode,
    2008             :                            getEdgeProbability(BrMBB, Succ0MBB),
    2009             :                            getEdgeProbability(BrMBB, Succ1MBB),
    2010             :                            /*InvertCond=*/false);
    2011             :       // If the compares in later blocks need to use values not currently
    2012             :       // exported from this block, export them now.  This block should always
    2013             :       // be the first entry.
    2014             :       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
    2015             : 
    2016             :       // Allow some cases to be rejected.
    2017         387 :       if (ShouldEmitAsBranches(SwitchCases)) {
    2018        1168 :         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
    2019         832 :           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
    2020         832 :           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
    2021             :         }
    2022             : 
    2023             :         // Emit the branch for this block.
    2024         376 :         visitSwitchCase(SwitchCases[0], BrMBB);
    2025             :         SwitchCases.erase(SwitchCases.begin());
    2026         376 :         return;
    2027             :       }
    2028             : 
    2029             :       // Okay, we decided not to do this, remove any inserted MBB's and clear
    2030             :       // SwitchCases.
    2031          33 :       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
    2032          22 :         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
    2033             : 
    2034          11 :       SwitchCases.clear();
    2035             :     }
    2036             :   }
    2037             : 
    2038             :   // Create a CaseBlock record representing this branch.
    2039       41154 :   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
    2040       82308 :                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
    2041             : 
    2042             :   // Use visitSwitchCase to actually insert the fast branch sequence for this
    2043             :   // cond branch.
    2044       41154 :   visitSwitchCase(CB, BrMBB);
    2045             : }
    2046             : 
    2047             : /// visitSwitchCase - Emits the necessary code to represent a single node in
    2048             : /// the binary search tree resulting from lowering a switch instruction.
    2049       44125 : void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
    2050             :                                           MachineBasicBlock *SwitchBB) {
    2051             :   SDValue Cond;
    2052       44125 :   SDValue CondLHS = getValue(CB.CmpLHS);
    2053             :   SDLoc dl = CB.DL;
    2054             : 
    2055             :   // Build the setcc now.
    2056       44125 :   if (!CB.CmpMHS) {
    2057             :     // Fold "(X == true)" to X and "(X == false)" to !X to
    2058             :     // handle common cases produced by branch lowering.
    2059       85116 :     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
    2060       41271 :         CB.CC == ISD::SETEQ)
    2061             :       Cond = CondLHS;
    2062        2586 :     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
    2063           4 :              CB.CC == ISD::SETEQ) {
    2064           8 :       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
    2065           8 :       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
    2066             :     } else
    2067        5156 :       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
    2068             :   } else {
    2069             :     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
    2070             : 
    2071         280 :     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
    2072         280 :     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
    2073             : 
    2074         280 :     SDValue CmpOp = getValue(CB.CmpMHS);
    2075         560 :     EVT VT = CmpOp.getValueType();
    2076             : 
    2077         280 :     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
    2078           2 :       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
    2079           2 :                           ISD::SETLE);
    2080             :     } else {
    2081         279 :       SDValue SUB = DAG.getNode(ISD::SUB, dl,
    2082         279 :                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
    2083         558 :       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
    2084        1116 :                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
    2085             :     }
    2086             :   }
    2087             : 
    2088             :   // Update successor info
    2089       44125 :   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
    2090             :   // TrueBB and FalseBB are always different unless the incoming IR is
    2091             :   // degenerate. This only happens when running llc on weird IR.
    2092       44125 :   if (CB.TrueBB != CB.FalseBB)
    2093       44118 :     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
    2094             :   SwitchBB->normalizeSuccProbs();
    2095             : 
    2096             :   // If the lhs block is the next block, invert the condition so that we can
    2097             :   // fall through to the lhs instead of the rhs block.
    2098       44125 :   if (CB.TrueBB == NextBlock(SwitchBB)) {
    2099             :     std::swap(CB.TrueBB, CB.FalseBB);
    2100       50254 :     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
    2101       50254 :     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
    2102             :   }
    2103             : 
    2104       44125 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2105             :                                MVT::Other, getControlRoot(), Cond,
    2106       88250 :                                DAG.getBasicBlock(CB.TrueBB));
    2107             : 
    2108             :   // Insert the false branch. Do this even if it's a fall through branch,
    2109             :   // this makes it easier to do DAG optimizations which require inverting
    2110             :   // the branch condition.
    2111       88250 :   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
    2112       88250 :                        DAG.getBasicBlock(CB.FalseBB));
    2113             : 
    2114       44125 :   DAG.setRoot(BrCond);
    2115       44125 : }
    2116             : 
    2117             : /// visitJumpTable - Emit JumpTable node in the current MBB
    2118         254 : void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
    2119             :   // Emit the code for the jump table
    2120             :   assert(JT.Reg != -1U && "Should lower JT Header first!");
    2121         254 :   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
    2122         762 :   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
    2123         508 :                                      JT.Reg, PTy);
    2124         254 :   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
    2125         762 :   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
    2126             :                                     MVT::Other, Index.getValue(1),
    2127         762 :                                     Table, Index);
    2128         254 :   DAG.setRoot(BrJumpTable);
    2129         254 : }
    2130             : 
    2131             : /// visitJumpTableHeader - This function emits necessary code to produce index
    2132             : /// in the JumpTable from switch case.
    2133         254 : void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
    2134             :                                                JumpTableHeader &JTH,
    2135             :                                                MachineBasicBlock *SwitchBB) {
    2136         254 :   SDLoc dl = getCurSDLoc();
    2137             : 
    2138             :   // Subtract the lowest switch case value from the value being switched on and
    2139             :   // conditional branch to default mbb if the result is greater than the
    2140             :   // difference between smallest and largest cases.
    2141         254 :   SDValue SwitchOp = getValue(JTH.SValue);
    2142         254 :   EVT VT = SwitchOp.getValueType();
    2143         254 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
    2144         254 :                             DAG.getConstant(JTH.First, dl, VT));
    2145             : 
    2146             :   // The SDNode we just created, which holds the value being switched on minus
    2147             :   // the smallest case value, needs to be copied to a virtual register so it
    2148             :   // can be used as an index into the jump table in a subsequent basic block.
    2149             :   // This value may be smaller or larger than the target's pointer type, and
    2150             :   // therefore require extension or truncating.
    2151         254 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2152         508 :   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
    2153             : 
    2154             :   unsigned JumpTableReg =
    2155         508 :       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
    2156         254 :   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
    2157         254 :                                     JumpTableReg, SwitchOp);
    2158         254 :   JT.Reg = JumpTableReg;
    2159             : 
    2160             :   // Emit the range check for the jump table, and branch to the default block
    2161             :   // for the switch statement if the value being switched on exceeds the largest
    2162             :   // case in the switch.
    2163         254 :   SDValue CMP = DAG.getSetCC(
    2164         254 :       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    2165         254 :                                  Sub.getValueType()),
    2166        1778 :       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
    2167             : 
    2168         254 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2169             :                                MVT::Other, CopyTo, CMP,
    2170         508 :                                DAG.getBasicBlock(JT.Default));
    2171             : 
    2172             :   // Avoid emitting unnecessary branches to the next block.
    2173         254 :   if (JT.MBB != NextBlock(SwitchBB))
    2174          56 :     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
    2175          56 :                          DAG.getBasicBlock(JT.MBB));
    2176             : 
    2177         254 :   DAG.setRoot(BrCond);
    2178         254 : }
    2179             : 
    2180             : /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
    2181             : /// variable if there exists one.
    2182         438 : static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
    2183             :                                  SDValue &Chain) {
    2184         438 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2185         438 :   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    2186         438 :   MachineFunction &MF = DAG.getMachineFunction();
    2187         438 :   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
    2188             :   MachineSDNode *Node =
    2189         438 :       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
    2190         438 :   if (Global) {
    2191             :     MachinePointerInfo MPInfo(Global);
    2192         423 :     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
    2193             :     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
    2194             :                  MachineMemOperand::MODereferenceable;
    2195         423 :     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
    2196             :                                        DAG.getEVTAlignment(PtrTy));
    2197         423 :     Node->setMemRefs(MemRefs, MemRefs + 1);
    2198             :   }
    2199         438 :   return SDValue(Node, 0);
    2200             : }
    2201             : 
    2202             : /// Codegen a new tail for a stack protector check ParentMBB which has had its
    2203             : /// tail spliced into a stack protector check success bb.
    2204             : ///
    2205             : /// For a high level explanation of how this fits into the stack protector
    2206             : /// generation see the comment on the declaration of class
    2207             : /// StackProtectorDescriptor.
    2208         339 : void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
    2209             :                                                   MachineBasicBlock *ParentBB) {
    2210             : 
    2211             :   // First create the loads to the guard/stack slot for the comparison.
    2212         339 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2213         339 :   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    2214             : 
    2215         339 :   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
    2216         339 :   int FI = MFI.getStackProtectorIndex();
    2217             : 
    2218             :   SDValue Guard;
    2219         339 :   SDLoc dl = getCurSDLoc();
    2220         339 :   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
    2221         339 :   const Module &M = *ParentBB->getParent()->getFunction().getParent();
    2222         339 :   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
    2223             : 
    2224             :   // Generate code to load the content of the guard slot.
    2225         339 :   SDValue GuardVal = DAG.getLoad(
    2226         339 :       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
    2227             :       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
    2228         678 :       MachineMemOperand::MOVolatile);
    2229             : 
    2230         339 :   if (TLI.useStackGuardXorFP())
    2231         143 :     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
    2232             : 
    2233             :   // Retrieve guard check function, nullptr if instrumentation is inlined.
    2234         339 :   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
    2235             :     // The target provides a guard check function to validate the guard value.
    2236             :     // Generate a call to that function with the content of the guard slot as
    2237             :     // argument.
    2238             :     auto *Fn = cast<Function>(GuardCheck);
    2239             :     FunctionType *FnTy = Fn->getFunctionType();
    2240             :     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
    2241             : 
    2242             :     TargetLowering::ArgListTy Args;
    2243             :     TargetLowering::ArgListEntry Entry;
    2244          80 :     Entry.Node = GuardVal;
    2245         160 :     Entry.Ty = FnTy->getParamType(0);
    2246          80 :     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
    2247          80 :       Entry.IsInReg = true;
    2248          80 :     Args.push_back(Entry);
    2249             : 
    2250         160 :     TargetLowering::CallLoweringInfo CLI(DAG);
    2251         160 :     CLI.setDebugLoc(getCurSDLoc())
    2252          80 :       .setChain(DAG.getEntryNode())
    2253             :       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
    2254          80 :                  getValue(GuardCheck), std::move(Args));
    2255             : 
    2256          80 :     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    2257          80 :     DAG.setRoot(Result.second);
    2258             :     return;
    2259             :   }
    2260             : 
    2261             :   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
    2262             :   // Otherwise, emit a volatile load to retrieve the stack guard value.
    2263         518 :   SDValue Chain = DAG.getEntryNode();
    2264         259 :   if (TLI.useLoadStackGuardNode()) {
    2265         142 :     Guard = getLoadStackGuard(DAG, dl, Chain);
    2266             :   } else {
    2267         117 :     const Value *IRGuard = TLI.getSDagStackGuard(M);
    2268         117 :     SDValue GuardPtr = getValue(IRGuard);
    2269             : 
    2270         117 :     Guard =
    2271         351 :         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
    2272         117 :                     Align, MachineMemOperand::MOVolatile);
    2273             :   }
    2274             : 
    2275             :   // Perform the comparison via a subtract/getsetcc.
    2276         259 :   EVT VT = Guard.getValueType();
    2277         518 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
    2278             : 
    2279         259 :   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
    2280         259 :                                                         *DAG.getContext(),
    2281         259 :                                                         Sub.getValueType()),
    2282        1036 :                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
    2283             : 
    2284             :   // If the sub is not 0, then we know the guard/stackslot do not equal, so
    2285             :   // branch to failure MBB.
    2286         259 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2287             :                                MVT::Other, GuardVal.getOperand(0),
    2288         518 :                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
    2289             :   // Otherwise branch to success MBB.
    2290         259 :   SDValue Br = DAG.getNode(ISD::BR, dl,
    2291             :                            MVT::Other, BrCond,
    2292         518 :                            DAG.getBasicBlock(SPD.getSuccessMBB()));
    2293             : 
    2294         259 :   DAG.setRoot(Br);
    2295             : }
    2296             : 
    2297             : /// Codegen the failure basic block for a stack protector check.
    2298             : ///
    2299             : /// A failure stack protector machine basic block consists simply of a call to
    2300             : /// __stack_chk_fail().
    2301             : ///
    2302             : /// For a high level explanation of how this fits into the stack protector
    2303             : /// generation see the comment on the declaration of class
    2304             : /// StackProtectorDescriptor.
    2305             : void
    2306         250 : SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
    2307         250 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2308             :   SDValue Chain =
    2309         500 :       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
    2310        1250 :                       None, false, getCurSDLoc(), false, false).second;
    2311         250 :   DAG.setRoot(Chain);
    2312         250 : }
    2313             : 
    2314             : /// visitBitTestHeader - This function emits necessary code to produce value
    2315             : /// suitable for "bit tests"
    2316          26 : void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
    2317             :                                              MachineBasicBlock *SwitchBB) {
    2318          26 :   SDLoc dl = getCurSDLoc();
    2319             : 
    2320             :   // Subtract the minimum value
    2321          26 :   SDValue SwitchOp = getValue(B.SValue);
    2322          52 :   EVT VT = SwitchOp.getValueType();
    2323          26 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
    2324          26 :                             DAG.getConstant(B.First, dl, VT));
    2325             : 
    2326             :   // Check range
    2327          26 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2328             :   SDValue RangeCmp = DAG.getSetCC(
    2329          26 :       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    2330          26 :                                  Sub.getValueType()),
    2331          78 :       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
    2332             : 
    2333             :   // Determine the type of the test operands.
    2334             :   bool UsePtrType = false;
    2335             :   if (!TLI.isTypeLegal(VT))
    2336             :     UsePtrType = true;
    2337             :   else {
    2338          57 :     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
    2339          76 :       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
    2340             :         // Switch table case range are encoded into series of masks.
    2341             :         // Just use pointer type, it's guaranteed to fit.
    2342             :         UsePtrType = true;
    2343             :         break;
    2344             :       }
    2345             :   }
    2346          26 :   if (UsePtrType) {
    2347          14 :     VT = TLI.getPointerTy(DAG.getDataLayout());
    2348           7 :     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
    2349             :   }
    2350             : 
    2351          26 :   B.RegVT = VT.getSimpleVT();
    2352          26 :   B.Reg = FuncInfo.CreateReg(B.RegVT);
    2353          26 :   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
    2354             : 
    2355          26 :   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
    2356             : 
    2357          26 :   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
    2358          26 :   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
    2359             :   SwitchBB->normalizeSuccProbs();
    2360             : 
    2361          26 :   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
    2362             :                                 MVT::Other, CopyTo, RangeCmp,
    2363          52 :                                 DAG.getBasicBlock(B.Default));
    2364             : 
    2365             :   // Avoid emitting unnecessary branches to the next block.
    2366          26 :   if (MBB != NextBlock(SwitchBB))
    2367          12 :     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
    2368          12 :                           DAG.getBasicBlock(MBB));
    2369             : 
    2370          26 :   DAG.setRoot(BrRange);
    2371          26 : }
    2372             : 
    2373             : /// visitBitTestCase - this function produces one "bit test"
    2374          37 : void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
    2375             :                                            MachineBasicBlock* NextMBB,
    2376             :                                            BranchProbability BranchProbToNext,
    2377             :                                            unsigned Reg,
    2378             :                                            BitTestCase &B,
    2379             :                                            MachineBasicBlock *SwitchBB) {
    2380          37 :   SDLoc dl = getCurSDLoc();
    2381          37 :   MVT VT = BB.RegVT;
    2382          74 :   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
    2383          37 :   SDValue Cmp;
    2384          37 :   unsigned PopCount = countPopulation(B.Mask);
    2385          37 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2386          37 :   if (PopCount == 1) {
    2387             :     // Testing for a single bit; just compare the shift count with what it
    2388             :     // would need to be to shift a 1 bit in that position.
    2389           3 :     Cmp = DAG.getSetCC(
    2390           6 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2391             :         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
    2392          12 :         ISD::SETEQ);
    2393          68 :   } else if (PopCount == BB.Range) {
    2394             :     // There is only one zero bit in the range, test for it directly.
    2395           3 :     Cmp = DAG.getSetCC(
    2396           6 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2397             :         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
    2398          12 :         ISD::SETNE);
    2399             :   } else {
    2400             :     // Make desired shift
    2401             :     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
    2402          62 :                                     DAG.getConstant(1, dl, VT), ShiftOp);
    2403             : 
    2404             :     // Emit bit tests and jumps
    2405          31 :     SDValue AndOp = DAG.getNode(ISD::AND, dl,
    2406          62 :                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
    2407          62 :     Cmp = DAG.getSetCC(
    2408          62 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2409         124 :         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
    2410             :   }
    2411             : 
    2412             :   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
    2413          37 :   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
    2414             :   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
    2415          37 :   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
    2416             :   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
    2417             :   // one as they are relative probabilities (and thus work more like weights),
    2418             :   // and hence we need to normalize them to let the sum of them become one.
    2419             :   SwitchBB->normalizeSuccProbs();
    2420             : 
    2421          37 :   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
    2422             :                               MVT::Other, getControlRoot(),
    2423          74 :                               Cmp, DAG.getBasicBlock(B.TargetBB));
    2424             : 
    2425             :   // Avoid emitting unnecessary branches to the next block.
    2426          37 :   if (NextMBB != NextBlock(SwitchBB))
    2427          44 :     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
    2428          44 :                         DAG.getBasicBlock(NextMBB));
    2429             : 
    2430          37 :   DAG.setRoot(BrAnd);
    2431          37 : }
    2432             : 
    2433       42742 : void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
    2434       42742 :   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
    2435             : 
    2436             :   // Retrieve successors. Look through artificial IR level blocks like
    2437             :   // catchswitch for successors.
    2438       85484 :   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
    2439             :   const BasicBlock *EHPadBB = I.getSuccessor(1);
    2440             : 
    2441             :   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
    2442             :   // have to do anything here to lower funclet bundles.
    2443             :   assert(!I.hasOperandBundlesOtherThan(
    2444             :              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
    2445             :          "Cannot lower invokes with arbitrary operand bundles yet!");
    2446             : 
    2447             :   const Value *Callee(I.getCalledValue());
    2448             :   const Function *Fn = dyn_cast<Function>(Callee);
    2449       42742 :   if (isa<InlineAsm>(Callee))
    2450           1 :     visitInlineAsm(&I);
    2451       85052 :   else if (Fn && Fn->isIntrinsic()) {
    2452          11 :     switch (Fn->getIntrinsicID()) {
    2453           0 :     default:
    2454           0 :       llvm_unreachable("Cannot invoke this intrinsic");
    2455             :     case Intrinsic::donothing:
    2456             :       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
    2457             :       break;
    2458             :     case Intrinsic::experimental_patchpoint_void:
    2459             :     case Intrinsic::experimental_patchpoint_i64:
    2460           2 :       visitPatchpoint(&I, EHPadBB);
    2461           2 :       break;
    2462           8 :     case Intrinsic::experimental_gc_statepoint:
    2463          16 :       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
    2464           8 :       break;
    2465             :     }
    2466       42730 :   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
    2467             :     // Currently we do not lower any intrinsic calls with deopt operand bundles.
    2468             :     // Eventually we will support lowering the @llvm.experimental.deoptimize
    2469             :     // intrinsic, and right now there are no plans to support other intrinsics
    2470             :     // with deopt state.
    2471           0 :     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
    2472             :   } else {
    2473       85460 :     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
    2474             :   }
    2475             : 
    2476             :   // If the value of the invoke is used outside of its defining block, make it
    2477             :   // available as a virtual register.
    2478             :   // We already took care of the exported value for the statepoint instruction
    2479             :   // during call to the LowerStatepoint.
    2480       42742 :   if (!isStatepoint(I)) {
    2481       42734 :     CopyToExportRegsIfNeeded(&I);
    2482             :   }
    2483             : 
    2484             :   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
    2485       42742 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    2486             :   BranchProbability EHPadBBProb =
    2487       28124 :       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
    2488       70866 :           : BranchProbability::getZero();
    2489       42742 :   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
    2490             : 
    2491             :   // Update successor info.
    2492       42742 :   addSuccessorWithProb(InvokeMBB, Return);
    2493      128302 :   for (auto &UnwindDest : UnwindDests) {
    2494       42780 :     UnwindDest.first->setIsEHPad();
    2495       42780 :     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
    2496             :   }
    2497             :   InvokeMBB->normalizeSuccProbs();
    2498             : 
    2499             :   // Drop into normal successor.
    2500      170968 :   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
    2501             :                           MVT::Other, getControlRoot(),
    2502      128226 :                           DAG.getBasicBlock(Return)));
    2503       42742 : }
    2504             : 
    2505           0 : void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
    2506           0 :   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
    2507             : }
    2508             : 
    2509       28421 : void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
    2510             :   assert(FuncInfo.MBB->isEHPad() &&
    2511             :          "Call to landingpad not in landing pad!");
    2512             : 
    2513       28421 :   MachineBasicBlock *MBB = FuncInfo.MBB;
    2514       28421 :   addLandingPadInfo(LP, *MBB);
    2515             : 
    2516             :   // If there aren't registers to copy the values into (e.g., during SjLj
    2517             :   // exceptions), then don't bother to create these DAG nodes.
    2518       28421 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2519       28421 :   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
    2520       28545 :   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
    2521         124 :       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
    2522         132 :     return;
    2523             : 
    2524             :   // If landingpad's return type is token type, we don't create DAG nodes
    2525             :   // for its exception pointer and selector value. The extraction of exception
    2526             :   // pointer or selector value from token type landingpads is not currently
    2527             :   // supported.
    2528       56594 :   if (LP.getType()->isTokenTy())
    2529             :     return;
    2530             : 
    2531             :   SmallVector<EVT, 2> ValueVTs;
    2532       28289 :   SDLoc dl = getCurSDLoc();
    2533       56578 :   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
    2534             :   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
    2535             : 
    2536             :   // Get the two live-in registers as SDValues. The physregs have already been
    2537             :   // copied into virtual registers.
    2538       28289 :   SDValue Ops[2];
    2539       28289 :   if (FuncInfo.ExceptionPointerVirtReg) {
    2540       56578 :     Ops[0] = DAG.getZExtOrTrunc(
    2541       28289 :         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    2542       28289 :                            FuncInfo.ExceptionPointerVirtReg,
    2543             :                            TLI.getPointerTy(DAG.getDataLayout())),
    2544      113156 :         dl, ValueVTs[0]);
    2545             :   } else {
    2546           0 :     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
    2547             :   }
    2548       56578 :   Ops[1] = DAG.getZExtOrTrunc(
    2549       28289 :       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    2550       28289 :                          FuncInfo.ExceptionSelectorVirtReg,
    2551             :                          TLI.getPointerTy(DAG.getDataLayout())),
    2552      113156 :       dl, ValueVTs[1]);
    2553             : 
    2554             :   // Merge into one.
    2555       28289 :   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
    2556       28289 :                             DAG.getVTList(ValueVTs), Ops);
    2557       28289 :   setValue(&LP, Res);
    2558             : }
    2559             : 
    2560        1166 : void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
    2561             : #ifndef NDEBUG
    2562             :   for (const CaseCluster &CC : Clusters)
    2563             :     assert(CC.Low == CC.High && "Input clusters must be single-case");
    2564             : #endif
    2565             : 
    2566             :   llvm::sort(Clusters.begin(), Clusters.end(),
    2567             :              [](const CaseCluster &a, const CaseCluster &b) {
    2568             :     return a.Low->getValue().slt(b.Low->getValue());
    2569             :   });
    2570             : 
    2571             :   // Merge adjacent clusters with the same destination.
    2572        2332 :   const unsigned N = Clusters.size();
    2573             :   unsigned DstIndex = 0;
    2574       11172 :   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
    2575        5003 :     CaseCluster &CC = Clusters[SrcIndex];
    2576        5003 :     const ConstantInt *CaseVal = CC.Low;
    2577        5003 :     MachineBasicBlock *Succ = CC.MBB;
    2578             : 
    2579       14967 :     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
    2580       17249 :         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
    2581             :       // If this case has the same successor and is a neighbour, merge it into
    2582             :       // the previous cluster.
    2583        1928 :       Clusters[DstIndex - 1].High = CaseVal;
    2584             :       Clusters[DstIndex - 1].Prob += CC.Prob;
    2585             :     } else {
    2586       12117 :       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
    2587             :                    sizeof(Clusters[SrcIndex]));
    2588             :     }
    2589             :   }
    2590        1166 :   Clusters.resize(DstIndex);
    2591        1166 : }
    2592             : 
    2593           0 : void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
    2594             :                                            MachineBasicBlock *Last) {
    2595             :   // Update JTCases.
    2596           0 :   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
    2597           0 :     if (JTCases[i].first.HeaderBB == First)
    2598           0 :       JTCases[i].first.HeaderBB = Last;
    2599             : 
    2600             :   // Update BitTestCases.
    2601           0 :   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
    2602           0 :     if (BitTestCases[i].Parent == First)
    2603           0 :       BitTestCases[i].Parent = Last;
    2604           0 : }
    2605             : 
    2606          83 : void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
    2607          83 :   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
    2608             : 
    2609             :   // Update machine-CFG edges with unique successors.
    2610             :   SmallSet<BasicBlock*, 32> Done;
    2611         302 :   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
    2612             :     BasicBlock *BB = I.getSuccessor(i);
    2613         219 :     bool Inserted = Done.insert(BB).second;
    2614         219 :     if (!Inserted)
    2615           6 :         continue;
    2616             : 
    2617         426 :     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
    2618         213 :     addSuccessorWithProb(IndirectBrMBB, Succ);
    2619             :   }
    2620             :   IndirectBrMBB->normalizeSuccProbs();
    2621             : 
    2622         332 :   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
    2623             :                           MVT::Other, getControlRoot(),
    2624         249 :                           getValue(I.getAddress())));
    2625          83 : }
    2626             : 
    2627       13434 : void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
    2628       13434 :   if (DAG.getTarget().Options.TrapUnreachable)
    2629         654 :     DAG.setRoot(
    2630        1962 :         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
    2631       13434 : }
    2632             : 
    2633        7023 : void SelectionDAGBuilder::visitFSub(const User &I) {
    2634             :   // -0.0 - X --> fneg
    2635        7023 :   Type *Ty = I.getType();
    2636       11014 :   if (isa<Constant>(I.getOperand(0)) &&
    2637        3991 :       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
    2638        3501 :     SDValue Op2 = getValue(I.getOperand(1));
    2639       17505 :     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
    2640             :                              Op2.getValueType(), Op2));
    2641             :     return;
    2642             :   }
    2643             : 
    2644        3522 :   visitBinary(I, ISD::FSUB);
    2645             : }
    2646             : 
    2647             : /// Checks if the given instruction performs a vector reduction, in which case
    2648             : /// we have the freedom to alter the elements in the result as long as the
    2649             : /// reduction of them stays unchanged.
    2650      300910 : static bool isVectorReductionOp(const User *I) {
    2651             :   const Instruction *Inst = dyn_cast<Instruction>(I);
    2652      601678 :   if (!Inst || !Inst->getType()->isVectorTy())
    2653             :     return false;
    2654             : 
    2655             :   auto OpCode = Inst->getOpcode();
    2656             :   switch (OpCode) {
    2657             :   case Instruction::Add:
    2658             :   case Instruction::Mul:
    2659             :   case Instruction::And:
    2660             :   case Instruction::Or:
    2661             :   case Instruction::Xor:
    2662             :     break;
    2663             :   case Instruction::FAdd:
    2664             :   case Instruction::FMul:
    2665             :     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
    2666        8659 :       if (FPOp->getFastMathFlags().isFast())
    2667             :         break;
    2668             :     LLVM_FALLTHROUGH;
    2669             :   default:
    2670             :     return false;
    2671             :   }
    2672             : 
    2673             :   unsigned ElemNum = Inst->getType()->getVectorNumElements();
    2674             :   unsigned ElemNumToReduce = ElemNum;
    2675             : 
    2676             :   // Do DFS search on the def-use chain from the given instruction. We only
    2677             :   // allow four kinds of operations during the search until we reach the
    2678             :   // instruction that extracts the first element from the vector:
    2679             :   //
    2680             :   //   1. The reduction operation of the same opcode as the given instruction.
    2681             :   //
    2682             :   //   2. PHI node.
    2683             :   //
    2684             :   //   3. ShuffleVector instruction together with a reduction operation that
    2685             :   //      does a partial reduction.
    2686             :   //
    2687             :   //   4. ExtractElement that extracts the first element from the vector, and we
    2688             :   //      stop searching the def-use chain here.
    2689             :   //
    2690             :   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
    2691             :   // from 1-3 to the stack to continue the DFS. The given instruction is not
    2692             :   // a reduction operation if we meet any other instructions other than those
    2693             :   // listed above.
    2694             : 
    2695      192504 :   SmallVector<const User *, 16> UsersToVisit{Inst};
    2696             :   SmallPtrSet<const User *, 16> Visited;
    2697             :   bool ReduxExtracted = false;
    2698             : 
    2699       99089 :   while (!UsersToVisit.empty()) {
    2700       98925 :     auto User = UsersToVisit.back();
    2701             :     UsersToVisit.pop_back();
    2702       98925 :     if (!Visited.insert(User).second)
    2703         297 :       continue;
    2704             : 
    2705      205324 :     for (const auto &U : User->users()) {
    2706             :       auto Inst = dyn_cast<Instruction>(U);
    2707             :       if (!Inst)
    2708             :         return false;
    2709             : 
    2710      101392 :       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
    2711             :         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
    2712         451 :           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
    2713             :             return false;
    2714        5023 :         UsersToVisit.push_back(U);
    2715             :       } else if (const ShuffleVectorInst *ShufInst =
    2716             :                      dyn_cast<ShuffleVectorInst>(U)) {
    2717             :         // Detect the following pattern: A ShuffleVector instruction together
    2718             :         // with a reduction that do partial reduction on the first and second
    2719             :         // ElemNumToReduce / 2 elements, and store the result in
    2720             :         // ElemNumToReduce / 2 elements in another vector.
    2721             : 
    2722             :         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
    2723        3810 :         if (ResultElements < ElemNum)
    2724             :           return false;
    2725             : 
    2726        3720 :         if (ElemNumToReduce == 1)
    2727             :           return false;
    2728        3720 :         if (!isa<UndefValue>(U->getOperand(1)))
    2729             :           return false;
    2730        5001 :         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
    2731        3659 :           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
    2732             :             return false;
    2733        9064 :         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
    2734        4421 :           if (ShufInst->getMaskValue(i) != -1)
    2735             :             return false;
    2736             : 
    2737             :         // There is only one user of this ShuffleVector instruction, which
    2738             :         // must be a reduction operation.
    2739         444 :         if (!U->hasOneUse())
    2740             :           return false;
    2741             : 
    2742             :         auto U2 = dyn_cast<Instruction>(*U->user_begin());
    2743         222 :         if (!U2 || U2->getOpcode() != OpCode)
    2744             :           return false;
    2745             : 
    2746             :         // Check operands of the reduction operation.
    2747         660 :         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
    2748           0 :             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
    2749         220 :           UsersToVisit.push_back(U2);
    2750             :           ElemNumToReduce /= 2;
    2751             :         } else
    2752             :           return false;
    2753             :       } else if (isa<ExtractElementInst>(U)) {
    2754             :         // At this moment we should have reduced all elements in the vector.
    2755        1504 :         if (ElemNumToReduce != 1)
    2756             :           return false;
    2757             : 
    2758             :         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
    2759          61 :         if (!Val || Val->getZExtValue() != 0)
    2760             :           return false;
    2761             : 
    2762             :         ReduxExtracted = true;
    2763             :       } else
    2764             :         return false;
    2765             :     }
    2766             :   }
    2767             :   return ReduxExtracted;
    2768             : }
    2769             : 
    2770      300910 : void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
    2771             :   SDNodeFlags Flags;
    2772             :   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
    2773             :     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
    2774             :     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
    2775             :   }
    2776             :   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
    2777             :     Flags.setExact(ExactOp->isExact());
    2778             :   }
    2779      300910 :   if (isVectorReductionOp(&I)) {
    2780             :     Flags.setVectorReduction(true);
    2781             :     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
    2782             :   }
    2783             : 
    2784      300910 :   SDValue Op1 = getValue(I.getOperand(0));
    2785      300910 :   SDValue Op2 = getValue(I.getOperand(1));
    2786      902730 :   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
    2787      601820 :                                      Op1, Op2, Flags);
    2788             :   setValue(&I, BinNodeValue);
    2789      300910 : }
    2790             : 
    2791       19084 : void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
    2792       19084 :   SDValue Op1 = getValue(I.getOperand(0));
    2793       19084 :   SDValue Op2 = getValue(I.getOperand(1));
    2794             : 
    2795       19084 :   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
    2796       57252 :       Op2.getValueType(), DAG.getDataLayout());
    2797             : 
    2798             :   // Coerce the shift amount to the right type if we can.
    2799       51375 :   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
    2800        9403 :     unsigned ShiftSize = ShiftTy.getSizeInBits();
    2801        9403 :     unsigned Op2Size = Op2.getValueSizeInBits();
    2802        9403 :     SDLoc DL = getCurSDLoc();
    2803             : 
    2804             :     // If the operand is smaller than the shift count type, promote it.
    2805        9403 :     if (ShiftSize > Op2Size)
    2806        1230 :       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
    2807             : 
    2808             :     // If the operand is larger than the shift count type but the shift
    2809             :     // count type has enough bits to represent any shift value, truncate
    2810             :     // it now. This is a common case and it exposes the truncate to
    2811             :     // optimization early.
    2812       17576 :     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
    2813       17558 :       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
    2814             :     // Otherwise we'll need to temporarily settle for some other convenient
    2815             :     // type.  Type legalization will make adjustments once the shiftee is split.
    2816             :     else
    2817          18 :       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
    2818             :   }
    2819             : 
    2820             :   bool nuw = false;
    2821             :   bool nsw = false;
    2822             :   bool exact = false;
    2823             : 
    2824       19084 :   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
    2825             : 
    2826             :     if (const OverflowingBinaryOperator *OFBinOp =
    2827             :             dyn_cast<const OverflowingBinaryOperator>(&I)) {
    2828             :       nuw = OFBinOp->hasNoUnsignedWrap();
    2829             :       nsw = OFBinOp->hasNoSignedWrap();
    2830             :     }
    2831             :     if (const PossiblyExactOperator *ExactOp =
    2832             :             dyn_cast<const PossiblyExactOperator>(&I))
    2833             :       exact = ExactOp->isExact();
    2834             :   }
    2835             :   SDNodeFlags Flags;
    2836             :   Flags.setExact(exact);
    2837             :   Flags.setNoSignedWrap(nsw);
    2838             :   Flags.setNoUnsignedWrap(nuw);
    2839       57252 :   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
    2840       38168 :                             Flags);
    2841       19084 :   setValue(&I, Res);
    2842       19084 : }
    2843             : 
    2844        1521 : void SelectionDAGBuilder::visitSDiv(const User &I) {
    2845        1521 :   SDValue Op1 = getValue(I.getOperand(0));
    2846        1521 :   SDValue Op2 = getValue(I.getOperand(1));
    2847             : 
    2848             :   SDNodeFlags Flags;
    2849        3042 :   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
    2850             :                  cast<PossiblyExactOperator>(&I)->isExact());
    2851        6084 :   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
    2852             :                            Op2, Flags));
    2853        1521 : }
    2854             : 
    2855       62926 : void SelectionDAGBuilder::visitICmp(const User &I) {
    2856             :   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
    2857             :   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
    2858             :     predicate = IC->getPredicate();
    2859             :   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
    2860         140 :     predicate = ICmpInst::Predicate(IC->getPredicate());
    2861       62926 :   SDValue Op1 = getValue(I.getOperand(0));
    2862       62926 :   SDValue Op2 = getValue(I.getOperand(1));
    2863       62926 :   ISD::CondCode Opcode = getICmpCondCode(predicate);
    2864             : 
    2865       62926 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2866      125852 :                                                         I.getType());
    2867      188778 :   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
    2868       62926 : }
    2869             : 
    2870        7811 : void SelectionDAGBuilder::visitFCmp(const User &I) {
    2871             :   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
    2872             :   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
    2873             :     predicate = FC->getPredicate();
    2874             :   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
    2875           2 :     predicate = FCmpInst::Predicate(FC->getPredicate());
    2876        7811 :   SDValue Op1 = getValue(I.getOperand(0));
    2877        7811 :   SDValue Op2 = getValue(I.getOperand(1));
    2878             : 
    2879        7811 :   ISD::CondCode Condition = getFCmpCondCode(predicate);
    2880             :   auto *FPMO = dyn_cast<FPMathOperator>(&I);
    2881        7811 :   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
    2882         916 :     Condition = getFCmpCodeWithoutNaN(Condition);
    2883             : 
    2884        7811 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2885       15622 :                                                         I.getType());
    2886       23433 :   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
    2887        7811 : }
    2888             : 
    2889             : // Check if the condition of the select has one use or two users that are both
    2890             : // selects with the same condition.
    2891             : static bool hasOnlySelectUsers(const Value *Cond) {
    2892             :   return llvm::all_of(Cond->users(), [](const Value *V) {
    2893             :     return isa<SelectInst>(V);
    2894             :   });
    2895             : }
    2896             : 
    2897       53657 : void SelectionDAGBuilder::visitSelect(const User &I) {
    2898             :   SmallVector<EVT, 4> ValueVTs;
    2899      107314 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
    2900             :                   ValueVTs);
    2901       53657 :   unsigned NumValues = ValueVTs.size();
    2902       53657 :   if (NumValues == 0) return;
    2903             : 
    2904      107300 :   SmallVector<SDValue, 4> Values(NumValues);
    2905       53650 :   SDValue Cond     = getValue(I.getOperand(0));
    2906       53650 :   SDValue LHSVal   = getValue(I.getOperand(1));
    2907       53650 :   SDValue RHSVal   = getValue(I.getOperand(2));
    2908       53650 :   auto BaseOps = {Cond};
    2909      160950 :   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
    2910             :     ISD::VSELECT : ISD::SELECT;
    2911             : 
    2912             :   // Min/max matching is only viable if all output VTs are the same.
    2913             :   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
    2914       53650 :     EVT VT = ValueVTs[0];
    2915       53650 :     LLVMContext &Ctx = *DAG.getContext();
    2916       53650 :     auto &TLI = DAG.getTargetLoweringInfo();
    2917             : 
    2918             :     // We care about the legality of the operation after it has been type
    2919             :     // legalized.
    2920      126893 :     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
    2921        6535 :            VT != TLI.getTypeToTransformTo(Ctx, VT))
    2922        6524 :       VT = TLI.getTypeToTransformTo(Ctx, VT);
    2923             : 
    2924             :     // If the vselect is legal, assume we want to leave this as a vector setcc +
    2925             :     // vselect. Otherwise, if this is going to be scalarized, we want to see if
    2926             :     // min/max is legal on the scalar type.
    2927       53650 :     bool UseScalarMinMax = VT.isVector() &&
    2928             :       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
    2929             : 
    2930             :     Value *LHS, *RHS;
    2931       53650 :     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
    2932             :     ISD::NodeType Opc = ISD::DELETED_NODE;
    2933       53650 :     switch (SPR.Flavor) {
    2934             :     case SPF_UMAX:    Opc = ISD::UMAX; break;
    2935             :     case SPF_UMIN:    Opc = ISD::UMIN; break;
    2936             :     case SPF_SMAX:    Opc = ISD::SMAX; break;
    2937             :     case SPF_SMIN:    Opc = ISD::SMIN; break;
    2938         443 :     case SPF_FMINNUM:
    2939         443 :       switch (SPR.NaNBehavior) {
    2940           0 :       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
    2941             :       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
    2942             :       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
    2943         319 :       case SPNB_RETURNS_ANY: {
    2944         319 :         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
    2945             :           Opc = ISD::FMINNUM;
    2946             :         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
    2947             :           Opc = ISD::FMINNAN;
    2948         249 :         else if (UseScalarMinMax)
    2949           2 :           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
    2950             :             ISD::FMINNUM : ISD::FMINNAN;
    2951             :         break;
    2952             :       }
    2953             :       }
    2954             :       break;
    2955         479 :     case SPF_FMAXNUM:
    2956         479 :       switch (SPR.NaNBehavior) {
    2957           0 :       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
    2958             :       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
    2959             :       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
    2960         335 :       case SPNB_RETURNS_ANY:
    2961             : 
    2962         335 :         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
    2963             :           Opc = ISD::FMAXNUM;
    2964             :         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
    2965             :           Opc = ISD::FMAXNAN;
    2966         248 :         else if (UseScalarMinMax)
    2967           2 :           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
    2968             :             ISD::FMAXNUM : ISD::FMAXNAN;
    2969             :         break;
    2970             :       }
    2971             :       break;
    2972             :     default: break;
    2973             :     }
    2974             : 
    2975       10011 :     if (Opc != ISD::DELETED_NODE &&
    2976       10979 :         (TLI.isOperationLegalOrCustom(Opc, VT) ||
    2977         105 :          (UseScalarMinMax &&
    2978        9250 :           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
    2979             :         // If the underlying comparison instruction is used by any other
    2980             :         // instruction, the consumed instructions won't be destroyed, so it is
    2981             :         // not profitable to convert to a min/max.
    2982             :         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
    2983             :       OpCode = Opc;
    2984        9122 :       LHSVal = getValue(LHS);
    2985        9122 :       RHSVal = getValue(RHS);
    2986             :       BaseOps = {};
    2987             :     }
    2988             :   }
    2989             : 
    2990      160958 :   for (unsigned i = 0; i != NumValues; ++i) {
    2991             :     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
    2992      107308 :     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
    2993      107308 :     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
    2994      268270 :     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
    2995             :                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
    2996      107308 :                             Ops);
    2997             :   }
    2998             : 
    2999      214600 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    3000             :                            DAG.getVTList(ValueVTs), Values));
    3001             : }
    3002             : 
    3003        9946 : void SelectionDAGBuilder::visitTrunc(const User &I) {
    3004             :   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
    3005        9946 :   SDValue N = getValue(I.getOperand(0));
    3006        9946 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3007       19892 :                                                         I.getType());
    3008       39784 :   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
    3009        9946 : }
    3010             : 
    3011       17627 : void SelectionDAGBuilder::visitZExt(const User &I) {
    3012             :   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
    3013             :   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
    3014       17627 :   SDValue N = getValue(I.getOperand(0));
    3015       17627 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3016       35254 :                                                         I.getType());
    3017       70508 :   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
    3018       17627 : }
    3019             : 
    3020       15466 : void SelectionDAGBuilder::visitSExt(const User &I) {
    3021             :   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
    3022             :   // SExt also can't be a cast to bool for same reason. So, nothing much to do
    3023       15466 :   SDValue N = getValue(I.getOperand(0));
    3024       15466 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3025       30932 :                                                         I.getType());
    3026       61864 :   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
    3027       15466 : }
    3028             : 
    3029         829 : void SelectionDAGBuilder::visitFPTrunc(const User &I) {
    3030             :   // FPTrunc is never a no-op cast, no need to check
    3031         829 :   SDValue N = getValue(I.getOperand(0));
    3032         829 :   SDLoc dl = getCurSDLoc();
    3033         829 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3034        1658 :   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    3035        3316 :   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
    3036             :                            DAG.getTargetConstant(
    3037             :                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
    3038         829 : }
    3039             : 
    3040        2099 : void SelectionDAGBuilder::visitFPExt(const User &I) {
    3041             :   // FPExt is never a no-op cast, no need to check
    3042        2099 :   SDValue N = getValue(I.getOperand(0));
    3043        2099 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3044        4198 :                                                         I.getType());
    3045        8396 :   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
    3046        2099 : }
    3047             : 
    3048        1370 : void SelectionDAGBuilder::visitFPToUI(const User &I) {
    3049             :   // FPToUI is never a no-op cast, no need to check
    3050        1370 :   SDValue N = getValue(I.getOperand(0));
    3051        1370 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3052        2740 :                                                         I.getType());
    3053        5480 :   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
    3054        1370 : }
    3055             : 
    3056        1841 : void SelectionDAGBuilder::visitFPToSI(const User &I) {
    3057             :   // FPToSI is never a no-op cast, no need to check
    3058        1841 :   SDValue N = getValue(I.getOperand(0));
    3059        1841 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3060        3682 :                                                         I.getType());
    3061        7364 :   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
    3062        1841 : }
    3063             : 
    3064        1865 : void SelectionDAGBuilder::visitUIToFP(const User &I) {
    3065             :   // UIToFP is never a no-op cast, no need to check
    3066        1865 :   SDValue N = getValue(I.getOperand(0));
    3067        1865 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3068        3730 :                                                         I.getType());
    3069        7460 :   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
    3070        1865 : }
    3071             : 
    3072        2675 : void SelectionDAGBuilder::visitSIToFP(const User &I) {
    3073             :   // SIToFP is never a no-op cast, no need to check
    3074        2675 :   SDValue N = getValue(I.getOperand(0));
    3075        2675 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3076        5350 :                                                         I.getType());
    3077       10700 :   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
    3078        2675 : }
    3079             : 
    3080        3021 : void SelectionDAGBuilder::visitPtrToInt(const User &I) {
    3081             :   // What to do depends on the size of the integer and the size of the pointer.
    3082             :   // We can either truncate, zero extend, or no-op, accordingly.
    3083        3021 :   SDValue N = getValue(I.getOperand(0));
    3084        3021 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3085        6042 :                                                         I.getType());
    3086        9063 :   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
    3087        3021 : }
    3088             : 
    3089        3611 : void SelectionDAGBuilder::visitIntToPtr(const User &I) {
    3090             :   // What to do depends on the size of the integer and the size of the pointer.
    3091             :   // We can either truncate, zero extend, or no-op, accordingly.
    3092        3611 :   SDValue N = getValue(I.getOperand(0));
    3093        3611 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3094        7222 :                                                         I.getType());
    3095       10833 :   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
    3096        3611 : }
    3097             : 
    3098      259724 : void SelectionDAGBuilder::visitBitCast(const User &I) {
    3099      259724 :   SDValue N = getValue(I.getOperand(0));
    3100      259724 :   SDLoc dl = getCurSDLoc();
    3101      259724 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3102      519448 :                                                         I.getType());
    3103             : 
    3104             :   // BitCast assures us that source and destination are the same size so this is
    3105             :   // either a BITCAST or a no-op.
    3106      519573 :   if (DestVT != N.getValueType())
    3107       96132 :     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
    3108             :                              DestVT, N)); // convert types.
    3109             :   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
    3110             :   // might fold any kind of constant expression to an integer constant and that
    3111             :   // is not what we are looking for. Only recognize a bitcast of a genuine
    3112             :   // constant integer as an opaque constant.
    3113             :   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
    3114         874 :     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
    3115             :                                  /*isOpaque*/true));
    3116             :   else
    3117      227243 :     setValue(&I, N);            // noop cast.
    3118      259724 : }
    3119             : 
    3120         305 : void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
    3121         305 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3122             :   const Value *SV = I.getOperand(0);
    3123         305 :   SDValue N = getValue(SV);
    3124         610 :   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    3125             : 
    3126         305 :   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
    3127         305 :   unsigned DestAS = I.getType()->getPointerAddressSpace();
    3128             : 
    3129         305 :   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
    3130         636 :     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
    3131             : 
    3132         305 :   setValue(&I, N);
    3133         305 : }
    3134             : 
    3135       27901 : void SelectionDAGBuilder::visitInsertElement(const User &I) {
    3136       27901 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3137       27901 :   SDValue InVec = getValue(I.getOperand(0));
    3138       27901 :   SDValue InVal = getValue(I.getOperand(1));
    3139       83703 :   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
    3140      111604 :                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
    3141      139505 :   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
    3142             :                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
    3143             :                            InVec, InVal, InIdx));
    3144       27901 : }
    3145             : 
    3146       25768 : void SelectionDAGBuilder::visitExtractElement(const User &I) {
    3147       25768 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3148       25768 :   SDValue InVec = getValue(I.getOperand(0));
    3149       77304 :   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
    3150      103072 :                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
    3151      128840 :   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
    3152             :                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
    3153             :                            InVec, InIdx));
    3154       25768 : }
    3155             : 
    3156       43733 : void SelectionDAGBuilder::visitShuffleVector(const User &I) {
    3157       43733 :   SDValue Src1 = getValue(I.getOperand(0));
    3158       43733 :   SDValue Src2 = getValue(I.getOperand(1));
    3159       43733 :   SDLoc DL = getCurSDLoc();
    3160             : 
    3161             :   SmallVector<int, 8> Mask;
    3162       43733 :   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
    3163       43733 :   unsigned MaskNumElts = Mask.size();
    3164             : 
    3165       43733 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3166       87466 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    3167       87466 :   EVT SrcVT = Src1.getValueType();
    3168       43733 :   unsigned SrcNumElts = SrcVT.getVectorNumElements();
    3169             : 
    3170       43733 :   if (SrcNumElts == MaskNumElts) {
    3171       93648 :     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
    3172       31216 :     return;
    3173             :   }
    3174             : 
    3175             :   // Normalize the shuffle vector since mask and vector length don't match.
    3176       12517 :   if (SrcNumElts < MaskNumElts) {
    3177             :     // Mask is longer than the source vectors. We can use concatenate vector to
    3178             :     // make the mask and vectors lengths match.
    3179             : 
    3180        5725 :     if (MaskNumElts % SrcNumElts == 0) {
    3181             :       // Mask length is a multiple of the source vector length.
    3182             :       // Check if the shuffle is some kind of concatenation of the input
    3183             :       // vectors.
    3184        5597 :       unsigned NumConcat = MaskNumElts / SrcNumElts;
    3185             :       bool IsConcat = true;
    3186       11194 :       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
    3187      195505 :       for (unsigned i = 0; i != MaskNumElts; ++i) {
    3188      192484 :         int Idx = Mask[i];
    3189       96242 :         if (Idx < 0)
    3190        2261 :           continue;
    3191             :         // Ensure the indices in each SrcVT sized piece are sequential and that
    3192             :         // the same source is used for the whole piece.
    3193      186678 :         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
    3194      260456 :             (ConcatSrcs[i / SrcNumElts] >= 0 &&
    3195       75062 :              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
    3196             :           IsConcat = false;
    3197             :           break;
    3198             :         }
    3199             :         // Remember which source this index came from.
    3200       92693 :         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
    3201             :       }
    3202             : 
    3203             :       // The shuffle is concatenating multiple vectors together. Just emit
    3204             :       // a CONCAT_VECTORS operation.
    3205        5597 :       if (IsConcat) {
    3206             :         SmallVector<SDValue, 8> ConcatOps;
    3207       38241 :         for (auto Src : ConcatSrcs) {
    3208       16966 :           if (Src < 0)
    3209         525 :             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
    3210       16441 :           else if (Src == 0)
    3211        6047 :             ConcatOps.push_back(Src1);
    3212             :           else
    3213       10394 :             ConcatOps.push_back(Src2);
    3214             :         }
    3215       12927 :         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
    3216             :         return;
    3217             :       }
    3218             :     }
    3219             : 
    3220        2832 :     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
    3221        1416 :     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
    3222        1416 :     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
    3223        2832 :                                     PaddedMaskNumElts);
    3224             : 
    3225             :     // Pad both vectors with undefs to make them the same length as the mask.
    3226        1416 :     SDValue UndefVal = DAG.getUNDEF(SrcVT);
    3227             : 
    3228        1416 :     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
    3229             :     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
    3230        1416 :     MOps1[0] = Src1;
    3231        1416 :     MOps2[0] = Src2;
    3232             : 
    3233        2832 :     Src1 = Src1.isUndef()
    3234        4242 :                ? DAG.getUNDEF(PaddedVT)
    3235        2826 :                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
    3236        2832 :     Src2 = Src2.isUndef()
    3237        3225 :                ? DAG.getUNDEF(PaddedVT)
    3238        1809 :                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
    3239             : 
    3240             :     // Readjust mask for new input vector length.
    3241        2832 :     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
    3242       47758 :     for (unsigned i = 0; i != MaskNumElts; ++i) {
    3243       46342 :       int Idx = Mask[i];
    3244       23171 :       if (Idx >= (int)SrcNumElts)
    3245        4675 :         Idx -= SrcNumElts - PaddedMaskNumElts;
    3246       23171 :       MappedOps[i] = Idx;
    3247             :     }
    3248             : 
    3249        2832 :     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
    3250             : 
    3251             :     // If the concatenated vector was padded, extract a subvector with the
    3252             :     // correct number of elements.
    3253        1416 :     if (MaskNumElts != PaddedMaskNumElts)
    3254         256 :       Result = DAG.getNode(
    3255             :           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
    3256         512 :           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
    3257             : 
    3258        1416 :     setValue(&I, Result);
    3259             :     return;
    3260             :   }
    3261             : 
    3262        6792 :   if (SrcNumElts > MaskNumElts) {
    3263             :     // Analyze the access pattern of the vector to see if we can extract
    3264             :     // two subvectors and do the shuffle.
    3265        6792 :     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
    3266             :     bool CanExtract = true;
    3267       72074 :     for (int Idx : Mask) {
    3268             :       unsigned Input = 0;
    3269       32641 :       if (Idx < 0)
    3270          17 :         continue;
    3271             : 
    3272       32624 :       if (Idx >= (int)SrcNumElts) {
    3273             :         Input = 1;
    3274        1880 :         Idx -= SrcNumElts;
    3275             :       }
    3276             : 
    3277             :       // If all the indices come from the same MaskNumElts sized portion of
    3278             :       // the sources we can use extract. Also make sure the extract wouldn't
    3279             :       // extract past the end of the source.
    3280       65248 :       int NewStartIdx = alignDown(Idx, MaskNumElts);
    3281       65237 :       if (NewStartIdx + MaskNumElts > SrcNumElts ||
    3282       58359 :           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
    3283             :         CanExtract = false;
    3284             :       // Make sure we always update StartIdx as we use it to track if all
    3285             :       // elements are undef.
    3286       32624 :       StartIdx[Input] = NewStartIdx;
    3287             :     }
    3288             : 
    3289        6792 :     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
    3290           0 :       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
    3291        5594 :       return;
    3292             :     }
    3293        6792 :     if (CanExtract) {
    3294             :       // Extract appropriate subvector and generate a vector shuffle
    3295       27970 :       for (unsigned Input = 0; Input < 2; ++Input) {
    3296       11188 :         SDValue &Src = Input == 0 ? Src1 : Src2;
    3297       11188 :         if (StartIdx[Input] < 0)
    3298        5542 :           Src = DAG.getUNDEF(VT);
    3299             :         else {
    3300       11292 :           Src = DAG.getNode(
    3301             :               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
    3302             :               DAG.getConstant(StartIdx[Input], DL,
    3303       22584 :                               TLI.getVectorIdxTy(DAG.getDataLayout())));
    3304             :         }
    3305             :       }
    3306             : 
    3307             :       // Calculate new mask.
    3308             :       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
    3309       54780 :       for (int &Idx : MappedOps) {
    3310       24593 :         if (Idx >= (int)SrcNumElts)
    3311        1831 :           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
    3312       22762 :         else if (Idx >= 0)
    3313       22751 :           Idx -= StartIdx[0];
    3314             :       }
    3315             : 
    3316       16782 :       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
    3317             :       return;
    3318             :     }
    3319             :   }
    3320             : 
    3321             :   // We can't use either concat vectors or extract subvectors so fall back to
    3322             :   // replacing the shuffle with extract and build vector.
    3323             :   // to insert and build vector.
    3324        1198 :   EVT EltVT = VT.getVectorElementType();
    3325        2396 :   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
    3326             :   SmallVector<SDValue,8> Ops;
    3327       17294 :   for (int Idx : Mask) {
    3328        8048 :     SDValue Res;
    3329             : 
    3330        8048 :     if (Idx < 0) {
    3331           6 :       Res = DAG.getUNDEF(EltVT);
    3332             :     } else {
    3333        8042 :       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
    3334        8042 :       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
    3335             : 
    3336       16084 :       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
    3337       16084 :                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
    3338             :     }
    3339             : 
    3340        8048 :     Ops.push_back(Res);
    3341             :   }
    3342             : 
    3343        3594 :   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
    3344             : }
    3345             : 
    3346        1021 : void SelectionDAGBuilder::visitInsertValue(const User &I) {
    3347             :   ArrayRef<unsigned> Indices;
    3348             :   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
    3349             :     Indices = IV->getIndices();
    3350             :   else
    3351           0 :     Indices = cast<ConstantExpr>(&I)->getIndices();
    3352             : 
    3353             :   const Value *Op0 = I.getOperand(0);
    3354             :   const Value *Op1 = I.getOperand(1);
    3355        1021 :   Type *AggTy = I.getType();
    3356        1021 :   Type *ValTy = Op1->getType();
    3357             :   bool IntoUndef = isa<UndefValue>(Op0);
    3358             :   bool FromUndef = isa<UndefValue>(Op1);
    3359             : 
    3360             :   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
    3361             : 
    3362        1021 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3363             :   SmallVector<EVT, 4> AggValueVTs;
    3364        2042 :   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
    3365             :   SmallVector<EVT, 4> ValValueVTs;
    3366        2042 :   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
    3367             : 
    3368        1021 :   unsigned NumAggValues = AggValueVTs.size();
    3369        1021 :   unsigned NumValValues = ValValueVTs.size();
    3370        2042 :   SmallVector<SDValue, 4> Values(NumAggValues);
    3371             : 
    3372             :   // Ignore an insertvalue that produces an empty object
    3373        1021 :   if (!NumAggValues) {
    3374           3 :     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
    3375             :     return;
    3376             :   }
    3377             : 
    3378        1020 :   SDValue Agg = getValue(Op0);
    3379             :   unsigned i = 0;
    3380             :   // Copy the beginning value(s) from the original aggregate.
    3381        4170 :   for (; i != LinearIndex; ++i)
    3382        3244 :     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3383             :                 SDValue(Agg.getNode(), Agg.getResNo() + i);
    3384             :   // Copy values from the inserted value(s).
    3385        1020 :   if (NumValValues) {
    3386        1018 :     SDValue Val = getValue(Op1);
    3387        3106 :     for (; i != LinearIndex + NumValValues; ++i)
    3388        3132 :       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3389        1027 :                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
    3390             :   }
    3391             :   // Copy remaining value(s) from the original aggregate.
    3392        4212 :   for (; i != NumAggValues; ++i)
    3393        3815 :     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3394             :                 SDValue(Agg.getNode(), Agg.getResNo() + i);
    3395             : 
    3396        4080 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    3397             :                            DAG.getVTList(AggValueVTs), Values));
    3398             : }
    3399             : 
    3400       45238 : void SelectionDAGBuilder::visitExtractValue(const User &I) {
    3401             :   ArrayRef<unsigned> Indices;
    3402             :   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
    3403             :     Indices = EV->getIndices();
    3404             :   else
    3405           1 :     Indices = cast<ConstantExpr>(&I)->getIndices();
    3406             : 
    3407             :   const Value *Op0 = I.getOperand(0);
    3408       45238 :   Type *AggTy = Op0->getType();
    3409       45238 :   Type *ValTy = I.getType();
    3410             :   bool OutOfUndef = isa<UndefValue>(Op0);
    3411             : 
    3412             :   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
    3413             : 
    3414       45238 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3415             :   SmallVector<EVT, 4> ValValueVTs;
    3416       90476 :   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
    3417             : 
    3418       45238 :   unsigned NumValValues = ValValueVTs.size();
    3419             : 
    3420             :   // Ignore a extractvalue that produces an empty object
    3421       45238 :   if (!NumValValues) {
    3422          12 :     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
    3423             :     return;
    3424             :   }
    3425             : 
    3426       90468 :   SmallVector<SDValue, 4> Values(NumValValues);
    3427             : 
    3428       45234 :   SDValue Agg = getValue(Op0);
    3429             :   // Copy out the selected value(s).
    3430      135732 :   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
    3431       90498 :     Values[i - LinearIndex] =
    3432       90513 :       OutOfUndef ?
    3433          15 :         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
    3434             :         SDValue(Agg.getNode(), Agg.getResNo() + i);
    3435             : 
    3436      180936 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    3437             :                            DAG.getVTList(ValValueVTs), Values));
    3438             : }
    3439             : 
    3440      325962 : void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
    3441             :   Value *Op0 = I.getOperand(0);
    3442             :   // Note that the pointer operand may be a vector of pointers. Take the scalar
    3443             :   // element which holds a pointer.
    3444      325962 :   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
    3445      325962 :   SDValue N = getValue(Op0);
    3446      325962 :   SDLoc dl = getCurSDLoc();
    3447             : 
    3448             :   // Normalize Vector GEP - all scalar operands should be converted to the
    3449             :   // splat vector.
    3450      651924 :   unsigned VectorWidth = I.getType()->isVectorTy() ?
    3451             :     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
    3452             : 
    3453         693 :   if (VectorWidth && !N.getValueType().isVector()) {
    3454         132 :     LLVMContext &Context = *DAG.getContext();
    3455         132 :     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
    3456         132 :     N = DAG.getSplatBuildVector(VT, dl, N);
    3457             :   }
    3458             : 
    3459      913470 :   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
    3460      913470 :        GTI != E; ++GTI) {
    3461             :     const Value *Idx = GTI.getOperand();
    3462       43969 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
    3463       87938 :       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
    3464       43969 :       if (Field) {
    3465             :         // N = N + Offset
    3466       24441 :         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
    3467             : 
    3468             :         // In an inbounds GEP with an offset that is nonnegative even when
    3469             :         // interpreted as signed, assume there is no unsigned overflow.
    3470             :         SDNodeFlags Flags;
    3471       48882 :         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
    3472             :           Flags.setNoUnsignedWrap(true);
    3473             : 
    3474       48882 :         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
    3475       24441 :                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
    3476             :       }
    3477             :     } else {
    3478      543539 :       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
    3479      543539 :       MVT IdxTy = MVT::getIntegerVT(IdxSize);
    3480      543539 :       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
    3481             : 
    3482             :       // If this is a scalar constant or a splat vector of constants,
    3483             :       // handle it quickly.
    3484             :       const auto *CI = dyn_cast<ConstantInt>(Idx);
    3485       48572 :       if (!CI && isa<ConstantDataVector>(Idx) &&
    3486          20 :           cast<ConstantDataVector>(Idx)->getSplatValue())
    3487          14 :         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
    3488             : 
    3489      543539 :       if (CI) {
    3490      495001 :         if (CI->isZero())
    3491      307385 :           continue;
    3492      375232 :         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
    3493      187616 :         LLVMContext &Context = *DAG.getContext();
    3494             :         SDValue OffsVal = VectorWidth ?
    3495      187637 :           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
    3496      375232 :           DAG.getConstant(Offs, dl, IdxTy);
    3497             : 
    3498             :         // In an inbouds GEP with an offset that is nonnegative even when
    3499             :         // interpreted as signed, assume there is no unsigned overflow.
    3500             :         SDNodeFlags Flags;
    3501      372023 :         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
    3502             :           Flags.setNoUnsignedWrap(true);
    3503             : 
    3504      375232 :         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
    3505             :         continue;
    3506             :       }
    3507             : 
    3508             :       // N = N + Idx * ElementSize;
    3509       48538 :       SDValue IdxN = getValue(Idx);
    3510             : 
    3511       97076 :       if (!IdxN.getValueType().isVector() && VectorWidth) {
    3512          12 :         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
    3513          12 :         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
    3514             :       }
    3515             : 
    3516             :       // If the index is smaller or larger than intptr_t, truncate or extend
    3517             :       // it.
    3518       97076 :       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
    3519             : 
    3520             :       // If this is a multiply by a power of two, turn it into a shl
    3521             :       // immediately.  This is a very common case.
    3522       48538 :       if (ElementSize != 1) {
    3523       42718 :         if (ElementSize.isPowerOf2()) {
    3524             :           unsigned Amt = ElementSize.logBase2();
    3525       81998 :           IdxN = DAG.getNode(ISD::SHL, dl,
    3526             :                              N.getValueType(), IdxN,
    3527       81998 :                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
    3528             :         } else {
    3529        3438 :           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
    3530        3438 :           IdxN = DAG.getNode(ISD::MUL, dl,
    3531        1719 :                              N.getValueType(), IdxN, Scale);
    3532             :         }
    3533             :       }
    3534             : 
    3535       97076 :       N = DAG.getNode(ISD::ADD, dl,
    3536       48538 :                       N.getValueType(), N, IdxN);
    3537             :     }
    3538             :   }
    3539             : 
    3540      325962 :   setValue(&I, N);
    3541      325962 : }
    3542             : 
    3543       44124 : void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
    3544             :   // If this is a fixed sized alloca in the entry block of the function,
    3545             :   // allocate it statically on the stack.
    3546       44124 :   if (FuncInfo.StaticAllocaMap.count(&I))
    3547       43657 :     return;   // getValue will auto-populate this.
    3548             : 
    3549         467 :   SDLoc dl = getCurSDLoc();
    3550         467 :   Type *Ty = I.getAllocatedType();
    3551         467 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3552         467 :   auto &DL = DAG.getDataLayout();
    3553         467 :   uint64_t TySize = DL.getTypeAllocSize(Ty);
    3554             :   unsigned Align =
    3555         934 :       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
    3556             : 
    3557         467 :   SDValue AllocSize = getValue(I.getArraySize());
    3558             : 
    3559         467 :   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
    3560           0 :   if (AllocSize.getValueType() != IntPtr)
    3561         109 :     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
    3562             : 
    3563         934 :   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
    3564             :                           AllocSize,
    3565         934 :                           DAG.getConstant(TySize, dl, IntPtr));
    3566             : 
    3567             :   // Handle alignment.  If the requested alignment is less than or equal to
    3568             :   // the stack alignment, ignore it.  If the size is greater than or equal to
    3569             :   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
    3570             :   unsigned StackAlign =
    3571         934 :       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
    3572         467 :   if (Align <= StackAlign)
    3573             :     Align = 0;
    3574             : 
    3575             :   // Round the size of the allocation up to the stack alignment size
    3576             :   // by add SA-1 to the size. This doesn't overflow because we're computing
    3577             :   // an address inside an alloca.
    3578             :   SDNodeFlags Flags;
    3579             :   Flags.setNoUnsignedWrap(true);
    3580         934 :   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
    3581         467 :                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
    3582             : 
    3583             :   // Mask out the low bits for alignment purposes.
    3584         467 :   AllocSize =
    3585        1401 :       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
    3586         934 :                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
    3587             : 
    3588         467 :   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
    3589         934 :   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
    3590         934 :   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
    3591         467 :   setValue(&I, DSA);
    3592         467 :   DAG.setRoot(DSA.getValue(1));
    3593             : 
    3594             :   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
    3595             : }
    3596             : 
    3597      336611 : void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
    3598      336611 :   if (I.isAtomic())
    3599        2786 :     return visitAtomicLoad(I);
    3600             : 
    3601      335246 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3602             :   const Value *SV = I.getOperand(0);
    3603      335246 :   if (TLI.supportSwiftError()) {
    3604             :     // Swifterror values can come from either a function parameter with
    3605             :     // swifterror attribute or an alloca with swifterror attribute.
    3606             :     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
    3607       26192 :       if (Arg->hasSwiftErrorAttr())
    3608           6 :         return visitLoadFromSwiftError(I);
    3609             :     }
    3610             : 
    3611             :     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
    3612       22458 :       if (Alloca->isSwiftError())
    3613          47 :         return visitLoadFromSwiftError(I);
    3614             :     }
    3615             :   }
    3616             : 
    3617      335193 :   SDValue Ptr = getValue(SV);
    3618             : 
    3619      335193 :   Type *Ty = I.getType();
    3620             : 
    3621             :   bool isVolatile = I.isVolatile();
    3622             :   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
    3623             :   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
    3624      670386 :   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
    3625             :   unsigned Alignment = I.getAlignment();
    3626             : 
    3627             :   AAMDNodes AAInfo;
    3628      335193 :   I.getAAMetadata(AAInfo);
    3629             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    3630             : 
    3631             :   SmallVector<EVT, 4> ValueVTs;
    3632             :   SmallVector<uint64_t, 4> Offsets;
    3633      670386 :   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
    3634      335193 :   unsigned NumValues = ValueVTs.size();
    3635      335193 :   if (NumValues == 0)
    3636             :     return;
    3637             : 
    3638      335190 :   SDValue Root;
    3639             :   bool ConstantMemory = false;
    3640      335190 :   if (isVolatile || NumValues > MaxParallelChains)
    3641             :     // Serialize volatile loads with other side effects.
    3642        9723 :     Root = getRoot();
    3643      622546 :   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
    3644      295212 :                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
    3645             :     // Do not serialize (non-volatile) loads of constant memory with anything.
    3646        3734 :     Root = DAG.getEntryNode();
    3647             :     ConstantMemory = true;
    3648             :   } else {
    3649             :     // Do not serialize non-volatile loads against each other.
    3650      323600 :     Root = DAG.getRoot();
    3651             :   }
    3652             : 
    3653      335190 :   SDLoc dl = getCurSDLoc();
    3654             : 
    3655      335190 :   if (isVolatile)
    3656        9723 :     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
    3657             : 
    3658             :   // An aggregate load cannot wrap around the address space, so offsets to its
    3659             :   // parts don't wrap either.
    3660             :   SDNodeFlags Flags;
    3661             :   Flags.setNoUnsignedWrap(true);
    3662             : 
    3663      670380 :   SmallVector<SDValue, 4> Values(NumValues);
    3664     1005570 :   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
    3665      670380 :   EVT PtrVT = Ptr.getValueType();
    3666             :   unsigned ChainI = 0;
    3667     1007466 :   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
    3668             :     // Serializing loads here may result in excessive register pressure, and
    3669             :     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
    3670             :     // could recover a bit by hoisting nodes upward in the chain by recognizing
    3671             :     // they are side-effect free or do not alias. The optimizer should really
    3672             :     // avoid this case by converting large object/array copies to llvm.memcpy
    3673             :     // (MaxParallelChains should always remain as failsafe).
    3674      336138 :     if (ChainI == MaxParallelChains) {
    3675             :       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
    3676           0 :       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3677           0 :                                   makeArrayRef(Chains.data(), ChainI));
    3678           0 :       Root = Chain;
    3679             :       ChainI = 0;
    3680             :     }
    3681      336138 :     SDValue A = DAG.getNode(ISD::ADD, dl,
    3682             :                             PtrVT, Ptr,
    3683      336138 :                             DAG.getConstant(Offsets[i], dl, PtrVT),
    3684      336138 :                             Flags);
    3685             :     auto MMOFlags = MachineMemOperand::MONone;
    3686      336138 :     if (isVolatile)
    3687             :       MMOFlags |= MachineMemOperand::MOVolatile;
    3688      336138 :     if (isNonTemporal)
    3689             :       MMOFlags |= MachineMemOperand::MONonTemporal;
    3690      336138 :     if (isInvariant)
    3691             :       MMOFlags |= MachineMemOperand::MOInvariant;
    3692      336138 :     if (isDereferenceable)
    3693             :       MMOFlags |= MachineMemOperand::MODereferenceable;
    3694      336138 :     MMOFlags |= TLI.getMMOFlags(I);
    3695             : 
    3696      336138 :     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
    3697             :                             MachinePointerInfo(SV, Offsets[i]), Alignment,
    3698     1008414 :                             MMOFlags, AAInfo, Ranges);
    3699             : 
    3700      336138 :     Values[i] = L;
    3701      672276 :     Chains[ChainI] = L.getValue(1);
    3702             :   }
    3703             : 
    3704      335190 :   if (!ConstantMemory) {
    3705      333323 :     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3706      666646 :                                 makeArrayRef(Chains.data(), ChainI));
    3707      333323 :     if (isVolatile)
    3708        9723 :       DAG.setRoot(Chain);
    3709             :     else
    3710      323600 :       PendingLoads.push_back(Chain);
    3711             :   }
    3712             : 
    3713     1005570 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
    3714             :                            DAG.getVTList(ValueVTs), Values));
    3715             : }
    3716             : 
    3717         108 : void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
    3718             :   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
    3719             :          "call visitStoreToSwiftError when backend supports swifterror");
    3720             : 
    3721             :   SmallVector<EVT, 4> ValueVTs;
    3722             :   SmallVector<uint64_t, 4> Offsets;
    3723             :   const Value *SrcV = I.getOperand(0);
    3724         216 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
    3725             :                   SrcV->getType(), ValueVTs, &Offsets);
    3726             :   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
    3727             :          "expect a single EVT for swifterror");
    3728             : 
    3729         108 :   SDValue Src = getValue(SrcV);
    3730             :   // Create a virtual register, then update the virtual register.
    3731             :   unsigned VReg; bool CreatedVReg;
    3732         216 :   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
    3733             :   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
    3734             :   // Chain can be getRoot or getControlRoot.
    3735         324 :   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
    3736         324 :                                       SDValue(Src.getNode(), Src.getResNo()));
    3737         108 :   DAG.setRoot(CopyNode);
    3738         108 :   if (CreatedVReg)
    3739         138 :     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
    3740         108 : }
    3741             : 
    3742          53 : void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
    3743             :   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
    3744             :          "call visitLoadFromSwiftError when backend supports swifterror");
    3745             : 
    3746             :   assert(!I.isVolatile() &&
    3747             :          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
    3748             :          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
    3749             :          "Support volatile, non temporal, invariant for load_from_swift_error");
    3750             : 
    3751             :   const Value *SV = I.getOperand(0);
    3752          53 :   Type *Ty = I.getType();
    3753             :   AAMDNodes AAInfo;
    3754          53 :   I.getAAMetadata(AAInfo);
    3755             :   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
    3756             :              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
    3757             :          "load_from_swift_error should not be constant memory");
    3758             : 
    3759             :   SmallVector<EVT, 4> ValueVTs;
    3760             :   SmallVector<uint64_t, 4> Offsets;
    3761         106 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
    3762             :                   ValueVTs, &Offsets);
    3763             :   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
    3764             :          "expect a single EVT for swifterror");
    3765             : 
    3766             :   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
    3767          53 :   SDValue L = DAG.getCopyFromReg(
    3768         106 :       getRoot(), getCurSDLoc(),
    3769          53 :       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
    3770         106 :       ValueVTs[0]);
    3771             : 
    3772          53 :   setValue(&I, L);
    3773          53 : }
    3774             : 
    3775      319409 : void SelectionDAGBuilder::visitStore(const StoreInst &I) {
    3776      319409 :   if (I.isAtomic())
    3777        1793 :     return visitAtomicStore(I);
    3778             : 
    3779             :   const Value *SrcV = I.getOperand(0);
    3780             :   const Value *PtrV = I.getOperand(1);
    3781             : 
    3782      318577 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3783      318577 :   if (TLI.supportSwiftError()) {
    3784             :     // Swifterror values can come from either a function parameter with
    3785             :     // swifterror attribute or an alloca with swifterror attribute.
    3786             :     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
    3787        8669 :       if (Arg->hasSwiftErrorAttr())
    3788          45 :         return visitStoreToSwiftError(I);
    3789             :     }
    3790             : 
    3791             :     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
    3792       16278 :       if (Alloca->isSwiftError())
    3793          63 :         return visitStoreToSwiftError(I);
    3794             :     }
    3795             :   }
    3796             : 
    3797             :   SmallVector<EVT, 4> ValueVTs;
    3798             :   SmallVector<uint64_t, 4> Offsets;
    3799      636938 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
    3800             :                   SrcV->getType(), ValueVTs, &Offsets);
    3801      318469 :   unsigned NumValues = ValueVTs.size();
    3802      318469 :   if (NumValues == 0)
    3803             :     return;
    3804             : 
    3805             :   // Get the lowered operands. Note that we do this after
    3806             :   // checking if NumResults is zero, because with zero results
    3807             :   // the operands won't have values in the map.
    3808      318448 :   SDValue Src = getValue(SrcV);
    3809      318448 :   SDValue Ptr = getValue(PtrV);
    3810             : 
    3811      318448 :   SDValue Root = getRoot();
    3812      955344 :   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
    3813      318448 :   SDLoc dl = getCurSDLoc();
    3814      636896 :   EVT PtrVT = Ptr.getValueType();
    3815             :   unsigned Alignment = I.getAlignment();
    3816             :   AAMDNodes AAInfo;
    3817      318448 :   I.getAAMetadata(AAInfo);
    3818             : 
    3819             :   auto MMOFlags = MachineMemOperand::MONone;
    3820      318448 :   if (I.isVolatile())
    3821             :     MMOFlags |= MachineMemOperand::MOVolatile;
    3822      248298 :   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
    3823             :     MMOFlags |= MachineMemOperand::MONonTemporal;
    3824      318448 :   MMOFlags |= TLI.getMMOFlags(I);
    3825             : 
    3826             :   // An aggregate load cannot wrap around the address space, so offsets to its
    3827             :   // parts don't wrap either.
    3828             :   SDNodeFlags Flags;
    3829             :   Flags.setNoUnsignedWrap(true);
    3830             : 
    3831             :   unsigned ChainI = 0;
    3832      956382 :   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
    3833             :     // See visitLoad comments.
    3834      318967 :     if (ChainI == MaxParallelChains) {
    3835           0 :       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3836           0 :                                   makeArrayRef(Chains.data(), ChainI));
    3837           0 :       Root = Chain;
    3838             :       ChainI = 0;
    3839             :     }
    3840      318967 :     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
    3841      637934 :                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
    3842      318967 :     SDValue St = DAG.getStore(
    3843      318967 :         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
    3844     1275868 :         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
    3845      637934 :     Chains[ChainI] = St;
    3846             :   }
    3847             : 
    3848      318448 :   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3849      636896 :                                   makeArrayRef(Chains.data(), ChainI));
    3850      318448 :   DAG.setRoot(StoreNode);
    3851             : }
    3852             : 
    3853         276 : void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
    3854             :                                            bool IsCompressing) {
    3855         276 :   SDLoc sdl = getCurSDLoc();
    3856             : 
    3857             :   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3858         148 :                            unsigned& Alignment) {
    3859             :     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
    3860         296 :     Src0 = I.getArgOperand(0);
    3861         148 :     Ptr = I.getArgOperand(1);
    3862         148 :     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
    3863         148 :     Mask = I.getArgOperand(3);
    3864         424 :   };
    3865             :   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3866             :                            unsigned& Alignment) {
    3867             :     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
    3868         256 :     Src0 = I.getArgOperand(0);
    3869         128 :     Ptr = I.getArgOperand(1);
    3870         128 :     Mask = I.getArgOperand(2);
    3871         128 :     Alignment = 0;
    3872             :   };
    3873             : 
    3874             :   Value  *PtrOperand, *MaskOperand, *Src0Operand;
    3875             :   unsigned Alignment;
    3876         276 :   if (IsCompressing)
    3877             :     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3878             :   else
    3879         148 :     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3880             : 
    3881         276 :   SDValue Ptr = getValue(PtrOperand);
    3882         276 :   SDValue Src0 = getValue(Src0Operand);
    3883         276 :   SDValue Mask = getValue(MaskOperand);
    3884             : 
    3885         552 :   EVT VT = Src0.getValueType();
    3886         276 :   if (!Alignment)
    3887         128 :     Alignment = DAG.getEVTAlignment(VT);
    3888             : 
    3889             :   AAMDNodes AAInfo;
    3890         276 :   I.getAAMetadata(AAInfo);
    3891             : 
    3892             :   MachineMemOperand *MMO =
    3893         276 :     DAG.getMachineFunction().
    3894         828 :     getMachineMemOperand(MachinePointerInfo(PtrOperand),
    3895             :                           MachineMemOperand::MOStore,  VT.getStoreSize(),
    3896         276 :                           Alignment, AAInfo);
    3897         276 :   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
    3898             :                                          MMO, false /* Truncating */,
    3899         276 :                                          IsCompressing);
    3900         276 :   DAG.setRoot(StoreNode);
    3901         276 :   setValue(&I, StoreNode);
    3902         276 : }
    3903             : 
    3904             : // Get a uniform base for the Gather/Scatter intrinsic.
    3905             : // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
    3906             : // We try to represent it as a base pointer + vector of indices.
    3907             : // Usually, the vector of pointers comes from a 'getelementptr' instruction.
    3908             : // The first operand of the GEP may be a single pointer or a vector of pointers
    3909             : // Example:
    3910             : //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
    3911             : //  or
    3912             : //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
    3913             : // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
    3914             : //
    3915             : // When the first GEP operand is a single pointer - it is the uniform base we
    3916             : // are looking for. If first operand of the GEP is a splat vector - we
    3917             : // extract the splat value and use it as a uniform base.
    3918             : // In all other cases the function returns 'false'.
    3919         373 : static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
    3920             :                            SDValue &Scale, SelectionDAGBuilder* SDB) {
    3921         373 :   SelectionDAG& DAG = SDB->DAG;
    3922         373 :   LLVMContext &Context = *DAG.getContext();
    3923             : 
    3924             :   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
    3925         373 :   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
    3926             :   if (!GEP)
    3927             :     return false;
    3928             : 
    3929             :   const Value *GEPPtr = GEP->getPointerOperand();
    3930         432 :   if (!GEPPtr->getType()->isVectorTy())
    3931         132 :     Ptr = GEPPtr;
    3932          84 :   else if (!(Ptr = getSplatValue(GEPPtr)))
    3933             :     return false;
    3934             : 
    3935         210 :   unsigned FinalIndex = GEP->getNumOperands() - 1;
    3936             :   Value *IndexVal = GEP->getOperand(FinalIndex);
    3937             : 
    3938             :   // Ensure all the other indices are 0.
    3939         222 :   for (unsigned i = 1; i < FinalIndex; ++i) {
    3940             :     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
    3941           6 :     if (!C || !C->isZero())
    3942             :       return false;
    3943             :   }
    3944             : 
    3945             :   // The operands of the GEP may be defined in another basic block.
    3946             :   // In this case we'll not find nodes for the operands.
    3947         198 :   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
    3948             :     return false;
    3949             : 
    3950             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3951         182 :   const DataLayout &DL = DAG.getDataLayout();
    3952         182 :   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
    3953         546 :                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
    3954         182 :   Base = SDB->getValue(Ptr);
    3955         182 :   Index = SDB->getValue(IndexVal);
    3956             : 
    3957         546 :   if (!Index.getValueType().isVector()) {
    3958           6 :     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
    3959           6 :     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
    3960          12 :     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
    3961             :   }
    3962             :   return true;
    3963             : }
    3964             : 
    3965          85 : void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
    3966          85 :   SDLoc sdl = getCurSDLoc();
    3967             : 
    3968             :   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
    3969          85 :   const Value *Ptr = I.getArgOperand(1);
    3970          85 :   SDValue Src0 = getValue(I.getArgOperand(0));
    3971          85 :   SDValue Mask = getValue(I.getArgOperand(3));
    3972         170 :   EVT VT = Src0.getValueType();
    3973          85 :   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
    3974          85 :   if (!Alignment)
    3975           0 :     Alignment = DAG.getEVTAlignment(VT);
    3976             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3977             : 
    3978             :   AAMDNodes AAInfo;
    3979          85 :   I.getAAMetadata(AAInfo);
    3980             : 
    3981          85 :   SDValue Base;
    3982          85 :   SDValue Index;
    3983          85 :   SDValue Scale;
    3984          85 :   const Value *BasePtr = Ptr;
    3985          85 :   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
    3986             : 
    3987          85 :   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
    3988          85 :   MachineMemOperand *MMO = DAG.getMachineFunction().
    3989         170 :     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
    3990             :                          MachineMemOperand::MOStore,  VT.getStoreSize(),
    3991          85 :                          Alignment, AAInfo);
    3992          85 :   if (!UniformBase) {
    3993         112 :     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    3994          56 :     Index = getValue(Ptr);
    3995         112 :     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    3996             :   }
    3997          85 :   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
    3998          85 :   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
    3999          85 :                                          Ops, MMO);
    4000          85 :   DAG.setRoot(Scatter);
    4001          85 :   setValue(&I, Scatter);
    4002          85 : }
    4003             : 
    4004         500 : void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
    4005         500 :   SDLoc sdl = getCurSDLoc();
    4006             : 
    4007             :   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    4008         302 :                            unsigned& Alignment) {
    4009             :     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
    4010         604 :     Ptr = I.getArgOperand(0);
    4011         302 :     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
    4012         302 :     Mask = I.getArgOperand(2);
    4013         302 :     Src0 = I.getArgOperand(3);
    4014         802 :   };
    4015             :   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    4016             :                            unsigned& Alignment) {
    4017             :     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
    4018         396 :     Ptr = I.getArgOperand(0);
    4019         198 :     Alignment = 0;
    4020         198 :     Mask = I.getArgOperand(1);
    4021         198 :     Src0 = I.getArgOperand(2);
    4022             :   };
    4023             : 
    4024             :   Value  *PtrOperand, *MaskOperand, *Src0Operand;
    4025             :   unsigned Alignment;
    4026         500 :   if (IsExpanding)
    4027             :     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    4028             :   else
    4029         302 :     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    4030             : 
    4031         500 :   SDValue Ptr = getValue(PtrOperand);
    4032         500 :   SDValue Src0 = getValue(Src0Operand);
    4033         500 :   SDValue Mask = getValue(MaskOperand);
    4034             : 
    4035        1000 :   EVT VT = Src0.getValueType();
    4036         500 :   if (!Alignment)
    4037         198 :     Alignment = DAG.getEVTAlignment(VT);
    4038             : 
    4039             :   AAMDNodes AAInfo;
    4040         500 :   I.getAAMetadata(AAInfo);
    4041             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    4042             : 
    4043             :   // Do not serialize masked loads of constant memory with anything.
    4044        2001 :   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
    4045         500 :       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
    4046         501 :   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
    4047             : 
    4048             :   MachineMemOperand *MMO =
    4049         500 :     DAG.getMachineFunction().
    4050        1500 :     getMachineMemOperand(MachinePointerInfo(PtrOperand),
    4051             :                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
    4052         500 :                           Alignment, AAInfo, Ranges);
    4053             : 
    4054         500 :   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
    4055         500 :                                    ISD::NON_EXTLOAD, IsExpanding);
    4056         500 :   if (AddToChain) {
    4057         499 :     SDValue OutChain = Load.getValue(1);
    4058         499 :     DAG.setRoot(OutChain);
    4059             :   }
    4060         500 :   setValue(&I, Load);
    4061         500 : }
    4062             : 
    4063         288 : void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
    4064         288 :   SDLoc sdl = getCurSDLoc();
    4065             : 
    4066             :   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
    4067         288 :   const Value *Ptr = I.getArgOperand(0);
    4068         288 :   SDValue Src0 = getValue(I.getArgOperand(3));
    4069         288 :   SDValue Mask = getValue(I.getArgOperand(2));
    4070             : 
    4071         288 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4072         576 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    4073         288 :   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
    4074         288 :   if (!Alignment)
    4075          36 :     Alignment = DAG.getEVTAlignment(VT);
    4076             : 
    4077             :   AAMDNodes AAInfo;
    4078         288 :   I.getAAMetadata(AAInfo);
    4079             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    4080             : 
    4081         288 :   SDValue Root = DAG.getRoot();
    4082         288 :   SDValue Base;
    4083         288 :   SDValue Index;
    4084         288 :   SDValue Scale;
    4085         288 :   const Value *BasePtr = Ptr;
    4086         288 :   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
    4087             :   bool ConstantMemory = false;
    4088         153 :   if (UniformBase &&
    4089         991 :       AA && AA->pointsToConstantMemory(MemoryLocation(
    4090         140 :           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
    4091             :           AAInfo))) {
    4092             :     // Do not serialize (non-volatile) loads of constant memory with anything.
    4093           5 :     Root = DAG.getEntryNode();
    4094             :     ConstantMemory = true;
    4095             :   }
    4096             : 
    4097             :   MachineMemOperand *MMO =
    4098         288 :     DAG.getMachineFunction().
    4099         576 :     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
    4100             :                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
    4101         288 :                          Alignment, AAInfo, Ranges);
    4102             : 
    4103         288 :   if (!UniformBase) {
    4104         270 :     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    4105         135 :     Index = getValue(Ptr);
    4106         270 :     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    4107             :   }
    4108         288 :   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
    4109         288 :   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
    4110         288 :                                        Ops, MMO);
    4111             : 
    4112         288 :   SDValue OutChain = Gather.getValue(1);
    4113         288 :   if (!ConstantMemory)
    4114         283 :     PendingLoads.push_back(OutChain);
    4115         288 :   setValue(&I, Gather);
    4116         288 : }
    4117             : 
    4118        1181 : void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
    4119        1181 :   SDLoc dl = getCurSDLoc();
    4120             :   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
    4121             :   AtomicOrdering FailureOrder = I.getFailureOrdering();
    4122        1181 :   SyncScope::ID SSID = I.getSyncScopeID();
    4123             : 
    4124        1181 :   SDValue InChain = getRoot();
    4125             : 
    4126        2362 :   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
    4127        2362 :   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
    4128        1181 :   SDValue L = DAG.getAtomicCmpSwap(
    4129             :       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
    4130             :       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
    4131             :       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
    4132        5905 :       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
    4133             : 
    4134        1181 :   SDValue OutChain = L.getValue(2);
    4135             : 
    4136        1181 :   setValue(&I, L);
    4137        1181 :   DAG.setRoot(OutChain);
    4138        1181 : }
    4139             : 
    4140        4789 : void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
    4141        4789 :   SDLoc dl = getCurSDLoc();
    4142             :   ISD::NodeType NT;
    4143        4789 :   switch (I.getOperation()) {
    4144           0 :   default: llvm_unreachable("Unknown atomicrmw operation");
    4145             :   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
    4146         722 :   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
    4147         684 :   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
    4148         460 :   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
    4149         124 :   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
    4150         429 :   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
    4151         414 :   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
    4152         346 :   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
    4153         359 :   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
    4154         350 :   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
    4155         350 :   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
    4156             :   }
    4157             :   AtomicOrdering Order = I.getOrdering();
    4158        4789 :   SyncScope::ID SSID = I.getSyncScopeID();
    4159             : 
    4160        4789 :   SDValue InChain = getRoot();
    4161             : 
    4162             :   SDValue L =
    4163        4789 :     DAG.getAtomic(NT, dl,
    4164        9578 :                   getValue(I.getValOperand()).getSimpleValueType(),
    4165             :                   InChain,
    4166             :                   getValue(I.getPointerOperand()),
    4167             :                   getValue(I.getValOperand()),
    4168             :                   I.getPointerOperand(),
    4169       19156 :                   /* Alignment=*/ 0, Order, SSID);
    4170             : 
    4171        4789 :   SDValue OutChain = L.getValue(1);
    4172             : 
    4173        4789 :   setValue(&I, L);
    4174        4789 :   DAG.setRoot(OutChain);
    4175        4789 : }
    4176             : 
    4177         334 : void SelectionDAGBuilder::visitFence(const FenceInst &I) {
    4178         334 :   SDLoc dl = getCurSDLoc();
    4179         334 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4180         334 :   SDValue Ops[3];
    4181         334 :   Ops[0] = getRoot();
    4182         668 :   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
    4183        1336 :                            TLI.getFenceOperandTy(DAG.getDataLayout()));
    4184        1002 :   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
    4185        1336 :                            TLI.getFenceOperandTy(DAG.getDataLayout()));
    4186         668 :   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
    4187         334 : }
    4188             : 
    4189        1365 : void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
    4190        1365 :   SDLoc dl = getCurSDLoc();
    4191             :   AtomicOrdering Order = I.getOrdering();
    4192        1365 :   SyncScope::ID SSID = I.getSyncScopeID();
    4193             : 
    4194        1365 :   SDValue InChain = getRoot();
    4195             : 
    4196        1365 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4197        2730 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    4198             : 
    4199        2724 :   if (!TLI.supportsUnalignedAtomics() &&
    4200             :       I.getAlignment() < VT.getStoreSize())
    4201           0 :     report_fatal_error("Cannot generate unaligned atomic load");
    4202             : 
    4203             :   MachineMemOperand *MMO =
    4204        1365 :       DAG.getMachineFunction().
    4205        5460 :       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
    4206             :                            MachineMemOperand::MOVolatile |
    4207             :                            MachineMemOperand::MOLoad,
    4208             :                            VT.getStoreSize(),
    4209             :                            I.getAlignment() ? I.getAlignment() :
    4210             :                                               DAG.getEVTAlignment(VT),
    4211        2730 :                            AAMDNodes(), nullptr, SSID, Order);
    4212             : 
    4213        1365 :   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
    4214             :   SDValue L =
    4215        1365 :       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
    4216        1365 :                     getValue(I.getPointerOperand()), MMO);
    4217             : 
    4218        1365 :   SDValue OutChain = L.getValue(1);
    4219             : 
    4220        1365 :   setValue(&I, L);
    4221        1365 :   DAG.setRoot(OutChain);
    4222        1365 : }
    4223             : 
    4224         832 : void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
    4225         832 :   SDLoc dl = getCurSDLoc();
    4226             : 
    4227             :   AtomicOrdering Order = I.getOrdering();
    4228         832 :   SyncScope::ID SSID = I.getSyncScopeID();
    4229             : 
    4230         832 :   SDValue InChain = getRoot();
    4231             : 
    4232         832 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4233             :   EVT VT =
    4234        2496 :       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
    4235             : 
    4236         832 :   if (I.getAlignment() < VT.getStoreSize())
    4237           0 :     report_fatal_error("Cannot generate unaligned atomic store");
    4238             : 
    4239             :   SDValue OutChain =
    4240         832 :     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
    4241             :                   InChain,
    4242             :                   getValue(I.getPointerOperand()),
    4243             :                   getValue(I.getValueOperand()),
    4244             :                   I.getPointerOperand(), I.getAlignment(),
    4245        2496 :                   Order, SSID);
    4246             : 
    4247         832 :   DAG.setRoot(OutChain);
    4248         832 : }
    4249             : 
    4250             : /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
    4251             : /// node.
    4252       48546 : void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
    4253             :                                                unsigned Intrinsic) {
    4254             :   // Ignore the callsite's attributes. A specific call site may be marked with
    4255             :   // readnone, but the lowering code will expect the chain based on the
    4256             :   // definition.
    4257             :   const Function *F = I.getCalledFunction();
    4258       48546 :   bool HasChain = !F->doesNotAccessMemory();
    4259       48546 :   bool OnlyLoad = HasChain && F->onlyReadsMemory();
    4260             : 
    4261             :   // Build the operand list.
    4262             :   SmallVector<SDValue, 8> Ops;
    4263       48546 :   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
    4264        9898 :     if (OnlyLoad) {
    4265             :       // We don't need to serialize loads against other loads.
    4266        4500 :       Ops.push_back(DAG.getRoot());
    4267             :     } else {
    4268        7648 :       Ops.push_back(getRoot());
    4269             :     }
    4270             :   }
    4271             : 
    4272             :   // Info is set by getTgtMemInstrinsic
    4273       48546 :   TargetLowering::IntrinsicInfo Info;
    4274       48546 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4275       97092 :   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
    4276             :                                                DAG.getMachineFunction(),
    4277       97092 :                                                Intrinsic);
    4278             : 
    4279             :   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
    4280       48546 :   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
    4281             :       Info.opc == ISD::INTRINSIC_W_CHAIN)
    4282      194144 :     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
    4283       97072 :                                         TLI.getPointerTy(DAG.getDataLayout())));
    4284             : 
    4285             :   // Add all operands of the call to the operand list.
    4286      319506 :   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
    4287      111207 :     SDValue Op = getValue(I.getArgOperand(i));
    4288      111207 :     Ops.push_back(Op);
    4289             :   }
    4290             : 
    4291             :   SmallVector<EVT, 4> ValueVTs;
    4292       97092 :   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
    4293             : 
    4294       48546 :   if (HasChain)
    4295        9898 :     ValueVTs.push_back(MVT::Other);
    4296             : 
    4297       97092 :   SDVTList VTs = DAG.getVTList(ValueVTs);
    4298             : 
    4299             :   // Create the node.
    4300             :   SDValue Result;
    4301       48546 :   if (IsTgtIntrinsic) {
    4302             :     // This is target intrinsic that touches memory
    4303       16340 :     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
    4304             :       Ops, Info.memVT,
    4305        4085 :       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
    4306       16340 :       Info.flags, Info.size);
    4307       44461 :   } else if (!HasChain) {
    4308      154592 :     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
    4309       11626 :   } else if (!I.getType()->isVoidTy()) {
    4310        8104 :     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
    4311             :   } else {
    4312       15148 :     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
    4313             :   }
    4314             : 
    4315       48546 :   if (HasChain) {
    4316       19796 :     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
    4317        9898 :     if (OnlyLoad)
    4318        2250 :       PendingLoads.push_back(Chain);
    4319             :     else
    4320        7648 :       DAG.setRoot(Chain);
    4321             :   }
    4322             : 
    4323       97092 :   if (!I.getType()->isVoidTy()) {
    4324             :     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
    4325       51370 :       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
    4326      102740 :       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
    4327             :     } else
    4328       17980 :       Result = lowerRangeToAssertZExt(DAG, I, Result);
    4329             : 
    4330       43665 :     setValue(&I, Result);
    4331             :   }
    4332       48546 : }
    4333             : 
    4334             : /// GetSignificand - Get the significand and build it into a floating-point
    4335             : /// number with exponent of 1:
    4336             : ///
    4337             : ///   Op = (Op & 0x007fffff) | 0x3f800000;
    4338             : ///
    4339             : /// where Op is the hexadecimal representation of floating point value.
    4340           9 : static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
    4341             :   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
    4342          18 :                            DAG.getConstant(0x007fffff, dl, MVT::i32));
    4343             :   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
    4344          18 :                            DAG.getConstant(0x3f800000, dl, MVT::i32));
    4345           9 :   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
    4346             : }
    4347             : 
    4348             : /// GetExponent - Get the exponent:
    4349             : ///
    4350             : ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
    4351             : ///
    4352             : /// where Op is the hexadecimal representation of floating point value.
    4353           9 : static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
    4354             :                            const TargetLowering &TLI, const SDLoc &dl) {
    4355             :   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
    4356          18 :                            DAG.getConstant(0x7f800000, dl, MVT::i32));
    4357             :   SDValue t1 = DAG.getNode(
    4358             :       ISD::SRL, dl, MVT::i32, t0,
    4359          27 :       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
    4360             :   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
    4361          18 :                            DAG.getConstant(127, dl, MVT::i32));
    4362           9 :   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
    4363             : }
    4364             : 
    4365             : /// getF32Constant - Get 32-bit floating point constant.
    4366          97 : static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
    4367             :                               const SDLoc &dl) {
    4368         388 :   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
    4369         194 :                            MVT::f32);
    4370             : }
    4371             : 
    4372           9 : static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
    4373             :                                        SelectionDAG &DAG) {
    4374             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4375             : 
    4376             :   //   IntegerPartOfX = ((int32_t)(t0);
    4377           9 :   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
    4378             : 
    4379             :   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
    4380           9 :   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
    4381           9 :   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
    4382             : 
    4383             :   //   IntegerPartOfX <<= 23;
    4384           9 :   IntegerPartOfX = DAG.getNode(
    4385             :       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
    4386             :       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
    4387          27 :                                   DAG.getDataLayout())));
    4388             : 
    4389           9 :   SDValue TwoToFractionalPartOfX;
    4390           9 :   if (LimitFloatPrecision <= 6) {
    4391             :     // For floating-point precision of 6:
    4392             :     //
    4393             :     //   TwoToFractionalPartOfX =
    4394             :     //     0.997535578f +
    4395             :     //       (0.735607626f + 0.252464424f * x) * x;
    4396             :     //
    4397             :     // error 0.0144103317, which is 6 bits
    4398             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4399           6 :                              getF32Constant(DAG, 0x3e814304, dl));
    4400             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4401           6 :                              getF32Constant(DAG, 0x3f3c50c8, dl));
    4402           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4403           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4404           6 :                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
    4405           6 :   } else if (LimitFloatPrecision <= 12) {
    4406             :     // For floating-point precision of 12:
    4407             :     //
    4408             :     //   TwoToFractionalPartOfX =
    4409             :     //     0.999892986f +
    4410             :     //       (0.696457318f +
    4411             :     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
    4412             :     //
    4413             :     // error 0.000107046256, which is 13 to 14 bits
    4414             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4415           6 :                              getF32Constant(DAG, 0x3da235e3, dl));
    4416             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4417           6 :                              getF32Constant(DAG, 0x3e65b8f3, dl));
    4418           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4419             :     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4420           6 :                              getF32Constant(DAG, 0x3f324b07, dl));
    4421           3 :     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4422           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4423           6 :                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
    4424             :   } else { // LimitFloatPrecision <= 18
    4425             :     // For floating-point precision of 18:
    4426             :     //
    4427             :     //   TwoToFractionalPartOfX =
    4428             :     //     0.999999982f +
    4429             :     //       (0.693148872f +
    4430             :     //         (0.240227044f +
    4431             :     //           (0.554906021e-1f +
    4432             :     //             (0.961591928e-2f +
    4433             :     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
    4434             :     // error 2.47208000*10^(-7), which is better than 18 bits
    4435             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4436           6 :                              getF32Constant(DAG, 0x3924b03e, dl));
    4437             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4438           6 :                              getF32Constant(DAG, 0x3ab24b87, dl));
    4439           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4440             :     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4441           6 :                              getF32Constant(DAG, 0x3c1d8c17, dl));
    4442           3 :     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4443             :     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4444           6 :                              getF32Constant(DAG, 0x3d634a1d, dl));
    4445           3 :     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4446             :     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4447           6 :                              getF32Constant(DAG, 0x3e75fe14, dl));
    4448           3 :     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4449             :     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
    4450           6 :                               getF32Constant(DAG, 0x3f317234, dl));
    4451           3 :     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
    4452           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
    4453           6 :                                          getF32Constant(DAG, 0x3f800000, dl));
    4454             :   }
    4455             : 
    4456             :   // Add the exponent into the result in integer domain.
    4457           9 :   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
    4458             :   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
    4459          18 :                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
    4460             : }
    4461             : 
    4462             : /// expandExp - Lower an exp intrinsic. Handles the special sequences for
    4463             : /// limited-precision mode.
    4464          71 : static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4465             :                          const TargetLowering &TLI) {
    4466          24 :   if (Op.getValueType() == MVT::f32 &&
    4467          27 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4468             : 
    4469             :     // Put the exponent in the right bit position for later addition to the
    4470             :     // final result:
    4471             :     //
    4472             :     //   #define LOG2OFe 1.4426950f
    4473             :     //   t0 = Op * LOG2OFe
    4474             : 
    4475             :     // TODO: What fast-math-flags should be set here?
    4476             :     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
    4477           6 :                              getF32Constant(DAG, 0x3fb8aa3b, dl));
    4478           3 :     return getLimitedPrecisionExp2(t0, dl, DAG);
    4479             :   }
    4480             : 
    4481             :   // No special expansion.
    4482          68 :   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
    4483             : }
    4484             : 
    4485             : /// expandLog - Lower a log intrinsic. Handles the special sequences for
    4486             : /// limited-precision mode.
    4487          75 : static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4488             :                          const TargetLowering &TLI) {
    4489             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4490             : 
    4491          22 :   if (Op.getValueType() == MVT::f32 &&
    4492          25 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4493           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4494             : 
    4495             :     // Scale the exponent by log(2) [0.69314718f].
    4496           3 :     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
    4497             :     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
    4498           6 :                                         getF32Constant(DAG, 0x3f317218, dl));
    4499             : 
    4500             :     // Get the significand and build it into a floating-point number with
    4501             :     // exponent of 1.
    4502           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4503             : 
    4504           3 :     SDValue LogOfMantissa;
    4505           3 :     if (LimitFloatPrecision <= 6) {
    4506             :       // For floating-point precision of 6:
    4507             :       //
    4508             :       //   LogofMantissa =
    4509             :       //     -1.1609546f +
    4510             :       //       (1.4034025f - 0.23903021f * x) * x;
    4511             :       //
    4512             :       // error 0.0034276066, which is better than 8 bits
    4513             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4514           2 :                                getF32Constant(DAG, 0xbe74c456, dl));
    4515             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4516           2 :                                getF32Constant(DAG, 0x3fb3a2b1, dl));
    4517           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4518           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4519           2 :                                   getF32Constant(DAG, 0x3f949a29, dl));
    4520           2 :     } else if (LimitFloatPrecision <= 12) {
    4521             :       // For floating-point precision of 12:
    4522             :       //
    4523             :       //   LogOfMantissa =
    4524             :       //     -1.7417939f +
    4525             :       //       (2.8212026f +
    4526             :       //         (-1.4699568f +
    4527             :       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
    4528             :       //
    4529             :       // error 0.000061011436, which is 14 bits
    4530             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4531           2 :                                getF32Constant(DAG, 0xbd67b6d6, dl));
    4532             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4533           2 :                                getF32Constant(DAG, 0x3ee4f4b8, dl));
    4534           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4535             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4536           2 :                                getF32Constant(DAG, 0x3fbc278b, dl));
    4537           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4538             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4539           2 :                                getF32Constant(DAG, 0x40348e95, dl));
    4540           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4541           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4542           2 :                                   getF32Constant(DAG, 0x3fdef31a, dl));
    4543             :     } else { // LimitFloatPrecision <= 18
    4544             :       // For floating-point precision of 18:
    4545             :       //
    4546             :       //   LogOfMantissa =
    4547             :       //     -2.1072184f +
    4548             :       //       (4.2372794f +
    4549             :       //         (-3.7029485f +
    4550             :       //           (2.2781945f +
    4551             :       //             (-0.87823314f +
    4552             :       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
    4553             :       //
    4554             :       // error 0.0000023660568, which is better than 18 bits
    4555             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4556           2 :                                getF32Constant(DAG, 0xbc91e5ac, dl));
    4557             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4558           2 :                                getF32Constant(DAG, 0x3e4350aa, dl));
    4559           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4560             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4561           2 :                                getF32Constant(DAG, 0x3f60d3e3, dl));
    4562           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4563             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4564           2 :                                getF32Constant(DAG, 0x4011cdf0, dl));
    4565           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4566             :       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4567           2 :                                getF32Constant(DAG, 0x406cfd1c, dl));
    4568           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4569             :       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4570           2 :                                getF32Constant(DAG, 0x408797cb, dl));
    4571           1 :       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4572           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
    4573           2 :                                   getF32Constant(DAG, 0x4006dcab, dl));
    4574             :     }
    4575             : 
    4576           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
    4577             :   }
    4578             : 
    4579             :   // No special expansion.
    4580          72 :   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
    4581             : }
    4582             : 
    4583             : /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
    4584             : /// limited-precision mode.
    4585          81 : static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4586             :                           const TargetLowering &TLI) {
    4587             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4588             : 
    4589          27 :   if (Op.getValueType() == MVT::f32 &&
    4590          30 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4591           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4592             : 
    4593             :     // Get the exponent.
    4594           3 :     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
    4595             : 
    4596             :     // Get the significand and build it into a floating-point number with
    4597             :     // exponent of 1.
    4598           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4599             : 
    4600             :     // Different possible minimax approximations of significand in
    4601             :     // floating-point for various degrees of accuracy over [1,2].
    4602           3 :     SDValue Log2ofMantissa;
    4603           3 :     if (LimitFloatPrecision <= 6) {
    4604             :       // For floating-point precision of 6:
    4605             :       //
    4606             :       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
    4607             :       //
    4608             :       // error 0.0049451742, which is more than 7 bits
    4609             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4610           2 :                                getF32Constant(DAG, 0xbeb08fe0, dl));
    4611             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4612           2 :                                getF32Constant(DAG, 0x40019463, dl));
    4613           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4614           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4615           2 :                                    getF32Constant(DAG, 0x3fd6633d, dl));
    4616           2 :     } else if (LimitFloatPrecision <= 12) {
    4617             :       // For floating-point precision of 12:
    4618             :       //
    4619             :       //   Log2ofMantissa =
    4620             :       //     -2.51285454f +
    4621             :       //       (4.07009056f +
    4622             :       //         (-2.12067489f +
    4623             :       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
    4624             :       //
    4625             :       // error 0.0000876136000, which is better than 13 bits
    4626             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4627           2 :                                getF32Constant(DAG, 0xbda7262e, dl));
    4628             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4629           2 :                                getF32Constant(DAG, 0x3f25280b, dl));
    4630           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4631             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4632           2 :                                getF32Constant(DAG, 0x4007b923, dl));
    4633           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4634             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4635           2 :                                getF32Constant(DAG, 0x40823e2f, dl));
    4636           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4637           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4638           2 :                                    getF32Constant(DAG, 0x4020d29c, dl));
    4639             :     } else { // LimitFloatPrecision <= 18
    4640             :       // For floating-point precision of 18:
    4641             :       //
    4642             :       //   Log2ofMantissa =
    4643             :       //     -3.0400495f +
    4644             :       //       (6.1129976f +
    4645             :       //         (-5.3420409f +
    4646             :       //           (3.2865683f +
    4647             :       //             (-1.2669343f +
    4648             :       //               (0.27515199f -
    4649             :       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
    4650             :       //
    4651             :       // error 0.0000018516, which is better than 18 bits
    4652             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4653           2 :                                getF32Constant(DAG, 0xbcd2769e, dl));
    4654             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4655           2 :                                getF32Constant(DAG, 0x3e8ce0b9, dl));
    4656           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4657             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4658           2 :                                getF32Constant(DAG, 0x3fa22ae7, dl));
    4659           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4660             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4661           2 :                                getF32Constant(DAG, 0x40525723, dl));
    4662           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4663             :       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4664           2 :                                getF32Constant(DAG, 0x40aaf200, dl));
    4665           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4666             :       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4667           2 :                                getF32Constant(DAG, 0x40c39dad, dl));
    4668           1 :       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4669           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
    4670           2 :                                    getF32Constant(DAG, 0x4042902c, dl));
    4671             :     }
    4672             : 
    4673           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
    4674             :   }
    4675             : 
    4676             :   // No special expansion.
    4677          78 :   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
    4678             : }
    4679             : 
    4680             : /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
    4681             : /// limited-precision mode.
    4682          81 : static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4683             :                            const TargetLowering &TLI) {
    4684             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4685             : 
    4686          28 :   if (Op.getValueType() == MVT::f32 &&
    4687          31 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4688           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4689             : 
    4690             :     // Scale the exponent by log10(2) [0.30102999f].
    4691           3 :     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
    4692             :     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
    4693           6 :                                         getF32Constant(DAG, 0x3e9a209a, dl));
    4694             : 
    4695             :     // Get the significand and build it into a floating-point number with
    4696             :     // exponent of 1.
    4697           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4698             : 
    4699           3 :     SDValue Log10ofMantissa;
    4700           3 :     if (LimitFloatPrecision <= 6) {
    4701             :       // For floating-point precision of 6:
    4702             :       //
    4703             :       //   Log10ofMantissa =
    4704             :       //     -0.50419619f +
    4705             :       //       (0.60948995f - 0.10380950f * x) * x;
    4706             :       //
    4707             :       // error 0.0014886165, which is 6 bits
    4708             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4709           2 :                                getF32Constant(DAG, 0xbdd49a13, dl));
    4710             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4711           2 :                                getF32Constant(DAG, 0x3f1c0789, dl));
    4712           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4713           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4714           2 :                                     getF32Constant(DAG, 0x3f011300, dl));
    4715           2 :     } else if (LimitFloatPrecision <= 12) {
    4716             :       // For floating-point precision of 12:
    4717             :       //
    4718             :       //   Log10ofMantissa =
    4719             :       //     -0.64831180f +
    4720             :       //       (0.91751397f +
    4721             :       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
    4722             :       //
    4723             :       // error 0.00019228036, which is better than 12 bits
    4724             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4725           2 :                                getF32Constant(DAG, 0x3d431f31, dl));
    4726             :       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
    4727           2 :                                getF32Constant(DAG, 0x3ea21fb2, dl));
    4728           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4729             :       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4730           2 :                                getF32Constant(DAG, 0x3f6ae232, dl));
    4731           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4732           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
    4733           2 :                                     getF32Constant(DAG, 0x3f25f7c3, dl));
    4734             :     } else { // LimitFloatPrecision <= 18
    4735             :       // For floating-point precision of 18:
    4736             :       //
    4737             :       //   Log10ofMantissa =
    4738             :       //     -0.84299375f +
    4739             :       //       (1.5327582f +
    4740             :       //         (-1.0688956f +
    4741             :       //           (0.49102474f +
    4742             :       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
    4743             :       //
    4744             :       // error 0.0000037995730, which is better than 18 bits
    4745             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4746           2 :                                getF32Constant(DAG, 0x3c5d51ce, dl));
    4747             :       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
    4748           2 :                                getF32Constant(DAG, 0x3e00685a, dl));
    4749           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4750             :       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4751           2 :                                getF32Constant(DAG, 0x3efb6798, dl));
    4752           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4753             :       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
    4754           2 :                                getF32Constant(DAG, 0x3f88d192, dl));
    4755           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4756             :       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4757           2 :                                getF32Constant(DAG, 0x3fc4316c, dl));
    4758           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4759           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
    4760           2 :                                     getF32Constant(DAG, 0x3f57ce70, dl));
    4761             :     }
    4762             : 
    4763           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
    4764             :   }
    4765             : 
    4766             :   // No special expansion.
    4767          78 :   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
    4768             : }
    4769             : 
    4770             : /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
    4771             : /// limited-precision mode.
    4772          95 : static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4773             :                           const TargetLowering &TLI) {
    4774          37 :   if (Op.getValueType() == MVT::f32 &&
    4775          40 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
    4776           3 :     return getLimitedPrecisionExp2(Op, dl, DAG);
    4777             : 
    4778             :   // No special expansion.
    4779          92 :   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
    4780             : }
    4781             : 
    4782             : /// visitPow - Lower a pow intrinsic. Handles the special sequences for
    4783             : /// limited-precision mode with x == 10.0f.
    4784          91 : static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
    4785             :                          SelectionDAG &DAG, const TargetLowering &TLI) {
    4786             :   bool IsExp10 = false;
    4787          68 :   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
    4788          37 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4789             :     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
    4790           3 :       APFloat Ten(10.0f);
    4791           3 :       IsExp10 = LHSC->isExactlyValue(Ten);
    4792             :     }
    4793             :   }
    4794             : 
    4795             :   // TODO: What fast-math-flags should be set on the FMUL node?
    4796           3 :   if (IsExp10) {
    4797             :     // Put the exponent in the right bit position for later addition to the
    4798             :     // final result:
    4799             :     //
    4800             :     //   #define LOG2OF10 3.3219281f
    4801             :     //   t0 = Op * LOG2OF10;
    4802             :     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
    4803           6 :                              getF32Constant(DAG, 0x40549a78, dl));
    4804           3 :     return getLimitedPrecisionExp2(t0, dl, DAG);
    4805             :   }
    4806             : 
    4807             :   // No special expansion.
    4808          88 :   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
    4809             : }
    4810             : 
    4811             : /// ExpandPowI - Expand a llvm.powi intrinsic.
    4812         104 : static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
    4813             :                           SelectionDAG &DAG) {
    4814             :   // If RHS is a constant, we can expand this out to a multiplication tree,
    4815             :   // otherwise we end up lowering to a call to __powidf2 (for example).  When
    4816             :   // optimizing for size, we only want to do this if the expansion would produce
    4817             :   // a small number of multiplies, otherwise we do the full expansion.
    4818             :   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
    4819             :     // Get the exponent as a positive value.
    4820          24 :     unsigned Val = RHSC->getSExtValue();
    4821          12 :     if ((int)Val < 0) Val = -Val;
    4822             : 
    4823             :     // powi(x, 0) -> 1.0
    4824          12 :     if (Val == 0)
    4825           0 :       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
    4826             : 
    4827          12 :     const Function &F = DAG.getMachineFunction().getFunction();
    4828          14 :     if (!F.optForSize() ||
    4829             :         // If optimizing for size, don't insert too many multiplies.
    4830             :         // This inserts up to 5 multiplies.
    4831           2 :         countPopulation(Val) + Log2_32(Val) < 7) {
    4832             :       // We use the simple binary decomposition method to generate the multiply
    4833             :       // sequence.  There are more optimal ways to do this (for example,
    4834             :       // powi(x,15) generates one more multiply than it should), but this has
    4835             :       // the benefit of being both really simple and much better than a libcall.
    4836             :       SDValue Res;  // Logically starts equal to 1.0
    4837          10 :       SDValue CurSquare = LHS;
    4838             :       // TODO: Intrinsics should have fast-math-flags that propagate to these
    4839             :       // nodes.
    4840          64 :       while (Val) {
    4841          27 :         if (Val & 1) {
    4842          14 :           if (Res.getNode())
    4843           4 :             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
    4844             :           else
    4845             :             Res = CurSquare;  // 1.0*CurSquare.
    4846             :         }
    4847             : 
    4848          27 :         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
    4849          27 :                                 CurSquare, CurSquare);
    4850          27 :         Val >>= 1;
    4851             :       }
    4852             : 
    4853             :       // If the original was negative, invert the result, producing 1/(x*x*x).
    4854          20 :       if (RHSC->getSExtValue() < 0)
    4855           1 :         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
    4856           2 :                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
    4857          10 :       return Res;
    4858             :     }
    4859             :   }
    4860             : 
    4861             :   // Otherwise, expand to a libcall.
    4862          94 :   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
    4863             : }
    4864             : 
    4865             : // getUnderlyingArgReg - Find underlying register used for a truncated or
    4866             : // bitcasted argument.
    4867             : static unsigned getUnderlyingArgReg(const SDValue &N) {
    4868        9350 :   switch (N.getOpcode()) {
    4869        4496 :   case ISD::CopyFromReg:
    4870        4496 :     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
    4871         132 :   case ISD::BITCAST:
    4872             :   case ISD::AssertZext:
    4873             :   case ISD::AssertSext:
    4874             :   case ISD::TRUNCATE:
    4875             :     return getUnderlyingArgReg(N.getOperand(0));
    4876             :   default:
    4877             :     return 0;
    4878             :   }
    4879             : }
    4880             : 
    4881             : /// If the DbgValueInst is a dbg_value of a function argument, create the
    4882             : /// corresponding DBG_VALUE machine instruction for it now.  At the end of
    4883             : /// instruction selection, they will be inserted to the entry BB.
    4884       23588 : bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
    4885             :     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
    4886             :     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
    4887             :   const Argument *Arg = dyn_cast<Argument>(V);
    4888             :   if (!Arg)
    4889             :     return false;
    4890             : 
    4891        4643 :   MachineFunction &MF = DAG.getMachineFunction();
    4892        4643 :   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
    4893             : 
    4894             :   bool IsIndirect = false;
    4895             :   Optional<MachineOperand> Op;
    4896             :   // Some arguments' frame index is recorded during argument lowering.
    4897        4643 :   int FI = FuncInfo.getArgumentFrameIndex(Arg);
    4898        4643 :   if (FI != std::numeric_limits<int>::max())
    4899             :     Op = MachineOperand::CreateFI(FI);
    4900             : 
    4901        4643 :   if (!Op && N.getNode()) {
    4902             :     unsigned Reg = getUnderlyingArgReg(N);
    4903        9039 :     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
    4904        4496 :       MachineRegisterInfo &RegInfo = MF.getRegInfo();
    4905        4496 :       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
    4906        4496 :       if (PR)
    4907             :         Reg = PR;
    4908             :     }
    4909        4543 :     if (Reg) {
    4910             :       Op = MachineOperand::CreateReg(Reg, false);
    4911             :       IsIndirect = IsDbgDeclare;
    4912             :     }
    4913             :   }
    4914             : 
    4915        4643 :   if (!Op && N.getNode())
    4916             :     // Check if frame index is available.
    4917             :     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
    4918             :       if (FrameIndexSDNode *FINode =
    4919          24 :           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
    4920          24 :         Op = MachineOperand::CreateFI(FINode->getIndex());
    4921             : 
    4922        4643 :   if (!Op) {
    4923             :     // Check if ValueMap has reg number.
    4924         116 :     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
    4925         232 :     if (VMI != FuncInfo.ValueMap.end()) {
    4926         102 :       const auto &TLI = DAG.getTargetLoweringInfo();
    4927             :       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
    4928         303 :                        V->getType(), isABIRegCopy(V));
    4929         102 :       if (RFV.occupiesMultipleRegs()) {
    4930             :         unsigned Offset = 0;
    4931          24 :         for (auto RegAndSize : RFV.getRegsAndSizes()) {
    4932             :           Op = MachineOperand::CreateReg(RegAndSize.first, false);
    4933             :           auto FragmentExpr = DIExpression::createFragmentExpression(
    4934           9 :               Expr, Offset, RegAndSize.second);
    4935           9 :           if (!FragmentExpr)
    4936             :             continue;
    4937          18 :           FuncInfo.ArgDbgValues.push_back(
    4938          18 :               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
    4939          45 :                       Op->getReg(), Variable, *FragmentExpr));
    4940           9 :           Offset += RegAndSize.second;
    4941             :         }
    4942           3 :         return true;
    4943             :       }
    4944          99 :       Op = MachineOperand::CreateReg(VMI->second, false);
    4945             :       IsIndirect = IsDbgDeclare;
    4946             :     }
    4947             :   }
    4948             : 
    4949        4640 :   if (!Op)
    4950             :     return false;
    4951             : 
    4952             :   assert(Variable->isValidLocationForIntrinsic(DL) &&
    4953             :          "Expected inlined-at fields to agree");
    4954        4626 :   if (Op->isReg())
    4955        9190 :     FuncInfo.ArgDbgValues.push_back(
    4956        9190 :         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
    4957       22975 :                 Op->getReg(), Variable, Expr));
    4958             :   else
    4959          62 :     FuncInfo.ArgDbgValues.push_back(
    4960          93 :         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
    4961             :             .add(*Op)
    4962             :             .addImm(0)
    4963             :             .addMetadata(Variable)
    4964          62 :             .addMetadata(Expr));
    4965             : 
    4966             :   return true;
    4967             : }
    4968             : 
    4969             : /// Return the appropriate SDDbgValue based on N.
    4970       18956 : SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
    4971             :                                              DILocalVariable *Variable,
    4972             :                                              DIExpression *Expr,
    4973             :                                              const DebugLoc &dl,
    4974             :                                              unsigned DbgSDNodeOrder) {
    4975             :   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
    4976             :     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
    4977             :     // stack slot locations as such instead of as indirectly addressed
    4978             :     // locations.
    4979        7547 :     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
    4980        7547 :                                      DbgSDNodeOrder);
    4981             :   }
    4982       11409 :   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
    4983       11409 :                          DbgSDNodeOrder);
    4984             : }
    4985             : 
    4986             : // VisualStudio defines setjmp as _setjmp
    4987             : #if defined(_MSC_VER) && defined(setjmp) && \
    4988             :                          !defined(setjmp_undefined_for_msvc)
    4989             : #  pragma push_macro("setjmp")
    4990             : #  undef setjmp
    4991             : #  define setjmp_undefined_for_msvc
    4992             : #endif
    4993             : 
    4994             : /// Lower the call to the specified intrinsic function. If we want to emit this
    4995             : /// as a call to a named external function, return the name. Otherwise, lower it
    4996             : /// and return null.
    4997             : const char *
    4998      187860 : SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
    4999      187860 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    5000      187860 :   SDLoc sdl = getCurSDLoc();
    5001      187860 :   DebugLoc dl = getCurDebugLoc();
    5002             :   SDValue Res;
    5003             : 
    5004      187860 :   switch (Intrinsic) {
    5005       48417 :   default:
    5006             :     // By default, turn this into a target intrinsic node.
    5007       48417 :     visitTargetIntrinsic(I, Intrinsic);
    5008       48417 :     return nullptr;
    5009         247 :   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
    5010         168 :   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
    5011          10 :   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
    5012          76 :   case Intrinsic::returnaddress:
    5013         380 :     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
    5014          76 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5015          76 :                              getValue(I.getArgOperand(0))));
    5016          76 :     return nullptr;
    5017           6 :   case Intrinsic::addressofreturnaddress:
    5018          18 :     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
    5019             :                              TLI.getPointerTy(DAG.getDataLayout())));
    5020           6 :     return nullptr;
    5021         122 :   case Intrinsic::frameaddress:
    5022         610 :     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
    5023         122 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5024         122 :                              getValue(I.getArgOperand(0))));
    5025         122 :     return nullptr;
    5026         198 :   case Intrinsic::read_register: {
    5027         198 :     Value *Reg = I.getArgOperand(0);
    5028         198 :     SDValue Chain = getRoot();
    5029             :     SDValue RegName =
    5030         198 :         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
    5031         396 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5032         396 :     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
    5033         396 :       DAG.getVTList(VT, MVT::Other), Chain, RegName);
    5034         198 :     setValue(&I, Res);
    5035         198 :     DAG.setRoot(Res.getValue(1));
    5036             :     return nullptr;
    5037             :   }
    5038         179 :   case Intrinsic::write_register: {
    5039         179 :     Value *Reg = I.getArgOperand(0);
    5040             :     Value *RegValue = I.getArgOperand(1);
    5041         179 :     SDValue Chain = getRoot();
    5042             :     SDValue RegName =
    5043         179 :         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
    5044         358 :     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
    5045         537 :                             RegName, getValue(RegValue)));
    5046             :     return nullptr;
    5047             :   }
    5048           0 :   case Intrinsic::setjmp:
    5049           0 :     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
    5050           0 :   case Intrinsic::longjmp:
    5051           0 :     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
    5052             :   case Intrinsic::memcpy: {
    5053             :     const auto &MCI = cast<MemCpyInst>(I);
    5054        4176 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5055        2088 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5056        2088 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5057             :     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
    5058        6264 :     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
    5059        6264 :     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
    5060        2088 :     unsigned Align = MinAlign(DstAlign, SrcAlign);
    5061        2088 :     bool isVol = MCI.isVolatile();
    5062        2356 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5063             :     // FIXME: Support passing different dest/src alignments to the memcpy DAG
    5064             :     // node.
    5065        2088 :     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5066             :                                false, isTC,
    5067             :                                MachinePointerInfo(I.getArgOperand(0)),
    5068        2088 :                                MachinePointerInfo(I.getArgOperand(1)));
    5069        2088 :     updateDAGForMaybeTailCall(MC);
    5070             :     return nullptr;
    5071             :   }
    5072             :   case Intrinsic::memset: {
    5073             :     const auto &MSI = cast<MemSetInst>(I);
    5074       49072 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5075       24536 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5076       24536 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5077             :     // @llvm.memset defines 0 and 1 to both mean no alignment.
    5078       73608 :     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
    5079       24536 :     bool isVol = MSI.isVolatile();
    5080       24754 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5081       24536 :     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5082       24536 :                                isTC, MachinePointerInfo(I.getArgOperand(0)));
    5083       24536 :     updateDAGForMaybeTailCall(MS);
    5084             :     return nullptr;
    5085             :   }
    5086             :   case Intrinsic::memmove: {
    5087             :     const auto &MMI = cast<MemMoveInst>(I);
    5088         768 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5089         384 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5090         384 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5091             :     // @llvm.memmove defines 0 and 1 to both mean no alignment.
    5092        1152 :     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
    5093        1152 :     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
    5094         384 :     unsigned Align = MinAlign(DstAlign, SrcAlign);
    5095         384 :     bool isVol = MMI.isVolatile();
    5096         486 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5097             :     // FIXME: Support passing different dest/src alignments to the memmove DAG
    5098             :     // node.
    5099         384 :     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5100             :                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
    5101         384 :                                 MachinePointerInfo(I.getArgOperand(1)));
    5102         384 :     updateDAGForMaybeTailCall(MM);
    5103             :     return nullptr;
    5104             :   }
    5105             :   case Intrinsic::memcpy_element_unordered_atomic: {
    5106             :     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
    5107           6 :     SDValue Dst = getValue(MI.getRawDest());
    5108           6 :     SDValue Src = getValue(MI.getRawSource());
    5109           6 :     SDValue Length = getValue(MI.getLength());
    5110             : 
    5111             :     unsigned DstAlign = MI.getDestAlignment();
    5112             :     unsigned SrcAlign = MI.getSourceAlignment();
    5113           6 :     Type *LengthTy = MI.getLength()->getType();
    5114             :     unsigned ElemSz = MI.getElementSizeInBytes();
    5115           6 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5116           6 :     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
    5117             :                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
    5118             :                                      MachinePointerInfo(MI.getRawDest()),
    5119           6 :                                      MachinePointerInfo(MI.getRawSource()));
    5120           6 :     updateDAGForMaybeTailCall(MC);
    5121             :     return nullptr;
    5122             :   }
    5123             :   case Intrinsic::memmove_element_unordered_atomic: {
    5124             :     auto &MI = cast<AtomicMemMoveInst>(I);
    5125           6 :     SDValue Dst = getValue(MI.getRawDest());
    5126           6 :     SDValue Src = getValue(MI.getRawSource());
    5127           6 :     SDValue Length = getValue(MI.getLength());
    5128             : 
    5129             :     unsigned DstAlign = MI.getDestAlignment();
    5130             :     unsigned SrcAlign = MI.getSourceAlignment();
    5131           6 :     Type *LengthTy = MI.getLength()->getType();
    5132             :     unsigned ElemSz = MI.getElementSizeInBytes();
    5133           6 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5134           6 :     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
    5135             :                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
    5136             :                                       MachinePointerInfo(MI.getRawDest()),
    5137           6 :                                       MachinePointerInfo(MI.getRawSource()));
    5138           6 :     updateDAGForMaybeTailCall(MC);
    5139             :     return nullptr;
    5140             :   }
    5141             :   case Intrinsic::memset_element_unordered_atomic: {
    5142             :     auto &MI = cast<AtomicMemSetInst>(I);
    5143           6 :     SDValue Dst = getValue(MI.getRawDest());
    5144           6 :     SDValue Val = getValue(MI.getValue());
    5145           6 :     SDValue Length = getValue(MI.getLength());
    5146             : 
    5147             :     unsigned DstAlign = MI.getDestAlignment();
    5148           6 :     Type *LengthTy = MI.getLength()->getType();
    5149             :     unsigned ElemSz = MI.getElementSizeInBytes();
    5150           6 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5151           6 :     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
    5152             :                                      LengthTy, ElemSz, isTC,
    5153           6 :                                      MachinePointerInfo(MI.getRawDest()));
    5154           6 :     updateDAGForMaybeTailCall(MC);
    5155             :     return nullptr;
    5156             :   }
    5157             :   case Intrinsic::dbg_addr:
    5158             :   case Intrinsic::dbg_declare: {
    5159             :     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
    5160             :     DILocalVariable *Variable = DI.getVariable();
    5161             :     DIExpression *Expression = DI.getExpression();
    5162       11137 :     dropDanglingDebugInfo(Variable, Expression);
    5163             :     assert(Variable && "Missing variable");
    5164             : 
    5165             :     // Check if address has undef value.
    5166       11137 :     const Value *Address = DI.getVariableLocation();
    5167       33374 :     if (!Address || isa<UndefValue>(Address) ||
    5168       11184 :         (Address->use_empty() && !isa<Argument>(Address))) {
    5169             :       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
    5170             :       return nullptr;
    5171             :     }
    5172             : 
    5173       11038 :     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
    5174             : 
    5175             :     // Check if this variable can be described by a frame index, typically
    5176             :     // either as a static alloca or a byval parameter.
    5177             :     int FI = std::numeric_limits<int>::max();
    5178             :     if (const auto *AI =
    5179       11038 :             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
    5180       10893 :       if (AI->isStaticAlloca()) {
    5181       10888 :         auto I = FuncInfo.StaticAllocaMap.find(AI);
    5182       21776 :         if (I != FuncInfo.StaticAllocaMap.end())
    5183       10888 :           FI = I->second;
    5184             :       }
    5185         145 :     } else if (const auto *Arg = dyn_cast<Argument>(
    5186             :                    Address->stripInBoundsConstantOffsets())) {
    5187         136 :       FI = FuncInfo.getArgumentFrameIndex(Arg);
    5188             :     }
    5189             : 
    5190             :     // llvm.dbg.addr is control dependent and always generates indirect
    5191             :     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
    5192             :     // the MachineFunction variable table.
    5193       11024 :     if (FI != std::numeric_limits<int>::max()) {
    5194       10907 :       if (Intrinsic == Intrinsic::dbg_addr) {
    5195           3 :          SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
    5196           3 :                                                      FI, dl, SDNodeOrder);
    5197           3 :          DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
    5198             :       }
    5199             :       return nullptr;
    5200             :     }
    5201             : 
    5202         131 :     SDValue &N = NodeMap[Address];
    5203         227 :     if (!N.getNode() && isa<Argument>(Address))
    5204             :       // Check unused arguments map.
    5205         186 :       N = UnusedArgNodeMap[Address];
    5206             :     SDDbgValue *SDV;
    5207         131 :     if (N.getNode()) {
    5208          35 :       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
    5209           2 :         Address = BCI->getOperand(0);
    5210             :       // Parameters are handled specially.
    5211             :       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
    5212          35 :       if (isParameter && FINode) {
    5213             :         // Byval parameter. We have a frame index at this point.
    5214           0 :         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
    5215           0 :                                         FINode->getIndex(), dl, SDNodeOrder);
    5216          70 :       } else if (isa<Argument>(Address)) {
    5217             :         // Address is an argument, so try to emit its dbg value using
    5218             :         // virtual register info from the FuncInfo.ValueMap.
    5219          24 :         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
    5220          24 :         return nullptr;
    5221             :       } else {
    5222          11 :         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
    5223             :                               true, dl, SDNodeOrder);
    5224             :       }
    5225          11 :       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
    5226             :     } else {
    5227             :       // If Address is an argument then try to emit its dbg value using
    5228             :       // virtual register info from the FuncInfo.ValueMap.
    5229          96 :       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
    5230             :                                     N)) {
    5231             :         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
    5232             :       }
    5233             :     }
    5234             :     return nullptr;
    5235             :   }
    5236             :   case Intrinsic::dbg_label: {
    5237             :     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
    5238             :     DILabel *Label = DI.getLabel();
    5239             :     assert(Label && "Missing label");
    5240             : 
    5241             :     SDDbgLabel *SDV;
    5242           0 :     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
    5243           0 :     DAG.AddDbgLabel(SDV);
    5244           0 :     return nullptr;
    5245             :   }
    5246             :   case Intrinsic::dbg_value: {
    5247             :     const DbgValueInst &DI = cast<DbgValueInst>(I);
    5248             :     assert(DI.getVariable() && "Missing variable");
    5249             : 
    5250             :     DILocalVariable *Variable = DI.getVariable();
    5251             :     DIExpression *Expression = DI.getExpression();
    5252       40025 :     dropDanglingDebugInfo(Variable, Expression);
    5253       40025 :     const Value *V = DI.getValue();
    5254       40025 :     if (!V)
    5255             :       return nullptr;
    5256             : 
    5257             :     SDDbgValue *SDV;
    5258       37711 :     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
    5259        9274 :       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
    5260        9274 :       DAG.AddDbgValue(SDV, nullptr, false);
    5261        9274 :       return nullptr;
    5262             :     }
    5263             : 
    5264             :     // Do not use getValue() in here; we don't want to generate code at
    5265             :     // this point if it hasn't been done yet.
    5266       56874 :     SDValue N = NodeMap[V];
    5267       54333 :     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
    5268        6630 :       N = UnusedArgNodeMap[V];
    5269       28437 :     if (N.getNode()) {
    5270       15587 :       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
    5271             :         return nullptr;
    5272       13750 :       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
    5273       13750 :       DAG.AddDbgValue(SDV, N.getNode(), false);
    5274       13750 :       return nullptr;
    5275             :     }
    5276             : 
    5277             :     // PHI nodes have already been selected, so we should know which VReg that
    5278             :     // is assigns to already.
    5279       12850 :     if (isa<PHINode>(V)) {
    5280        3797 :       auto VMI = FuncInfo.ValueMap.find(V);
    5281        7594 :       if (VMI != FuncInfo.ValueMap.end()) {
    5282        3797 :         unsigned Reg = VMI->second;
    5283             :         // The PHI node may be split up into several MI PHI nodes (in
    5284             :         // FunctionLoweringInfo::set).
    5285        3797 :         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
    5286       15188 :                          V->getType(), false);
    5287        3797 :         if (RFV.occupiesMultipleRegs()) {
    5288             :           unsigned Offset = 0;
    5289             :           unsigned BitsToDescribe = 0;
    5290           7 :           if (auto VarSize = Variable->getSizeInBits())
    5291           7 :             BitsToDescribe = *VarSize;
    5292           7 :           if (auto Fragment = Expression->getFragmentInfo())
    5293           2 :             BitsToDescribe = Fragment->SizeInBits;
    5294          44 :           for (auto RegAndSize : RFV.getRegsAndSizes()) {
    5295             :             unsigned RegisterSize = RegAndSize.second;
    5296             :             // Bail out if all bits are described already.
    5297          16 :             if (Offset >= BitsToDescribe)
    5298             :               break;
    5299          15 :             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
    5300          15 :                 ? BitsToDescribe - Offset
    5301             :                 : RegisterSize;
    5302             :             auto FragmentExpr = DIExpression::createFragmentExpression(
    5303          15 :                 Expression, Offset, FragmentSize);
    5304          15 :             if (!FragmentExpr)
    5305             :                 continue;
    5306          15 :             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
    5307             :                                       false, dl, SDNodeOrder);
    5308          15 :             DAG.AddDbgValue(SDV, nullptr, false);
    5309             :             Offset += RegisterSize;
    5310             :           }
    5311             :         } else {
    5312        3790 :           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
    5313             :                                     SDNodeOrder);
    5314        3790 :           DAG.AddDbgValue(SDV, nullptr, false);
    5315             :         }
    5316             :         return nullptr;
    5317             :       }
    5318             :     }
    5319             : 
    5320             :     // TODO: When we get here we will either drop the dbg.value completely, or
    5321             :     // we try to move it forward by letting it dangle for awhile. So we should
    5322             :     // probably add an extra DbgValue to the DAG here, with a reference to
    5323             :     // "noreg", to indicate that we have lost the debug location for the
    5324             :     // variable.
    5325             : 
    5326        9053 :     if (!V->use_empty() ) {
    5327             :       // Do not call getValue(V) yet, as we don't want to generate code.
    5328             :       // Remember it for later.
    5329       17986 :       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
    5330       17986 :       DanglingDebugInfoMap[V].push_back(DDI);
    5331             :       return nullptr;
    5332             :     }
    5333             : 
    5334             :     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
    5335             :     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
    5336             :     return nullptr;
    5337             :   }
    5338             : 
    5339          97 :   case Intrinsic::eh_typeid_for: {
    5340             :     // Find the type id for the given typeinfo.
    5341         194 :     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
    5342          97 :     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
    5343         194 :     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
    5344          97 :     setValue(&I, Res);
    5345          97 :     return nullptr;
    5346             :   }
    5347             : 
    5348          29 :   case Intrinsic::eh_return_i32:
    5349             :   case Intrinsic::eh_return_i64:
    5350          29 :     DAG.getMachineFunction().setCallsEHReturn(true);
    5351          58 :     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
    5352             :                             MVT::Other,
    5353             :                             getControlRoot(),
    5354             :                             getValue(I.getArgOperand(0)),
    5355         145 :                             getValue(I.getArgOperand(1))));
    5356          29 :     return nullptr;
    5357          15 :   case Intrinsic::eh_unwind_init:
    5358          15 :     DAG.getMachineFunction().setCallsUnwindInit(true);
    5359          15 :     return nullptr;
    5360          19 :   case Intrinsic::eh_dwarf_cfa:
    5361          95 :     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
    5362          19 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5363          19 :                              getValue(I.getArgOperand(0))));
    5364          19 :     return nullptr;
    5365         175 :   case Intrinsic::eh_sjlj_callsite: {
    5366         175 :     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
    5367         175 :     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
    5368             :     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
    5369             :     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
    5370             : 
    5371         175 :     MMI.setCurrentCallSite(CI->getZExtValue());
    5372         175 :     return nullptr;
    5373             :   }
    5374          36 :   case Intrinsic::eh_sjlj_functioncontext: {
    5375             :     // Get and store the index of the function context.
    5376          36 :     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    5377             :     AllocaInst *FnCtx =
    5378          36 :       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
    5379          72 :     int FI = FuncInfo.StaticAllocaMap[FnCtx];
    5380             :     MFI.setFunctionContextIndex(FI);
    5381          36 :     return nullptr;
    5382             :   }
    5383          33 :   case Intrinsic::eh_sjlj_setjmp: {
    5384          33 :     SDValue Ops[2];
    5385          33 :     Ops[0] = getRoot();
    5386          66 :     Ops[1] = getValue(I.getArgOperand(0));
    5387          33 :     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
    5388          33 :                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
    5389          33 :     setValue(&I, Op.getValue(0));
    5390          33 :     DAG.setRoot(Op.getValue(1));
    5391             :     return nullptr;
    5392             :   }
    5393          24 :   case Intrinsic::eh_sjlj_longjmp:
    5394          48 :     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
    5395          96 :                             getRoot(), getValue(I.getArgOperand(0))));
    5396          24 :     return nullptr;
    5397          36 :   case Intrinsic::eh_sjlj_setup_dispatch:
    5398          72 :     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
    5399         108 :                             getRoot()));
    5400          36 :     return nullptr;
    5401         288 :   case Intrinsic::masked_gather:
    5402         288 :     visitMaskedGather(I);
    5403         288 :     return nullptr;
    5404         302 :   case Intrinsic::masked_load:
    5405         302 :     visitMaskedLoad(I);
    5406         302 :     return nullptr;
    5407          85 :   case Intrinsic::masked_scatter:
    5408          85 :     visitMaskedScatter(I);
    5409          85 :     return nullptr;
    5410         148 :   case Intrinsic::masked_store:
    5411         148 :     visitMaskedStore(I);
    5412         148 :     return nullptr;
    5413         198 :   case Intrinsic::masked_expandload:
    5414         198 :     visitMaskedLoad(I, true /* IsExpanding */);
    5415         198 :     return nullptr;
    5416         128 :   case Intrinsic::masked_compressstore:
    5417         128 :     visitMaskedStore(I, true /* IsCompressing */);
    5418         128 :     return nullptr;
    5419         154 :   case Intrinsic::x86_mmx_pslli_w:
    5420             :   case Intrinsic::x86_mmx_pslli_d:
    5421             :   case Intrinsic::x86_mmx_pslli_q:
    5422             :   case Intrinsic::x86_mmx_psrli_w:
    5423             :   case Intrinsic::x86_mmx_psrli_d:
    5424             :   case Intrinsic::x86_mmx_psrli_q:
    5425             :   case Intrinsic::x86_mmx_psrai_w:
    5426             :   case Intrinsic::x86_mmx_psrai_d: {
    5427         308 :     SDValue ShAmt = getValue(I.getArgOperand(1));
    5428             :     if (isa<ConstantSDNode>(ShAmt)) {
    5429         129 :       visitTargetIntrinsic(I, Intrinsic);
    5430         129 :       return nullptr;
    5431             :     }
    5432             :     unsigned NewIntrinsic = 0;
    5433          25 :     EVT ShAmtVT = MVT::v2i32;
    5434          25 :     switch (Intrinsic) {
    5435             :     case Intrinsic::x86_mmx_pslli_w:
    5436             :       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
    5437             :       break;
    5438           2 :     case Intrinsic::x86_mmx_pslli_d:
    5439             :       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
    5440           2 :       break;
    5441           9 :     case Intrinsic::x86_mmx_pslli_q:
    5442             :       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
    5443           9 :       break;
    5444           2 :     case Intrinsic::x86_mmx_psrli_w:
    5445             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
    5446           2 :       break;
    5447           2 :     case Intrinsic::x86_mmx_psrli_d:
    5448             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
    5449           2 :       break;
    5450           4 :     case Intrinsic::x86_mmx_psrli_q:
    5451             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
    5452           4 :       break;
    5453           2 :     case Intrinsic::x86_mmx_psrai_w:
    5454             :       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
    5455           2 :       break;
    5456           2 :     case Intrinsic::x86_mmx_psrai_d:
    5457             :       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
    5458           2 :       break;
    5459           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5460             :     }
    5461             : 
    5462             :     // The vector shift intrinsics with scalars uses 32b shift amounts but
    5463             :     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
    5464             :     // to be zero.
    5465             :     // We must do this early because v2i32 is not a legal type.
    5466          25 :     SDValue ShOps[2];
    5467          25 :     ShOps[0] = ShAmt;
    5468          50 :     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
    5469          50 :     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
    5470          50 :     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5471          50 :     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
    5472          50 :     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
    5473          25 :                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
    5474          75 :                        getValue(I.getArgOperand(0)), ShAmt);
    5475          25 :     setValue(&I, Res);
    5476          25 :     return nullptr;
    5477             :   }
    5478         104 :   case Intrinsic::powi:
    5479         312 :     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
    5480         104 :                             getValue(I.getArgOperand(1)), DAG));
    5481         104 :     return nullptr;
    5482          75 :   case Intrinsic::log:
    5483         150 :     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5484          75 :     return nullptr;
    5485          81 :   case Intrinsic::log2:
    5486         162 :     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5487          81 :     return nullptr;
    5488          81 :   case Intrinsic::log10:
    5489         162 :     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5490          81 :     return nullptr;
    5491          71 :   case Intrinsic::exp:
    5492         142 :     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5493          71 :     return nullptr;
    5494          95 :   case Intrinsic::exp2:
    5495         190 :     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5496          95 :     return nullptr;
    5497          91 :   case Intrinsic::pow:
    5498         273 :     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
    5499          91 :                            getValue(I.getArgOperand(1)), DAG, TLI));
    5500          91 :     return nullptr;
    5501        2955 :   case Intrinsic::sqrt:
    5502             :   case Intrinsic::fabs:
    5503             :   case Intrinsic::sin:
    5504             :   case Intrinsic::cos:
    5505             :   case Intrinsic::floor:
    5506             :   case Intrinsic::ceil:
    5507             :   case Intrinsic::trunc:
    5508             :   case Intrinsic::rint:
    5509             :   case Intrinsic::nearbyint:
    5510             :   case Intrinsic::round:
    5511             :   case Intrinsic::canonicalize: {
    5512             :     unsigned Opcode;
    5513        2955 :     switch (Intrinsic) {
    5514           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5515             :     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
    5516         799 :     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
    5517          91 :     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
    5518          82 :     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
    5519         259 :     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
    5520         153 :     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
    5521         157 :     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
    5522         126 :     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
    5523         119 :     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
    5524          82 :     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
    5525         280 :     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
    5526             :     }
    5527             : 
    5528       14775 :     setValue(&I, DAG.getNode(Opcode, sdl,
    5529        5910 :                              getValue(I.getArgOperand(0)).getValueType(),
    5530        2955 :                              getValue(I.getArgOperand(0))));
    5531        2955 :     return nullptr;
    5532             :   }
    5533         862 :   case Intrinsic::minnum: {
    5534        2586 :     auto VT = getValue(I.getArgOperand(0)).getValueType();
    5535             :     unsigned Opc =
    5536         862 :         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
    5537         862 :             ? ISD::FMINNAN
    5538             :             : ISD::FMINNUM;
    5539        3448 :     setValue(&I, DAG.getNode(Opc, sdl, VT,
    5540             :                              getValue(I.getArgOperand(0)),
    5541             :                              getValue(I.getArgOperand(1))));
    5542             :     return nullptr;
    5543             :   }
    5544         868 :   case Intrinsic::maxnum: {
    5545        2604 :     auto VT = getValue(I.getArgOperand(0)).getValueType();
    5546             :     unsigned Opc =
    5547         868 :         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
    5548         868 :             ? ISD::FMAXNAN
    5549             :             : ISD::FMAXNUM;
    5550        3472 :     setValue(&I, DAG.getNode(Opc, sdl, VT,
    5551             :                              getValue(I.getArgOperand(0)),
    5552             :                              getValue(I.getArgOperand(1))));
    5553             :     return nullptr;
    5554             :   }
    5555         193 :   case Intrinsic::copysign:
    5556        1158 :     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
    5557         386 :                              getValue(I.getArgOperand(0)).getValueType(),
    5558             :                              getValue(I.getArgOperand(0)),
    5559         193 :                              getValue(I.getArgOperand(1))));
    5560         193 :     return nullptr;
    5561        1621 :   case Intrinsic::fma:
    5562       11347 :     setValue(&I, DAG.getNode(ISD::FMA, sdl,
    5563        3242 :                              getValue(I.getArgOperand(0)).getValueType(),
    5564             :                              getValue(I.getArgOperand(0)),
    5565             :                              getValue(I.getArgOperand(1)),
    5566        1621 :                              getValue(I.getArgOperand(2))));
    5567        1621 :     return nullptr;
    5568             :   case Intrinsic::experimental_constrained_fadd:
    5569             :   case Intrinsic::experimental_constrained_fsub:
    5570             :   case Intrinsic::experimental_constrained_fmul:
    5571             :   case Intrinsic::experimental_constrained_fdiv:
    5572             :   case Intrinsic::experimental_constrained_frem:
    5573             :   case Intrinsic::experimental_constrained_fma:
    5574             :   case Intrinsic::experimental_constrained_sqrt:
    5575             :   case Intrinsic::experimental_constrained_pow:
    5576             :   case Intrinsic::experimental_constrained_powi:
    5577             :   case Intrinsic::experimental_constrained_sin:
    5578             :   case Intrinsic::experimental_constrained_cos:
    5579             :   case Intrinsic::experimental_constrained_exp:
    5580             :   case Intrinsic::experimental_constrained_exp2:
    5581             :   case Intrinsic::experimental_constrained_log:
    5582             :   case Intrinsic::experimental_constrained_log10:
    5583             :   case Intrinsic::experimental_constrained_log2:
    5584             :   case Intrinsic::experimental_constrained_rint:
    5585             :   case Intrinsic::experimental_constrained_nearbyint:
    5586          76 :     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
    5587          76 :     return nullptr;
    5588        1026 :   case Intrinsic::fmuladd: {
    5589        2052 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5590        2052 :     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
    5591        1026 :         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
    5592        1064 :       setValue(&I, DAG.getNode(ISD::FMA, sdl,
    5593         304 :                                getValue(I.getArgOperand(0)).getValueType(),
    5594             :                                getValue(I.getArgOperand(0)),
    5595             :                                getValue(I.getArgOperand(1)),
    5596         152 :                                getValue(I.getArgOperand(2))));
    5597             :     } else {
    5598             :       // TODO: Intrinsic calls should have fast-math-flags.
    5599         874 :       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
    5600        1748 :                                 getValue(I.getArgOperand(0)).getValueType(),
    5601             :                                 getValue(I.getArgOperand(0)),
    5602        5244 :                                 getValue(I.getArgOperand(1)));
    5603         874 :       SDValue Add = DAG.getNode(ISD::FADD, sdl,
    5604        1748 :                                 getValue(I.getArgOperand(0)).getValueType(),
    5605             :                                 Mul,
    5606        3496 :                                 getValue(I.getArgOperand(2)));
    5607         874 :       setValue(&I, Add);
    5608             :     }
    5609             :     return nullptr;
    5610             :   }
    5611         229 :   case Intrinsic::convert_to_fp16:
    5612        1145 :     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
    5613             :                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
    5614         229 :                                          getValue(I.getArgOperand(0)),
    5615             :                                          DAG.getTargetConstant(0, sdl,
    5616             :                                                                MVT::i32))));
    5617         229 :     return nullptr;
    5618         275 :   case Intrinsic::convert_from_fp16:
    5619        1650 :     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
    5620         275 :                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
    5621             :                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
    5622         275 :                                          getValue(I.getArgOperand(0)))));
    5623         275 :     return nullptr;
    5624           0 :   case Intrinsic::pcmarker: {
    5625           0 :     SDValue Tmp = getValue(I.getArgOperand(0));
    5626           0 :     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
    5627             :     return nullptr;
    5628             :   }
    5629          22 :   case Intrinsic::readcyclecounter: {
    5630          22 :     SDValue Op = getRoot();
    5631          44 :     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
    5632          44 :                       DAG.getVTList(MVT::i64, MVT::Other), Op);
    5633          22 :     setValue(&I, Res);
    5634          22 :     DAG.setRoot(Res.getValue(1));
    5635             :     return nullptr;
    5636             :   }
    5637         279 :   case Intrinsic::bitreverse:
    5638        1395 :     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
    5639         558 :                              getValue(I.getArgOperand(0)).getValueType(),
    5640         279 :                              getValue(I.getArgOperand(0))));
    5641         279 :     return nullptr;
    5642         632 :   case Intrinsic::bswap:
    5643        3160 :     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
    5644        1264 :                              getValue(I.getArgOperand(0)).getValueType(),
    5645         632 :                              getValue(I.getArgOperand(0))));
    5646         632 :     return nullptr;
    5647         729 :   case Intrinsic::cttz: {
    5648        1458 :     SDValue Arg = getValue(I.getArgOperand(0));
    5649             :     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
    5650        1458 :     EVT Ty = Arg.getValueType();
    5651        2187 :     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
    5652             :                              sdl, Ty, Arg));
    5653             :     return nullptr;
    5654             :   }
    5655         862 :   case Intrinsic::ctlz: {
    5656        1724 :     SDValue Arg = getValue(I.getArgOperand(0));
    5657             :     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
    5658        1724 :     EVT Ty = Arg.getValueType();
    5659        2586 :     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
    5660             :                              sdl, Ty, Arg));
    5661             :     return nullptr;
    5662             :   }
    5663         559 :   case Intrinsic::ctpop: {
    5664        1118 :     SDValue Arg = getValue(I.getArgOperand(0));
    5665        1118 :     EVT Ty = Arg.getValueType();
    5666        1677 :     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
    5667             :     return nullptr;
    5668             :   }
    5669         123 :   case Intrinsic::stacksave: {
    5670         123 :     SDValue Op = getRoot();
    5671         246 :     Res = DAG.getNode(
    5672             :         ISD::STACKSAVE, sdl,
    5673         369 :         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
    5674         123 :     setValue(&I, Res);
    5675         123 :     DAG.setRoot(Res.getValue(1));
    5676             :     return nullptr;
    5677             :   }
    5678          30 :   case Intrinsic::stackrestore:
    5679          60 :     Res = getValue(I.getArgOperand(0));
    5680          90 :     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
    5681          30 :     return nullptr;
    5682           4 :   case Intrinsic::get_dynamic_area_offset: {
    5683           4 :     SDValue Op = getRoot();
    5684           4 :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5685           8 :     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5686             :     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
    5687             :     // target.
    5688           4 :     if (PtrTy != ResTy)
    5689           0 :       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
    5690             :                          " intrinsic!");
    5691           8 :     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
    5692           4 :                       Op);
    5693           4 :     DAG.setRoot(Op);
    5694           4 :     setValue(&I, Res);
    5695             :     return nullptr;
    5696             :   }
    5697         353 :   case Intrinsic::stackguard: {
    5698         353 :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5699         353 :     MachineFunction &MF = DAG.getMachineFunction();
    5700         353 :     const Module &M = *MF.getFunction().getParent();
    5701         353 :     SDValue Chain = getRoot();
    5702         353 :     if (TLI.useLoadStackGuardNode()) {
    5703         155 :       Res = getLoadStackGuard(DAG, sdl, Chain);
    5704             :     } else {
    5705         198 :       const Value *Global = TLI.getSDagStackGuard(M);
    5706         198 :       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
    5707         396 :       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
    5708             :                         MachinePointerInfo(Global, 0), Align,
    5709         396 :                         MachineMemOperand::MOVolatile);
    5710             :     }
    5711         353 :     if (TLI.useStackGuardXorFP())
    5712         135 :       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
    5713         353 :     DAG.setRoot(Chain);
    5714         353 :     setValue(&I, Res);
    5715             :     return nullptr;
    5716             :   }
    5717         768 :   case Intrinsic::stackprotector: {
    5718             :     // Emit code into the DAG to store the stack guard onto the stack.
    5719         768 :     MachineFunction &MF = DAG.getMachineFunction();
    5720         768 :     MachineFrameInfo &MFI = MF.getFrameInfo();
    5721             :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5722         768 :     SDValue Src, Chain = getRoot();
    5723             : 
    5724         768 :     if (TLI.useLoadStackGuardNode())
    5725         141 :       Src = getLoadStackGuard(DAG, sdl, Chain);
    5726             :     else
    5727        1254 :       Src = getValue(I.getArgOperand(0));   // The guard's value.
    5728             : 
    5729         768 :     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
    5730             : 
    5731        1536 :     int FI = FuncInfo.StaticAllocaMap[Slot];
    5732             :     MFI.setStackProtectorIndex(FI);
    5733             : 
    5734         768 :     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
    5735             : 
    5736             :     // Store the stack protector onto the stack.
    5737        1536 :     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
    5738             :                                                  DAG.getMachineFunction(), FI),
    5739        1536 :                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
    5740         768 :     setValue(&I, Res);
    5741         768 :     DAG.setRoot(Res);
    5742             :     return nullptr;
    5743             :   }
    5744           0 :   case Intrinsic::objectsize: {
    5745             :     // If we don't know by now, we're never going to know.
    5746           0 :     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
    5747             : 
    5748             :     assert(CI && "Non-constant type in __builtin_object_size?");
    5749             : 
    5750           0 :     SDValue Arg = getValue(I.getCalledValue());
    5751           0 :     EVT Ty = Arg.getValueType();
    5752             : 
    5753           0 :     if (CI->isZero())
    5754           0 :       Res = DAG.getConstant(-1ULL, sdl, Ty);
    5755             :     else
    5756           0 :       Res = DAG.getConstant(0, sdl, Ty);
    5757             : 
    5758           0 :     setValue(&I, Res);
    5759             :     return nullptr;
    5760             :   }
    5761           4 :   case Intrinsic::annotation:
    5762             :   case Intrinsic::ptr_annotation:
    5763             :   case Intrinsic::launder_invariant_group:
    5764             :     // Drop the intrinsic, but forward the value
    5765           8 :     setValue(&I, getValue(I.getOperand(0)));
    5766           4 :     return nullptr;
    5767             :   case Intrinsic::assume:
    5768             :   case Intrinsic::var_annotation:
    5769             :   case Intrinsic::sideeffect:
    5770             :     // Discard annotate attributes, assumptions, and artificial side-effects.
    5771             :     return nullptr;
    5772             : 
    5773           1 :   case Intrinsic::codeview_annotation: {
    5774             :     // Emit a label associated with this metadata.
    5775           1 :     MachineFunction &MF = DAG.getMachineFunction();
    5776             :     MCSymbol *Label =
    5777           2 :         MF.getMMI().getContext().createTempSymbol("annotation", true);
    5778           2 :     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
    5779             :     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
    5780           1 :     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
    5781           1 :     DAG.setRoot(Res);
    5782           1 :     return nullptr;
    5783             :   }
    5784             : 
    5785           4 :   case Intrinsic::init_trampoline: {
    5786           4 :     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
    5787             : 
    5788           4 :     SDValue Ops[6];
    5789           4 :     Ops[0] = getRoot();
    5790           4 :     Ops[1] = getValue(I.getArgOperand(0));
    5791           4 :     Ops[2] = getValue(I.getArgOperand(1));
    5792           4 :     Ops[3] = getValue(I.getArgOperand(2));
    5793           8 :     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
    5794           4 :     Ops[5] = DAG.getSrcValue(F);
    5795             : 
    5796           8 :     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
    5797             : 
    5798           4 :     DAG.setRoot(Res);
    5799             :     return nullptr;
    5800             :   }
    5801           4 :   case Intrinsic::adjust_trampoline:
    5802          20 :     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
    5803           4 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5804           4 :                              getValue(I.getArgOperand(0))));
    5805           4 :     return nullptr;
    5806           2 :   case Intrinsic::gcroot: {
    5807             :     assert(DAG.getMachineFunction().getFunction().hasGC() &&
    5808             :            "only valid in functions with gc specified, enforced by Verifier");
    5809             :     assert(GFI && "implied by previous");
    5810           2 :     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
    5811             :     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
    5812             : 
    5813           2 :     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
    5814           2 :     GFI->addStackRoot(FI->getIndex(), TypeMap);
    5815           2 :     return nullptr;
    5816             :   }
    5817           0 :   case Intrinsic::gcread:
    5818             :   case Intrinsic::gcwrite:
    5819           0 :     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
    5820           6 :   case Intrinsic::flt_rounds:
    5821          18 :     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
    5822           6 :     return nullptr;
    5823             : 
    5824          11 :   case Intrinsic::expect:
    5825             :     // Just replace __builtin_expect(exp, c) with EXP.
    5826          22 :     setValue(&I, getValue(I.getArgOperand(0)));
    5827          11 :     return nullptr;
    5828             : 
    5829         236 :   case Intrinsic::debugtrap:
    5830             :   case Intrinsic::trap: {
    5831             :     StringRef TrapFuncName =
    5832         472 :         I.getAttributes()
    5833         472 :             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
    5834         236 :             .getValueAsString();
    5835         236 :     if (TrapFuncName.empty()) {
    5836         227 :       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
    5837             :         ISD::TRAP : ISD::DEBUGTRAP;
    5838         681 :       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
    5839         227 :       return nullptr;
    5840             :     }
    5841             :     TargetLowering::ArgListTy Args;
    5842             : 
    5843          18 :     TargetLowering::CallLoweringInfo CLI(DAG);
    5844          18 :     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
    5845             :         CallingConv::C, I.getType(),
    5846           9 :         DAG.getExternalSymbol(TrapFuncName.data(),
    5847             :                               TLI.getPointerTy(DAG.getDataLayout())),
    5848          27 :         std::move(Args));
    5849             : 
    5850           9 :     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    5851           9 :     DAG.setRoot(Result.second);
    5852             :     return nullptr;
    5853             :   }
    5854             : 
    5855        1282 :   case Intrinsic::uadd_with_overflow:
    5856             :   case Intrinsic::sadd_with_overflow:
    5857             :   case Intrinsic::usub_with_overflow:
    5858             :   case Intrinsic::ssub_with_overflow:
    5859             :   case Intrinsic::umul_with_overflow:
    5860             :   case Intrinsic::smul_with_overflow: {
    5861             :     ISD::NodeType Op;
    5862        1282 :     switch (Intrinsic) {
    5863           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5864             :     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
    5865         334 :     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
    5866         241 :     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
    5867         283 :     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
    5868          69 :     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
    5869          54 :     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
    5870             :     }
    5871        2564 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5872        1282 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5873             : 
    5874        3846 :     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
    5875        1282 :     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
    5876             :     return nullptr;
    5877             :   }
    5878         208 :   case Intrinsic::prefetch: {
    5879         208 :     SDValue Ops[5];
    5880         416 :     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
    5881         208 :     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
    5882         208 :     Ops[0] = DAG.getRoot();
    5883         208 :     Ops[1] = getValue(I.getArgOperand(0));
    5884         208 :     Ops[2] = getValue(I.getArgOperand(1));
    5885         208 :     Ops[3] = getValue(I.getArgOperand(2));
    5886         208 :     Ops[4] = getValue(I.getArgOperand(3));
    5887         208 :     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
    5888         208 :                                              DAG.getVTList(MVT::Other), Ops,
    5889         208 :                                              EVT::getIntegerVT(*Context, 8),
    5890             :                                              MachinePointerInfo(I.getArgOperand(0)),
    5891             :                                              0, /* align */
    5892         624 :                                              Flags);
    5893             : 
    5894             :     // Chain the prefetch in parallell with any pending loads, to stay out of
    5895             :     // the way of later optimizations.
    5896         208 :     PendingLoads.push_back(Result);
    5897         208 :     Result = getRoot();
    5898         208 :     DAG.setRoot(Result);
    5899             :     return nullptr;
    5900             :   }
    5901       42793 :   case Intrinsic::lifetime_start:
    5902             :   case Intrinsic::lifetime_end: {
    5903             :     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
    5904             :     // Stack coloring is not enabled in O0, discard region information.
    5905       42793 :     if (TM.getOptLevel() == CodeGenOpt::None)
    5906             :       return nullptr;
    5907             : 
    5908             :     SmallVector<Value *, 4> Allocas;
    5909       85580 :     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
    5910             : 
    5911       42794 :     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
    5912       85584 :            E = Allocas.end(); Object != E; ++Object) {
    5913       42796 :       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
    5914             : 
    5915             :       // Could not find an Alloca.
    5916           2 :       if (!LifetimeObject)
    5917           2 :         continue;
    5918             : 
    5919             :       // First check that the Alloca is static, otherwise it won't have a
    5920             :       // valid frame index.
    5921       42794 :       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
    5922       85588 :       if (SI == FuncInfo.StaticAllocaMap.end())
    5923           2 :         return nullptr;
    5924             : 
    5925       42792 :       int FI = SI->second;
    5926             : 
    5927       42792 :       SDValue Ops[2];
    5928       42792 :       Ops[0] = getRoot();
    5929       42792 :       Ops[1] =
    5930      171168 :           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
    5931       42792 :       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
    5932             : 
    5933       85584 :       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
    5934       42792 :       DAG.setRoot(Res);
    5935             :     }
    5936             :     return nullptr;
    5937             :   }
    5938         328 :   case Intrinsic::invariant_start:
    5939             :     // Discard region information.
    5940         984 :     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
    5941         328 :     return nullptr;
    5942             :   case Intrinsic::invariant_end:
    5943             :     // Discard region information.
    5944             :     return nullptr;
    5945           3 :   case Intrinsic::clear_cache:
    5946           3 :     return TLI.getClearCacheBuiltinName();
    5947             :   case Intrinsic::donothing:
    5948             :     // ignore
    5949             :     return nullptr;
    5950         140 :   case Intrinsic::experimental_stackmap:
    5951         140 :     visitStackmap(I);
    5952         140 :     return nullptr;
    5953             :   case Intrinsic::experimental_patchpoint_void:
    5954             :   case Intrinsic::experimental_patchpoint_i64:
    5955         144 :     visitPatchpoint(&I);
    5956         144 :     return nullptr;
    5957          59 :   case Intrinsic::experimental_gc_statepoint:
    5958         118 :     LowerStatepoint(ImmutableStatepoint(&I));
    5959          59 :     return nullptr;
    5960             :   case Intrinsic::experimental_gc_result:
    5961          24 :     visitGCResult(cast<GCResultInst>(I));
    5962          24 :     return nullptr;
    5963             :   case Intrinsic::experimental_gc_relocate:
    5964          66 :     visitGCRelocate(cast<GCRelocateInst>(I));
    5965          66 :     return nullptr;
    5966           0 :   case Intrinsic::instrprof_increment:
    5967           0 :     llvm_unreachable("instrprof failed to lower an increment");
    5968           0 :   case Intrinsic::instrprof_value_profile:
    5969           0 :     llvm_unreachable("instrprof failed to lower a value profiling call");
    5970          10 :   case Intrinsic::localescape: {
    5971          10 :     MachineFunction &MF = DAG.getMachineFunction();
    5972          10 :     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
    5973             : 
    5974             :     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
    5975             :     // is the same on all targets.
    5976          52 :     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
    5977             :       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
    5978          16 :       if (isa<ConstantPointerNull>(Arg))
    5979             :         continue; // Skip null pointers. They represent a hole in index space.
    5980             :       AllocaInst *Slot = cast<AllocaInst>(Arg);
    5981             :       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
    5982             :              "can only escape static allocas");
    5983          32 :       int FI = FuncInfo.StaticAllocaMap[Slot];
    5984             :       MCSymbol *FrameAllocSym =
    5985          32 :           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
    5986          16 :               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
    5987          16 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
    5988          16 :               TII->get(TargetOpcode::LOCAL_ESCAPE))
    5989             :           .addSym(FrameAllocSym)
    5990             :           .addFrameIndex(FI);
    5991             :     }
    5992             : 
    5993             :     return nullptr;
    5994             :   }
    5995             : 
    5996          12 :   case Intrinsic::localrecover: {
    5997             :     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
    5998          12 :     MachineFunction &MF = DAG.getMachineFunction();
    5999             :     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
    6000             : 
    6001             :     // Get the symbol that defines the frame offset.
    6002          12 :     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
    6003             :     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
    6004             :     unsigned IdxVal =
    6005          12 :         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
    6006             :     MCSymbol *FrameAllocSym =
    6007          24 :         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
    6008          12 :             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
    6009             : 
    6010             :     // Create a MCSymbol for the label to avoid any target lowering
    6011             :     // that would make this PC relative.
    6012          24 :     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
    6013             :     SDValue OffsetVal =
    6014          24 :         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
    6015             : 
    6016             :     // Add the offset to the FP.
    6017             :     Value *FP = I.getArgOperand(1);
    6018          12 :     SDValue FPVal = getValue(FP);
    6019          24 :     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
    6020          12 :     setValue(&I, Add);
    6021             : 
    6022             :     return nullptr;
    6023             :   }
    6024             : 
    6025           6 :   case Intrinsic::eh_exceptionpointer:
    6026             :   case Intrinsic::eh_exceptioncode: {
    6027             :     // Get the exception pointer vreg, copy from it, and resize it to fit.
    6028           6 :     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
    6029           6 :     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
    6030           6 :     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
    6031           6 :     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
    6032             :     SDValue N =
    6033          30 :         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
    6034           6 :     if (Intrinsic == Intrinsic::eh_exceptioncode)
    6035          12 :       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
    6036           6 :     setValue(&I, N);
    6037             :     return nullptr;
    6038             :   }
    6039           2 :   case Intrinsic::xray_customevent: {
    6040             :     // Here we want to make sure that the intrinsic behaves as if it has a
    6041             :     // specific calling convention, and only for x86_64.
    6042             :     // FIXME: Support other platforms later.
    6043           2 :     const auto &Triple = DAG.getTarget().getTargetTriple();
    6044           4 :     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
    6045             :       return nullptr;
    6046             : 
    6047           2 :     SDLoc DL = getCurSDLoc();
    6048             :     SmallVector<SDValue, 8> Ops;
    6049             : 
    6050             :     // We want to say that we always want the arguments in registers.
    6051           4 :     SDValue LogEntryVal = getValue(I.getArgOperand(0));
    6052           2 :     SDValue StrSizeVal = getValue(I.getArgOperand(1));
    6053           4 :     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    6054           2 :     SDValue Chain = getRoot();
    6055           2 :     Ops.push_back(LogEntryVal);
    6056           2 :     Ops.push_back(StrSizeVal);
    6057           2 :     Ops.push_back(Chain);
    6058             : 
    6059             :     // We need to enforce the calling convention for the callsite, so that
    6060             :     // argument ordering is enforced correctly, and that register allocation can
    6061             :     // see that some registers may be assumed clobbered and have to preserve
    6062             :     // them across calls to the intrinsic.
    6063           4 :     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
    6064           2 :                                            DL, NodeTys, Ops);
    6065             :     SDValue patchableNode = SDValue(MN, 0);
    6066           2 :     DAG.setRoot(patchableNode);
    6067           2 :     setValue(&I, patchableNode);
    6068             :     return nullptr;
    6069             :   }
    6070           2 :   case Intrinsic::xray_typedevent: {
    6071             :     // Here we want to make sure that the intrinsic behaves as if it has a
    6072             :     // specific calling convention, and only for x86_64.
    6073             :     // FIXME: Support other platforms later.
    6074           2 :     const auto &Triple = DAG.getTarget().getTargetTriple();
    6075           4 :     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
    6076             :       return nullptr;
    6077             : 
    6078           2 :     SDLoc DL = getCurSDLoc();
    6079             :     SmallVector<SDValue, 8> Ops;
    6080             : 
    6081             :     // We want to say that we always want the arguments in registers.
    6082             :     // It's unclear to me how manipulating the selection DAG here forces callers
    6083             :     // to provide arguments in registers instead of on the stack.
    6084           4 :     SDValue LogTypeId = getValue(I.getArgOperand(0));
    6085           2 :     SDValue LogEntryVal = getValue(I.getArgOperand(1));
    6086           2 :     SDValue StrSizeVal = getValue(I.getArgOperand(2));
    6087           4 :     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    6088           2 :     SDValue Chain = getRoot();
    6089           2 :     Ops.push_back(LogTypeId);
    6090           2 :     Ops.push_back(LogEntryVal);
    6091           2 :     Ops.push_back(StrSizeVal);
    6092           2 :     Ops.push_back(Chain);
    6093             : 
    6094             :     // We need to enforce the calling convention for the callsite, so that
    6095             :     // argument ordering is enforced correctly, and that register allocation can
    6096             :     // see that some registers may be assumed clobbered and have to preserve
    6097             :     // them across calls to the intrinsic.
    6098           4 :     MachineSDNode *MN = DAG.getMachineNode(
    6099           2 :         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
    6100             :     SDValue patchableNode = SDValue(MN, 0);
    6101           2 :     DAG.setRoot(patchableNode);
    6102           2 :     setValue(&I, patchableNode);
    6103             :     return nullptr;
    6104             :   }
    6105           0 :   case Intrinsic::experimental_deoptimize:
    6106           0 :     LowerDeoptimizeCall(&I);
    6107           0 :     return nullptr;
    6108             : 
    6109          58 :   case Intrinsic::experimental_vector_reduce_fadd:
    6110             :   case Intrinsic::experimental_vector_reduce_fmul:
    6111             :   case Intrinsic::experimental_vector_reduce_add:
    6112             :   case Intrinsic::experimental_vector_reduce_mul:
    6113             :   case Intrinsic::experimental_vector_reduce_and:
    6114             :   case Intrinsic::experimental_vector_reduce_or:
    6115             :   case Intrinsic::experimental_vector_reduce_xor:
    6116             :   case Intrinsic::experimental_vector_reduce_smax:
    6117             :   case Intrinsic::experimental_vector_reduce_smin:
    6118             :   case Intrinsic::experimental_vector_reduce_umax:
    6119             :   case Intrinsic::experimental_vector_reduce_umin:
    6120             :   case Intrinsic::experimental_vector_reduce_fmax:
    6121             :   case Intrinsic::experimental_vector_reduce_fmin:
    6122          58 :     visitVectorReduce(I, Intrinsic);
    6123          58 :     return nullptr;
    6124             : 
    6125             :   case Intrinsic::icall_branch_funnel: {
    6126             :     SmallVector<SDValue, 16> Ops;
    6127          10 :     Ops.push_back(DAG.getRoot());
    6128          10 :     Ops.push_back(getValue(I.getArgOperand(0)));
    6129             : 
    6130             :     int64_t Offset;
    6131          10 :     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
    6132           5 :         I.getArgOperand(1), Offset, DAG.getDataLayout()));
    6133             :     if (!Base)
    6134           0 :       report_fatal_error(
    6135             :           "llvm.icall.branch.funnel operand must be a GlobalValue");
    6136          15 :     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
    6137             : 
    6138             :     struct BranchFunnelTarget {
    6139             :       int64_t Offset;
    6140             :       SDValue Target;
    6141             :     };
    6142             :     SmallVector<BranchFunnelTarget, 8> Targets;
    6143             : 
    6144          53 :     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
    6145          48 :       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
    6146          24 :           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
    6147          24 :       if (ElemBase != Base)
    6148           0 :         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
    6149             :                            "to the same GlobalValue");
    6150             : 
    6151          48 :       SDValue Val = getValue(I.getArgOperand(Op + 1));
    6152             :       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
    6153             :       if (!GA)
    6154           0 :         report_fatal_error(
    6155             :             "llvm.icall.branch.funnel operand must be a GlobalValue");
    6156          48 :       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
    6157          48 :                                      GA->getGlobal(), getCurSDLoc(),
    6158          48 :                                      Val.getValueType(), GA->getOffset())});
    6159             :     }
    6160             :     llvm::sort(Targets.begin(), Targets.end(),
    6161             :                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
    6162             :                  return T1.Offset < T2.Offset;
    6163             :                });
    6164             : 
    6165          53 :     for (auto &T : Targets) {
    6166          96 :       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
    6167          24 :       Ops.push_back(T.Target);
    6168             :     }
    6169             : 
    6170          15 :     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
    6171          10 :                                  getCurSDLoc(), MVT::Other, Ops),
    6172             :               0);
    6173           5 :     DAG.setRoot(N);
    6174           5 :     setValue(&I, N);
    6175           5 :     HasTailCall = true;
    6176             :     return nullptr;
    6177             :   }
    6178             : 
    6179             :   case Intrinsic::wasm_landingpad_index: {
    6180             :     // TODO store landing pad index in a map, which will be used when generating
    6181             :     // LSDA information
    6182             :     return nullptr;
    6183             :   }
    6184             :   }
    6185             : }
    6186             : 
    6187          76 : void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
    6188             :     const ConstrainedFPIntrinsic &FPI) {
    6189          76 :   SDLoc sdl = getCurSDLoc();
    6190             :   unsigned Opcode;
    6191          76 :   switch (FPI.getIntrinsicID()) {
    6192           0 :   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    6193             :   case Intrinsic::experimental_constrained_fadd:
    6194             :     Opcode = ISD::STRICT_FADD;
    6195             :     break;
    6196           8 :   case Intrinsic::experimental_constrained_fsub:
    6197             :     Opcode = ISD::STRICT_FSUB;
    6198           8 :     break;
    6199           4 :   case Intrinsic::experimental_constrained_fmul:
    6200             :     Opcode = ISD::STRICT_FMUL;
    6201           4 :     break;
    6202           4 :   case Intrinsic::experimental_constrained_fdiv:
    6203             :     Opcode = ISD::STRICT_FDIV;
    6204           4 :     break;
    6205           0 :   case Intrinsic::experimental_constrained_frem:
    6206             :     Opcode = ISD::STRICT_FREM;
    6207           0 :     break;
    6208           8 :   case Intrinsic::experimental_constrained_fma:
    6209             :     Opcode = ISD::STRICT_FMA;
    6210           8 :     break;
    6211           4 :   case Intrinsic::experimental_constrained_sqrt:
    6212             :     Opcode = ISD::STRICT_FSQRT;
    6213           4 :     break;
    6214           4 :   case Intrinsic::experimental_constrained_pow:
    6215             :     Opcode = ISD::STRICT_FPOW;
    6216           4 :     break;
    6217           4 :   case Intrinsic::experimental_constrained_powi:
    6218             :     Opcode = ISD::STRICT_FPOWI;
    6219           4 :     break;
    6220           4 :   case Intrinsic::experimental_constrained_sin:
    6221             :     Opcode = ISD::STRICT_FSIN;
    6222           4 :     break;
    6223           4 :   case Intrinsic::experimental_constrained_cos:
    6224             :     Opcode = ISD::STRICT_FCOS;
    6225           4 :     break;
    6226           4 :   case Intrinsic::experimental_constrained_exp:
    6227             :     Opcode = ISD::STRICT_FEXP;
    6228           4 :     break;
    6229           4 :   case Intrinsic::experimental_constrained_exp2:
    6230             :     Opcode = ISD::STRICT_FEXP2;
    6231           4 :     break;
    6232           4 :   case Intrinsic::experimental_constrained_log:
    6233             :     Opcode = ISD::STRICT_FLOG;
    6234           4 :     break;
    6235           4 :   case Intrinsic::experimental_constrained_log10:
    6236             :     Opcode = ISD::STRICT_FLOG10;
    6237           4 :     break;
    6238           4 :   case Intrinsic::experimental_constrained_log2:
    6239             :     Opcode = ISD::STRICT_FLOG2;
    6240           4 :     break;
    6241           4 :   case Intrinsic::experimental_constrained_rint:
    6242             :     Opcode = ISD::STRICT_FRINT;
    6243           4 :     break;
    6244           4 :   case Intrinsic::experimental_constrained_nearbyint:
    6245             :     Opcode = ISD::STRICT_FNEARBYINT;
    6246           4 :     break;
    6247             :   }
    6248          76 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6249          76 :   SDValue Chain = getRoot();
    6250             :   SmallVector<EVT, 4> ValueVTs;
    6251         152 :   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
    6252          76 :   ValueVTs.push_back(MVT::Other); // Out chain
    6253             : 
    6254         152 :   SDVTList VTs = DAG.getVTList(ValueVTs);
    6255             :   SDValue Result;
    6256          76 :   if (FPI.isUnaryOp())
    6257          80 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6258         120 :                          { Chain, getValue(FPI.getArgOperand(0)) });
    6259          36 :   else if (FPI.isTernaryOp())
    6260          16 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6261           8 :                          { Chain, getValue(FPI.getArgOperand(0)),
    6262             :                                   getValue(FPI.getArgOperand(1)),
    6263          40 :                                   getValue(FPI.getArgOperand(2)) });
    6264             :   else
    6265          56 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6266          28 :                          { Chain, getValue(FPI.getArgOperand(0)),
    6267         112 :                            getValue(FPI.getArgOperand(1))  });
    6268             : 
    6269             :   assert(Result.getNode()->getNumValues() == 2);
    6270          76 :   SDValue OutChain = Result.getValue(1);
    6271          76 :   DAG.setRoot(OutChain);
    6272             :   SDValue FPResult = Result.getValue(0);
    6273          76 :   setValue(&FPI, FPResult);
    6274          76 : }
    6275             : 
    6276             : std::pair<SDValue, SDValue>
    6277      172972 : SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
    6278             :                                     const BasicBlock *EHPadBB) {
    6279      172972 :   MachineFunction &MF = DAG.getMachineFunction();
    6280      172972 :   MachineModuleInfo &MMI = MF.getMMI();
    6281             :   MCSymbol *BeginLabel = nullptr;
    6282             : 
    6283      172972 :   if (EHPadBB) {
    6284             :     // Insert a label before the invoke call to mark the try range.  This can be
    6285             :     // used to detect deletion of the invoke via the MachineModuleInfo.
    6286       42740 :     BeginLabel = MMI.getContext().createTempSymbol();
    6287             : 
    6288             :     // For SjLj, keep track of which landing pads go with which invokes
    6289             :     // so as to maintain the ordering of pads in the LSDA.
    6290       42740 :     unsigned CallSiteIndex = MMI.getCurrentCallSite();
    6291       42740 :     if (CallSiteIndex) {
    6292             :       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
    6293         525 :       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
    6294             : 
    6295             :       // Now that the call site is handled, stop tracking it.
    6296             :       MMI.setCurrentCallSite(0);
    6297             :     }
    6298             : 
    6299             :     // Both PendingLoads and PendingExports must be flushed here;
    6300             :     // this call might not return.
    6301       42740 :     (void)getRoot();
    6302      128220 :     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
    6303             : 
    6304       42740 :     CLI.setChain(getRoot());
    6305             :   }
    6306      172972 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6307      172972 :   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    6308             : 
    6309             :   assert((CLI.IsTailCall || Result.second.getNode()) &&
    6310             :          "Non-null chain expected with non-tail call!");
    6311             :   assert((Result.second.getNode() || !Result.first.getNode()) &&
    6312             :          "Null value expected with tail call!");
    6313             : 
    6314      172966 :   if (!Result.second.getNode()) {
    6315             :     // As a special case, a null chain means that a tail call has been emitted
    6316             :     // and the DAG root is already updated.
    6317        2743 :     HasTailCall = true;
    6318             : 
    6319             :     // Since there's no actual continuation from this block, nothing can be
    6320             :     // relying on us setting vregs for them.
    6321             :     PendingExports.clear();
    6322             :   } else {
    6323      170223 :     DAG.setRoot(Result.second);
    6324             :   }
    6325             : 
    6326      172966 :   if (EHPadBB) {
    6327             :     // Insert a label at the end of the invoke call to mark the try range.  This
    6328             :     // can be used to detect deletion of the invoke via the MachineModuleInfo.
    6329       42740 :     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
    6330      128220 :     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
    6331             : 
    6332             :     // Inform MachineModuleInfo of range.
    6333       42740 :     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    6334             :     // There is a platform (e.g. wasm) that uses funclet style IR but does not
    6335             :     // actually use outlined funclets and their LSDA info style.
    6336       42740 :     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
    6337             :       assert(CLI.CS);
    6338         144 :       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
    6339         144 :       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
    6340             :                                 BeginLabel, EndLabel);
    6341             :     } else {
    6342       85192 :       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
    6343             :     }
    6344             :   }
    6345             : 
    6346      172966 :   return Result;
    6347             : }
    6348             : 
    6349      172756 : void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
    6350             :                                       bool isTailCall,
    6351             :                                       const BasicBlock *EHPadBB) {
    6352      172756 :   auto &DL = DAG.getDataLayout();
    6353             :   FunctionType *FTy = CS.getFunctionType();
    6354             :   Type *RetTy = CS.getType();
    6355             : 
    6356             :   TargetLowering::ArgListTy Args;
    6357      172756 :   Args.reserve(CS.arg_size());
    6358             : 
    6359             :   const Value *SwiftErrorVal = nullptr;
    6360      172756 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6361             : 
    6362             :   // We can't tail call inside a function with a swifterror argument. Lowering
    6363             :   // does not support this yet. It would have to move into the swifterror
    6364             :   // register before the call.
    6365      172756 :   auto *Caller = CS.getInstruction()->getParent()->getParent();
    6366      274628 :   if (TLI.supportSwiftError() &&
    6367      101983 :       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
    6368             :     isTailCall = false;
    6369             : 
    6370      488273 :   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
    6371      488273 :        i != e; ++i) {
    6372             :     TargetLowering::ArgListEntry Entry;
    6373      315517 :     const Value *V = *i;
    6374             : 
    6375             :     // Skip empty types
    6376      315517 :     if (V->getType()->isEmptyTy())
    6377           6 :       continue;
    6378             : 
    6379      315511 :     SDValue ArgNode = getValue(V);
    6380      315511 :     Entry.Node = ArgNode; Entry.Ty = V->getType();
    6381             : 
    6382      631022 :     Entry.setAttributes(&CS, i - CS.arg_begin());
    6383             : 
    6384             :     // Use swifterror virtual register as input to the call.
    6385      315511 :     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
    6386             :       SwiftErrorVal = V;
    6387             :       // We find the virtual register for the actual swifterror argument.
    6388             :       // Instead of using the Value, we use the virtual register instead.
    6389         330 :       Entry.Node = DAG.getRegister(FuncInfo
    6390         110 :                                        .getOrCreateSwiftErrorVRegUseAt(
    6391         110 :                                            CS.getInstruction(), FuncInfo.MBB, V)
    6392             :                                        .first,
    6393         220 :                                    EVT(TLI.getPointerTy(DL)));
    6394             :     }
    6395             : 
    6396      315511 :     Args.push_back(Entry);
    6397             : 
    6398             :     // If we have an explicit sret argument that is an Instruction, (i.e., it
    6399             :     // might point to function-local memory), we can't meaningfully tail-call.
    6400      322244 :     if (Entry.IsSRet && isa<Instruction>(V))
    6401             :       isTailCall = false;
    6402             :   }
    6403             : 
    6404             :   // Check if target-independent constraints permit a tail call here.
    6405             :   // Target-dependent constraints are checked within TLI->LowerCallTo.
    6406      172756 :   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
    6407             :     isTailCall = false;
    6408             : 
    6409             :   // Disable tail calls if there is an swifterror argument. Targets have not
    6410             :   // been updated to support tail calls.
    6411      172756 :   if (TLI.supportSwiftError() && SwiftErrorVal)
    6412             :     isTailCall = false;
    6413             : 
    6414      345506 :   TargetLowering::CallLoweringInfo CLI(DAG);
    6415      345512 :   CLI.setDebugLoc(getCurSDLoc())
    6416      172756 :       .setChain(getRoot())
    6417      172756 :       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
    6418             :       .setTailCall(isTailCall)
    6419      172756 :       .setConvergent(CS.isConvergent());
    6420      172756 :   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
    6421             : 
    6422      172750 :   if (Result.first.getNode()) {
    6423             :     const Instruction *Inst = CS.getInstruction();
    6424       37489 :     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
    6425             :     setValue(Inst, Result.first);
    6426             :   }
    6427             : 
    6428             :   // The last element of CLI.InVals has the SDValue for swifterror return.
    6429             :   // Here we copy it to a virtual register and update SwiftErrorMap for
    6430             :   // book-keeping.
    6431      172750 :   if (SwiftErrorVal && TLI.supportSwiftError()) {
    6432             :     // Get the last element of InVals.
    6433         110 :     SDValue Src = CLI.InVals.back();
    6434             :     unsigned VReg; bool CreatedVReg;
    6435             :     std::tie(VReg, CreatedVReg) =
    6436         330 :         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
    6437         110 :     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
    6438             :     // We update the virtual register for the actual swifterror argument.
    6439         110 :     if (CreatedVReg)
    6440          67 :       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
    6441         110 :     DAG.setRoot(CopyNode);
    6442             :   }
    6443      172750 : }
    6444             : 
    6445          56 : static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
    6446             :                              SelectionDAGBuilder &Builder) {
    6447             :   // Check to see if this load can be trivially constant folded, e.g. if the
    6448             :   // input is from a string literal.
    6449             :   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
    6450             :     // Cast pointer to the type we really want to load.
    6451             :     Type *LoadTy =
    6452          14 :         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
    6453          14 :     if (LoadVT.isVector())
    6454           4 :       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
    6455             : 
    6456          14 :     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
    6457             :                                          PointerType::getUnqual(LoadTy));
    6458             : 
    6459          14 :     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
    6460          14 :             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
    6461          14 :       return Builder.getValue(LoadCst);
    6462             :   }
    6463             : 
    6464             :   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
    6465             :   // still constant memory, the input chain can be the entry node.
    6466          42 :   SDValue Root;
    6467             :   bool ConstantMemory = false;
    6468             : 
    6469             :   // Do not serialize (non-volatile) loads of constant memory with anything.
    6470          84 :   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
    6471           0 :     Root = Builder.DAG.getEntryNode();
    6472             :     ConstantMemory = true;
    6473             :   } else {
    6474             :     // Do not serialize non-volatile loads against each other.
    6475          42 :     Root = Builder.DAG.getRoot();
    6476             :   }
    6477             : 
    6478          42 :   SDValue Ptr = Builder.getValue(PtrVal);
    6479         126 :   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
    6480             :                                         Ptr, MachinePointerInfo(PtrVal),
    6481          84 :                                         /* Alignment = */ 1);
    6482             : 
    6483          42 :   if (!ConstantMemory)
    6484          42 :     Builder.PendingLoads.push_back(LoadVal.getValue(1));
    6485          42 :   return LoadVal;
    6486             : }
    6487             : 
    6488             : /// Record the value for an instruction that produces an integer result,
    6489             : /// converting the type where necessary.
    6490          46 : void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
    6491             :                                                   SDValue Value,
    6492             :                                                   bool IsSigned) {
    6493          46 :   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    6494          92 :                                                     I.getType(), true);
    6495          46 :   if (IsSigned)
    6496          48 :     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
    6497             :   else
    6498          90 :     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
    6499          46 :   setValue(&I, Value);
    6500          46 : }
    6501             : 
    6502             : /// See if we can lower a memcmp call into an optimized form. If so, return
    6503             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6504             : /// normal call.
    6505             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6506             : /// correct prototype.
    6507         270 : bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
    6508         810 :   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
    6509             :   const Value *Size = I.getArgOperand(2);
    6510             :   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
    6511         224 :   if (CSize && CSize->getZExtValue() == 0) {
    6512          13 :     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    6513          26 :                                                           I.getType(), true);
    6514          39 :     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
    6515             :     return true;
    6516             :   }
    6517             : 
    6518         257 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6519             :   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
    6520         771 :       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
    6521        1028 :       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
    6522         257 :   if (Res.first.getNode()) {
    6523          12 :     processIntegerCallValue(I, Res.first, true);
    6524          12 :     PendingLoads.push_back(Res.second);
    6525          12 :     return true;
    6526             :   }
    6527             : 
    6528             :   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
    6529             :   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
    6530         245 :   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
    6531             :     return false;
    6532             : 
    6533             :   // If the target has a fast compare for the given size, it will return a
    6534             :   // preferred load type for that size. Require that the load VT is legal and
    6535             :   // that the target supports unaligned loads of that type. Otherwise, return
    6536             :   // INVALID.
    6537          36 :   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
    6538          36 :     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6539          36 :     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
    6540          36 :     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
    6541             :       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
    6542             :       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
    6543             :       // TODO: Check alignment of src and dest ptrs.
    6544          12 :       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
    6545          12 :       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
    6546          12 :       if (!TLI.isTypeLegal(LVT) ||
    6547          48 :           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
    6548          36 :           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
    6549             :         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
    6550             :     }
    6551             : 
    6552          36 :     return LVT;
    6553         111 :   };
    6554             : 
    6555             :   // This turns into unaligned loads. We only do this if the target natively
    6556             :   // supports the MVT we'll be loading or if it is small enough (<= 4) that
    6557             :   // we'll only produce a small number of byte loads.
    6558         111 :   MVT LoadVT;
    6559         111 :   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
    6560         111 :   switch (NumBitsToCompare) {
    6561             :   default:
    6562             :     return false;
    6563             :   case 16:
    6564           8 :     LoadVT = MVT::i16;
    6565           8 :     break;
    6566             :   case 32:
    6567           8 :     LoadVT = MVT::i32;
    6568           8 :     break;
    6569          36 :   case 64:
    6570             :   case 128:
    6571             :   case 256:
    6572          36 :     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
    6573          36 :     break;
    6574             :   }
    6575             : 
    6576          52 :   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
    6577             :     return false;
    6578             : 
    6579          28 :   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
    6580          28 :   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
    6581             : 
    6582             :   // Bitcast to a wide integer type if the loads are vectors.
    6583          28 :   if (LoadVT.isVector()) {
    6584           8 :     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
    6585           8 :     LoadL = DAG.getBitcast(CmpVT, LoadL);
    6586           8 :     LoadR = DAG.getBitcast(CmpVT, LoadR);
    6587             :   }
    6588             : 
    6589         112 :   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
    6590          28 :   processIntegerCallValue(I, Cmp, false);
    6591          28 :   return true;
    6592             : }
    6593             : 
    6594             : /// See if we can lower a memchr call into an optimized form. If so, return
    6595             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6596             : /// normal call.
    6597             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6598             : /// correct prototype.
    6599           7 : bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
    6600           7 :   const Value *Src = I.getArgOperand(0);
    6601             :   const Value *Char = I.getArgOperand(1);
    6602             :   const Value *Length = I.getArgOperand(2);
    6603             : 
    6604           7 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6605             :   std::pair<SDValue, SDValue> Res =
    6606          21 :     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
    6607             :                                 getValue(Src), getValue(Char), getValue(Length),
    6608          28 :                                 MachinePointerInfo(Src));
    6609           7 :   if (Res.first.getNode()) {
    6610           5 :     setValue(&I, Res.first);
    6611           5 :     PendingLoads.push_back(Res.second);
    6612           5 :     return true;
    6613             :   }
    6614             : 
    6615             :   return false;
    6616             : }
    6617             : 
    6618             : /// See if we can lower a mempcpy call into an optimized form. If so, return
    6619             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6620             : /// normal call.
    6621             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6622             : /// correct prototype.
    6623           2 : bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
    6624           4 :   SDValue Dst = getValue(I.getArgOperand(0));
    6625           2 :   SDValue Src = getValue(I.getArgOperand(1));
    6626           2 :   SDValue Size = getValue(I.getArgOperand(2));
    6627             : 
    6628           2 :   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
    6629           2 :   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
    6630           2 :   unsigned Align = std::min(DstAlign, SrcAlign);
    6631           2 :   if (Align == 0) // Alignment of one or both could not be inferred.
    6632             :     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
    6633             : 
    6634             :   bool isVol = false;
    6635           2 :   SDLoc sdl = getCurSDLoc();
    6636             : 
    6637             :   // In the mempcpy context we need to pass in a false value for isTailCall
    6638             :   // because the return pointer needs to be adjusted by the size of
    6639             :   // the copied memory.
    6640           2 :   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
    6641             :                              false, /*isTailCall=*/false,
    6642             :                              MachinePointerInfo(I.getArgOperand(0)),
    6643           2 :                              MachinePointerInfo(I.getArgOperand(1)));
    6644             :   assert(MC.getNode() != nullptr &&
    6645             :          "** memcpy should not be lowered as TailCall in mempcpy context **");
    6646           2 :   DAG.setRoot(MC);
    6647             : 
    6648             :   // Check if Size needs to be truncated or extended.
    6649           4 :   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
    6650             : 
    6651             :   // Adjust return pointer to point just past the last dst byte.
    6652           2 :   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
    6653           2 :                                     Dst, Size);
    6654           2 :   setValue(&I, DstPlusSize);
    6655           2 :   return true;
    6656             : }
    6657             : 
    6658             : /// See if we can lower a strcpy call into an optimized form.  If so, return
    6659             : /// true and lower it, otherwise return false and it will be lowered like a
    6660             : /// normal call.
    6661             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6662             : /// correct prototype.
    6663         151 : bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
    6664         151 :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6665             : 
    6666         151 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6667             :   std::pair<SDValue, SDValue> Res =
    6668         302 :     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
    6669             :                                 getValue(Arg0), getValue(Arg1),
    6670             :                                 MachinePointerInfo(Arg0),
    6671         604 :                                 MachinePointerInfo(Arg1), isStpcpy);
    6672         151 :   if (Res.first.getNode()) {
    6673           3 :     setValue(&I, Res.first);
    6674           3 :     DAG.setRoot(Res.second);
    6675           3 :     return true;
    6676             :   }
    6677             : 
    6678             :   return false;
    6679             : }
    6680             : 
    6681             : /// See if we can lower a strcmp call into an optimized form.  If so, return
    6682             : /// true and lower it, otherwise return false and it will be lowered like a
    6683             : /// normal call.
    6684             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6685             : /// correct prototype.
    6686          54 : bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
    6687          54 :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6688             : 
    6689          54 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6690             :   std::pair<SDValue, SDValue> Res =
    6691         162 :     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
    6692             :                                 getValue(Arg0), getValue(Arg1),
    6693             :                                 MachinePointerInfo(Arg0),
    6694         216 :                                 MachinePointerInfo(Arg1));
    6695          54 :   if (Res.first.getNode()) {
    6696           4 :     processIntegerCallValue(I, Res.first, true);
    6697           4 :     PendingLoads.push_back(Res.second);
    6698           4 :     return true;
    6699             :   }
    6700             : 
    6701             :   return false;
    6702             : }
    6703             : 
    6704             : /// See if we can lower a strlen call into an optimized form.  If so, return
    6705             : /// true and lower it, otherwise return false and it will be lowered like a
    6706             : /// normal call.
    6707             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6708             : /// correct prototype.
    6709         240 : bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
    6710         240 :   const Value *Arg0 = I.getArgOperand(0);
    6711             : 
    6712         240 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6713             :   std::pair<SDValue, SDValue> Res =
    6714         720 :     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
    6715         960 :                                 getValue(Arg0), MachinePointerInfo(Arg0));
    6716         240 :   if (Res.first.getNode()) {
    6717           1 :     processIntegerCallValue(I, Res.first, false);
    6718           1 :     PendingLoads.push_back(Res.second);
    6719           1 :     return true;
    6720             :   }
    6721             : 
    6722             :   return false;
    6723             : }
    6724             : 
    6725             : /// See if we can lower a strnlen call into an optimized form.  If so, return
    6726             : /// true and lower it, otherwise return false and it will be lowered like a
    6727             : /// normal call.
    6728             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6729             : /// correct prototype.
    6730           2 : bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
    6731           2 :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6732             : 
    6733           2 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6734             :   std::pair<SDValue, SDValue> Res =
    6735           6 :     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
    6736             :                                  getValue(Arg0), getValue(Arg1),
    6737           8 :                                  MachinePointerInfo(Arg0));
    6738           2 :   if (Res.first.getNode()) {
    6739           1 :     processIntegerCallValue(I, Res.first, false);
    6740           1 :     PendingLoads.push_back(Res.second);
    6741           1 :     return true;
    6742             :   }
    6743             : 
    6744             :   return false;
    6745             : }
    6746             : 
    6747             : /// See if we can lower a unary floating-point operation into an SDNode with
    6748             : /// the specified Opcode.  If so, return true and lower it, otherwise return
    6749             : /// false and it will be lowered like a normal call.
    6750             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6751             : /// correct prototype.
    6752         723 : bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
    6753             :                                               unsigned Opcode) {
    6754             :   // We already checked this call's prototype; verify it doesn't modify errno.
    6755         723 :   if (!I.onlyReadsMemory())
    6756             :     return false;
    6757             : 
    6758         539 :   SDValue Tmp = getValue(I.getArgOperand(0));
    6759        2695 :   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
    6760         539 :   return true;
    6761             : }
    6762             : 
    6763             : /// See if we can lower a binary floating-point operation into an SDNode with
    6764             : /// the specified Opcode. If so, return true and lower it. Otherwise return
    6765             : /// false, and it will be lowered like a normal call.
    6766             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6767             : /// correct prototype.
    6768          38 : bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
    6769             :                                                unsigned Opcode) {
    6770             :   // We already checked this call's prototype; verify it doesn't modify errno.
    6771          38 :   if (!I.onlyReadsMemory())
    6772             :     return false;
    6773             : 
    6774          38 :   SDValue Tmp0 = getValue(I.getArgOperand(0));
    6775          38 :   SDValue Tmp1 = getValue(I.getArgOperand(1));
    6776          76 :   EVT VT = Tmp0.getValueType();
    6777         152 :   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
    6778          38 :   return true;
    6779             : }
    6780             : 
    6781      335102 : void SelectionDAGBuilder::visitCall(const CallInst &I) {
    6782             :   // Handle inline assembly differently.
    6783      335102 :   if (isa<InlineAsm>(I.getCalledValue())) {
    6784       16466 :     visitInlineAsm(&I);
    6785      221539 :     return;
    6786             :   }
    6787             : 
    6788      318636 :   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
    6789      318636 :   computeUsesVAFloatArgument(I, MMI);
    6790             : 
    6791             :   const char *RenameFn = nullptr;
    6792             :   if (Function *F = I.getCalledFunction()) {
    6793      316373 :     if (F->isDeclaration()) {
    6794             :       // Is this an LLVM intrinsic or a target-specific intrinsic?
    6795      237402 :       unsigned IID = F->getIntrinsicID();
    6796      237402 :       if (!IID)
    6797       50047 :         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
    6798         814 :           IID = II->getIntrinsicID(F);
    6799             : 
    6800      237402 :       if (IID) {
    6801      187860 :         RenameFn = visitIntrinsicCall(I, IID);
    6802      187860 :         if (!RenameFn)
    6803      188607 :           return;
    6804             :       }
    6805             :     }
    6806             : 
    6807             :     // Check for well-known libc/libm calls.  If the function is internal, it
    6808             :     // can't be a library call.  Don't do the check if marked as nobuiltin for
    6809             :     // some reason or the call site requires strict floating point semantics.
    6810             :     LibFunc Func;
    6811      314013 :     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
    6812      269503 :         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
    6813        8216 :         LibInfo->hasOptimizedCodeGen(Func)) {
    6814        1595 :       switch (Func) {
    6815             :       default: break;
    6816         108 :       case LibFunc_copysign:
    6817             :       case LibFunc_copysignf:
    6818             :       case LibFunc_copysignl:
    6819             :         // We already checked this call's prototype; verify it doesn't modify
    6820             :         // errno.
    6821         108 :         if (I.onlyReadsMemory()) {
    6822         103 :           SDValue LHS = getValue(I.getArgOperand(0));
    6823         103 :           SDValue RHS = getValue(I.getArgOperand(1));
    6824         515 :           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
    6825             :                                    LHS.getValueType(), LHS, RHS));
    6826             :           return;
    6827           5 :         }
    6828             :         break;
    6829          77 :       case LibFunc_fabs:
    6830             :       case LibFunc_fabsf:
    6831             :       case LibFunc_fabsl:
    6832          77 :         if (visitUnaryFloatCall(I, ISD::FABS))
    6833             :           return;
    6834             :         break;
    6835          18 :       case LibFunc_fmin:
    6836             :       case LibFunc_fminf:
    6837             :       case LibFunc_fminl:
    6838          18 :         if (visitBinaryFloatCall(I, ISD::FMINNUM))
    6839             :           return;
    6840             :         break;
    6841          20 :       case LibFunc_fmax:
    6842             :       case LibFunc_fmaxf:
    6843             :       case LibFunc_fmaxl:
    6844          20 :         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
    6845             :           return;
    6846             :         break;
    6847         146 :       case LibFunc_sin:
    6848             :       case LibFunc_sinf:
    6849             :       case LibFunc_sinl:
    6850         146 :         if (visitUnaryFloatCall(I, ISD::FSIN))
    6851             :           return;
    6852             :         break;
    6853         112 :       case LibFunc_cos:
    6854             :       case LibFunc_cosf:
    6855             :       case LibFunc_cosl:
    6856         112 :         if (visitUnaryFloatCall(I, ISD::FCOS))
    6857             :           return;
    6858             :         break;
    6859         108 :       case LibFunc_sqrt:
    6860             :       case LibFunc_sqrtf:
    6861             :       case LibFunc_sqrtl:
    6862             :       case LibFunc_sqrt_finite:
    6863             :       case LibFunc_sqrtf_finite:
    6864             :       case LibFunc_sqrtl_finite:
    6865         108 :         if (visitUnaryFloatCall(I, ISD::FSQRT))
    6866             :           return;
    6867             :         break;
    6868          69 :       case LibFunc_floor:
    6869             :       case LibFunc_floorf:
    6870             :       case LibFunc_floorl:
    6871          69 :         if (visitUnaryFloatCall(I, ISD::FFLOOR))
    6872             :           return;
    6873             :         break;
    6874          25 :       case LibFunc_nearbyint:
    6875             :       case LibFunc_nearbyintf:
    6876             :       case LibFunc_nearbyintl:
    6877          25 :         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
    6878             :           return;
    6879             :         break;
    6880          56 :       case LibFunc_ceil:
    6881             :       case LibFunc_ceilf:
    6882             :       case LibFunc_ceill:
    6883          56 :         if (visitUnaryFloatCall(I, ISD::FCEIL))
    6884             :           return;
    6885             :         break;
    6886          25 :       case LibFunc_rint:
    6887             :       case LibFunc_rintf:
    6888             :       case LibFunc_rintl:
    6889          25 :         if (visitUnaryFloatCall(I, ISD::FRINT))
    6890             :           return;
    6891             :         break;
    6892          39 :       case LibFunc_round:
    6893             :       case LibFunc_roundf:
    6894             :       case LibFunc_roundl:
    6895          39 :         if (visitUnaryFloatCall(I, ISD::FROUND))
    6896             :           return;
    6897             :         break;
    6898          46 :       case LibFunc_trunc:
    6899             :       case LibFunc_truncf:
    6900             :       case LibFunc_truncl:
    6901          46 :         if (visitUnaryFloatCall(I, ISD::FTRUNC))
    6902             :           return;
    6903             :         break;
    6904          10 :       case LibFunc_log2:
    6905             :       case LibFunc_log2f:
    6906             :       case LibFunc_log2l:
    6907          10 :         if (visitUnaryFloatCall(I, ISD::FLOG2))
    6908             :           return;
    6909             :         break;
    6910          10 :       case LibFunc_exp2:
    6911             :       case LibFunc_exp2f:
    6912             :       case LibFunc_exp2l:
    6913          10 :         if (visitUnaryFloatCall(I, ISD::FEXP2))
    6914             :           return;
    6915             :         break;
    6916         270 :       case LibFunc_memcmp:
    6917         270 :         if (visitMemCmpCall(I))
    6918             :           return;
    6919             :         break;
    6920           2 :       case LibFunc_mempcpy:
    6921           2 :         if (visitMemPCpyCall(I))
    6922             :           return;
    6923             :         break;
    6924           7 :       case LibFunc_memchr:
    6925           7 :         if (visitMemChrCall(I))
    6926             :           return;
    6927             :         break;
    6928         150 :       case LibFunc_strcpy:
    6929         150 :         if (visitStrCpyCall(I, false))
    6930             :           return;
    6931             :         break;
    6932           1 :       case LibFunc_stpcpy:
    6933           1 :         if (visitStrCpyCall(I, true))
    6934             :           return;
    6935             :         break;
    6936          54 :       case LibFunc_strcmp:
    6937          54 :         if (visitStrCmpCall(I))
    6938             :           return;
    6939             :         break;
    6940         240 :       case LibFunc_strlen:
    6941         240 :         if (visitStrLenCall(I))
    6942             :           return;
    6943             :         break;
    6944           2 :       case LibFunc_strnlen:
    6945           2 :         if (visitStrNLenCall(I))
    6946             :           return;
    6947             :         break;
    6948             :       }
    6949             :     }
    6950             :   }
    6951             : 
    6952      130029 :   SDValue Callee;
    6953      130029 :   if (!RenameFn)
    6954      130027 :     Callee = getValue(I.getCalledValue());
    6955             :   else
    6956           4 :     Callee = DAG.getExternalSymbol(
    6957             :         RenameFn,
    6958           4 :         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
    6959             : 
    6960             :   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
    6961             :   // have to do anything here to lower funclet bundles.
    6962             :   assert(!I.hasOperandBundlesOtherThan(
    6963             :              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
    6964             :          "Cannot lower calls with arbitrary operand bundles!");
    6965             : 
    6966      130029 :   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
    6967           3 :     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
    6968             :   else
    6969             :     // Check if we can potentially perform a tail call. More detailed checking
    6970             :     // is be done within LowerCallTo, after more information about the call is
    6971             :     // known.
    6972      260052 :     LowerCallTo(&I, Callee, I.isTailCall());
    6973             : }
    6974             : 
    6975             : namespace {
    6976             : 
    6977             : /// AsmOperandInfo - This contains information for each constraint that we are
    6978             : /// lowering.
    6979      256567 : class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
    6980             : public:
    6981             :   /// CallOperand - If this is the result output operand or a clobber
    6982             :   /// this is null, otherwise it is the incoming operand to the CallInst.
    6983             :   /// This gets modified as the asm is processed.
    6984             :   SDValue CallOperand;
    6985             : 
    6986             :   /// AssignedRegs - If this is a register or register class operand, this
    6987             :   /// contains the set of register corresponding to the operand.
    6988             :   RegsForValue AssignedRegs;
    6989             : 
    6990       66781 :   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
    6991       66781 :     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
    6992       66781 :   }
    6993             : 
    6994             :   /// Whether or not this operand accesses memory
    6995       62656 :   bool hasMemory(const TargetLowering &TLI) const {
    6996             :     // Indirect operand accesses access memory.
    6997       62656 :     if (isIndirect)
    6998             :       return true;
    6999             : 
    7000       60204 :     for (const auto &Code : Codes)
    7001      210984 :       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
    7002             :         return true;
    7003             : 
    7004             :     return false;
    7005             :   }
    7006             : 
    7007             :   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
    7008             :   /// corresponds to.  If there is no Value* for this operand, it returns
    7009             :   /// MVT::Other.
    7010       11214 :   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
    7011             :                            const DataLayout &DL) const {
    7012       11214 :     if (!CallOperandVal) return MVT::Other;
    7013             : 
    7014       11214 :     if (isa<BasicBlock>(CallOperandVal))
    7015           2 :       return TLI.getPointerTy(DL);
    7016             : 
    7017       11212 :     llvm::Type *OpTy = CallOperandVal->getType();
    7018             : 
    7019             :     // FIXME: code duplicated from TargetLowering::ParseConstraints().
    7020             :     // If this is an indirect operand, the operand is a pointer to the
    7021             :     // accessed type.
    7022       11212 :     if (isIndirect) {
    7023             :       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
    7024             :       if (!PtrTy)
    7025           0 :         report_fatal_error("Indirect operand for inline asm not a pointer!");
    7026        3046 :       OpTy = PtrTy->getElementType();
    7027             :     }
    7028             : 
    7029             :     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
    7030             :     if (StructType *STy = dyn_cast<StructType>(OpTy))
    7031          13 :       if (STy->getNumElements() == 1)
    7032           8 :         OpTy = STy->getElementType(0);
    7033             : 
    7034             :     // If OpTy is not a single value, it may be a struct/union that we
    7035             :     // can tile with integers.
    7036       11212 :     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
    7037          16 :       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
    7038          16 :       switch (BitSize) {
    7039             :       default: break;
    7040           8 :       case 1:
    7041             :       case 8:
    7042             :       case 16:
    7043             :       case 32:
    7044             :       case 64:
    7045             :       case 128:
    7046           8 :         OpTy = IntegerType::get(Context, BitSize);
    7047             :         break;
    7048             :       }
    7049             :     }
    7050             : 
    7051       11212 :     return TLI.getValueType(DL, OpTy, true);
    7052             :   }
    7053             : };
    7054             : 
    7055             : using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
    7056             : 
    7057             : } // end anonymous namespace
    7058             : 
    7059             : /// Make sure that the output operand \p OpInfo and its corresponding input
    7060             : /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
    7061             : /// out).
    7062         281 : static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
    7063             :                                SDISelAsmOperandInfo &MatchingOpInfo,
    7064             :                                SelectionDAG &DAG) {
    7065         281 :   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
    7066         268 :     return;
    7067             : 
    7068          26 :   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
    7069          13 :   const auto &TLI = DAG.getTargetLoweringInfo();
    7070             : 
    7071             :   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
    7072             :       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
    7073          26 :                                        OpInfo.ConstraintVT);
    7074             :   std::pair<unsigned, const TargetRegisterClass *> InputRC =
    7075             :       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
    7076          26 :                                        MatchingOpInfo.ConstraintVT);
    7077             :   if ((OpInfo.ConstraintVT.isInteger() !=
    7078          26 :        MatchingOpInfo.ConstraintVT.isInteger()) ||
    7079          13 :       (MatchRC.second != InputRC.second)) {
    7080             :     // FIXME: error out in a more elegant fashion
    7081           0 :     report_fatal_error("Unsupported asm: input constraint"
    7082             :                        " with a matching output constraint of"
    7083             :                        " incompatible type!");
    7084             :   }
    7085          13 :   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
    7086             : }
    7087             : 
    7088             : /// Get a direct memory input to behave well as an indirect operand.
    7089             : /// This may introduce stores, hence the need for a \p Chain.
    7090             : /// \return The (possibly updated) chain.
    7091         137 : static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
    7092             :                                         SDISelAsmOperandInfo &OpInfo,
    7093             :                                         SelectionDAG &DAG) {
    7094             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7095             : 
    7096             :   // If we don't have an indirect input, put it in the constpool if we can,
    7097             :   // otherwise spill it to a stack slot.
    7098             :   // TODO: This isn't quite right. We need to handle these according to
    7099             :   // the addressing mode that the constraint wants. Also, this may take
    7100             :   // an additional register for the computation and we don't want that
    7101             :   // either.
    7102             : 
    7103             :   // If the operand is a float, integer, or vector constant, spill to a
    7104             :   // constant pool entry to get its address.
    7105         137 :   const Value *OpVal = OpInfo.CallOperandVal;
    7106         133 :   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
    7107         264 :       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
    7108          10 :     OpInfo.CallOperand = DAG.getConstantPool(
    7109          20 :         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
    7110          10 :     return Chain;
    7111             :   }
    7112             : 
    7113             :   // Otherwise, create a stack slot and emit a store to it before the asm.
    7114         127 :   Type *Ty = OpVal->getType();
    7115         127 :   auto &DL = DAG.getDataLayout();
    7116         127 :   uint64_t TySize = DL.getTypeAllocSize(Ty);
    7117         127 :   unsigned Align = DL.getPrefTypeAlignment(Ty);
    7118         127 :   MachineFunction &MF = DAG.getMachineFunction();
    7119         127 :   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
    7120         254 :   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
    7121         127 :   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
    7122         254 :                        MachinePointerInfo::getFixedStack(MF, SSFI));
    7123         127 :   OpInfo.CallOperand = StackSlot;
    7124             : 
    7125         127 :   return Chain;
    7126             : }
    7127             : 
    7128             : /// GetRegistersForValue - Assign registers (virtual or physical) for the
    7129             : /// specified operand.  We prefer to assign virtual registers, to allow the
    7130             : /// register allocator to handle the assignment process.  However, if the asm
    7131             : /// uses features that we can't model on machineinstrs, we have SDISel do the
    7132             : /// allocation.  This produces generally horrible, but correct, code.
    7133             : ///
    7134             : ///   OpInfo describes the operand.
    7135       61348 : static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
    7136             :                                  const SDLoc &DL,
    7137             :                                  SDISelAsmOperandInfo &OpInfo) {
    7138       61348 :   LLVMContext &Context = *DAG.getContext();
    7139             : 
    7140       61348 :   MachineFunction &MF = DAG.getMachineFunction();
    7141             :   SmallVector<unsigned, 4> Regs;
    7142       61348 :   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
    7143             : 
    7144             :   // If this is a constraint for a single physreg, or a constraint for a
    7145             :   // register class, find it.
    7146             :   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
    7147             :       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
    7148      122696 :                                        OpInfo.ConstraintVT);
    7149             : 
    7150             :   unsigned NumRegs = 1;
    7151       61348 :   if (OpInfo.ConstraintVT != MVT::Other) {
    7152             :     // If this is a FP input in an integer register (or visa versa) insert a bit
    7153             :     // cast of the input value.  More generally, handle any case where the input
    7154             :     // value disagrees with the register class we plan to stick this in.
    7155       16420 :     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
    7156             :         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
    7157             :       // Try to convert to the first EVT that the reg class contains.  If the
    7158             :       // types are identical size, use a bitcast to convert (e.g. two differing
    7159             :       // vector types).
    7160         202 :       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
    7161         202 :       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
    7162          73 :         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
    7163          73 :                                          RegVT, OpInfo.CallOperand);
    7164          73 :         OpInfo.ConstraintVT = RegVT;
    7165         249 :       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
    7166             :         // If the input is a FP value and we want it in FP registers, do a
    7167             :         // bitcast to the corresponding integer type.  This turns an f64 value
    7168             :         // into i64, which can be passed with two i32 values on a 32-bit
    7169             :         // machine.
    7170           1 :         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
    7171           1 :         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
    7172           1 :                                          RegVT, OpInfo.CallOperand);
    7173           1 :         OpInfo.ConstraintVT = RegVT;
    7174             :       }
    7175             :     }
    7176             : 
    7177       20398 :     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
    7178             :   }
    7179             : 
    7180             :   MVT RegVT;
    7181             :   EVT ValueVT = OpInfo.ConstraintVT;
    7182             : 
    7183             :   // If this is a constraint for a specific physical register, like {r17},
    7184             :   // assign it now.
    7185       61348 :   if (unsigned AssignedReg = PhysReg.first) {
    7186             :     const TargetRegisterClass *RC = PhysReg.second;
    7187       49876 :     if (OpInfo.ConstraintVT == MVT::Other)
    7188       48475 :       ValueVT = *TRI.legalclasstypes_begin(*RC);
    7189             : 
    7190             :     // Get the actual register value type.  This is important, because the user
    7191             :     // may have asked for (e.g.) the AX register in i32 type.  We need to
    7192             :     // remember that AX is actually i16 to get the right extension.
    7193       49876 :     RegVT = *TRI.legalclasstypes_begin(*RC);
    7194             : 
    7195             :     // This is a explicit reference to a physical register.
    7196       49876 :     Regs.push_back(AssignedReg);
    7197             : 
    7198             :     // If this is an expanded reference, add the rest of the regs to Regs.
    7199       49876 :     if (NumRegs != 1) {
    7200           8 :       TargetRegisterClass::iterator I = RC->begin();
    7201          30 :       for (; *I != AssignedReg; ++I)
    7202             :         assert(I != RC->end() && "Didn't find reg!");
    7203             : 
    7204             :       // Already added the first reg.
    7205           8 :       --NumRegs; ++I;
    7206          24 :       for (; NumRegs; --NumRegs, ++I) {
    7207             :         assert(I != RC->end() && "Ran out of registers to allocate!");
    7208           8 :         Regs.push_back(*I);
    7209             :       }
    7210             :     }
    7211             : 
    7212       49876 :     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
    7213       49876 :     return;
    7214             :   }
    7215             : 
    7216             :   // Otherwise, if this was a reference to an LLVM register class, create vregs
    7217             :   // for this reference.
    7218       11472 :   if (const TargetRegisterClass *RC = PhysReg.second) {
    7219        8748 :     RegVT = *TRI.legalclasstypes_begin(*RC);
    7220        8748 :     if (OpInfo.ConstraintVT == MVT::Other)
    7221           1 :       ValueVT = RegVT;
    7222             : 
    7223             :     // Create the appropriate number of virtual registers.
    7224        8748 :     MachineRegisterInfo &RegInfo = MF.getRegInfo();
    7225       26510 :     for (; NumRegs; --NumRegs)
    7226        8881 :       Regs.push_back(RegInfo.createVirtualRegister(RC));
    7227             : 
    7228        8748 :     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
    7229        8748 :     return;
    7230             :   }
    7231             : 
    7232             :   // Otherwise, we couldn't allocate enough registers for this.
    7233             : }
    7234             : 
    7235             : static unsigned
    7236             : findMatchingInlineAsmOperand(unsigned OperandNo,
    7237             :                              const std::vector<SDValue> &AsmNodeOperands) {
    7238             :   // Scan until we find the definition we already emitted of this operand.
    7239             :   unsigned CurOp = InlineAsm::Op_FirstOperand;
    7240        5263 :   for (; OperandNo; --OperandNo) {
    7241             :     // Advance to the next operand.
    7242             :     unsigned OpFlag =
    7243        7485 :         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
    7244             :     assert((InlineAsm::isRegDefKind(OpFlag) ||
    7245             :             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
    7246             :             InlineAsm::isMemKind(OpFlag)) &&
    7247             :            "Skipped past definitions?");
    7248        2495 :     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
    7249             :   }
    7250             :   return CurOp;
    7251             : }
    7252             : 
    7253             : /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
    7254             : /// \return true if it has succeeded, false otherwise
    7255         272 : static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
    7256             :                               MVT RegVT, SelectionDAG &DAG) {
    7257         272 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7258         272 :   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
    7259         844 :   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
    7260         286 :     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
    7261         572 :       Regs.push_back(RegInfo.createVirtualRegister(RC));
    7262             :     else
    7263             :       return false;
    7264             :   }
    7265             :   return true;
    7266             : }
    7267             : 
    7268             : namespace {
    7269             : 
    7270             : class ExtraFlags {
    7271             :   unsigned Flags = 0;
    7272             : 
    7273             : public:
    7274       16467 :   explicit ExtraFlags(ImmutableCallSite CS) {
    7275             :     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    7276       16467 :     if (IA->hasSideEffects())
    7277       13995 :       Flags |= InlineAsm::Extra_HasSideEffects;
    7278       16467 :     if (IA->isAlignStack())
    7279          21 :       Flags |= InlineAsm::Extra_IsAlignStack;
    7280       16467 :     if (CS.isConvergent())
    7281           1 :       Flags |= InlineAsm::Extra_IsConvergent;
    7282       16467 :     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
    7283       16467 :   }
    7284             : 
    7285             :   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
    7286             :     // Ideally, we would only check against memory constraints.  However, the
    7287             :     // meaning of an Other constraint can be target-specific and we can't easily
    7288             :     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
    7289             :     // for Other constraints as well.
    7290       66781 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
    7291             :         OpInfo.ConstraintType == TargetLowering::C_Other) {
    7292        5118 :       if (OpInfo.Type == InlineAsm::isInput)
    7293        4426 :         Flags |= InlineAsm::Extra_MayLoad;
    7294         692 :       else if (OpInfo.Type == InlineAsm::isOutput)
    7295         187 :         Flags |= InlineAsm::Extra_MayStore;
    7296         505 :       else if (OpInfo.Type == InlineAsm::isClobber)
    7297         505 :         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
    7298             :     }
    7299             :   }
    7300             : 
    7301       16467 :   unsigned get() const { return Flags; }
    7302             : };
    7303             : 
    7304             : } // end anonymous namespace
    7305             : 
    7306             : /// visitInlineAsm - Handle a call to an InlineAsm object.
    7307       16467 : void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
    7308             :   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    7309             : 
    7310             :   /// ConstraintOperands - Information about all of the constraints.
    7311       15616 :   SDISelAsmOperandInfoVector ConstraintOperands;
    7312             : 
    7313       16467 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7314             :   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
    7315       65017 :       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
    7316             : 
    7317             :   bool hasMemory = false;
    7318             : 
    7319             :   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
    7320       16467 :   ExtraFlags ExtraInfo(CS);
    7321             : 
    7322             :   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
    7323             :   unsigned ResNo = 0;   // ResNo - The result number of the next output.
    7324       99715 :   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
    7325      200343 :     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
    7326       66781 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
    7327             : 
    7328             :     MVT OpVT = MVT::Other;
    7329             : 
    7330             :     // Compute the value type for each operand.
    7331       66781 :     if (OpInfo.Type == InlineAsm::isInput ||
    7332        4140 :         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
    7333       22428 :       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    7334             : 
    7335             :       // Process the call argument. BasicBlocks are labels, currently appearing
    7336             :       // only in asm's.
    7337       11214 :       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
    7338           4 :         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
    7339             :       } else {
    7340       11212 :         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
    7341             :       }
    7342             : 
    7343             :       OpVT =
    7344             :           OpInfo
    7345       22428 :               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
    7346             :               .getSimpleVT();
    7347             :     }
    7348             : 
    7349       66781 :     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
    7350             :       // The return value of the call is this value.  As such, there is no
    7351             :       // corresponding argument.
    7352             :       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
    7353             :       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
    7354         569 :         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
    7355        1138 :                                       STy->getElementType(ResNo));
    7356             :       } else {
    7357             :         assert(ResNo == 0 && "Asm only has one result!");
    7358        3346 :         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
    7359             :       }
    7360        3915 :       ++ResNo;
    7361             :     }
    7362             : 
    7363       66781 :     OpInfo.ConstraintVT = OpVT;
    7364             : 
    7365       66781 :     if (!hasMemory)
    7366       62656 :       hasMemory = OpInfo.hasMemory(TLI);
    7367             : 
    7368             :     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
    7369             :     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
    7370      200343 :     auto TargetConstraint = TargetConstraints[i];
    7371             : 
    7372             :     // Compute the constraint code and ConstraintType to use.
    7373       66781 :     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
    7374             : 
    7375       66781 :     ExtraInfo.update(TargetConstraint);
    7376             :   }
    7377             : 
    7378       16467 :   SDValue Chain, Flag;
    7379             : 
    7380             :   // We won't need to flush pending loads if this asm doesn't touch
    7381             :   // memory and is nonvolatile.
    7382       16467 :   if (hasMemory || IA->hasSideEffects())
    7383       15373 :     Chain = getRoot();
    7384             :   else
    7385        1094 :     Chain = DAG.getRoot();
    7386             : 
    7387             :   // Second pass over the constraints: compute which constraint option to use
    7388             :   // and assign registers to constraints that want a specific physreg.
    7389       83248 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7390       66781 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7391             : 
    7392             :     // If this is an output operand with a matching input operand, look up the
    7393             :     // matching input. If their types mismatch, e.g. one is an integer, the
    7394             :     // other is floating point, or their sizes are different, flag it as an
    7395             :     // error.
    7396       66781 :     if (OpInfo.hasMatchingInput()) {
    7397         281 :       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    7398         281 :       patchMatchingInput(OpInfo, Input, DAG);
    7399             :     }
    7400             : 
    7401             :     // Compute the constraint code and ConstraintType to use.
    7402       66781 :     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
    7403             : 
    7404       70424 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
    7405        3643 :         OpInfo.Type == InlineAsm::isClobber)
    7406         505 :       continue;
    7407             : 
    7408             :     // If this is a memory input, and if the operand is not indirect, do what we
    7409             :     // need to provide an address for the memory input.
    7410       69414 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
    7411        3138 :         !OpInfo.isIndirect) {
    7412             :       assert((OpInfo.isMultipleAlternative ||
    7413             :               (OpInfo.Type == InlineAsm::isInput)) &&
    7414             :              "Can only indirectify direct input operands!");
    7415             : 
    7416             :       // Memory operands really want the address of the value.
    7417         411 :       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
    7418             : 
    7419             :       // There is no longer a Value* corresponding to this operand.
    7420         137 :       OpInfo.CallOperandVal = nullptr;
    7421             : 
    7422             :       // It is now an indirect operand.
    7423         137 :       OpInfo.isIndirect = true;
    7424             :     }
    7425             : 
    7426             :     // If this constraint is for a specific register, allocate it before
    7427             :     // anything else.
    7428       66276 :     if (OpInfo.ConstraintType == TargetLowering::C_Register)
    7429      157650 :       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
    7430             :   }
    7431             : 
    7432             :   // Third pass - Loop over all of the operands, assigning virtual or physregs
    7433             :   // to register class operands.
    7434       83248 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7435       66781 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7436             : 
    7437             :     // C_Register operands have already been allocated, Other/Memory don't need
    7438             :     // to be.
    7439       66781 :     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
    7440       26394 :       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
    7441             :   }
    7442             : 
    7443             :   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
    7444             :   std::vector<SDValue> AsmNodeOperands;
    7445       32934 :   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
    7446       49401 :   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
    7447       32934 :       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
    7448             : 
    7449             :   // If we have a !srcloc metadata node associated with it, we want to attach
    7450             :   // this to the ultimately generated inline asm machineinstr.  To do this, we
    7451             :   // pass in the third operand as this (potentially null) inline asm MDNode.
    7452             :   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
    7453       32934 :   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
    7454             : 
    7455             :   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
    7456             :   // bits as operand 3.
    7457       49401 :   AsmNodeOperands.push_back(DAG.getTargetConstant(
    7458       65868 :       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7459             : 
    7460             :   // Loop over all of the inputs, copying the operand values into the
    7461             :   // appropriate registers and processing the output regs.
    7462       15616 :   RegsForValue RetValRegs;
    7463             : 
    7464             :   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
    7465       15616 :   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
    7466             : 
    7467       83153 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7468       66755 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7469             : 
    7470       66755 :     switch (OpInfo.Type) {
    7471        4139 :     case InlineAsm::isOutput:
    7472        4139 :       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
    7473             :           OpInfo.ConstraintType != TargetLowering::C_Register) {
    7474             :         // Memory output, or 'other' output (e.g. 'X' constraint).
    7475             :         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
    7476             : 
    7477             :         unsigned ConstraintID =
    7478         374 :             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
    7479             :         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
    7480             :                "Failed to convert memory constraint code to constraint id.");
    7481             : 
    7482             :         // Add information to the INLINEASM node to know about this output.
    7483             :         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
    7484             :         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
    7485         748 :         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
    7486         187 :                                                         MVT::i32));
    7487         187 :         AsmNodeOperands.push_back(OpInfo.CallOperand);
    7488         187 :         break;
    7489        3952 :       }
    7490             : 
    7491             :       // Otherwise, this is a register or register class output.
    7492             : 
    7493             :       // Copy the output from the appropriate register.  Find a register that
    7494             :       // we can use.
    7495        3952 :       if (OpInfo.AssignedRegs.Regs.empty()) {
    7496          25 :         emitInlineAsmError(
    7497          25 :             CS, "couldn't allocate output register for constraint '" +
    7498          75 :                     Twine(OpInfo.ConstraintCode) + "'");
    7499         876 :         return;
    7500             :       }
    7501             : 
    7502             :       // If this is an indirect operand, store through the pointer after the
    7503             :       // asm.
    7504        3927 :       if (OpInfo.isIndirect) {
    7505          74 :         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
    7506             :                                                       OpInfo.CallOperandVal));
    7507             :       } else {
    7508             :         // This is the result value of the call.
    7509             :         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
    7510             :         // Concatenate this output onto the outputs list.
    7511        3890 :         RetValRegs.append(OpInfo.AssignedRegs);
    7512             :       }
    7513             : 
    7514             :       // Add information to the INLINEASM node to know that this register is
    7515             :       // set.
    7516             :       OpInfo.AssignedRegs
    7517        7854 :           .AddInlineAsmOperands(OpInfo.isEarlyClobber
    7518             :                                     ? InlineAsm::Kind_RegDefEarlyClobber
    7519             :                                     : InlineAsm::Kind_RegDef,
    7520        7854 :                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
    7521        3927 :       break;
    7522             : 
    7523       10965 :     case InlineAsm::isInput: {
    7524       10965 :       SDValue InOperandVal = OpInfo.CallOperand;
    7525             : 
    7526       10965 :       if (OpInfo.isMatchingInputConstraint()) {
    7527             :         // If this is required to match an output register we have already set,
    7528             :         // just use its register.
    7529         273 :         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
    7530             :                                                   AsmNodeOperands);
    7531             :         unsigned OpFlag =
    7532         819 :           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
    7533         273 :         if (InlineAsm::isRegDefKind(OpFlag) ||
    7534             :             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
    7535             :           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
    7536         273 :           if (OpInfo.isIndirect) {
    7537             :             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
    7538           1 :             emitInlineAsmError(CS, "inline asm not supported yet:"
    7539             :                                    " don't know how to handle tied "
    7540             :                                    "indirect register inputs");
    7541           2 :             return;
    7542             :           }
    7543             : 
    7544         544 :           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
    7545             :           SmallVector<unsigned, 4> Regs;
    7546             : 
    7547         544 :           if (!createVirtualRegs(Regs,
    7548             :                                  InlineAsm::getNumOperandRegisters(OpFlag),
    7549             :                                  RegVT, DAG)) {
    7550           0 :             emitInlineAsmError(CS, "inline asm error: This value type register "
    7551             :                                    "class is not natively supported!");
    7552             :             return;
    7553             :           }
    7554             : 
    7555         816 :           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
    7556             : 
    7557         272 :           SDLoc dl = getCurSDLoc();
    7558             :           // Use the produced MatchedRegs object to
    7559         272 :           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
    7560             :                                     CS.getInstruction());
    7561         272 :           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
    7562             :                                            true, OpInfo.getMatchedOperand(), dl,
    7563             :                                            DAG, AsmNodeOperands);
    7564             :           break;
    7565             :         }
    7566             : 
    7567             :         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
    7568             :         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
    7569             :                "Unexpected number of operands");
    7570             :         // Add information to the INLINEASM node to know about this input.
    7571             :         // See InlineAsm.h isUseOperandTiedToDef.
    7572             :         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
    7573           0 :         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
    7574             :                                                     OpInfo.getMatchedOperand());
    7575           0 :         AsmNodeOperands.push_back(DAG.getTargetConstant(
    7576           0 :             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7577           0 :         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
    7578           0 :         break;
    7579             :       }
    7580             : 
    7581             :       // Treat indirect 'X' constraint as memory.
    7582       12199 :       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
    7583        1507 :           OpInfo.isIndirect)
    7584           1 :         OpInfo.ConstraintType = TargetLowering::C_Memory;
    7585             : 
    7586       10692 :       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
    7587             :         std::vector<SDValue> Ops;
    7588        1506 :         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
    7589        1506 :                                           Ops, DAG);
    7590        1506 :         if (Ops.empty()) {
    7591          38 :           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
    7592          38 :                                      Twine(OpInfo.ConstraintCode) + "'");
    7593             :           return;
    7594             :         }
    7595             : 
    7596             :         // Add information to the INLINEASM node to know about this input.
    7597             :         unsigned ResOpType =
    7598        1487 :           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
    7599        4461 :         AsmNodeOperands.push_back(DAG.getTargetConstant(
    7600        5948 :             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7601        1487 :         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
    7602             :         break;
    7603             :       }
    7604             : 
    7605        9186 :       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
    7606             :         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
    7607             :         assert(InOperandVal.getValueType() ==
    7608             :                    TLI.getPointerTy(DAG.getDataLayout()) &&
    7609             :                "Memory operands expect pointer values");
    7610             : 
    7611             :         unsigned ConstraintID =
    7612        5910 :             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
    7613             :         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
    7614             :                "Failed to convert memory constraint code to constraint id.");
    7615             : 
    7616             :         // Add information to the INLINEASM node to know about this input.
    7617             :         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
    7618             :         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
    7619        8865 :         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
    7620        5910 :                                                         getCurSDLoc(),
    7621        2955 :                                                         MVT::i32));
    7622        2955 :         AsmNodeOperands.push_back(InOperandVal);
    7623        2955 :         break;
    7624             :       }
    7625             : 
    7626             :       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
    7627             :               OpInfo.ConstraintType == TargetLowering::C_Register) &&
    7628             :              "Unknown constraint type!");
    7629             : 
    7630             :       // TODO: Support this.
    7631        6231 :       if (OpInfo.isIndirect) {
    7632           2 :         emitInlineAsmError(
    7633             :             CS, "Don't know how to handle indirect register inputs yet "
    7634           2 :                 "for constraint '" +
    7635           6 :                     Twine(OpInfo.ConstraintCode) + "'");
    7636           2 :         return;
    7637             :       }
    7638             : 
    7639             :       // Copy the input into the appropriate registers.
    7640        6229 :       if (OpInfo.AssignedRegs.Regs.empty()) {
    7641          44 :         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
    7642          66 :                                    Twine(OpInfo.ConstraintCode) + "'");
    7643          22 :         return;
    7644             :       }
    7645             : 
    7646        6207 :       SDLoc dl = getCurSDLoc();
    7647             : 
    7648        6207 :       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
    7649             :                                         Chain, &Flag, CS.getInstruction());
    7650             : 
    7651        6207 :       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
    7652             :                                                dl, DAG, AsmNodeOperands);
    7653             :       break;
    7654             :     }
    7655       51651 :     case InlineAsm::isClobber:
    7656             :       // Add the clobbered value to the operand list, so that the register
    7657             :       // allocator is aware that the physreg got clobbered.
    7658       51651 :       if (!OpInfo.AssignedRegs.Regs.empty())
    7659       96948 :         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
    7660       96948 :                                                  false, 0, getCurSDLoc(), DAG,
    7661             :                                                  AsmNodeOperands);
    7662             :       break;
    7663             :     }
    7664             :   }
    7665             : 
    7666             :   // Finish up input operands.  Set the input chain and add the flag last.
    7667       16398 :   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
    7668       16398 :   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
    7669             : 
    7670       65592 :   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
    7671       32796 :                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
    7672       16398 :   Flag = Chain.getValue(1);
    7673             : 
    7674             :   // If this asm returns a register value, copy the result from that register
    7675             :   // and set it as the value of the call.
    7676       16398 :   if (!RetValRegs.Regs.empty()) {
    7677        6974 :     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
    7678        3487 :                                              Chain, &Flag, CS.getInstruction());
    7679             : 
    7680             :     // FIXME: Why don't we do this for inline asms with MRVs?
    7681        3487 :     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
    7682        6616 :       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
    7683             : 
    7684             :       // If any of the results of the inline asm is a vector, it may have the
    7685             :       // wrong width/num elts.  This can happen for register classes that can
    7686             :       // contain multiple different value types.  The preg or vreg allocated may
    7687             :       // not have the same VT as was expected.  Convert it to the right type
    7688             :       // with bit_convert.
    7689        3308 :       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
    7690           0 :         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
    7691           0 :                           ResultType, Val);
    7692             : 
    7693           0 :       } else if (ResultType != Val.getValueType() &&
    7694           0 :                  ResultType.isInteger() && Val.getValueType().isInteger()) {
    7695             :         // If a result value was tied to an input value, the computed result may
    7696             :         // have a wider width than the expected result.  Extract the relevant
    7697             :         // portion.
    7698           0 :         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
    7699             :       }
    7700             : 
    7701             :       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
    7702             :     }
    7703             : 
    7704             :     setValue(CS.getInstruction(), Val);
    7705             :     // Don't need to use this as a chain in this case.
    7706        4269 :     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
    7707         782 :       return;
    7708             :   }
    7709             : 
    7710             :   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
    7711             : 
    7712             :   // Process indirect outputs, first output all of the flagged copies out of
    7713             :   // physregs.
    7714       31266 :   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
    7715          68 :     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
    7716          34 :     const Value *Ptr = IndirectStoresToEmit[i].second;
    7717          68 :     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
    7718          34 :                                              Chain, &Flag, IA);
    7719          34 :     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
    7720             :   }
    7721             : 
    7722             :   // Emit the non-flagged stores from the physregs.
    7723             :   SmallVector<SDValue, 8> OutChains;
    7724       31266 :   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
    7725         136 :     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
    7726             :                                getValue(StoresToEmit[i].second),
    7727         170 :                                MachinePointerInfo(StoresToEmit[i].second));
    7728          34 :     OutChains.push_back(Val);
    7729             :   }
    7730             : 
    7731       15616 :   if (!OutChains.empty())
    7732         124 :     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
    7733             : 
    7734       15616 :   DAG.setRoot(Chain);
    7735             : }
    7736             : 
    7737          69 : void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
    7738             :                                              const Twine &Message) {
    7739          69 :   LLVMContext &Ctx = *DAG.getContext();
    7740          69 :   Ctx.emitError(CS.getInstruction(), Message);
    7741             : 
    7742             :   // Make sure we leave the DAG in a valid state
    7743          69 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7744         207 :   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
    7745          69 :   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
    7746          69 : }
    7747             : 
    7748         247 : void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
    7749         988 :   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
    7750             :                           MVT::Other, getRoot(),
    7751             :                           getValue(I.getArgOperand(0)),
    7752        1235 :                           DAG.getSrcValue(I.getArgOperand(0))));
    7753         247 : }
    7754             : 
    7755         181 : void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
    7756         181 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7757         181 :   const DataLayout &DL = DAG.getDataLayout();
    7758         362 :   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
    7759         362 :                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
    7760         181 :                            DAG.getSrcValue(I.getOperand(0)),
    7761        1086 :                            DL.getABITypeAlignment(I.getType()));
    7762         181 :   setValue(&I, V);
    7763         181 :   DAG.setRoot(V.getValue(1));
    7764         181 : }
    7765             : 
    7766         168 : void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
    7767         672 :   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
    7768             :                           MVT::Other, getRoot(),
    7769             :                           getValue(I.getArgOperand(0)),
    7770         840 :                           DAG.getSrcValue(I.getArgOperand(0))));
    7771         168 : }
    7772             : 
    7773          10 : void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
    7774          40 :   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
    7775             :                           MVT::Other, getRoot(),
    7776             :                           getValue(I.getArgOperand(0)),
    7777             :                           getValue(I.getArgOperand(1)),
    7778          10 :                           DAG.getSrcValue(I.getArgOperand(0)),
    7779          70 :                           DAG.getSrcValue(I.getArgOperand(1))));
    7780          10 : }
    7781             : 
    7782       55469 : SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
    7783             :                                                     const Instruction &I,
    7784             :                                                     SDValue Op) {
    7785             :   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
    7786       33416 :   if (!Range)
    7787       51978 :     return Op;
    7788             : 
    7789        6982 :   ConstantRange CR = getConstantRangeFromMetadata(*Range);
    7790        3491 :   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
    7791           0 :     return Op;
    7792             : 
    7793        3491 :   APInt Lo = CR.getUnsignedMin();
    7794        3491 :   if (!Lo.isMinValue())
    7795           1 :     return Op;
    7796             : 
    7797        3490 :   APInt Hi = CR.getUnsignedMax();
    7798             :   unsigned Bits = Hi.getActiveBits();
    7799             : 
    7800        3490 :   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
    7801             : 
    7802        3490 :   SDLoc SL = getCurSDLoc();
    7803             : 
    7804             :   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
    7805        6980 :                              DAG.getValueType(SmallVT));
    7806        3490 :   unsigned NumVals = Op.getNode()->getNumValues();
    7807        3490 :   if (NumVals == 1)
    7808        3486 :     return ZExt;
    7809             : 
    7810             :   SmallVector<SDValue, 4> Ops;
    7811             : 
    7812           4 :   Ops.push_back(ZExt);
    7813          20 :   for (unsigned I = 1; I != NumVals; ++I)
    7814           8 :     Ops.push_back(Op.getValue(I));
    7815             : 
    7816           4 :   return DAG.getMergeValues(Ops, SL);
    7817             : }
    7818             : 
    7819             : /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
    7820             : /// the call being lowered.
    7821             : ///
    7822             : /// This is a helper for lowering intrinsics that follow a target calling
    7823             : /// convention or require stack pointer adjustment. Only a subset of the
    7824             : /// intrinsic's operands need to participate in the calling convention.
    7825         216 : void SelectionDAGBuilder::populateCallLoweringInfo(
    7826             :     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
    7827             :     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
    7828             :     bool IsPatchPoint) {
    7829             :   TargetLowering::ArgListTy Args;
    7830         216 :   Args.reserve(NumArgs);
    7831             : 
    7832             :   // Populate the argument list.
    7833             :   // Attributes for args start at offset 1, after the return attribute.
    7834         413 :   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
    7835         413 :        ArgI != ArgE; ++ArgI) {
    7836         197 :     const Value *V = CS->getOperand(ArgI);
    7837             : 
    7838             :     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
    7839             : 
    7840             :     TargetLowering::ArgListEntry Entry;
    7841         197 :     Entry.Node = getValue(V);
    7842         197 :     Entry.Ty = V->getType();
    7843         197 :     Entry.setAttributes(&CS, ArgI);
    7844         197 :     Args.push_back(Entry);
    7845             :   }
    7846             : 
    7847         432 :   CLI.setDebugLoc(getCurSDLoc())
    7848         216 :       .setChain(getRoot())
    7849             :       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
    7850         216 :       .setDiscardResult(CS->use_empty())
    7851             :       .setIsPatchPoint(IsPatchPoint);
    7852         216 : }
    7853             : 
    7854             : /// Add a stack map intrinsic call's live variable operands to a stackmap
    7855             : /// or patchpoint target node's operand list.
    7856             : ///
    7857             : /// Constants are converted to TargetConstants purely as an optimization to
    7858             : /// avoid constant materialization and register allocation.
    7859             : ///
    7860             : /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
    7861             : /// generate addess computation nodes, and so ExpandISelPseudo can convert the
    7862             : /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
    7863             : /// address materialization and register allocation, but may also be required
    7864             : /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
    7865             : /// alloca in the entry block, then the runtime may assume that the alloca's
    7866             : /// StackMap location can be read immediately after compilation and that the
    7867             : /// location is valid at any point during execution (this is similar to the
    7868             : /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
    7869             : /// only available in a register, then the runtime would need to trap when
    7870             : /// execution reaches the StackMap in order to read the alloca's location.
    7871         286 : static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
    7872             :                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
    7873             :                                 SelectionDAGBuilder &Builder) {
    7874         671 :   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
    7875         385 :     SDValue OpVal = Builder.getValue(CS.getArgument(i));
    7876             :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
    7877         116 :       Ops.push_back(
    7878         174 :         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
    7879          58 :       Ops.push_back(
    7880         232 :         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
    7881             :     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
    7882          21 :       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
    7883          42 :       Ops.push_back(Builder.DAG.getTargetFrameIndex(
    7884          42 :           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
    7885             :     } else
    7886         306 :       Ops.push_back(OpVal);
    7887             :   }
    7888         286 : }
    7889             : 
    7890             : /// Lower llvm.experimental.stackmap directly to its target opcode.
    7891         140 : void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
    7892             :   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
    7893             :   //                                  [live variables...])
    7894             : 
    7895             :   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
    7896             : 
    7897         140 :   SDValue Chain, InFlag, Callee, NullPtr;
    7898             :   SmallVector<SDValue, 32> Ops;
    7899             : 
    7900         140 :   SDLoc DL = getCurSDLoc();
    7901         140 :   Callee = getValue(CI.getCalledValue());
    7902         140 :   NullPtr = DAG.getIntPtrConstant(0, DL, true);
    7903             : 
    7904             :   // The stackmap intrinsic only records the live variables (the arguemnts
    7905             :   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
    7906             :   // intrinsic, this won't be lowered to a function call. This means we don't
    7907             :   // have to worry about calling conventions and target specific lowering code.
    7908             :   // Instead we perform the call lowering right here.
    7909             :   //
    7910             :   // chain, flag = CALLSEQ_START(chain, 0, 0)
    7911             :   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
    7912             :   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
    7913             :   //
    7914         140 :   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
    7915         140 :   InFlag = Chain.getValue(1);
    7916             : 
    7917             :   // Add the <id> and <numBytes> constants.
    7918         280 :   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
    7919         280 :   Ops.push_back(DAG.getTargetConstant(
    7920         140 :                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
    7921         140 :   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
    7922         280 :   Ops.push_back(DAG.getTargetConstant(
    7923             :                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
    7924         140 :                   MVT::i32));
    7925             : 
    7926             :   // Push live variables for the stack map.
    7927         140 :   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
    7928             : 
    7929             :   // We are not pushing any register mask info here on the operands list,
    7930             :   // because the stackmap doesn't clobber anything.
    7931             : 
    7932             :   // Push the chain and the glue flag.
    7933         140 :   Ops.push_back(Chain);
    7934         140 :   Ops.push_back(InFlag);
    7935             : 
    7936             :   // Create the STACKMAP node.
    7937         280 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    7938         280 :   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
    7939         140 :   Chain = SDValue(SM, 0);
    7940         140 :   InFlag = Chain.getValue(1);
    7941             : 
    7942         140 :   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
    7943             : 
    7944             :   // Stackmaps don't generate values, so nothing goes into the NodeMap.
    7945             : 
    7946             :   // Set the root to the target-lowered call chain.
    7947         140 :   DAG.setRoot(Chain);
    7948             : 
    7949             :   // Inform the Frame Information that we have a stackmap in this function.
    7950         140 :   FuncInfo.MF->getFrameInfo().setHasStackMap();
    7951         140 : }
    7952             : 
    7953             : /// Lower llvm.experimental.patchpoint directly to its target opcode.
    7954         146 : void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
    7955             :                                           const BasicBlock *EHPadBB) {
    7956             :   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
    7957             :   //                                                 i32 <numBytes>,
    7958             :   //                                                 i8* <target>,
    7959             :   //                                                 i32 <numArgs>,
    7960             :   //                                                 [Args...],
    7961             :   //                                                 [live variables...])
    7962             : 
    7963             :   CallingConv::ID CC = CS.getCallingConv();
    7964         146 :   bool IsAnyRegCC = CC == CallingConv::AnyReg;
    7965         292 :   bool HasDef = !CS->getType()->isVoidTy();
    7966         146 :   SDLoc dl = getCurSDLoc();
    7967         292 :   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
    7968             : 
    7969             :   // Handle immediate and symbolic callees.
    7970             :   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
    7971         282 :     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
    7972         141 :                                    /*isTarget=*/true);
    7973             :   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
    7974          10 :     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
    7975           5 :                                          SDLoc(SymbolicCallee),
    7976          10 :                                          SymbolicCallee->getValueType(0));
    7977             : 
    7978             :   // Get the real number of arguments participating in the call <numArgs>
    7979         146 :   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
    7980         292 :   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
    7981             : 
    7982             :   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
    7983             :   // Intrinsics include all meta-operands up to but not including CC.
    7984             :   unsigned NumMetaOpers = PatchPointOpers::CCPos;
    7985             :   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
    7986             :          "Not enough arguments provided to the patchpoint intrinsic");
    7987             : 
    7988             :   // For AnyRegCC the arguments are lowered later on manually.
    7989         146 :   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
    7990             :   Type *ReturnTy =
    7991         146 :     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
    7992             : 
    7993         292 :   TargetLowering::CallLoweringInfo CLI(DAG);
    7994         146 :   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
    7995             :                            true);
    7996         146 :   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
    7997             : 
    7998         146 :   SDNode *CallEnd = Result.second.getNode();
    7999         146 :   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
    8000          34 :     CallEnd = CallEnd->getOperand(0).getNode();
    8001             : 
    8002             :   /// Get a call instruction from the call sequence chain.
    8003             :   /// Tail calls are not allowed.
    8004             :   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
    8005             :          "Expected a callseq node.");
    8006         146 :   SDNode *Call = CallEnd->getOperand(0).getNode();
    8007             :   bool HasGlue = Call->getGluedNode();
    8008             : 
    8009             :   // Replace the target specific call node with the patchable intrinsic.
    8010             :   SmallVector<SDValue, 8> Ops;
    8011             : 
    8012             :   // Add the <id> and <numBytes> constants.
    8013         146 :   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
    8014         292 :   Ops.push_back(DAG.getTargetConstant(
    8015         146 :                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
    8016         146 :   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
    8017         292 :   Ops.push_back(DAG.getTargetConstant(
    8018             :                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
    8019         146 :                   MVT::i32));
    8020             : 
    8021             :   // Add the callee.
    8022         146 :   Ops.push_back(Callee);
    8023             : 
    8024             :   // Adjust <numArgs> to account for any arguments that have been passed on the
    8025             :   // stack instead.
    8026             :   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
    8027         292 :   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
    8028         146 :   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
    8029         292 :   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
    8030             : 
    8031             :   // Add the calling convention
    8032         292 :   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
    8033             : 
    8034             :   // Add the arguments we omitted previously. The register allocator should
    8035             :   // place these in any free register.
    8036         146 :   if (IsAnyRegCC)
    8037         329 :     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
    8038         263 :       Ops.push_back(getValue(CS.getArgument(i)));
    8039             : 
    8040             :   // Push the arguments from the call instruction up to the register mask.
    8041         292 :   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
    8042         146 :   Ops.append(Call->op_begin() + 2, e);
    8043             : 
    8044             :   // Push live variables for the stack map.
    8045         146 :   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
    8046             : 
    8047             :   // Push the register mask info.
    8048         146 :   if (HasGlue)
    8049         116 :     Ops.push_back(*(Call->op_end()-2));
    8050             :   else
    8051         176 :     Ops.push_back(*(Call->op_end()-1));
    8052             : 
    8053             :   // Push the chain (this is originally the first operand of the call, but
    8054             :   // becomes now the last or second to last operand).
    8055         292 :   Ops.push_back(*(Call->op_begin()));
    8056             : 
    8057             :   // Push the glue flag (last operand).
    8058         146 :   if (HasGlue)
    8059         116 :     Ops.push_back(*(Call->op_end()-1));
    8060             : 
    8061             :   SDVTList NodeTys;
    8062         146 :   if (IsAnyRegCC && HasDef) {
    8063             :     // Create the return types based on the intrinsic definition
    8064          47 :     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    8065             :     SmallVector<EVT, 3> ValueVTs;
    8066          94 :     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
    8067             :     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
    8068             : 
    8069             :     // There is always a chain and a glue type at the end
    8070          47 :     ValueVTs.push_back(MVT::Other);
    8071          47 :     ValueVTs.push_back(MVT::Glue);
    8072          94 :     NodeTys = DAG.getVTList(ValueVTs);
    8073             :   } else
    8074         198 :     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    8075             : 
    8076             :   // Replace the target specific call node with a PATCHPOINT node.
    8077         292 :   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
    8078         146 :                                          dl, NodeTys, Ops);
    8079             : 
    8080             :   // Update the NodeMap.
    8081         146 :   if (HasDef) {
    8082          81 :     if (IsAnyRegCC)
    8083             :       setValue(CS.getInstruction(), SDValue(MN, 0));
    8084             :     else
    8085             :       setValue(CS.getInstruction(), Result.first);
    8086             :   }
    8087             : 
    8088             :   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
    8089             :   // call sequence. Furthermore the location of the chain and glue can change
    8090             :   // when the AnyReg calling convention is used and the intrinsic returns a
    8091             :   // value.
    8092         146 :   if (IsAnyRegCC && HasDef) {
    8093             :     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
    8094             :     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
    8095          47 :     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
    8096             :   } else
    8097          99 :     DAG.ReplaceAllUsesWith(Call, MN);
    8098         146 :   DAG.DeleteNode(Call);
    8099             : 
    8100             :   // Inform the Frame Information that we have a patchpoint in this function.
    8101         146 :   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
    8102         146 : }
    8103             : 
    8104          58 : void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
    8105             :                                             unsigned Intrinsic) {
    8106          58 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    8107         116 :   SDValue Op1 = getValue(I.getArgOperand(0));
    8108          58 :   SDValue Op2;
    8109          58 :   if (I.getNumArgOperands() > 1)
    8110           0 :     Op2 = getValue(I.getArgOperand(1));
    8111          58 :   SDLoc dl = getCurSDLoc();
    8112         116 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    8113             :   SDValue Res;
    8114             :   FastMathFlags FMF;
    8115          58 :   if (isa<FPMathOperator>(I))
    8116           4 :     FMF = I.getFastMathFlags();
    8117             : 
    8118          58 :   switch (Intrinsic) {
    8119             :   case Intrinsic::experimental_vector_reduce_fadd:
    8120           0 :     if (FMF.isFast())
    8121           0 :       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
    8122             :     else
    8123           0 :       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
    8124             :     break;
    8125             :   case Intrinsic::experimental_vector_reduce_fmul:
    8126           0 :     if (FMF.isFast())
    8127           0 :       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
    8128             :     else
    8129           0 :       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
    8130             :     break;
    8131          14 :   case Intrinsic::experimental_vector_reduce_add:
    8132          28 :     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
    8133          14 :     break;
    8134           0 :   case Intrinsic::experimental_vector_reduce_mul:
    8135           0 :     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
    8136           0 :     break;
    8137           0 :   case Intrinsic::experimental_vector_reduce_and:
    8138           0 :     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
    8139           0 :     break;
    8140           0 :   case Intrinsic::experimental_vector_reduce_or:
    8141           0 :     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
    8142           0 :     break;
    8143           0 :   case Intrinsic::experimental_vector_reduce_xor:
    8144           0 :     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
    8145           0 :     break;
    8146          10 :   case Intrinsic::experimental_vector_reduce_smax:
    8147          20 :     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
    8148          10 :     break;
    8149          10 :   case Intrinsic::experimental_vector_reduce_smin:
    8150          20 :     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
    8151          10 :     break;
    8152          10 :   case Intrinsic::experimental_vector_reduce_umax:
    8153          20 :     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
    8154          10 :     break;
    8155          10 :   case Intrinsic::experimental_vector_reduce_umin:
    8156          20 :     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
    8157          10 :     break;
    8158           2 :   case Intrinsic::experimental_vector_reduce_fmax:
    8159           4 :     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
    8160           2 :     break;
    8161           2 :   case Intrinsic::experimental_vector_reduce_fmin:
    8162           4 :     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
    8163           2 :     break;
    8164           0 :   default:
    8165           0 :     llvm_unreachable("Unhandled vector reduce intrinsic");
    8166             :   }
    8167          58 :   setValue(&I, Res);
    8168          58 : }
    8169             : 
    8170             : /// Returns an AttributeList representing the attributes applied to the return
    8171             : /// value of the given call.
    8172      181711 : static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
    8173             :   SmallVector<Attribute::AttrKind, 2> Attrs;
    8174      181711 :   if (CLI.RetSExt)
    8175        1047 :     Attrs.push_back(Attribute::SExt);
    8176      181711 :   if (CLI.RetZExt)
    8177       10385 :     Attrs.push_back(Attribute::ZExt);
    8178      181711 :   if (CLI.IsInReg)
    8179         231 :     Attrs.push_back(Attribute::InReg);
    8180             : 
    8181      181711 :   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
    8182      363422 :                             Attrs);
    8183             : }
    8184             : 
    8185             : /// TargetLowering::LowerCallTo - This is the default LowerCallTo
    8186             : /// implementation, which just calls LowerCall.
    8187             : /// FIXME: When all targets are
    8188             : /// migrated to using LowerCall, this hook should be integrated into SDISel.
    8189             : std::pair<SDValue, SDValue>
    8190      181711 : TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
    8191             :   // Handle the incoming return values from the call.
    8192             :   CLI.Ins.clear();
    8193      181711 :   Type *OrigRetTy = CLI.RetTy;
    8194             :   SmallVector<EVT, 4> RetTys;
    8195             :   SmallVector<uint64_t, 4> Offsets;
    8196      181711 :   auto &DL = CLI.DAG.getDataLayout();
    8197      181711 :   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
    8198             : 
    8199      181711 :   if (CLI.IsPostTypeLegalization) {
    8200             :     // If we are lowering a libcall after legalization, split the return type.
    8201             :     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
    8202             :     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
    8203        7971 :     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
    8204        2657 :       EVT RetVT = OldRetTys[i];
    8205        2657 :       uint64_t Offset = OldOffsets[i];
    8206        2657 :       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
    8207        2657 :       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
    8208        2657 :       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
    8209        2657 :       RetTys.append(NumRegs, RegisterVT);
    8210        7987 :       for (unsigned j = 0; j != NumRegs; ++j)
    8211        2665 :         Offsets.push_back(Offset + j * RegisterVTByteSZ);
    8212             :     }
    8213             :   }
    8214             : 
    8215             :   SmallVector<ISD::OutputArg, 4> Outs;
    8216      181711 :   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
    8217             : 
    8218             :   bool CanLowerReturn =
    8219      363422 :       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
    8220      545133 :                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
    8221             : 
    8222             :   SDValue DemoteStackSlot;
    8223             :   int DemoteStackIdx = -100;
    8224      181709 :   if (!CanLowerReturn) {
    8225             :     // FIXME: equivalent assert?
    8226             :     // assert(!CS.hasInAllocaArgument() &&
    8227             :     //        "sret demotion is incompatible with inalloca");
    8228         200 :     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
    8229         200 :     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
    8230         200 :     MachineFunction &MF = CLI.DAG.getMachineFunction();
    8231         200 :     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
    8232         200 :     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
    8233             : 
    8234         400 :     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
    8235             :     ArgListEntry Entry;
    8236         200 :     Entry.Node = DemoteStackSlot;
    8237         200 :     Entry.Ty = StackSlotPtrType;
    8238             :     Entry.IsSExt = false;
    8239             :     Entry.IsZExt = false;
    8240             :     Entry.IsInReg = false;
    8241         200 :     Entry.IsSRet = true;
    8242             :     Entry.IsNest = false;
    8243             :     Entry.IsByVal = false;
    8244             :     Entry.IsReturned = false;
    8245             :     Entry.IsSwiftSelf = false;
    8246             :     Entry.IsSwiftError = false;
    8247         200 :     Entry.Alignment = Align;
    8248         200 :     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
    8249         200 :     CLI.NumFixedArgs += 1;
    8250         200 :     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
    8251             : 
    8252             :     // sret demotion isn't compatible with tail-calls, since the sret argument
    8253             :     // points into the callers stack frame.
    8254         200 :     CLI.IsTailCall = false;
    8255             :   } else {
    8256      229130 :     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
    8257       95242 :       EVT VT = RetTys[I];
    8258             :       MVT RegisterVT =
    8259       47621 :           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8260             :       unsigned NumRegs =
    8261       47621 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8262      146773 :       for (unsigned i = 0; i != NumRegs; ++i) {
    8263             :         ISD::InputArg MyFlags;
    8264       49576 :         MyFlags.VT = RegisterVT;
    8265       49576 :         MyFlags.ArgVT = VT;
    8266       49576 :         MyFlags.Used = CLI.IsReturnValueUsed;
    8267       49576 :         if (CLI.RetSExt)
    8268             :           MyFlags.Flags.setSExt();
    8269       49576 :         if (CLI.RetZExt)
    8270             :           MyFlags.Flags.setZExt();
    8271       49576 :         if (CLI.IsInReg)
    8272             :           MyFlags.Flags.setInReg();
    8273       49576 :         CLI.Ins.push_back(MyFlags);
    8274             :       }
    8275             :     }
    8276             :   }
    8277             : 
    8278             :   // We push in swifterror return as the last element of CLI.Ins.
    8279             :   ArgListTy &Args = CLI.getArgs();
    8280      181709 :   if (supportSwiftError()) {
    8281      414262 :     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    8282      397140 :       if (Args[i].IsSwiftError) {
    8283             :         ISD::InputArg MyFlags;
    8284         110 :         MyFlags.VT = getPointerTy(DL);
    8285         110 :         MyFlags.ArgVT = EVT(getPointerTy(DL));
    8286             :         MyFlags.Flags.setSwiftError();
    8287         110 :         CLI.Ins.push_back(MyFlags);
    8288             :       }
    8289             :     }
    8290             :   }
    8291             : 
    8292             :   // Handle all of the outgoing arguments.
    8293             :   CLI.Outs.clear();
    8294             :   CLI.OutVals.clear();
    8295      694850 :   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    8296             :     SmallVector<EVT, 4> ValueVTs;
    8297      662864 :     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
    8298             :     // FIXME: Split arguments if CLI.IsPostTypeLegalization
    8299      662864 :     Type *FinalType = Args[i].Ty;
    8300      331432 :     if (Args[i].IsByVal)
    8301        1176 :       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
    8302      331432 :     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
    8303      662864 :         FinalType, CLI.CallConv, CLI.IsVarArg);
    8304      664281 :     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
    8305             :          ++Value) {
    8306      665698 :       EVT VT = ValueVTs[Value];
    8307      332849 :       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
    8308             :       SDValue Op = SDValue(Args[i].Node.getNode(),
    8309      665698 :                            Args[i].Node.getResNo() + Value);
    8310             :       ISD::ArgFlagsTy Flags;
    8311             : 
    8312             :       // Certain targets (such as MIPS), may have a different ABI alignment
    8313             :       // for a type depending on the context. Give the target a chance to
    8314             :       // specify the alignment it wants.
    8315      332849 :       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
    8316             : 
    8317      665698 :       if (Args[i].IsZExt)
    8318             :         Flags.setZExt();
    8319      332849 :       if (Args[i].IsSExt)
    8320             :         Flags.setSExt();
    8321      332849 :       if (Args[i].IsInReg) {
    8322             :         // If we are using vectorcall calling convention, a structure that is
    8323             :         // passed InReg - is surely an HVA
    8324         248 :         if (CLI.CallConv == CallingConv::X86_VectorCall &&
    8325             :             isa<StructType>(FinalType)) {
    8326             :           // The first value of a structure is marked
    8327           8 :           if (0 == Value)
    8328             :             Flags.setHvaStart();
    8329             :           Flags.setHva();
    8330             :         }
    8331             :         // Set InReg Flag
    8332             :         Flags.setInReg();
    8333             :       }
    8334      332849 :       if (Args[i].IsSRet)
    8335             :         Flags.setSRet();
    8336      332849 :       if (Args[i].IsSwiftSelf)
    8337             :         Flags.setSwiftSelf();
    8338      332849 :       if (Args[i].IsSwiftError)
    8339             :         Flags.setSwiftError();
    8340      332849 :       if (Args[i].IsByVal)
    8341             :         Flags.setByVal();
    8342      332849 :       if (Args[i].IsInAlloca) {
    8343             :         Flags.setInAlloca();
    8344             :         // Set the byval flag for CCAssignFn callbacks that don't know about
    8345             :         // inalloca.  This way we can know how many bytes we should've allocated
    8346             :         // and how many bytes a callee cleanup function will pop.  If we port
    8347             :         // inalloca to more targets, we'll have to add custom inalloca handling
    8348             :         // in the various CC lowering callbacks.
    8349             :         Flags.setByVal();
    8350             :       }
    8351      332849 :       if (Args[i].IsByVal || Args[i].IsInAlloca) {
    8352        1198 :         PointerType *Ty = cast<PointerType>(Args[i].Ty);
    8353        1198 :         Type *ElementTy = Ty->getElementType();
    8354        1198 :         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
    8355             :         // For ByVal, alignment should come from FE.  BE will guess if this
    8356             :         // info is not there but there are cases it cannot get right.
    8357             :         unsigned FrameAlign;
    8358        2396 :         if (Args[i].Alignment)
    8359         948 :           FrameAlign = Args[i].Alignment;
    8360             :         else
    8361         250 :           FrameAlign = getByValTypeAlignment(ElementTy, DL);
    8362             :         Flags.setByValAlign(FrameAlign);
    8363             :       }
    8364      665698 :       if (Args[i].IsNest)
    8365             :         Flags.setNest();
    8366      332849 :       if (NeedsRegBlock)
    8367             :         Flags.setInConsecutiveRegs();
    8368             :       Flags.setOrigAlign(OriginalAlignment);
    8369             : 
    8370      332849 :       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8371             :       unsigned NumParts =
    8372      332849 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8373      665698 :       SmallVector<SDValue, 4> Parts(NumParts);
    8374             :       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
    8375             : 
    8376      665698 :       if (Args[i].IsSExt)
    8377             :         ExtendKind = ISD::SIGN_EXTEND;
    8378      331048 :       else if (Args[i].IsZExt)
    8379             :         ExtendKind = ISD::ZERO_EXTEND;
    8380             : 
    8381             :       // Conservatively only handle 'returned' on non-vectors that can be lowered,
    8382             :       // for now.
    8383      333151 :       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
    8384             :           CanLowerReturn) {
    8385             :         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
    8386             :                "unexpected use of 'returned'");
    8387             :         // Before passing 'returned' to the target lowering code, ensure that
    8388             :         // either the register MVT and the actual EVT are the same size or that
    8389             :         // the return value and argument are extended in the same way; in these
    8390             :         // cases it's safe to pass the argument register value unchanged as the
    8391             :         // return register value (although it's at the target's option whether
    8392             :         // to do so)
    8393             :         // TODO: allow code generation to take advantage of partially preserved
    8394             :         // registers rather than clobbering the entire register when the
    8395             :         // parameter extension method is not compatible with the return
    8396             :         // extension method
    8397         150 :         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
    8398          24 :             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
    8399          12 :              CLI.RetZExt == Args[i].IsZExt))
    8400             :           Flags.setReturned();
    8401             :       }
    8402             : 
    8403      332849 :       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
    8404             :                      CLI.CS.getInstruction(), ExtendKind, true);
    8405             : 
    8406     1011335 :       for (unsigned j = 0; j != NumParts; ++j) {
    8407             :         // if it isn't first piece, alignment must be 1
    8408             :         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
    8409      339243 :                                i < CLI.NumFixedArgs,
    8410     2035458 :                                i, j*Parts[j].getValueType().getStoreSize());
    8411      339243 :         if (NumParts > 1 && j == 0)
    8412             :           MyFlags.Flags.setSplit();
    8413      333956 :         else if (j != 0) {
    8414             :           MyFlags.Flags.setOrigAlign(1);
    8415        6394 :           if (j == NumParts - 1)
    8416             :             MyFlags.Flags.setSplitEnd();
    8417             :         }
    8418             : 
    8419      339243 :         CLI.Outs.push_back(MyFlags);
    8420      678486 :         CLI.OutVals.push_back(Parts[j]);
    8421             :       }
    8422             : 
    8423      332849 :       if (NeedsRegBlock && Value == NumValues - 1)
    8424         636 :         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
    8425             :     }
    8426             :   }
    8427             : 
    8428             :   SmallVector<SDValue, 4> InVals;
    8429      181709 :   CLI.Chain = LowerCall(CLI, InVals);
    8430             : 
    8431             :   // Update CLI.InVals to use outside of this function.
    8432             :   CLI.InVals = InVals;
    8433             : 
    8434             :   // Verify that the target's LowerCall behaved as expected.
    8435             :   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
    8436             :          "LowerCall didn't return a valid chain!");
    8437             :   assert((!CLI.IsTailCall || InVals.empty()) &&
    8438             :          "LowerCall emitted a return value for a tail call!");
    8439             :   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
    8440             :          "LowerCall didn't emit the correct number of values!");
    8441             : 
    8442             :   // For a tail call, the return value is merely live-out and there aren't
    8443             :   // any nodes in the DAG representing it. Return a special value to
    8444             :   // indicate that a tail call has been emitted and no more Instructions
    8445             :   // should be processed in the current block.
    8446      181705 :   if (CLI.IsTailCall) {
    8447        3089 :     CLI.DAG.setRoot(CLI.Chain);
    8448        3089 :     return std::make_pair(SDValue(), SDValue());
    8449             :   }
    8450             : 
    8451             : #ifndef NDEBUG
    8452             :   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
    8453             :     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
    8454             :     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
    8455             :            "LowerCall emitted a value with the wrong type!");
    8456             :   }
    8457             : #endif
    8458             : 
    8459             :   SmallVector<SDValue, 4> ReturnValues;
    8460      178616 :   if (!CanLowerReturn) {
    8461             :     // The instruction result is the result of loading from the
    8462             :     // hidden sret parameter.
    8463             :     SmallVector<EVT, 1> PVTs;
    8464         200 :     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
    8465             : 
    8466         200 :     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
    8467             :     assert(PVTs.size() == 1 && "Pointers should fit in one register");
    8468         200 :     EVT PtrVT = PVTs[0];
    8469             : 
    8470         200 :     unsigned NumValues = RetTys.size();
    8471         200 :     ReturnValues.resize(NumValues);
    8472         400 :     SmallVector<SDValue, 4> Chains(NumValues);
    8473             : 
    8474             :     // An aggregate return value cannot wrap around the address space, so
    8475             :     // offsets to its parts don't wrap either.
    8476             :     SDNodeFlags Flags;
    8477             :     Flags.setNoUnsignedWrap(true);
    8478             : 
    8479         926 :     for (unsigned i = 0; i < NumValues; ++i) {
    8480         363 :       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
    8481         363 :                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
    8482         726 :                                                         PtrVT), Flags);
    8483         363 :       SDValue L = CLI.DAG.getLoad(
    8484             :           RetTys[i], CLI.DL, CLI.Chain, Add,
    8485             :           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
    8486             :                                             DemoteStackIdx, Offsets[i]),
    8487         726 :           /* Alignment = */ 1);
    8488         363 :       ReturnValues[i] = L;
    8489         726 :       Chains[i] = L.getValue(1);
    8490             :     }
    8491             : 
    8492         400 :     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
    8493             :   } else {
    8494             :     // Collect the legal value parts into potentially illegal values
    8495             :     // that correspond to the original function's return values.
    8496             :     Optional<ISD::NodeType> AssertOp;
    8497      178416 :     if (CLI.RetSExt)
    8498             :       AssertOp = ISD::AssertSext;
    8499      177398 :     else if (CLI.RetZExt)
    8500             :       AssertOp = ISD::AssertZext;
    8501             :     unsigned CurReg = 0;
    8502      224804 :     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
    8503       92776 :       EVT VT = RetTys[I];
    8504             :       MVT RegisterVT =
    8505       46388 :           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8506             :       unsigned NumRegs =
    8507       46388 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8508             : 
    8509       92776 :       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
    8510             :                                               NumRegs, RegisterVT, VT, nullptr,
    8511       92776 :                                               AssertOp, true));
    8512       46388 :       CurReg += NumRegs;
    8513             :     }
    8514             : 
    8515             :     // For a function returning void, there is no return value. We can't create
    8516             :     // such a node, so we just return a null return value in that case. In
    8517             :     // that case, nothing will actually look at the value.
    8518      178416 :     if (ReturnValues.empty())
    8519             :       return std::make_pair(SDValue(), CLI.Chain);
    8520             :   }
    8521             : 
    8522       45345 :   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
    8523       45345 :                                 CLI.DAG.getVTList(RetTys), ReturnValues);
    8524             :   return std::make_pair(Res, CLI.Chain);
    8525             : }
    8526             : 
    8527        1231 : void TargetLowering::LowerOperationWrapper(SDNode *N,
    8528             :                                            SmallVectorImpl<SDValue> &Results,
    8529             :                                            SelectionDAG &DAG) const {
    8530        2462 :   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
    8531        1100 :     Results.push_back(Res);
    8532        1231 : }
    8533             : 
    8534           0 : SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
    8535           0 :   llvm_unreachable("LowerOperation not implemented for this target!");
    8536             : }
    8537             : 
    8538             : void
    8539      145001 : SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
    8540      145001 :   SDValue Op = getNonRegisterValue(V);
    8541             :   assert((Op.getOpcode() != ISD::CopyFromReg ||
    8542             :           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
    8543             :          "Copy from a reg to the same reg!");
    8544             :   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
    8545             : 
    8546      145001 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    8547             :   // If this is an InlineAsm we have to match the registers required, not the
    8548             :   // notional registers required by the type.
    8549             : 
    8550             :   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
    8551      435003 :                    V->getType(), isABIRegCopy(V));
    8552      290002 :   SDValue Chain = DAG.getEntryNode();
    8553             : 
    8554      290002 :   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
    8555      145001 :                               FuncInfo.PreferredExtendType.end())
    8556      251245 :                                  ? ISD::ANY_EXTEND
    8557      106244 :                                  : FuncInfo.PreferredExtendType[V];
    8558      435003 :   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
    8559      145001 :   PendingExports.push_back(Chain);
    8560      145001 : }
    8561             : 
    8562             : #include "llvm/CodeGen/SelectionDAGISel.h"
    8563             : 
    8564             : /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
    8565             : /// entry block, return true.  This includes arguments used by switches, since
    8566             : /// the switch may expand into multiple basic blocks.
    8567      117546 : static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
    8568             :   // With FastISel active, we may be splitting blocks, so force creation
    8569             :   // of virtual registers for all non-dead arguments.
    8570      117546 :   if (FastISel)
    8571       44494 :     return A->use_empty();
    8572             : 
    8573       95299 :   const BasicBlock &Entry = A->getParent()->front();
    8574      201140 :   for (const User *U : A->users())
    8575      111119 :     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
    8576             :       return false;  // Use not in entry block.
    8577             : 
    8578             :   return true;
    8579             : }
    8580             : 
    8581             : using ArgCopyElisionMapTy =
    8582             :     DenseMap<const Argument *,
    8583             :              std::pair<const AllocaInst *, const StoreInst *>>;
    8584             : 
    8585             : /// Scan the entry block of the function in FuncInfo for arguments that look
    8586             : /// like copies into a local alloca. Record any copied arguments in
    8587             : /// ArgCopyElisionCandidates.
    8588             : static void
    8589      184924 : findArgumentCopyElisionCandidates(const DataLayout &DL,
    8590             :                                   FunctionLoweringInfo *FuncInfo,
    8591             :                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
    8592             :   // Record the state of every static alloca used in the entry block. Argument
    8593             :   // allocas are all used in the entry block, so we need approximately as many
    8594             :   // entries as we have arguments.
    8595             :   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
    8596             :   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
    8597      184924 :   unsigned NumArgs = FuncInfo->Fn->arg_size();
    8598      184924 :   StaticAllocas.reserve(NumArgs * 2);
    8599             : 
    8600     1611805 :   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
    8601     1611805 :     if (!V)
    8602             :       return nullptr;
    8603     1611805 :     V = V->stripPointerCasts();
    8604             :     const auto *AI = dyn_cast<AllocaInst>(V);
    8605       24078 :     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
    8606             :       return nullptr;
    8607       47388 :     auto Iter = StaticAllocas.insert({AI, Unknown});
    8608       23694 :     return &Iter.first->second;
    8609      184924 :   };
    8610             : 
    8611             :   // Look for stores of arguments to static allocas. Look through bitcasts and
    8612             :   // GEPs to handle type coercions, as long as the alloca is fully initialized
    8613             :   // by the store. Any non-store use of an alloca escapes it and any subsequent
    8614             :   // unanalyzed store might write it.
    8615             :   // FIXME: Handle structs initialized with multiple stores.
    8616     1312172 :   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
    8617             :     // Look for stores, and handle non-store uses conservatively.
    8618             :     const auto *SI = dyn_cast<StoreInst>(&I);
    8619             :     if (!SI) {
    8620             :       // We will look through cast uses, so ignore them completely.
    8621      865234 :       if (I.isCast())
    8622       99074 :         continue;
    8623             :       // Ignore debug info intrinsics, they don't escape or store to allocas.
    8624        5841 :       if (isa<DbgInfoIntrinsic>(I))
    8625        5841 :         continue;
    8626             :       // This is an unknown instruction. Assume it escapes or writes to all
    8627             :       // static alloca operands.
    8628     4430964 :       for (const Use &U : I.operands()) {
    8629     1455163 :         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
    8630       15822 :           *Info = StaticAllocaInfo::Clobbered;
    8631             :       }
    8632      760319 :       continue;
    8633             :     }
    8634             : 
    8635             :     // If the stored value is a static alloca, mark it as escaped.
    8636       78321 :     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
    8637         290 :       *Info = StaticAllocaInfo::Clobbered;
    8638             : 
    8639             :     // Check if the destination is a static alloca.
    8640       78321 :     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
    8641       78321 :     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
    8642       78321 :     if (!Info)
    8643       70739 :       continue;
    8644             :     const AllocaInst *AI = cast<AllocaInst>(Dst);
    8645             : 
    8646             :     // Skip allocas that have been initialized or clobbered.
    8647        7582 :     if (*Info != StaticAllocaInfo::Unknown)
    8648        1510 :       continue;
    8649             : 
    8650             :     // Check if the stored value is an argument, and that this store fully
    8651             :     // initializes the alloca. Don't elide copies from the same argument twice.
    8652        6072 :     const Value *Val = SI->getValueOperand()->stripPointerCasts();
    8653             :     const auto *Arg = dyn_cast<Argument>(Val);
    8654        9225 :     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
    8655        6155 :         Arg->getType()->isEmptyTy() ||
    8656        3077 :         DL.getTypeStoreSize(Arg->getType()) !=
    8657        3077 :             DL.getTypeAllocSize(AI->getAllocatedType()) ||
    8658             :         ArgCopyElisionCandidates.count(Arg)) {
    8659        3066 :       *Info = StaticAllocaInfo::Clobbered;
    8660        3066 :       continue;
    8661             :     }
    8662             : 
    8663             :     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
    8664             :                       << '\n');
    8665             : 
    8666             :     // Mark this alloca and store for argument copy elision.
    8667        3006 :     *Info = StaticAllocaInfo::Elidable;
    8668        3006 :     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
    8669             : 
    8670             :     // Stop scanning if we've seen all arguments. This will happen early in -O0
    8671             :     // builds, which is useful, because -O0 builds have large entry blocks and
    8672             :     // many allocas.
    8673        3006 :     if (ArgCopyElisionCandidates.size() == NumArgs)
    8674             :       break;
    8675             :   }
    8676      184924 : }
    8677             : 
    8678             : /// Try to elide argument copies from memory into a local alloca. Succeeds if
    8679             : /// ArgVal is a load from a suitable fixed stack object.
    8680        3006 : static void tryToElideArgumentCopy(
    8681             :     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
    8682             :     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
    8683             :     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
    8684             :     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
    8685             :     SDValue ArgVal, bool &ArgHasUses) {
    8686             :   // Check if this is a load from a fixed stack object.
    8687             :   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
    8688             :   if (!LNode)
    8689        2555 :     return;
    8690         489 :   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
    8691             :   if (!FINode)
    8692             :     return;
    8693             : 
    8694             :   // Check that the fixed stack object is the right size and alignment.
    8695             :   // Look at the alignment that the user wrote on the alloca instead of looking
    8696             :   // at the stack object.
    8697         489 :   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
    8698             :   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
    8699         489 :   const AllocaInst *AI = ArgCopyIter->second.first;
    8700         489 :   int FixedIndex = FINode->getIndex();
    8701         489 :   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
    8702         489 :   int OldIndex = AllocaIndex;
    8703         489 :   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
    8704         489 :   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
    8705             :     LLVM_DEBUG(
    8706             :         dbgs() << "  argument copy elision failed due to bad fixed stack "
    8707             :                   "object size\n");
    8708             :     return;
    8709             :   }
    8710         488 :   unsigned RequiredAlignment = AI->getAlignment();
    8711         488 :   if (!RequiredAlignment) {
    8712          64 :     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
    8713             :         AI->getAllocatedType());
    8714             :   }
    8715         488 :   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
    8716             :     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
    8717             :                          "greater than stack argument alignment ("
    8718             :                       << RequiredAlignment << " vs "
    8719             :                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
    8720             :     return;
    8721             :   }
    8722             : 
    8723             :   // Perform the elision. Delete the old stack object and replace its only use
    8724             :   // in the variable info map. Mark the stack object as mutable.
    8725             :   LLVM_DEBUG({
    8726             :     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
    8727             :            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
    8728             :            << '\n';
    8729             :   });
    8730             :   MFI.RemoveStackObject(OldIndex);
    8731             :   MFI.setIsImmutableObjectIndex(FixedIndex, false);
    8732         451 :   AllocaIndex = FixedIndex;
    8733         451 :   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
    8734         451 :   Chains.push_back(ArgVal.getValue(1));
    8735             : 
    8736             :   // Avoid emitting code for the store implementing the copy.
    8737         451 :   const StoreInst *SI = ArgCopyIter->second.second;
    8738         451 :   ElidedArgCopyInstrs.insert(SI);
    8739             : 
    8740             :   // Check for uses of the argument again so that we can avoid exporting ArgVal
    8741             :   // if it is't used by anything other than the store.
    8742         847 :   for (const Value *U : Arg.users()) {
    8743         451 :     if (U != SI) {
    8744          55 :       ArgHasUses = true;
    8745             :       break;
    8746             :     }
    8747             :   }
    8748             : }
    8749             : 
    8750      184924 : void SelectionDAGISel::LowerArguments(const Function &F) {
    8751      184924 :   SelectionDAG &DAG = SDB->DAG;
    8752      184924 :   SDLoc dl = SDB->getCurSDLoc();
    8753      184924 :   const DataLayout &DL = DAG.getDataLayout();
    8754             :   SmallVector<ISD::InputArg, 16> Ins;
    8755             : 
    8756      184924 :   if (!FuncInfo->CanLowerReturn) {
    8757             :     // Put in an sret pointer parameter before all the other parameters.
    8758             :     SmallVector<EVT, 1> ValueVTs;
    8759        1762 :     ComputeValueVTs(*TLI, DAG.getDataLayout(),
    8760         881 :                     F.getReturnType()->getPointerTo(
    8761         881 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    8762             :                     ValueVTs);
    8763             : 
    8764             :     // NOTE: Assuming that a pointer will never break down to more than one VT
    8765             :     // or one register.
    8766             :     ISD::ArgFlagsTy Flags;
    8767             :     Flags.setSRet();
    8768        1762 :     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
    8769             :     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
    8770             :                          ISD::InputArg::NoArgIndex, 0);
    8771         881 :     Ins.push_back(RetArg);
    8772             :   }
    8773             : 
    8774             :   // Look for stores of arguments to static allocas. Mark such arguments with a
    8775             :   // flag to ask the target to give us the memory location of that argument if
    8776             :   // available.
    8777             :   ArgCopyElisionMapTy ArgCopyElisionCandidates;
    8778      184924 :   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
    8779             : 
    8780             :   // Set up the incoming argument description vector.
    8781      522892 :   for (const Argument &Arg : F.args()) {
    8782      337968 :     unsigned ArgNo = Arg.getArgNo();
    8783             :     SmallVector<EVT, 4> ValueVTs;
    8784      675936 :     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
    8785      337968 :     bool isArgValueUsed = !Arg.use_empty();
    8786             :     unsigned PartBase = 0;
    8787      337968 :     Type *FinalType = Arg.getType();
    8788      337968 :     if (Arg.hasAttribute(Attribute::ByVal))
    8789         821 :       FinalType = cast<PointerType>(FinalType)->getElementType();
    8790      675936 :     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
    8791      675936 :         FinalType, F.getCallingConv(), F.isVarArg());
    8792      679581 :     for (unsigned Value = 0, NumValues = ValueVTs.size();
    8793      679581 :          Value != NumValues; ++Value) {
    8794      683226 :       EVT VT = ValueVTs[Value];
    8795      341613 :       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
    8796             :       ISD::ArgFlagsTy Flags;
    8797             : 
    8798             :       // Certain targets (such as MIPS), may have a different ABI alignment
    8799             :       // for a type depending on the context. Give the target a chance to
    8800             :       // specify the alignment it wants.
    8801             :       unsigned OriginalAlignment =
    8802      341613 :           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
    8803             : 
    8804      341613 :       if (Arg.hasAttribute(Attribute::ZExt))
    8805             :         Flags.setZExt();
    8806      341613 :       if (Arg.hasAttribute(Attribute::SExt))
    8807             :         Flags.setSExt();
    8808      341613 :       if (Arg.hasAttribute(Attribute::InReg)) {
    8809             :         // If we are using vectorcall calling convention, a structure that is
    8810             :         // passed InReg - is surely an HVA
    8811        2143 :         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
    8812          74 :             isa<StructType>(Arg.getType())) {
    8813             :           // The first value of a structure is marked
    8814          50 :           if (0 == Value)
    8815             :             Flags.setHvaStart();
    8816             :           Flags.setHva();
    8817             :         }
    8818             :         // Set InReg Flag
    8819             :         Flags.setInReg();
    8820             :       }
    8821      341613 :       if (Arg.hasAttribute(Attribute::StructRet))
    8822             :         Flags.setSRet();
    8823      341613 :       if (Arg.hasAttribute(Attribute::SwiftSelf))
    8824             :         Flags.setSwiftSelf();
    8825      341613 :       if (Arg.hasAttribute(Attribute::SwiftError))
    8826             :         Flags.setSwiftError();
    8827      341613 :       if (Arg.hasAttribute(Attribute::ByVal))
    8828             :         Flags.setByVal();
    8829      341613 :       if (Arg.hasAttribute(Attribute::InAlloca)) {
    8830             :         Flags.setInAlloca();
    8831             :         // Set the byval flag for CCAssignFn callbacks that don't know about
    8832             :         // inalloca.  This way we can know how many bytes we should've allocated
    8833             :         // and how many bytes a callee cleanup function will pop.  If we port
    8834             :         // inalloca to more targets, we'll have to add custom inalloca handling
    8835             :         // in the various CC lowering callbacks.
    8836             :         Flags.setByVal();
    8837             :       }
    8838      341613 :       if (F.getCallingConv() == CallingConv::X86_INTR) {
    8839             :         // IA Interrupt passes frame (1st parameter) by value in the stack.
    8840          36 :         if (ArgNo == 0)
    8841             :           Flags.setByVal();
    8842             :       }
    8843      682360 :       if (Flags.isByVal() || Flags.isInAlloca()) {
    8844         866 :         PointerType *Ty = cast<PointerType>(Arg.getType());
    8845         866 :         Type *ElementTy = Ty->getElementType();
    8846         866 :         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
    8847             :         // For ByVal, alignment should be passed from FE.  BE will guess if
    8848             :         // this info is not there but there are cases it cannot get right.
    8849             :         unsigned FrameAlign;
    8850         866 :         if (Arg.getParamAlignment())
    8851         325 :           FrameAlign = Arg.getParamAlignment();
    8852             :         else
    8853         541 :           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
    8854             :         Flags.setByValAlign(FrameAlign);
    8855             :       }
    8856      341613 :       if (Arg.hasAttribute(Attribute::Nest))
    8857             :         Flags.setNest();
    8858      341613 :       if (NeedsRegBlock)
    8859             :         Flags.setInConsecutiveRegs();
    8860             :       Flags.setOrigAlign(OriginalAlignment);
    8861             :       if (ArgCopyElisionCandidates.count(&Arg))
    8862             :         Flags.setCopyElisionCandidate();
    8863             : 
    8864             :       MVT RegisterVT =
    8865      341613 :           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
    8866             :       unsigned NumRegs =
    8867      341613 :           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
    8868     1080423 :       for (unsigned i = 0; i != NumRegs; ++i) {
    8869             :         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
    8870      369405 :                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
    8871      369405 :         if (NumRegs > 1 && i == 0)
    8872             :           MyFlags.Flags.setSplit();
    8873             :         // if it isn't first piece, alignment must be 1
    8874      355078 :         else if (i > 0) {
    8875             :           MyFlags.Flags.setOrigAlign(1);
    8876       27792 :           if (i == NumRegs - 1)
    8877             :             MyFlags.Flags.setSplitEnd();
    8878             :         }
    8879      369405 :         Ins.push_back(MyFlags);
    8880             :       }
    8881      341613 :       if (NeedsRegBlock && Value == NumValues - 1)
    8882        2348 :         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
    8883      341613 :       PartBase += VT.getStoreSize();
    8884             :     }
    8885             :   }
    8886             : 
    8887             :   // Call the target to set up the argument values.
    8888             :   SmallVector<SDValue, 8> InVals;
    8889      184924 :   SDValue NewRoot = TLI->LowerFormalArguments(
    8890      554772 :       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
    8891             : 
    8892             :   // Verify that the target's LowerFormalArguments behaved as expected.
    8893             :   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
    8894             :          "LowerFormalArguments didn't return a valid chain!");
    8895             :   assert(InVals.size() == Ins.size() &&
    8896             :          "LowerFormalArguments didn't emit the correct number of values!");
    8897             :   LLVM_DEBUG({
    8898             :     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
    8899             :       assert(InVals[i].getNode() &&
    8900             :              "LowerFormalArguments emitted a null value!");
    8901             :       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
    8902             :              "LowerFormalArguments emitted a value with the wrong type!");
    8903             :     }
    8904             :   });
    8905             : 
    8906             :   // Update the DAG with the new chain value resulting from argument lowering.
    8907      184920 :   DAG.setRoot(NewRoot);
    8908             : 
    8909             :   // Set up the argument values.
    8910             :   unsigned i = 0;
    8911      184920 :   if (!FuncInfo->CanLowerReturn) {
    8912             :     // Create a virtual register for the sret pointer, and put in a copy
    8913             :     // from the sret argument into it.
    8914             :     SmallVector<EVT, 1> ValueVTs;
    8915        1762 :     ComputeValueVTs(*TLI, DAG.getDataLayout(),
    8916         881 :                     F.getReturnType()->getPointerTo(
    8917         881 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    8918             :                     ValueVTs);
    8919             :     MVT VT = ValueVTs[0].getSimpleVT();
    8920        1762 :     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
    8921             :     Optional<ISD::NodeType> AssertOp = None;
    8922             :     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
    8923         881 :                                         RegVT, VT, nullptr, AssertOp);
    8924             : 
    8925         881 :     MachineFunction& MF = SDB->DAG.getMachineFunction();
    8926         881 :     MachineRegisterInfo& RegInfo = MF.getRegInfo();
    8927         881 :     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
    8928         881 :     FuncInfo->DemoteRegister = SRetReg;
    8929         881 :     NewRoot =
    8930        3524 :         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
    8931         881 :     DAG.setRoot(NewRoot);
    8932             : 
    8933             :     // i indexes lowered arguments.  Bump it past the hidden sret argument.
    8934             :     ++i;
    8935             :   }
    8936             : 
    8937             :   SmallVector<SDValue, 4> Chains;
    8938             :   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
    8939      522883 :   for (const Argument &Arg : F.args()) {
    8940             :     SmallVector<SDValue, 4> ArgValues;
    8941             :     SmallVector<EVT, 4> ValueVTs;
    8942      675926 :     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
    8943      337963 :     unsigned NumValues = ValueVTs.size();
    8944      337963 :     if (NumValues == 0)
    8945          18 :       continue;
    8946             : 
    8947      337945 :     bool ArgHasUses = !Arg.use_empty();
    8948             : 
    8949             :     // Elide the copying store if the target loaded this argument from a
    8950             :     // suitable fixed stack object.
    8951      675890 :     if (Ins[i].Flags.isCopyElisionCandidate()) {
    8952        3006 :       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
    8953             :                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
    8954             :                              InVals[i], ArgHasUses);
    8955             :     }
    8956             : 
    8957             :     // If this argument is unused then remember its value. It is used to generate
    8958             :     // debugging information.
    8959             :     bool isSwiftErrorArg =
    8960      545198 :         TLI->supportSwiftError() &&
    8961      207253 :         Arg.hasAttribute(Attribute::SwiftError);
    8962      337945 :     if (!ArgHasUses && !isSwiftErrorArg) {
    8963       34600 :       SDB->setUnusedArgValue(&Arg, InVals[i]);
    8964             : 
    8965             :       // Also remember any frame index for use in FastISel.
    8966             :       if (FrameIndexSDNode *FI =
    8967       17300 :           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
    8968          81 :         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    8969             :     }
    8970             : 
    8971     1021161 :     for (unsigned Val = 0; Val != NumValues; ++Val) {
    8972      683216 :       EVT VT = ValueVTs[Val];
    8973             :       MVT PartVT =
    8974      341608 :           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
    8975             :       unsigned NumParts =
    8976      341608 :           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
    8977             : 
    8978             :       // Even an apparant 'unused' swifterror argument needs to be returned. So
    8979             :       // we do generate a copy for it that can be used on return from the
    8980             :       // function.
    8981      341608 :       if (ArgHasUses || isSwiftErrorArg) {
    8982             :         Optional<ISD::NodeType> AssertOp;
    8983      321766 :         if (Arg.hasAttribute(Attribute::SExt))
    8984             :           AssertOp = ISD::AssertSext;
    8985      314390 :         else if (Arg.hasAttribute(Attribute::ZExt))
    8986             :           AssertOp = ISD::AssertZext;
    8987             : 
    8988      643532 :         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
    8989             :                                              PartVT, VT, nullptr, AssertOp,
    8990      321766 :                                              true));
    8991             :       }
    8992             : 
    8993      341608 :       i += NumParts;
    8994             :     }
    8995             : 
    8996             :     // We don't need to do anything else for unused arguments.
    8997      337945 :     if (ArgValues.empty())
    8998       17300 :       continue;
    8999             : 
    9000             :     // Note down frame index.
    9001             :     if (FrameIndexSDNode *FI =
    9002      320645 :         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
    9003         491 :       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    9004             : 
    9005      320645 :     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
    9006     1282580 :                                      SDB->getCurSDLoc());
    9007             : 
    9008      320645 :     SDB->setValue(&Arg, Res);
    9009      619043 :     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
    9010             :       // We want to associate the argument with the frame index, among
    9011             :       // involved operands, that correspond to the lowest address. The
    9012             :       // getCopyFromParts function, called earlier, is swapping the order of
    9013             :       // the operands to BUILD_PAIR depending on endianness. The result of
    9014             :       // that swapping is that the least significant bits of the argument will
    9015             :       // be in the first operand of the BUILD_PAIR node, and the most
    9016             :       // significant bits will be in the second operand.
    9017        8158 :       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
    9018             :       if (LoadSDNode *LNode =
    9019        4079 :           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
    9020             :         if (FrameIndexSDNode *FI =
    9021        1395 :             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
    9022        1111 :           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    9023             :     }
    9024             : 
    9025             :     // Update the SwiftErrorVRegDefMap.
    9026      320645 :     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
    9027         101 :       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
    9028         101 :       if (TargetRegisterInfo::isVirtualRegister(Reg))
    9029         101 :         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
    9030             :                                            FuncInfo->SwiftErrorArg, Reg);
    9031             :     }
    9032             : 
    9033             :     // If this argument is live outside of the entry block, insert a copy from
    9034             :     // wherever we got it to the vreg that other BB's will reference it as.
    9035      619043 :     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
    9036             :       // If we can, though, try to skip creating an unnecessary vreg.
    9037             :       // FIXME: This isn't very clean... it would be nice to make this more
    9038             :       // general.  It's also subtly incompatible with the hacks FastISel
    9039             :       // uses with vregs.
    9040      203099 :       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
    9041      406198 :       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
    9042      406198 :         FuncInfo->ValueMap[&Arg] = Reg;
    9043      203099 :         continue;
    9044             :       }
    9045             :     }
    9046      117546 :     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
    9047       27518 :       FuncInfo->InitializeRegForValue(&Arg);
    9048       27518 :       SDB->CopyToExportRegsIfNeeded(&Arg);
    9049             :     }
    9050             :   }
    9051             : 
    9052      184920 :   if (!Chains.empty()) {
    9053         251 :     Chains.push_back(NewRoot);
    9054         251 :     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
    9055             :   }
    9056             : 
    9057      184920 :   DAG.setRoot(NewRoot);
    9058             : 
    9059             :   assert(i == InVals.size() && "Argument register count mismatch!");
    9060             : 
    9061             :   // If any argument copy elisions occurred and we have debug info, update the
    9062             :   // stale frame indices used in the dbg.declare variable info table.
    9063      184920 :   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
    9064      184920 :   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
    9065           0 :     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
    9066           0 :       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
    9067           0 :       if (I != ArgCopyElisionFrameIndexMap.end())
    9068           0 :         VI.Slot = I->second;
    9069             :     }
    9070             :   }
    9071             : 
    9072             :   // Finally, if the target has anything special to do, allow it to do so.
    9073      184920 :   EmitFunctionEntryCode();
    9074      184920 : }
    9075             : 
    9076             : /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
    9077             : /// ensure constants are generated when needed.  Remember the virtual registers
    9078             : /// that need to be added to the Machine PHI nodes as input.  We cannot just
    9079             : /// directly add them, because expansion might result in multiple MBB's for one
    9080             : /// BB.  As such, the start of the BB might correspond to a different MBB than
    9081             : /// the end.
    9082             : void
    9083      337168 : SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
    9084      337168 :   const TerminatorInst *TI = LLVMBB->getTerminator();
    9085             : 
    9086             :   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
    9087             : 
    9088             :   // Check PHI nodes in successors that expect a value to be available from this
    9089             :   // block.
    9090      573882 :   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
    9091      236714 :     const BasicBlock *SuccBB = TI->getSuccessor(succ);
    9092      419923 :     if (!isa<PHINode>(SuccBB->begin())) continue;
    9093      107094 :     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
    9094             : 
    9095             :     // If this terminator has multiple identical successors (common for
    9096             :     // switches), only handle each succ once.
    9097       53547 :     if (!SuccsHandled.insert(SuccMBB).second)
    9098          42 :       continue;
    9099             : 
    9100       53505 :     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
    9101             : 
    9102             :     // At this point we know that there is a 1-1 correspondence between LLVM PHI
    9103             :     // nodes and Machine PHI nodes, but the incoming operands have not been
    9104             :     // emitted yet.
    9105      202938 :     for (const PHINode &PN : SuccBB->phis()) {
    9106             :       // Ignore dead phi's.
    9107       95928 :       if (PN.use_empty())
    9108        7976 :         continue;
    9109             : 
    9110             :       // Skip empty types
    9111       91942 :       if (PN.getType()->isEmptyTy())
    9112           4 :         continue;
    9113             : 
    9114             :       unsigned Reg;
    9115       91938 :       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
    9116             : 
    9117       91938 :       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
    9118       13799 :         unsigned &RegOut = ConstantsOut[C];
    9119       13799 :         if (RegOut == 0) {
    9120       11232 :           RegOut = FuncInfo.CreateRegs(C->getType());
    9121       11232 :           CopyValueToVirtualRegister(C, RegOut);
    9122             :         }
    9123       13799 :         Reg = RegOut;
    9124             :       } else {
    9125             :         DenseMap<const Value *, unsigned>::iterator I =
    9126       78139 :           FuncInfo.ValueMap.find(PHIOp);
    9127      156278 :         if (I != FuncInfo.ValueMap.end())
    9128       78059 :           Reg = I->second;
    9129             :         else {
    9130             :           assert(isa<AllocaInst>(PHIOp) &&
    9131             :                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
    9132             :                  "Didn't codegen value into a register!??");
    9133          80 :           Reg = FuncInfo.CreateRegs(PHIOp->getType());
    9134          80 :           CopyValueToVirtualRegister(PHIOp, Reg);
    9135             :         }
    9136             :       }
    9137             : 
    9138             :       // Remember that this register needs to added to the machine PHI node as
    9139             :       // the input for this MBB.
    9140             :       SmallVector<EVT, 4> ValueVTs;
    9141       91938 :       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9142      183876 :       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
    9143      185119 :       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
    9144      186362 :         EVT VT = ValueVTs[vti];
    9145       93181 :         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
    9146      283147 :         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
    9147       94983 :           FuncInfo.PHINodesToUpdate.push_back(
    9148      284949 :               std::make_pair(&*MBBI++, Reg + i));
    9149       93181 :         Reg += NumRegisters;
    9150             :       }
    9151             :     }
    9152             :   }
    9153             : 
    9154      337168 :   ConstantsOut.clear();
    9155      337168 : }
    9156             : 
    9157             : /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
    9158             : /// is 0.
    9159             : MachineBasicBlock *
    9160         518 : SelectionDAGBuilder::StackProtectorDescriptor::
    9161             : AddSuccessorMBB(const BasicBlock *BB,
    9162             :                 MachineBasicBlock *ParentMBB,
    9163             :                 bool IsLikely,
    9164             :                 MachineBasicBlock *SuccMBB) {
    9165             :   // If SuccBB has not been created yet, create it.
    9166         518 :   if (!SuccMBB) {
    9167         509 :     MachineFunction *MF = ParentMBB->getParent();
    9168             :     MachineFunction::iterator BBI(ParentMBB);
    9169         509 :     SuccMBB = MF->CreateMachineBasicBlock(BB);
    9170             :     MF->insert(++BBI, SuccMBB);
    9171             :   }
    9172             :   // Add it as a successor of ParentMBB.
    9173         518 :   ParentMBB->addSuccessor(
    9174             :       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
    9175         518 :   return SuccMBB;
    9176             : }
    9177             : 
    9178      106155 : MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
    9179             :   MachineFunction::iterator I(MBB);
    9180      212310 :   if (++I == FuncInfo.MF->end())
    9181             :     return nullptr;
    9182      105480 :   return &*I;
    9183             : }
    9184             : 
    9185             : /// During lowering new call nodes can be created (such as memset, etc.).
    9186             : /// Those will become new roots of the current DAG, but complications arise
    9187             : /// when they are tail calls. In such cases, the call lowering will update
    9188             : /// the root, but the builder still needs to know that a tail call has been
    9189             : /// lowered in order to avoid generating an additional return.
    9190       27026 : void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
    9191             :   // If the node is null, we do have a tail call.
    9192       27026 :   if (MaybeTC.getNode() != nullptr)
    9193       26992 :     DAG.setRoot(MaybeTC);
    9194             :   else
    9195          34 :     HasTailCall = true;
    9196       27026 : }
    9197             : 
    9198             : uint64_t
    9199        1961 : SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
    9200             :                                        unsigned First, unsigned Last) const {
    9201             :   assert(Last >= First);
    9202        3922 :   const APInt &LowCase = Clusters[First].Low->getValue();
    9203        3922 :   const APInt &HighCase = Clusters[Last].High->getValue();
    9204             :   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
    9205             : 
    9206             :   // FIXME: A range of consecutive cases has 100% density, but only requires one
    9207             :   // comparison to lower. We should discriminate against such consecutive ranges
    9208             :   // in jump tables.
    9209             : 
    9210        5883 :   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
    9211             : }
    9212             : 
    9213        1961 : uint64_t SelectionDAGBuilder::getJumpTableNumCases(
    9214             :     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
    9215             :     unsigned Last) const {
    9216             :   assert(Last >= First);
    9217             :   assert(TotalCases[Last] >= TotalCases[First]);
    9218             :   uint64_t NumCases =
    9219        5207 :       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
    9220        1961 :   return NumCases;
    9221             : }
    9222             : 
    9223         278 : bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
    9224             :                                          unsigned First, unsigned Last,
    9225             :                                          const SwitchInst *SI,
    9226             :                                          MachineBasicBlock *DefaultMBB,
    9227             :                                          CaseCluster &JTCluster) {
    9228             :   assert(First <= Last);
    9229             : 
    9230             :   auto Prob = BranchProbability::getZero();
    9231             :   unsigned NumCmps = 0;
    9232             :   std::vector<MachineBasicBlock*> Table;
    9233             :   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
    9234             : 
    9235             :   // Initialize probabilities in JTProbs.
    9236        4118 :   for (unsigned I = First; I <= Last; ++I)
    9237        5760 :     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
    9238             : 
    9239        4118 :   for (unsigned I = First; I <= Last; ++I) {
    9240             :     assert(Clusters[I].Kind == CC_Range);
    9241        1920 :     Prob += Clusters[I].Prob;
    9242        1920 :     const APInt &Low = Clusters[I].Low->getValue();
    9243        1920 :     const APInt &High = Clusters[I].High->getValue();
    9244        1920 :     NumCmps += (Low == High) ? 1 : 2;
    9245        1920 :     if (I != First) {
    9246             :       // Fill the gap between this and the previous cluster.
    9247        3284 :       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
    9248             :       assert(PreviousHigh.slt(Low));
    9249        4926 :       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
    9250        6780 :       for (uint64_t J = 0; J < Gap; J++)
    9251        2569 :         Table.push_back(DefaultMBB);
    9252             :     }
    9253        5760 :     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
    9254        6888 :     for (uint64_t J = 0; J < ClusterSize; ++J)
    9255        4968 :       Table.push_back(Clusters[I].MBB);
    9256        3840 :     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
    9257             :   }
    9258             : 
    9259         278 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9260             :   unsigned NumDests = JTProbs.size();
    9261         556 :   if (TLI.isSuitableForBitTests(
    9262         556 :           NumDests, NumCmps, Clusters[First].Low->getValue(),
    9263         556 :           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
    9264             :     // Clusters[First..Last] should be lowered as bit tests instead.
    9265             :     return false;
    9266             :   }
    9267             : 
    9268             :   // Create the MBB that will load from and jump through the table.
    9269             :   // Note: We create it here, but it's not inserted into the function yet.
    9270         254 :   MachineFunction *CurMF = FuncInfo.MF;
    9271             :   MachineBasicBlock *JumpTableMBB =
    9272         254 :       CurMF->CreateMachineBasicBlock(SI->getParent());
    9273             : 
    9274             :   // Add successors. Note: use table order for determinism.
    9275             :   SmallPtrSet<MachineBasicBlock *, 8> Done;
    9276        5039 :   for (MachineBasicBlock *Succ : Table) {
    9277        4785 :     if (Done.count(Succ))
    9278        3057 :       continue;
    9279        1728 :     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
    9280        1728 :     Done.insert(Succ);
    9281             :   }
    9282             :   JumpTableMBB->normalizeSuccProbs();
    9283             : 
    9284         254 :   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
    9285         254 :                      ->createJumpTableIndex(Table);
    9286             : 
    9287             :   // Set up the jump table info.
    9288             :   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
    9289         508 :   JumpTableHeader JTH(Clusters[First].Low->getValue(),
    9290         508 :                       Clusters[Last].High->getValue(), SI->getCondition(),
    9291         508 :                       nullptr, false);
    9292         254 :   JTCases.emplace_back(std::move(JTH), std::move(JT));
    9293             : 
    9294         762 :   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
    9295         508 :                                      JTCases.size() - 1, Prob);
    9296             :   return true;
    9297             : }
    9298             : 
    9299        1162 : void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
    9300             :                                          const SwitchInst *SI,
    9301             :                                          MachineBasicBlock *DefaultMBB) {
    9302             : #ifndef NDEBUG
    9303             :   // Clusters must be non-empty, sorted, and only contain Range clusters.
    9304             :   assert(!Clusters.empty());
    9305             :   for (CaseCluster &C : Clusters)
    9306             :     assert(C.Kind == CC_Range);
    9307             :   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
    9308             :     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
    9309             : #endif
    9310             : 
    9311        1162 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9312        1162 :   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
    9313        1096 :     return;
    9314             : 
    9315        1149 :   const int64_t N = Clusters.size();
    9316        1149 :   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
    9317        1149 :   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
    9318             : 
    9319        1149 :   if (N < 2 || N < MinJumpTableEntries)
    9320             :     return;
    9321             : 
    9322             :   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
    9323         614 :   SmallVector<unsigned, 8> TotalCases(N);
    9324        4625 :   for (unsigned i = 0; i < N; ++i) {
    9325        4318 :     const APInt &Hi = Clusters[i].High->getValue();
    9326        2159 :     const APInt &Lo = Clusters[i].Low->getValue();
    9327        8636 :     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
    9328        2159 :     if (i != 0)
    9329        5556 :       TotalCases[i] += TotalCases[i - 1];
    9330             :   }
    9331             : 
    9332             :   // Cheap case: the whole range may be suitable for jump table.
    9333         307 :   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
    9334         307 :   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
    9335             :   assert(NumCases < UINT64_MAX / 100);
    9336             :   assert(Range >= NumCases);
    9337         307 :   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
    9338             :     CaseCluster JTCluster;
    9339         239 :     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
    9340         225 :       Clusters[0] = JTCluster;
    9341         225 :       Clusters.resize(1);
    9342         225 :       return;
    9343             :     }
    9344             :   }
    9345             : 
    9346             :   // The algorithm below is not suitable for -O0.
    9347          82 :   if (TM.getOptLevel() == CodeGenOpt::None)
    9348             :     return;
    9349             : 
    9350             :   // Split Clusters into minimum number of dense partitions. The algorithm uses
    9351             :   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
    9352             :   // for the Case Statement'" (1994), but builds the MinPartitions array in
    9353             :   // reverse order to make it easier to reconstruct the partitions in ascending
    9354             :   // order. In the choice between two optimal partitionings, it picks the one
    9355             :   // which yields more jump tables.
    9356             : 
    9357             :   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
    9358         132 :   SmallVector<unsigned, 8> MinPartitions(N);
    9359             :   // LastElement[i] is the last element of the partition starting at i.
    9360         132 :   SmallVector<unsigned, 8> LastElement(N);
    9361             :   // PartitionsScore[i] is used to break ties when choosing between two
    9362             :   // partitionings resulting in the same number of partitions.
    9363         132 :   SmallVector<unsigned, 8> PartitionsScore(N);
    9364             :   // For PartitionsScore, a small number of comparisons is considered as good as
    9365             :   // a jump table and a single comparison is considered better than a jump
    9366             :   // table.
    9367             :   enum PartitionScores : unsigned {
    9368             :     NoTable = 0,
    9369             :     Table = 1,
    9370             :     FewCases = 1,
    9371             :     SingleCase = 2
    9372             :   };
    9373             : 
    9374             :   // Base case: There is only one way to partition Clusters[N-1].
    9375         132 :   MinPartitions[N - 1] = 1;
    9376          66 :   LastElement[N - 1] = N - 1;
    9377          66 :   PartitionsScore[N - 1] = PartitionScores::SingleCase;
    9378             : 
    9379             :   // Note: loop indexes are signed to avoid underflow.
    9380         435 :   for (int64_t i = N - 2; i >= 0; i--) {
    9381             :     // Find optimal partitioning of Clusters[i..N-1].
    9382             :     // Baseline: Put Clusters[i] into a partition on its own.
    9383        1107 :     MinPartitions[i] = MinPartitions[i + 1] + 1;
    9384         369 :     LastElement[i] = i;
    9385         738 :     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
    9386             : 
    9387             :     // Search for a solution that results in fewer partitions.
    9388        3677 :     for (int64_t j = N - 1; j > i; j--) {
    9389             :       // Try building a partition from Clusters[i..j].
    9390        1654 :       uint64_t Range = getJumpTableRange(Clusters, i, j);
    9391        1654 :       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
    9392             :       assert(NumCases < UINT64_MAX / 100);
    9393             :       assert(Range >= NumCases);
    9394        1654 :       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
    9395        1371 :         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
    9396        1371 :         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
    9397         743 :         int64_t NumEntries = j - i + 1;
    9398             : 
    9399         743 :         if (NumEntries == 1)
    9400           0 :           Score += PartitionScores::SingleCase;
    9401         743 :         else if (NumEntries <= SmallNumberOfEntries)
    9402         220 :           Score += PartitionScores::FewCases;
    9403         523 :         else if (NumEntries >= MinJumpTableEntries)
    9404         360 :           Score += PartitionScores::Table;
    9405             : 
    9406             :         // If this leads to fewer partitions, or to the same number of
    9407             :         // partitions with better score, it is a better partitioning.
    9408         743 :         if (NumPartitions < MinPartitions[i] ||
    9409          94 :             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
    9410         220 :           MinPartitions[i] = NumPartitions;
    9411         220 :           LastElement[i] = j;
    9412         220 :           PartitionsScore[i] = Score;
    9413             :         }
    9414             :       }
    9415             :     }
    9416             :   }
    9417             : 
    9418             :   // Iterate over the partitions, replacing some with jump tables in-place.
    9419             :   unsigned DstIndex = 0;
    9420         494 :   for (unsigned First = 0, Last; First < N; First = Last + 1) {
    9421         428 :     Last = LastElement[First];
    9422             :     assert(Last >= First);
    9423             :     assert(DstIndex <= First);
    9424         214 :     unsigned NumClusters = Last - First + 1;
    9425             : 
    9426             :     CaseCluster JTCluster;
    9427         253 :     if (NumClusters >= MinJumpTableEntries &&
    9428          39 :         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
    9429          58 :       Clusters[DstIndex++] = JTCluster;
    9430             :     } else {
    9431         729 :       for (unsigned I = First; I <= Last; ++I)
    9432         816 :         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
    9433             :     }
    9434             :   }
    9435          66 :   Clusters.resize(DstIndex);
    9436             : }
    9437             : 
    9438         723 : bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
    9439             :                                         unsigned First, unsigned Last,
    9440             :                                         const SwitchInst *SI,
    9441             :                                         CaseCluster &BTCluster) {
    9442             :   assert(First <= Last);
    9443         723 :   if (First == Last)
    9444             :     return false;
    9445             : 
    9446         676 :   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
    9447             :   unsigned NumCmps = 0;
    9448        1154 :   for (int64_t I = First; I <= Last; ++I) {
    9449             :     assert(Clusters[I].Kind == CC_Range);
    9450        1632 :     Dests.set(Clusters[I].MBB->getNumber());
    9451         816 :     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
    9452             :   }
    9453             :   unsigned NumDests = Dests.count();
    9454             : 
    9455         676 :   APInt Low = Clusters[First].Low->getValue();
    9456         676 :   APInt High = Clusters[Last].High->getValue();
    9457             :   assert(Low.slt(High));
    9458             : 
    9459         338 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9460         338 :   const DataLayout &DL = DAG.getDataLayout();
    9461         338 :   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
    9462             :     return false;
    9463             : 
    9464             :   APInt LowBound;
    9465             :   APInt CmpRange;
    9466             : 
    9467          26 :   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
    9468             :   assert(TLI.rangeFitsInWord(Low, High, DL) &&
    9469             :          "Case range must fit in bit mask!");
    9470             : 
    9471             :   // Check if the clusters cover a contiguous range such that no value in the
    9472             :   // range will jump to the default statement.
    9473          26 :   bool ContiguousRange = true;
    9474          61 :   for (int64_t I = First + 1; I <= Last; ++I) {
    9475         336 :     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
    9476          21 :       ContiguousRange = false;
    9477          21 :       break;
    9478             :     }
    9479             :   }
    9480             : 
    9481          26 :   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
    9482             :     // Optimize the case where all the case values fit in a word without having
    9483             :     // to subtract minValue. In this case, we can optimize away the subtraction.
    9484           8 :     LowBound = APInt::getNullValue(Low.getBitWidth());
    9485           4 :     CmpRange = High;
    9486           4 :     ContiguousRange = false;
    9487             :   } else {
    9488          22 :     LowBound = Low;
    9489          22 :     CmpRange = High - Low;
    9490             :   }
    9491             : 
    9492             :   CaseBitsVector CBV;
    9493          26 :   auto TotalProb = BranchProbability::getZero();
    9494         240 :   for (unsigned i = First; i <= Last; ++i) {
    9495             :     // Find the CaseBits for this destination.
    9496             :     unsigned j;
    9497         361 :     for (j = 0; j < CBV.size(); ++j)
    9498         228 :       if (CBV[j].BB == Clusters[i].MBB)
    9499             :         break;
    9500         107 :     if (j == CBV.size())
    9501             :       CBV.push_back(
    9502         126 :           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
    9503         107 :     CaseBits *CB = &CBV[j];
    9504             : 
    9505             :     // Update Mask, Bits and ExtraProb.
    9506         321 :     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
    9507         321 :     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
    9508             :     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
    9509         107 :     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
    9510         107 :     CB->Bits += Hi - Lo + 1;
    9511         107 :     CB->ExtraProb += Clusters[i].Prob;
    9512             :     TotalProb += Clusters[i].Prob;
    9513             :   }
    9514             : 
    9515             :   BitTestInfo BTI;
    9516             :   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
    9517             :     // Sort by probability first, number of bits second, bit mask third.
    9518          32 :     if (a.ExtraProb != b.ExtraProb)
    9519             :       return a.ExtraProb > b.ExtraProb;
    9520          13 :     if (a.Bits != b.Bits)
    9521           0 :       return a.Bits > b.Bits;
    9522          13 :     return a.Mask < b.Mask;
    9523             :   });
    9524             : 
    9525          68 :   for (auto &CB : CBV) {
    9526             :     MachineBasicBlock *BitTestBB =
    9527          42 :         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
    9528          84 :     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
    9529             :   }
    9530          78 :   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
    9531          52 :                             SI->getCondition(), -1U, MVT::Other, false,
    9532             :                             ContiguousRange, nullptr, nullptr, std::move(BTI),
    9533             :                             TotalProb);
    9534             : 
    9535          52 :   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
    9536         104 :                                     BitTestCases.size() - 1, TotalProb);
    9537             :   return true;
    9538             : }
    9539             : 
    9540        1162 : void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
    9541             :                                               const SwitchInst *SI) {
    9542             : // Partition Clusters into as few subsets as possible, where each subset has a
    9543             : // range that fits in a machine word and has <= 3 unique destinations.
    9544             : 
    9545             : #ifndef NDEBUG
    9546             :   // Clusters must be sorted and contain Range or JumpTable clusters.
    9547             :   assert(!Clusters.empty());
    9548             :   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
    9549             :   for (const CaseCluster &C : Clusters)
    9550             :     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
    9551             :   for (unsigned i = 1; i < Clusters.size(); ++i)
    9552             :     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
    9553             : #endif
    9554             : 
    9555             :   // The algorithm below is not suitable for -O0.
    9556        1162 :   if (TM.getOptLevel() == CodeGenOpt::None)
    9557         592 :     return;
    9558             : 
    9559             :   // If target does not have legal shift left, do not emit bit tests at all.
    9560         573 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9561         573 :   const DataLayout &DL = DAG.getDataLayout();
    9562             : 
    9563         573 :   EVT PTy = TLI.getPointerTy(DL);
    9564             :   if (!TLI.isOperationLegal(ISD::SHL, PTy))
    9565             :     return;
    9566             : 
    9567         570 :   int BitWidth = PTy.getSizeInBits();
    9568         570 :   const int64_t N = Clusters.size();
    9569             : 
    9570             :   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
    9571        1140 :   SmallVector<unsigned, 8> MinPartitions(N);
    9572             :   // LastElement[i] is the last element of the partition starting at i.
    9573        1140 :   SmallVector<unsigned, 8> LastElement(N);
    9574             : 
    9575             :   // FIXME: This might not be the best algorithm for finding bit test clusters.
    9576             : 
    9577             :   // Base case: There is only one way to partition Clusters[N-1].
    9578        1140 :   MinPartitions[N - 1] = 1;
    9579        1140 :   LastElement[N - 1] = N - 1;
    9580             : 
    9581             :   // Note: loop indexes are signed to avoid underflow.
    9582        1201 :   for (int64_t i = N - 2; i >= 0; --i) {
    9583             :     // Find optimal partitioning of Clusters[i..N-1].
    9584             :     // Baseline: Put Clusters[i] into a partition on its own.
    9585        1893 :     MinPartitions[i] = MinPartitions[i + 1] + 1;
    9586         631 :     LastElement[i] = i;
    9587             : 
    9588             :     // Search for a solution that results in fewer partitions.
    9589             :     // Note: the search is limited by BitWidth, reducing time complexity.
    9590        2249 :     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
    9591             :       // Try building a partition from Clusters[i..j].
    9592             : 
    9593             :       // Check the range.
    9594        2076 :       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
    9595        2076 :                                Clusters[j].High->getValue(), DL))
    9596         255 :         continue;
    9597             : 
    9598             :       // Check nbr of destinations and cluster types.
    9599             :       // FIXME: This works, but doesn't seem very efficient.
    9600             :       bool RangesOnly = true;
    9601        1566 :       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
    9602        5085 :       for (int64_t k = i; k <= j; k++) {
    9603        4330 :         if (Clusters[k].Kind != CC_Range) {
    9604             :           RangesOnly = false;
    9605             :           break;
    9606             :         }
    9607        2151 :         Dests.set(Clusters[k].MBB->getNumber());
    9608             :       }
    9609        1552 :       if (!RangesOnly || Dests.count() > 3)
    9610             :         break;
    9611             : 
    9612             :       // Check if it's a better partition.
    9613        1292 :       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
    9614         732 :       if (NumPartitions < MinPartitions[i]) {
    9615             :         // Found a better partition.
    9616         478 :         MinPartitions[i] = NumPartitions;
    9617         478 :         LastElement[i] = j;
    9618             :       }
    9619             :     }
    9620             :   }
    9621             : 
    9622             :   // Iterate over the partitions, replacing with bit-test clusters in-place.
    9623             :   unsigned DstIndex = 0;
    9624        2016 :   for (unsigned First = 0, Last; First < N; First = Last + 1) {
    9625        1446 :     Last = LastElement[First];
    9626             :     assert(First <= Last);
    9627             :     assert(DstIndex <= First);
    9628             : 
    9629             :     CaseCluster BitTestCluster;
    9630         723 :     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
    9631          52 :       Clusters[DstIndex++] = BitTestCluster;
    9632             :     } else {
    9633         697 :       size_t NumClusters = Last - First + 1;
    9634        2091 :       std::memmove(&Clusters[DstIndex], &Clusters[First],
    9635             :                    sizeof(Clusters[0]) * NumClusters);
    9636         697 :       DstIndex += NumClusters;
    9637             :     }
    9638             :   }
    9639         570 :   Clusters.resize(DstIndex);
    9640             : }
    9641             : 
    9642        1229 : void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
    9643             :                                         MachineBasicBlock *SwitchMBB,
    9644             :                                         MachineBasicBlock *DefaultMBB) {
    9645        1229 :   MachineFunction *CurMF = FuncInfo.MF;
    9646             :   MachineBasicBlock *NextMBB = nullptr;
    9647             :   MachineFunction::iterator BBI(W.MBB);
    9648        1229 :   if (++BBI != FuncInfo.MF->end())
    9649             :     NextMBB = &*BBI;
    9650             : 
    9651        1229 :   unsigned Size = W.LastCluster - W.FirstCluster + 1;
    9652             : 
    9653        1229 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    9654             : 
    9655        1229 :   if (Size == 2 && W.MBB == SwitchMBB) {
    9656             :     // If any two of the cases has the same destination, and if one value
    9657             :     // is the same as the other, but has one bit unset that the other has set,
    9658             :     // use bit manipulation to do two compares at once.  For example:
    9659             :     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
    9660             :     // TODO: This could be extended to merge any 2 cases in switches with 3
    9661             :     // cases.
    9662             :     // TODO: Handle cases where W.CaseBB != SwitchBB.
    9663             :     CaseCluster &Small = *W.FirstCluster;
    9664             :     CaseCluster &Big = *W.LastCluster;
    9665             : 
    9666        1159 :     if (Small.Low == Small.High && Big.Low == Big.High &&
    9667         446 :         Small.MBB == Big.MBB) {
    9668             :       const APInt &SmallValue = Small.Low->getValue();
    9669             :       const APInt &BigValue = Big.Low->getValue();
    9670             : 
    9671             :       // Check that there is only one bit different.
    9672          42 :       APInt CommonBit = BigValue ^ SmallValue;
    9673          42 :       if (CommonBit.isPowerOf2()) {
    9674           8 :         SDValue CondLHS = getValue(Cond);
    9675          16 :         EVT VT = CondLHS.getValueType();
    9676           8 :         SDLoc DL = getCurSDLoc();
    9677             : 
    9678           8 :         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
    9679           8 :                                  DAG.getConstant(CommonBit, DL, VT));
    9680           8 :         SDValue Cond = DAG.getSetCC(
    9681          16 :             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
    9682          16 :             ISD::SETEQ);
    9683             : 
    9684             :         // Update successor info.
    9685             :         // Both Small and Big will jump to Small.BB, so we sum up the
    9686             :         // probabilities.
    9687           8 :         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
    9688           8 :         if (BPI)
    9689           8 :           addSuccessorWithProb(
    9690             :               SwitchMBB, DefaultMBB,
    9691             :               // The default destination is the first successor in IR.
    9692             :               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
    9693             :         else
    9694           0 :           addSuccessorWithProb(SwitchMBB, DefaultMBB);
    9695             : 
    9696             :         // Insert the true branch.
    9697             :         SDValue BrCond =
    9698           8 :             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
    9699          16 :                         DAG.getBasicBlock(Small.MBB));
    9700             :         // Insert the false branch.
    9701          16 :         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
    9702          16 :                              DAG.getBasicBlock(DefaultMBB));
    9703             : 
    9704           8 :         DAG.setRoot(BrCond);
    9705             :         return;
    9706             :       }
    9707             :     }
    9708             :   }
    9709             : 
    9710        1221 :   if (TM.getOptLevel() != CodeGenOpt::None) {
    9711             :     // Here, we order cases by probability so the most likely case will be
    9712             :     // checked first. However, two clusters can have the same probability in
    9713             :     // which case their relative ordering is non-deterministic. So we use Low
    9714             :     // as a tie-breaker as clusters are guaranteed to never overlap.
    9715             :     llvm::sort(W.FirstCluster, W.LastCluster + 1,
    9716             :                [](const CaseCluster &a, const CaseCluster &b) {
    9717         952 :       return a.Prob != b.Prob ?
    9718             :              a.Prob > b.Prob :
    9719        1218 :              a.Low->getValue().slt(b.Low->getValue());
    9720             :     });
    9721             : 
    9722             :     // Rearrange the case blocks so that the last one falls through if possible
    9723             :     // without changing the order of probabilities.
    9724         933 :     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
    9725             :       --I;
    9726         469 :       if (I->Prob > W.LastCluster->Prob)
    9727             :         break;
    9728         403 :       if (I->Kind == CC_Range && I->MBB == NextMBB) {
    9729             :         std::swap(*I, *W.LastCluster);
    9730             :         break;
    9731             :       }
    9732             :     }
    9733             :   }
    9734             : 
    9735             :   // Compute total probability.
    9736        1221 :   BranchProbability DefaultProb = W.DefaultProb;
    9737             :   BranchProbability UnhandledProbs = DefaultProb;
    9738        3629 :   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
    9739             :     UnhandledProbs += I->Prob;
    9740             : 
    9741             :   MachineBasicBlock *CurMBB = W.MBB;
    9742        3629 :   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
    9743             :     MachineBasicBlock *Fallthrough;
    9744        2408 :     if (I == W.LastCluster) {
    9745             :       // For the last cluster, fall through to the default destination.
    9746             :       Fallthrough = DefaultMBB;
    9747             :     } else {
    9748        1187 :       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
    9749             :       CurMF->insert(BBI, Fallthrough);
    9750             :       // Put Cond in a virtual register to make it available from the new blocks.
    9751        1187 :       ExportFromCurrentBlock(Cond);
    9752             :     }
    9753             :     UnhandledProbs -= I->Prob;
    9754             : 
    9755        2408 :     switch (I->Kind) {
    9756             :       case CC_JumpTable: {
    9757             :         // FIXME: Optimize away range check based on pivot comparisons.
    9758         508 :         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
    9759         254 :         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
    9760             : 
    9761             :         // The jump block hasn't been inserted yet; insert it here.
    9762         254 :         MachineBasicBlock *JumpMBB = JT->MBB;
    9763             :         CurMF->insert(BBI, JumpMBB);
    9764             : 
    9765         254 :         auto JumpProb = I->Prob;
    9766             :         auto FallthroughProb = UnhandledProbs;
    9767             : 
    9768             :         // If the default statement is a target of the jump table, we evenly
    9769             :         // distribute the default probability to successors of CurMBB. Also
    9770             :         // update the probability on the edge from JumpMBB to Fallthrough.
    9771             :         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
    9772             :                                               SE = JumpMBB->succ_end();
    9773        1349 :              SI != SE; ++SI) {
    9774        1171 :           if (*SI == DefaultMBB) {
    9775             :             JumpProb += DefaultProb / 2;
    9776             :             FallthroughProb -= DefaultProb / 2;
    9777          76 :             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
    9778             :             JumpMBB->normalizeSuccProbs();
    9779             :             break;
    9780             :           }
    9781             :         }
    9782             : 
    9783         254 :         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
    9784         254 :         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
    9785             :         CurMBB->normalizeSuccProbs();
    9786             : 
    9787             :         // The jump table header will be inserted in our current block, do the
    9788             :         // range check, and fall through to our fallthrough block.
    9789         254 :         JTH->HeaderBB = CurMBB;
    9790         254 :         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
    9791             : 
    9792             :         // If we're in the right place, emit the jump table header right now.
    9793         254 :         if (CurMBB == SwitchMBB) {
    9794         241 :           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
    9795         241 :           JTH->Emitted = true;
    9796             :         }
    9797             :         break;
    9798             :       }
    9799             :       case CC_BitTests: {
    9800             :         // FIXME: Optimize away range check based on pivot comparisons.
    9801          26 :         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
    9802             : 
    9803             :         // The bit test blocks haven't been inserted yet; insert them here.
    9804         110 :         for (BitTestCase &BTC : BTB->Cases)
    9805          42 :           CurMF->insert(BBI, BTC.ThisBB);
    9806             : 
    9807             :         // Fill in fields of the BitTestBlock.
    9808          26 :         BTB->Parent = CurMBB;
    9809          26 :         BTB->Default = Fallthrough;
    9810             : 
    9811          26 :         BTB->DefaultProb = UnhandledProbs;
    9812             :         // If the cases in bit test don't form a contiguous range, we evenly
    9813             :         // distribute the probability on the edge to Fallthrough to two
    9814             :         // successors of CurMBB.
    9815          26 :         if (!BTB->ContiguousRange) {
    9816             :           BTB->Prob += DefaultProb / 2;
    9817             :           BTB->DefaultProb -= DefaultProb / 2;
    9818             :         }
    9819             : 
    9820             :         // If we're in the right place, emit the bit test header right now.
    9821          26 :         if (CurMBB == SwitchMBB) {
    9822          25 :           visitBitTestHeader(*BTB, SwitchMBB);
    9823          25 :           BTB->Emitted = true;
    9824             :         }
    9825             :         break;
    9826             :       }
    9827             :       case CC_Range: {
    9828             :         const Value *RHS, *LHS, *MHS;
    9829             :         ISD::CondCode CC;
    9830        2128 :         if (I->Low == I->High) {
    9831             :           // Check Cond == I->Low.
    9832             :           CC = ISD::SETEQ;
    9833             :           LHS = Cond;
    9834             :           RHS=I->Low;
    9835             :           MHS = nullptr;
    9836             :         } else {
    9837             :           // Check I->Low <= Cond <= I->High.
    9838             :           CC = ISD::SETLE;
    9839             :           LHS = I->Low;
    9840             :           MHS = Cond;
    9841             :           RHS = I->High;
    9842             :         }
    9843             : 
    9844             :         // The false probability is the sum of all unhandled cases.