LLVM  mainline
PPCISelLowering.cpp
Go to the documentation of this file.
00001 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the PPCISelLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCISelLowering.h"
00015 #include "MCTargetDesc/PPCPredicates.h"
00016 #include "PPCCallingConv.h"
00017 #include "PPCMachineFunctionInfo.h"
00018 #include "PPCPerfectShuffle.h"
00019 #include "PPCTargetMachine.h"
00020 #include "PPCTargetObjectFile.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/StringSwitch.h"
00023 #include "llvm/ADT/Triple.h"
00024 #include "llvm/CodeGen/CallingConvLower.h"
00025 #include "llvm/CodeGen/MachineFrameInfo.h"
00026 #include "llvm/CodeGen/MachineFunction.h"
00027 #include "llvm/CodeGen/MachineInstrBuilder.h"
00028 #include "llvm/CodeGen/MachineLoopInfo.h"
00029 #include "llvm/CodeGen/MachineRegisterInfo.h"
00030 #include "llvm/CodeGen/SelectionDAG.h"
00031 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00032 #include "llvm/IR/CallingConv.h"
00033 #include "llvm/IR/Constants.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/Function.h"
00036 #include "llvm/IR/Intrinsics.h"
00037 #include "llvm/Support/CommandLine.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/MathExtras.h"
00040 #include "llvm/Support/raw_ostream.h"
00041 #include "llvm/Target/TargetOptions.h"
00042 
00043 using namespace llvm;
00044 
00045 // FIXME: Remove this once soft-float is supported.
00046 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
00047 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
00048 
00049 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
00050 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
00051 
00052 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
00053 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
00054 
00055 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
00056 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
00057 
00058 // FIXME: Remove this once the bug has been fixed!
00059 extern cl::opt<bool> ANDIGlueBug;
00060 
00061 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
00062                                      const PPCSubtarget &STI)
00063     : TargetLowering(TM), Subtarget(STI) {
00064   // Use _setjmp/_longjmp instead of setjmp/longjmp.
00065   setUseUnderscoreSetJmp(true);
00066   setUseUnderscoreLongJmp(true);
00067 
00068   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
00069   // arguments are at least 4/8 bytes aligned.
00070   bool isPPC64 = Subtarget.isPPC64();
00071   setMinStackArgumentAlignment(isPPC64 ? 8:4);
00072 
00073   // Set up the register classes.
00074   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
00075   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
00076   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
00077 
00078   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
00079   for (MVT VT : MVT::integer_valuetypes()) {
00080     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
00081     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
00082   }
00083 
00084   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00085 
00086   // PowerPC has pre-inc load and store's.
00087   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
00088   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
00089   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
00090   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
00091   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
00092   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
00093   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
00094   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
00095   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
00096   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
00097   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
00098   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
00099   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
00100   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
00101 
00102   if (Subtarget.useCRBits()) {
00103     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00104 
00105     if (isPPC64 || Subtarget.hasFPCVT()) {
00106       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
00107       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
00108                          isPPC64 ? MVT::i64 : MVT::i32);
00109       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
00110       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
00111                          isPPC64 ? MVT::i64 : MVT::i32);
00112     } else {
00113       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
00114       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
00115     }
00116 
00117     // PowerPC does not support direct load / store of condition registers
00118     setOperationAction(ISD::LOAD, MVT::i1, Custom);
00119     setOperationAction(ISD::STORE, MVT::i1, Custom);
00120 
00121     // FIXME: Remove this once the ANDI glue bug is fixed:
00122     if (ANDIGlueBug)
00123       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
00124 
00125     for (MVT VT : MVT::integer_valuetypes()) {
00126       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
00127       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
00128       setTruncStoreAction(VT, MVT::i1, Expand);
00129     }
00130 
00131     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
00132   }
00133 
00134   // This is used in the ppcf128->int sequence.  Note it has different semantics
00135   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
00136   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
00137 
00138   // We do not currently implement these libm ops for PowerPC.
00139   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
00140   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
00141   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
00142   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
00143   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
00144   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
00145 
00146   // PowerPC has no SREM/UREM instructions
00147   setOperationAction(ISD::SREM, MVT::i32, Expand);
00148   setOperationAction(ISD::UREM, MVT::i32, Expand);
00149   setOperationAction(ISD::SREM, MVT::i64, Expand);
00150   setOperationAction(ISD::UREM, MVT::i64, Expand);
00151 
00152   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
00153   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00155   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
00156   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
00157   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00158   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00159   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
00160   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
00161 
00162   // We don't support sin/cos/sqrt/fmod/pow
00163   setOperationAction(ISD::FSIN , MVT::f64, Expand);
00164   setOperationAction(ISD::FCOS , MVT::f64, Expand);
00165   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
00166   setOperationAction(ISD::FREM , MVT::f64, Expand);
00167   setOperationAction(ISD::FPOW , MVT::f64, Expand);
00168   setOperationAction(ISD::FMA  , MVT::f64, Legal);
00169   setOperationAction(ISD::FSIN , MVT::f32, Expand);
00170   setOperationAction(ISD::FCOS , MVT::f32, Expand);
00171   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
00172   setOperationAction(ISD::FREM , MVT::f32, Expand);
00173   setOperationAction(ISD::FPOW , MVT::f32, Expand);
00174   setOperationAction(ISD::FMA  , MVT::f32, Legal);
00175 
00176   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00177 
00178   // If we're enabling GP optimizations, use hardware square root
00179   if (!Subtarget.hasFSQRT() &&
00180       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
00181         Subtarget.hasFRE()))
00182     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
00183 
00184   if (!Subtarget.hasFSQRT() &&
00185       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
00186         Subtarget.hasFRES()))
00187     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
00188 
00189   if (Subtarget.hasFCPSGN()) {
00190     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
00191     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
00192   } else {
00193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
00195   }
00196 
00197   if (Subtarget.hasFPRND()) {
00198     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
00199     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
00200     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
00201     setOperationAction(ISD::FROUND, MVT::f64, Legal);
00202 
00203     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
00204     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
00205     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
00206     setOperationAction(ISD::FROUND, MVT::f32, Legal);
00207   }
00208 
00209   // PowerPC does not have BSWAP, CTPOP or CTTZ
00210   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
00211   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
00212   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
00213   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
00214   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
00215   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
00216   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
00217   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
00218 
00219   if (Subtarget.hasPOPCNTD()) {
00220     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
00221     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
00222   } else {
00223     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
00224     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
00225   }
00226 
00227   // PowerPC does not have ROTR
00228   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
00229   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
00230 
00231   if (!Subtarget.useCRBits()) {
00232     // PowerPC does not have Select
00233     setOperationAction(ISD::SELECT, MVT::i32, Expand);
00234     setOperationAction(ISD::SELECT, MVT::i64, Expand);
00235     setOperationAction(ISD::SELECT, MVT::f32, Expand);
00236     setOperationAction(ISD::SELECT, MVT::f64, Expand);
00237   }
00238 
00239   // PowerPC wants to turn select_cc of FP into fsel when possible.
00240   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00241   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00242 
00243   // PowerPC wants to optimize integer setcc a bit
00244   if (!Subtarget.useCRBits())
00245     setOperationAction(ISD::SETCC, MVT::i32, Custom);
00246 
00247   // PowerPC does not have BRCOND which requires SetCC
00248   if (!Subtarget.useCRBits())
00249     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00250 
00251   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
00252 
00253   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
00254   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00255 
00256   // PowerPC does not have [U|S]INT_TO_FP
00257   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
00258   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
00259 
00260   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
00261   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
00262   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
00263   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
00264 
00265   // We cannot sextinreg(i1).  Expand to shifts.
00266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00267 
00268   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
00269   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
00270   // support continuation, user-level threading, and etc.. As a result, no
00271   // other SjLj exception interfaces are implemented and please don't build
00272   // your own exception handling based on them.
00273   // LLVM/Clang supports zero-cost DWARF exception handling.
00274   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
00275   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
00276 
00277   // We want to legalize GlobalAddress and ConstantPool nodes into the
00278   // appropriate instructions to materialize the address.
00279   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
00280   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00281   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
00282   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
00283   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
00284   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
00285   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
00286   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
00287   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
00288   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
00289 
00290   // TRAP is legal.
00291   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00292 
00293   // TRAMPOLINE is custom lowered.
00294   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
00295   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
00296 
00297   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
00298   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
00299 
00300   if (Subtarget.isSVR4ABI()) {
00301     if (isPPC64) {
00302       // VAARG always uses double-word chunks, so promote anything smaller.
00303       setOperationAction(ISD::VAARG, MVT::i1, Promote);
00304       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
00305       setOperationAction(ISD::VAARG, MVT::i8, Promote);
00306       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
00307       setOperationAction(ISD::VAARG, MVT::i16, Promote);
00308       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
00309       setOperationAction(ISD::VAARG, MVT::i32, Promote);
00310       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
00311       setOperationAction(ISD::VAARG, MVT::Other, Expand);
00312     } else {
00313       // VAARG is custom lowered with the 32-bit SVR4 ABI.
00314       setOperationAction(ISD::VAARG, MVT::Other, Custom);
00315       setOperationAction(ISD::VAARG, MVT::i64, Custom);
00316     }
00317   } else
00318     setOperationAction(ISD::VAARG, MVT::Other, Expand);
00319 
00320   if (Subtarget.isSVR4ABI() && !isPPC64)
00321     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
00322     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
00323   else
00324     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
00325 
00326   // Use the default implementation.
00327   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
00328   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
00329   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
00330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
00331   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
00332 
00333   // We want to custom lower some of our intrinsics.
00334   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00335 
00336   // To handle counter-based loop conditions.
00337   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
00338 
00339   // Comparisons that require checking two conditions.
00340   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
00341   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
00342   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
00343   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
00344   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
00345   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
00346   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
00347   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
00348   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
00349   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
00350   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
00351   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
00352 
00353   if (Subtarget.has64BitSupport()) {
00354     // They also have instructions for converting between i64 and fp.
00355     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
00356     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
00357     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
00358     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
00359     // This is just the low 32 bits of a (signed) fp->i64 conversion.
00360     // We cannot do this with Promote because i64 is not a legal type.
00361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00362 
00363     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
00364       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00365   } else {
00366     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
00367     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
00368   }
00369 
00370   // With the instructions enabled under FPCVT, we can do everything.
00371   if (Subtarget.hasFPCVT()) {
00372     if (Subtarget.has64BitSupport()) {
00373       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
00374       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
00375       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
00376       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
00377     }
00378 
00379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
00383   }
00384 
00385   if (Subtarget.use64BitRegs()) {
00386     // 64-bit PowerPC implementations can support i64 types directly
00387     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
00388     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
00389     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
00390     // 64-bit PowerPC wants to expand i128 shifts itself.
00391     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
00392     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
00393     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
00394   } else {
00395     // 32-bit PowerPC wants to expand i64 shifts itself.
00396     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00397     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00398     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00399   }
00400 
00401   if (Subtarget.hasAltivec()) {
00402     // First set operation action for all vector types to expand. Then we
00403     // will selectively turn on ones that can be effectively codegen'd.
00404     for (MVT VT : MVT::vector_valuetypes()) {
00405       // add/sub are legal for all supported vector VT's.
00406       setOperationAction(ISD::ADD , VT, Legal);
00407       setOperationAction(ISD::SUB , VT, Legal);
00408       
00409       // Vector instructions introduced in P8
00410       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
00411         setOperationAction(ISD::CTPOP, VT, Legal);
00412         setOperationAction(ISD::CTLZ, VT, Legal);
00413       }
00414       else {
00415         setOperationAction(ISD::CTPOP, VT, Expand);
00416         setOperationAction(ISD::CTLZ, VT, Expand);
00417       }
00418 
00419       // We promote all shuffles to v16i8.
00420       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
00421       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
00422 
00423       // We promote all non-typed operations to v4i32.
00424       setOperationAction(ISD::AND   , VT, Promote);
00425       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
00426       setOperationAction(ISD::OR    , VT, Promote);
00427       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
00428       setOperationAction(ISD::XOR   , VT, Promote);
00429       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
00430       setOperationAction(ISD::LOAD  , VT, Promote);
00431       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
00432       setOperationAction(ISD::SELECT, VT, Promote);
00433       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
00434       setOperationAction(ISD::STORE, VT, Promote);
00435       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
00436 
00437       // No other operations are legal.
00438       setOperationAction(ISD::MUL , VT, Expand);
00439       setOperationAction(ISD::SDIV, VT, Expand);
00440       setOperationAction(ISD::SREM, VT, Expand);
00441       setOperationAction(ISD::UDIV, VT, Expand);
00442       setOperationAction(ISD::UREM, VT, Expand);
00443       setOperationAction(ISD::FDIV, VT, Expand);
00444       setOperationAction(ISD::FREM, VT, Expand);
00445       setOperationAction(ISD::FNEG, VT, Expand);
00446       setOperationAction(ISD::FSQRT, VT, Expand);
00447       setOperationAction(ISD::FLOG, VT, Expand);
00448       setOperationAction(ISD::FLOG10, VT, Expand);
00449       setOperationAction(ISD::FLOG2, VT, Expand);
00450       setOperationAction(ISD::FEXP, VT, Expand);
00451       setOperationAction(ISD::FEXP2, VT, Expand);
00452       setOperationAction(ISD::FSIN, VT, Expand);
00453       setOperationAction(ISD::FCOS, VT, Expand);
00454       setOperationAction(ISD::FABS, VT, Expand);
00455       setOperationAction(ISD::FPOWI, VT, Expand);
00456       setOperationAction(ISD::FFLOOR, VT, Expand);
00457       setOperationAction(ISD::FCEIL,  VT, Expand);
00458       setOperationAction(ISD::FTRUNC, VT, Expand);
00459       setOperationAction(ISD::FRINT,  VT, Expand);
00460       setOperationAction(ISD::FNEARBYINT, VT, Expand);
00461       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
00462       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
00463       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
00464       setOperationAction(ISD::MULHU, VT, Expand);
00465       setOperationAction(ISD::MULHS, VT, Expand);
00466       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
00467       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
00468       setOperationAction(ISD::UDIVREM, VT, Expand);
00469       setOperationAction(ISD::SDIVREM, VT, Expand);
00470       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
00471       setOperationAction(ISD::FPOW, VT, Expand);
00472       setOperationAction(ISD::BSWAP, VT, Expand);
00473       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
00474       setOperationAction(ISD::CTTZ, VT, Expand);
00475       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
00476       setOperationAction(ISD::VSELECT, VT, Expand);
00477       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
00478 
00479       for (MVT InnerVT : MVT::vector_valuetypes()) {
00480         setTruncStoreAction(VT, InnerVT, Expand);
00481         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
00482         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
00483         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
00484       }
00485     }
00486 
00487     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
00488     // with merges, splats, etc.
00489     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
00490 
00491     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
00492     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
00493     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
00494     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
00495     setOperationAction(ISD::SELECT, MVT::v4i32,
00496                        Subtarget.useCRBits() ? Legal : Expand);
00497     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
00498     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
00499     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
00500     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
00501     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
00502     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
00503     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
00504     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
00505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
00506 
00507     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
00508     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
00509     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
00510     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
00511 
00512     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
00513     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
00514 
00515     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
00516       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
00517       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
00518     }
00519 
00520     
00521     if (Subtarget.hasP8Altivec()) 
00522       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
00523     else
00524       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00525       
00526     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00527     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
00528 
00529     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
00530     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
00531 
00532     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
00533     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
00534     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
00535     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
00536 
00537     // Altivec does not contain unordered floating-point compare instructions
00538     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
00539     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
00540     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
00541     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
00542 
00543     if (Subtarget.hasVSX()) {
00544       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
00545       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
00546 
00547       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
00548       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
00549       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
00550       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
00551       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
00552 
00553       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
00554 
00555       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
00556       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
00557 
00558       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
00559       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
00560 
00561       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
00562       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
00563       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
00564       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
00565       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
00566 
00567       // Share the Altivec comparison restrictions.
00568       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
00569       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
00570       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
00571       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
00572 
00573       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
00574       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
00575 
00576       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
00577 
00578       if (Subtarget.hasP8Vector())
00579         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
00580 
00581       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
00582 
00583       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
00584       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
00585 
00586       if (Subtarget.hasP8Altivec()) {
00587         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
00588         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
00589         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
00590 
00591         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
00592       }
00593       else {
00594         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
00595         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
00596         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
00597 
00598         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
00599 
00600         // VSX v2i64 only supports non-arithmetic operations.
00601         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
00602         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
00603       }
00604 
00605       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
00606       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
00607       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
00608       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
00609 
00610       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
00611 
00612       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
00613       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
00614       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
00615       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
00616 
00617       // Vector operation legalization checks the result type of
00618       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
00619       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
00620       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
00621       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
00622       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
00623 
00624       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
00625     }
00626 
00627     if (Subtarget.hasP8Altivec()) {
00628       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
00629       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
00630     }
00631   }
00632 
00633   if (Subtarget.hasQPX()) {
00634     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
00635     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
00636     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
00637     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
00638 
00639     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
00640     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
00641 
00642     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
00643     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
00644 
00645     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
00646     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
00647 
00648     if (!Subtarget.useCRBits())
00649       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
00650     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
00651 
00652     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
00653     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
00654     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
00655     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
00656     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
00657     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
00658     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
00659 
00660     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
00661     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
00662 
00663     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
00664     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
00665     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
00666 
00667     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
00668     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
00669     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
00670     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
00671     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
00672     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
00673     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
00674     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
00675     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
00676     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
00677     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
00678 
00679     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
00680     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
00681 
00682     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
00683     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
00684 
00685     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
00686 
00687     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
00688     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
00689     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
00690     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
00691 
00692     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
00693     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
00694 
00695     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
00696     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
00697 
00698     if (!Subtarget.useCRBits())
00699       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
00700     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
00701 
00702     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
00703     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
00704     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
00705     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
00706     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
00707     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
00708     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
00709 
00710     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
00711     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
00712 
00713     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
00714     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
00715     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
00716     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
00717     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
00718     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
00719     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
00720     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
00721     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
00722     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
00723     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
00724 
00725     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
00726     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
00727 
00728     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
00729     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
00730 
00731     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
00732 
00733     setOperationAction(ISD::AND , MVT::v4i1, Legal);
00734     setOperationAction(ISD::OR , MVT::v4i1, Legal);
00735     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
00736 
00737     if (!Subtarget.useCRBits())
00738       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
00739     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
00740 
00741     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
00742     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
00743 
00744     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
00745     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
00746     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
00747     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
00748     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
00749     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
00750     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
00751 
00752     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
00753     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
00754 
00755     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
00756 
00757     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
00758     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
00759     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
00760     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
00761 
00762     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
00763     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
00764     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
00765     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
00766 
00767     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
00768     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
00769 
00770     // These need to set FE_INEXACT, and so cannot be vectorized here.
00771     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
00772     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
00773 
00774     if (TM.Options.UnsafeFPMath) {
00775       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
00776       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
00777 
00778       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
00779       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
00780     } else {
00781       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
00782       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
00783 
00784       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
00785       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
00786     }
00787   }
00788 
00789   if (Subtarget.has64BitSupport())
00790     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
00791 
00792   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
00793 
00794   if (!isPPC64) {
00795     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
00796     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
00797   }
00798 
00799   setBooleanContents(ZeroOrOneBooleanContent);
00800 
00801   if (Subtarget.hasAltivec()) {
00802     // Altivec instructions set fields to all zeros or all ones.
00803     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00804   }
00805 
00806   if (!isPPC64) {
00807     // These libcalls are not available in 32-bit.
00808     setLibcallName(RTLIB::SHL_I128, nullptr);
00809     setLibcallName(RTLIB::SRL_I128, nullptr);
00810     setLibcallName(RTLIB::SRA_I128, nullptr);
00811   }
00812 
00813   if (isPPC64) {
00814     setStackPointerRegisterToSaveRestore(PPC::X1);
00815     setExceptionPointerRegister(PPC::X3);
00816     setExceptionSelectorRegister(PPC::X4);
00817   } else {
00818     setStackPointerRegisterToSaveRestore(PPC::R1);
00819     setExceptionPointerRegister(PPC::R3);
00820     setExceptionSelectorRegister(PPC::R4);
00821   }
00822 
00823   // We have target-specific dag combine patterns for the following nodes:
00824   setTargetDAGCombine(ISD::SINT_TO_FP);
00825   if (Subtarget.hasFPCVT())
00826     setTargetDAGCombine(ISD::UINT_TO_FP);
00827   setTargetDAGCombine(ISD::LOAD);
00828   setTargetDAGCombine(ISD::STORE);
00829   setTargetDAGCombine(ISD::BR_CC);
00830   if (Subtarget.useCRBits())
00831     setTargetDAGCombine(ISD::BRCOND);
00832   setTargetDAGCombine(ISD::BSWAP);
00833   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
00834   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
00835   setTargetDAGCombine(ISD::INTRINSIC_VOID);
00836 
00837   setTargetDAGCombine(ISD::SIGN_EXTEND);
00838   setTargetDAGCombine(ISD::ZERO_EXTEND);
00839   setTargetDAGCombine(ISD::ANY_EXTEND);
00840 
00841   if (Subtarget.useCRBits()) {
00842     setTargetDAGCombine(ISD::TRUNCATE);
00843     setTargetDAGCombine(ISD::SETCC);
00844     setTargetDAGCombine(ISD::SELECT_CC);
00845   }
00846 
00847   // Use reciprocal estimates.
00848   if (TM.Options.UnsafeFPMath) {
00849     setTargetDAGCombine(ISD::FDIV);
00850     setTargetDAGCombine(ISD::FSQRT);
00851   }
00852 
00853   // Darwin long double math library functions have $LDBL128 appended.
00854   if (Subtarget.isDarwin()) {
00855     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
00856     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
00857     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
00858     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
00859     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
00860     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
00861     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
00862     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
00863     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
00864     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
00865   }
00866 
00867   // With 32 condition bits, we don't need to sink (and duplicate) compares
00868   // aggressively in CodeGenPrep.
00869   if (Subtarget.useCRBits()) {
00870     setHasMultipleConditionRegisters();
00871     setJumpIsExpensive();
00872   }
00873 
00874   setMinFunctionAlignment(2);
00875   if (Subtarget.isDarwin())
00876     setPrefFunctionAlignment(4);
00877 
00878   switch (Subtarget.getDarwinDirective()) {
00879   default: break;
00880   case PPC::DIR_970:
00881   case PPC::DIR_A2:
00882   case PPC::DIR_E500mc:
00883   case PPC::DIR_E5500:
00884   case PPC::DIR_PWR4:
00885   case PPC::DIR_PWR5:
00886   case PPC::DIR_PWR5X:
00887   case PPC::DIR_PWR6:
00888   case PPC::DIR_PWR6X:
00889   case PPC::DIR_PWR7:
00890   case PPC::DIR_PWR8:
00891     setPrefFunctionAlignment(4);
00892     setPrefLoopAlignment(4);
00893     break;
00894   }
00895 
00896   setInsertFencesForAtomic(true);
00897 
00898   if (Subtarget.enableMachineScheduler())
00899     setSchedulingPreference(Sched::Source);
00900   else
00901     setSchedulingPreference(Sched::Hybrid);
00902 
00903   computeRegisterProperties(STI.getRegisterInfo());
00904 
00905   // The Freescale cores do better with aggressive inlining of memcpy and
00906   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
00907   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
00908       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
00909     MaxStoresPerMemset = 32;
00910     MaxStoresPerMemsetOptSize = 16;
00911     MaxStoresPerMemcpy = 32;
00912     MaxStoresPerMemcpyOptSize = 8;
00913     MaxStoresPerMemmove = 32;
00914     MaxStoresPerMemmoveOptSize = 8;
00915   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
00916     // The A2 also benefits from (very) aggressive inlining of memcpy and
00917     // friends. The overhead of a the function call, even when warm, can be
00918     // over one hundred cycles.
00919     MaxStoresPerMemset = 128;
00920     MaxStoresPerMemcpy = 128;
00921     MaxStoresPerMemmove = 128;
00922   }
00923 }
00924 
00925 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
00926 /// the desired ByVal argument alignment.
00927 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
00928                              unsigned MaxMaxAlign) {
00929   if (MaxAlign == MaxMaxAlign)
00930     return;
00931   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00932     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
00933       MaxAlign = 32;
00934     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
00935       MaxAlign = 16;
00936   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00937     unsigned EltAlign = 0;
00938     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
00939     if (EltAlign > MaxAlign)
00940       MaxAlign = EltAlign;
00941   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
00942     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00943       unsigned EltAlign = 0;
00944       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
00945       if (EltAlign > MaxAlign)
00946         MaxAlign = EltAlign;
00947       if (MaxAlign == MaxMaxAlign)
00948         break;
00949     }
00950   }
00951 }
00952 
00953 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
00954 /// function arguments in the caller parameter area.
00955 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
00956   // Darwin passes everything on 4 byte boundary.
00957   if (Subtarget.isDarwin())
00958     return 4;
00959 
00960   // 16byte and wider vectors are passed on 16byte boundary.
00961   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
00962   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
00963   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
00964     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
00965   return Align;
00966 }
00967 
00968 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
00969   switch ((PPCISD::NodeType)Opcode) {
00970   case PPCISD::FIRST_NUMBER:    break;
00971   case PPCISD::FSEL:            return "PPCISD::FSEL";
00972   case PPCISD::FCFID:           return "PPCISD::FCFID";
00973   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
00974   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
00975   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
00976   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
00977   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
00978   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
00979   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
00980   case PPCISD::FRE:             return "PPCISD::FRE";
00981   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
00982   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
00983   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
00984   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
00985   case PPCISD::VPERM:           return "PPCISD::VPERM";
00986   case PPCISD::CMPB:            return "PPCISD::CMPB";
00987   case PPCISD::Hi:              return "PPCISD::Hi";
00988   case PPCISD::Lo:              return "PPCISD::Lo";
00989   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
00990   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
00991   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
00992   case PPCISD::SRL:             return "PPCISD::SRL";
00993   case PPCISD::SRA:             return "PPCISD::SRA";
00994   case PPCISD::SHL:             return "PPCISD::SHL";
00995   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
00996   case PPCISD::CALL:            return "PPCISD::CALL";
00997   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
00998   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
00999   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
01000   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
01001   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
01002   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
01003   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
01004   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
01005   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
01006   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
01007   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
01008   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
01009   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
01010   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
01011   case PPCISD::VCMP:            return "PPCISD::VCMP";
01012   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
01013   case PPCISD::LBRX:            return "PPCISD::LBRX";
01014   case PPCISD::STBRX:           return "PPCISD::STBRX";
01015   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
01016   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
01017   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
01018   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
01019   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
01020   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
01021   case PPCISD::BDZ:             return "PPCISD::BDZ";
01022   case PPCISD::MFFS:            return "PPCISD::MFFS";
01023   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
01024   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
01025   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
01026   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
01027   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
01028   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
01029   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
01030   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
01031   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
01032   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
01033   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
01034   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
01035   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
01036   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
01037   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
01038   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
01039   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
01040   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
01041   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
01042   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
01043   case PPCISD::SC:              return "PPCISD::SC";
01044   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
01045   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
01046   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
01047   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
01048   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
01049   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
01050   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
01051   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
01052   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
01053   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
01054   }
01055   return nullptr;
01056 }
01057 
01058 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
01059   if (!VT.isVector())
01060     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
01061 
01062   if (Subtarget.hasQPX())
01063     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
01064 
01065   return VT.changeVectorElementTypeToInteger();
01066 }
01067 
01068 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
01069   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
01070   return true;
01071 }
01072 
01073 //===----------------------------------------------------------------------===//
01074 // Node matching predicates, for use by the tblgen matching code.
01075 //===----------------------------------------------------------------------===//
01076 
01077 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
01078 static bool isFloatingPointZero(SDValue Op) {
01079   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
01080     return CFP->getValueAPF().isZero();
01081   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
01082     // Maybe this has already been legalized into the constant pool?
01083     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
01084       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
01085         return CFP->getValueAPF().isZero();
01086   }
01087   return false;
01088 }
01089 
01090 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
01091 /// true if Op is undef or if it matches the specified value.
01092 static bool isConstantOrUndef(int Op, int Val) {
01093   return Op < 0 || Op == Val;
01094 }
01095 
01096 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
01097 /// VPKUHUM instruction.
01098 /// The ShuffleKind distinguishes between big-endian operations with
01099 /// two different inputs (0), either-endian operations with two identical
01100 /// inputs (1), and little-endian operations with two different inputs (2).
01101 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
01102 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
01103                                SelectionDAG &DAG) {
01104   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
01105   if (ShuffleKind == 0) {
01106     if (IsLE)
01107       return false;
01108     for (unsigned i = 0; i != 16; ++i)
01109       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
01110         return false;
01111   } else if (ShuffleKind == 2) {
01112     if (!IsLE)
01113       return false;
01114     for (unsigned i = 0; i != 16; ++i)
01115       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
01116         return false;
01117   } else if (ShuffleKind == 1) {
01118     unsigned j = IsLE ? 0 : 1;
01119     for (unsigned i = 0; i != 8; ++i)
01120       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
01121           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
01122         return false;
01123   }
01124   return true;
01125 }
01126 
01127 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
01128 /// VPKUWUM instruction.
01129 /// The ShuffleKind distinguishes between big-endian operations with
01130 /// two different inputs (0), either-endian operations with two identical
01131 /// inputs (1), and little-endian operations with two different inputs (2).
01132 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
01133 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
01134                                SelectionDAG &DAG) {
01135   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
01136   if (ShuffleKind == 0) {
01137     if (IsLE)
01138       return false;
01139     for (unsigned i = 0; i != 16; i += 2)
01140       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
01141           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
01142         return false;
01143   } else if (ShuffleKind == 2) {
01144     if (!IsLE)
01145       return false;
01146     for (unsigned i = 0; i != 16; i += 2)
01147       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
01148           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
01149         return false;
01150   } else if (ShuffleKind == 1) {
01151     unsigned j = IsLE ? 0 : 2;
01152     for (unsigned i = 0; i != 8; i += 2)
01153       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
01154           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
01155           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
01156           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
01157         return false;
01158   }
01159   return true;
01160 }
01161 
01162 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
01163 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
01164 /// current subtarget.
01165 ///
01166 /// The ShuffleKind distinguishes between big-endian operations with
01167 /// two different inputs (0), either-endian operations with two identical
01168 /// inputs (1), and little-endian operations with two different inputs (2).
01169 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
01170 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
01171                                SelectionDAG &DAG) {
01172   const PPCSubtarget& Subtarget =
01173     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
01174   if (!Subtarget.hasP8Vector())
01175     return false;
01176 
01177   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
01178   if (ShuffleKind == 0) {
01179     if (IsLE)
01180       return false;
01181     for (unsigned i = 0; i != 16; i += 4)
01182       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
01183           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
01184           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
01185           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
01186         return false;
01187   } else if (ShuffleKind == 2) {
01188     if (!IsLE)
01189       return false;
01190     for (unsigned i = 0; i != 16; i += 4)
01191       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
01192           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
01193           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
01194           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
01195         return false;
01196   } else if (ShuffleKind == 1) {
01197     unsigned j = IsLE ? 0 : 4;
01198     for (unsigned i = 0; i != 8; i += 4)
01199       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
01200           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
01201           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
01202           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
01203           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
01204           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
01205           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
01206           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
01207         return false;
01208   }
01209   return true;
01210 }
01211 
01212 /// isVMerge - Common function, used to match vmrg* shuffles.
01213 ///
01214 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
01215                      unsigned LHSStart, unsigned RHSStart) {
01216   if (N->getValueType(0) != MVT::v16i8)
01217     return false;
01218   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
01219          "Unsupported merge size!");
01220 
01221   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
01222     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
01223       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
01224                              LHSStart+j+i*UnitSize) ||
01225           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
01226                              RHSStart+j+i*UnitSize))
01227         return false;
01228     }
01229   return true;
01230 }
01231 
01232 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
01233 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
01234 /// The ShuffleKind distinguishes between big-endian merges with two 
01235 /// different inputs (0), either-endian merges with two identical inputs (1),
01236 /// and little-endian merges with two different inputs (2).  For the latter,
01237 /// the input operands are swapped (see PPCInstrAltivec.td).
01238 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
01239                              unsigned ShuffleKind, SelectionDAG &DAG) {
01240   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
01241     if (ShuffleKind == 1) // unary
01242       return isVMerge(N, UnitSize, 0, 0);
01243     else if (ShuffleKind == 2) // swapped
01244       return isVMerge(N, UnitSize, 0, 16);
01245     else
01246       return false;
01247   } else {
01248     if (ShuffleKind == 1) // unary
01249       return isVMerge(N, UnitSize, 8, 8);
01250     else if (ShuffleKind == 0) // normal
01251       return isVMerge(N, UnitSize, 8, 24);
01252     else
01253       return false;
01254   }
01255 }
01256 
01257 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
01258 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
01259 /// The ShuffleKind distinguishes between big-endian merges with two 
01260 /// different inputs (0), either-endian merges with two identical inputs (1),
01261 /// and little-endian merges with two different inputs (2).  For the latter,
01262 /// the input operands are swapped (see PPCInstrAltivec.td).
01263 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
01264                              unsigned ShuffleKind, SelectionDAG &DAG) {
01265   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
01266     if (ShuffleKind == 1) // unary
01267       return isVMerge(N, UnitSize, 8, 8);
01268     else if (ShuffleKind == 2) // swapped
01269       return isVMerge(N, UnitSize, 8, 24);
01270     else
01271       return false;
01272   } else {
01273     if (ShuffleKind == 1) // unary
01274       return isVMerge(N, UnitSize, 0, 0);
01275     else if (ShuffleKind == 0) // normal
01276       return isVMerge(N, UnitSize, 0, 16);
01277     else
01278       return false;
01279   }
01280 }
01281 
01282 
01283 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
01284 /// amount, otherwise return -1.
01285 /// The ShuffleKind distinguishes between big-endian operations with two 
01286 /// different inputs (0), either-endian operations with two identical inputs
01287 /// (1), and little-endian operations with two different inputs (2).  For the
01288 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
01289 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
01290                              SelectionDAG &DAG) {
01291   if (N->getValueType(0) != MVT::v16i8)
01292     return -1;
01293 
01294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
01295 
01296   // Find the first non-undef value in the shuffle mask.
01297   unsigned i;
01298   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
01299     /*search*/;
01300 
01301   if (i == 16) return -1;  // all undef.
01302 
01303   // Otherwise, check to see if the rest of the elements are consecutively
01304   // numbered from this value.
01305   unsigned ShiftAmt = SVOp->getMaskElt(i);
01306   if (ShiftAmt < i) return -1;
01307 
01308   ShiftAmt -= i;
01309   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
01310 
01311   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
01312     // Check the rest of the elements to see if they are consecutive.
01313     for (++i; i != 16; ++i)
01314       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
01315         return -1;
01316   } else if (ShuffleKind == 1) {
01317     // Check the rest of the elements to see if they are consecutive.
01318     for (++i; i != 16; ++i)
01319       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
01320         return -1;
01321   } else
01322     return -1;
01323 
01324   if (ShuffleKind == 2 && isLE)
01325     ShiftAmt = 16 - ShiftAmt;
01326 
01327   return ShiftAmt;
01328 }
01329 
01330 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
01331 /// specifies a splat of a single element that is suitable for input to
01332 /// VSPLTB/VSPLTH/VSPLTW.
01333 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
01334   assert(N->getValueType(0) == MVT::v16i8 &&
01335          (EltSize == 1 || EltSize == 2 || EltSize == 4));
01336 
01337   // This is a splat operation if each element of the permute is the same, and
01338   // if the value doesn't reference the second vector.
01339   unsigned ElementBase = N->getMaskElt(0);
01340 
01341   // FIXME: Handle UNDEF elements too!
01342   if (ElementBase >= 16)
01343     return false;
01344 
01345   // Check that the indices are consecutive, in the case of a multi-byte element
01346   // splatted with a v16i8 mask.
01347   for (unsigned i = 1; i != EltSize; ++i)
01348     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
01349       return false;
01350 
01351   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
01352     if (N->getMaskElt(i) < 0) continue;
01353     for (unsigned j = 0; j != EltSize; ++j)
01354       if (N->getMaskElt(i+j) != N->getMaskElt(j))
01355         return false;
01356   }
01357   return true;
01358 }
01359 
01360 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
01361 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
01362 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
01363                                 SelectionDAG &DAG) {
01364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
01365   assert(isSplatShuffleMask(SVOp, EltSize));
01366   if (DAG.getTarget().getDataLayout()->isLittleEndian())
01367     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
01368   else
01369     return SVOp->getMaskElt(0) / EltSize;
01370 }
01371 
01372 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
01373 /// by using a vspltis[bhw] instruction of the specified element size, return
01374 /// the constant being splatted.  The ByteSize field indicates the number of
01375 /// bytes of each element [124] -> [bhw].
01376 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
01377   SDValue OpVal(nullptr, 0);
01378 
01379   // If ByteSize of the splat is bigger than the element size of the
01380   // build_vector, then we have a case where we are checking for a splat where
01381   // multiple elements of the buildvector are folded together into a single
01382   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
01383   unsigned EltSize = 16/N->getNumOperands();
01384   if (EltSize < ByteSize) {
01385     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
01386     SDValue UniquedVals[4];
01387     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
01388 
01389     // See if all of the elements in the buildvector agree across.
01390     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
01391       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
01392       // If the element isn't a constant, bail fully out.
01393       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
01394 
01395 
01396       if (!UniquedVals[i&(Multiple-1)].getNode())
01397         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
01398       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
01399         return SDValue();  // no match.
01400     }
01401 
01402     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
01403     // either constant or undef values that are identical for each chunk.  See
01404     // if these chunks can form into a larger vspltis*.
01405 
01406     // Check to see if all of the leading entries are either 0 or -1.  If
01407     // neither, then this won't fit into the immediate field.
01408     bool LeadingZero = true;
01409     bool LeadingOnes = true;
01410     for (unsigned i = 0; i != Multiple-1; ++i) {
01411       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
01412 
01413       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
01414       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
01415     }
01416     // Finally, check the least significant entry.
01417     if (LeadingZero) {
01418       if (!UniquedVals[Multiple-1].getNode())
01419         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
01420       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
01421       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
01422         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
01423     }
01424     if (LeadingOnes) {
01425       if (!UniquedVals[Multiple-1].getNode())
01426         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
01427       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
01428       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
01429         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
01430     }
01431 
01432     return SDValue();
01433   }
01434 
01435   // Check to see if this buildvec has a single non-undef value in its elements.
01436   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
01437     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
01438     if (!OpVal.getNode())
01439       OpVal = N->getOperand(i);
01440     else if (OpVal != N->getOperand(i))
01441       return SDValue();
01442   }
01443 
01444   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
01445 
01446   unsigned ValSizeInBytes = EltSize;
01447   uint64_t Value = 0;
01448   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
01449     Value = CN->getZExtValue();
01450   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
01451     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
01452     Value = FloatToBits(CN->getValueAPF().convertToFloat());
01453   }
01454 
01455   // If the splat value is larger than the element value, then we can never do
01456   // this splat.  The only case that we could fit the replicated bits into our
01457   // immediate field for would be zero, and we prefer to use vxor for it.
01458   if (ValSizeInBytes < ByteSize) return SDValue();
01459 
01460   // If the element value is larger than the splat value, check if it consists
01461   // of a repeated bit pattern of size ByteSize.
01462   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
01463     return SDValue();
01464 
01465   // Properly sign extend the value.
01466   int MaskVal = SignExtend32(Value, ByteSize * 8);
01467 
01468   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
01469   if (MaskVal == 0) return SDValue();
01470 
01471   // Finally, if this value fits in a 5 bit sext field, return it
01472   if (SignExtend32<5>(MaskVal) == MaskVal)
01473     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
01474   return SDValue();
01475 }
01476 
01477 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
01478 /// amount, otherwise return -1.
01479 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
01480   EVT VT = N->getValueType(0);
01481   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
01482     return -1;
01483 
01484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
01485 
01486   // Find the first non-undef value in the shuffle mask.
01487   unsigned i;
01488   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
01489     /*search*/;
01490 
01491   if (i == 4) return -1;  // all undef.
01492 
01493   // Otherwise, check to see if the rest of the elements are consecutively
01494   // numbered from this value.
01495   unsigned ShiftAmt = SVOp->getMaskElt(i);
01496   if (ShiftAmt < i) return -1;
01497   ShiftAmt -= i;
01498 
01499   // Check the rest of the elements to see if they are consecutive.
01500   for (++i; i != 4; ++i)
01501     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
01502       return -1;
01503 
01504   return ShiftAmt;
01505 }
01506 
01507 //===----------------------------------------------------------------------===//
01508 //  Addressing Mode Selection
01509 //===----------------------------------------------------------------------===//
01510 
01511 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
01512 /// or 64-bit immediate, and if the value can be accurately represented as a
01513 /// sign extension from a 16-bit value.  If so, this returns true and the
01514 /// immediate.
01515 static bool isIntS16Immediate(SDNode *N, short &Imm) {
01516   if (!isa<ConstantSDNode>(N))
01517     return false;
01518 
01519   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
01520   if (N->getValueType(0) == MVT::i32)
01521     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
01522   else
01523     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
01524 }
01525 static bool isIntS16Immediate(SDValue Op, short &Imm) {
01526   return isIntS16Immediate(Op.getNode(), Imm);
01527 }
01528 
01529 
01530 /// SelectAddressRegReg - Given the specified addressed, check to see if it
01531 /// can be represented as an indexed [r+r] operation.  Returns false if it
01532 /// can be more efficiently represented with [r+imm].
01533 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
01534                                             SDValue &Index,
01535                                             SelectionDAG &DAG) const {
01536   short imm = 0;
01537   if (N.getOpcode() == ISD::ADD) {
01538     if (isIntS16Immediate(N.getOperand(1), imm))
01539       return false;    // r+i
01540     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
01541       return false;    // r+i
01542 
01543     Base = N.getOperand(0);
01544     Index = N.getOperand(1);
01545     return true;
01546   } else if (N.getOpcode() == ISD::OR) {
01547     if (isIntS16Immediate(N.getOperand(1), imm))
01548       return false;    // r+i can fold it if we can.
01549 
01550     // If this is an or of disjoint bitfields, we can codegen this as an add
01551     // (for better address arithmetic) if the LHS and RHS of the OR are provably
01552     // disjoint.
01553     APInt LHSKnownZero, LHSKnownOne;
01554     APInt RHSKnownZero, RHSKnownOne;
01555     DAG.computeKnownBits(N.getOperand(0),
01556                          LHSKnownZero, LHSKnownOne);
01557 
01558     if (LHSKnownZero.getBoolValue()) {
01559       DAG.computeKnownBits(N.getOperand(1),
01560                            RHSKnownZero, RHSKnownOne);
01561       // If all of the bits are known zero on the LHS or RHS, the add won't
01562       // carry.
01563       if (~(LHSKnownZero | RHSKnownZero) == 0) {
01564         Base = N.getOperand(0);
01565         Index = N.getOperand(1);
01566         return true;
01567       }
01568     }
01569   }
01570 
01571   return false;
01572 }
01573 
01574 // If we happen to be doing an i64 load or store into a stack slot that has
01575 // less than a 4-byte alignment, then the frame-index elimination may need to
01576 // use an indexed load or store instruction (because the offset may not be a
01577 // multiple of 4). The extra register needed to hold the offset comes from the
01578 // register scavenger, and it is possible that the scavenger will need to use
01579 // an emergency spill slot. As a result, we need to make sure that a spill slot
01580 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
01581 // stack slot.
01582 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
01583   // FIXME: This does not handle the LWA case.
01584   if (VT != MVT::i64)
01585     return;
01586 
01587   // NOTE: We'll exclude negative FIs here, which come from argument
01588   // lowering, because there are no known test cases triggering this problem
01589   // using packed structures (or similar). We can remove this exclusion if
01590   // we find such a test case. The reason why this is so test-case driven is
01591   // because this entire 'fixup' is only to prevent crashes (from the
01592   // register scavenger) on not-really-valid inputs. For example, if we have:
01593   //   %a = alloca i1
01594   //   %b = bitcast i1* %a to i64*
01595   //   store i64* a, i64 b
01596   // then the store should really be marked as 'align 1', but is not. If it
01597   // were marked as 'align 1' then the indexed form would have been
01598   // instruction-selected initially, and the problem this 'fixup' is preventing
01599   // won't happen regardless.
01600   if (FrameIdx < 0)
01601     return;
01602 
01603   MachineFunction &MF = DAG.getMachineFunction();
01604   MachineFrameInfo *MFI = MF.getFrameInfo();
01605 
01606   unsigned Align = MFI->getObjectAlignment(FrameIdx);
01607   if (Align >= 4)
01608     return;
01609 
01610   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01611   FuncInfo->setHasNonRISpills();
01612 }
01613 
01614 /// Returns true if the address N can be represented by a base register plus
01615 /// a signed 16-bit displacement [r+imm], and if it is not better
01616 /// represented as reg+reg.  If Aligned is true, only accept displacements
01617 /// suitable for STD and friends, i.e. multiples of 4.
01618 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
01619                                             SDValue &Base,
01620                                             SelectionDAG &DAG,
01621                                             bool Aligned) const {
01622   // FIXME dl should come from parent load or store, not from address
01623   SDLoc dl(N);
01624   // If this can be more profitably realized as r+r, fail.
01625   if (SelectAddressRegReg(N, Disp, Base, DAG))
01626     return false;
01627 
01628   if (N.getOpcode() == ISD::ADD) {
01629     short imm = 0;
01630     if (isIntS16Immediate(N.getOperand(1), imm) &&
01631         (!Aligned || (imm & 3) == 0)) {
01632       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
01633       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
01634         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01635         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01636       } else {
01637         Base = N.getOperand(0);
01638       }
01639       return true; // [r+i]
01640     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
01641       // Match LOAD (ADD (X, Lo(G))).
01642       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
01643              && "Cannot handle constant offsets yet!");
01644       Disp = N.getOperand(1).getOperand(0);  // The global address.
01645       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
01646              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
01647              Disp.getOpcode() == ISD::TargetConstantPool ||
01648              Disp.getOpcode() == ISD::TargetJumpTable);
01649       Base = N.getOperand(0);
01650       return true;  // [&g+r]
01651     }
01652   } else if (N.getOpcode() == ISD::OR) {
01653     short imm = 0;
01654     if (isIntS16Immediate(N.getOperand(1), imm) &&
01655         (!Aligned || (imm & 3) == 0)) {
01656       // If this is an or of disjoint bitfields, we can codegen this as an add
01657       // (for better address arithmetic) if the LHS and RHS of the OR are
01658       // provably disjoint.
01659       APInt LHSKnownZero, LHSKnownOne;
01660       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
01661 
01662       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
01663         // If all of the bits are known zero on the LHS or RHS, the add won't
01664         // carry.
01665         if (FrameIndexSDNode *FI =
01666               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
01667           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01668           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01669         } else {
01670           Base = N.getOperand(0);
01671         }
01672         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
01673         return true;
01674       }
01675     }
01676   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
01677     // Loading from a constant address.
01678 
01679     // If this address fits entirely in a 16-bit sext immediate field, codegen
01680     // this as "d, 0"
01681     short Imm;
01682     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
01683       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
01684       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
01685                              CN->getValueType(0));
01686       return true;
01687     }
01688 
01689     // Handle 32-bit sext immediates with LIS + addr mode.
01690     if ((CN->getValueType(0) == MVT::i32 ||
01691          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
01692         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
01693       int Addr = (int)CN->getZExtValue();
01694 
01695       // Otherwise, break this down into an LIS + disp.
01696       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
01697 
01698       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
01699                                    MVT::i32);
01700       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
01701       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
01702       return true;
01703     }
01704   }
01705 
01706   Disp = DAG.getTargetConstant(0, dl, getPointerTy());
01707   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
01708     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01709     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01710   } else
01711     Base = N;
01712   return true;      // [r+0]
01713 }
01714 
01715 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
01716 /// represented as an indexed [r+r] operation.
01717 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
01718                                                 SDValue &Index,
01719                                                 SelectionDAG &DAG) const {
01720   // Check to see if we can easily represent this as an [r+r] address.  This
01721   // will fail if it thinks that the address is more profitably represented as
01722   // reg+imm, e.g. where imm = 0.
01723   if (SelectAddressRegReg(N, Base, Index, DAG))
01724     return true;
01725 
01726   // If the operand is an addition, always emit this as [r+r], since this is
01727   // better (for code size, and execution, as the memop does the add for free)
01728   // than emitting an explicit add.
01729   if (N.getOpcode() == ISD::ADD) {
01730     Base = N.getOperand(0);
01731     Index = N.getOperand(1);
01732     return true;
01733   }
01734 
01735   // Otherwise, do it the hard way, using R0 as the base register.
01736   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
01737                          N.getValueType());
01738   Index = N;
01739   return true;
01740 }
01741 
01742 /// getPreIndexedAddressParts - returns true by value, base pointer and
01743 /// offset pointer and addressing mode by reference if the node's address
01744 /// can be legally represented as pre-indexed load / store address.
01745 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
01746                                                   SDValue &Offset,
01747                                                   ISD::MemIndexedMode &AM,
01748                                                   SelectionDAG &DAG) const {
01749   if (DisablePPCPreinc) return false;
01750 
01751   bool isLoad = true;
01752   SDValue Ptr;
01753   EVT VT;
01754   unsigned Alignment;
01755   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01756     Ptr = LD->getBasePtr();
01757     VT = LD->getMemoryVT();
01758     Alignment = LD->getAlignment();
01759   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
01760     Ptr = ST->getBasePtr();
01761     VT  = ST->getMemoryVT();
01762     Alignment = ST->getAlignment();
01763     isLoad = false;
01764   } else
01765     return false;
01766 
01767   // PowerPC doesn't have preinc load/store instructions for vectors (except
01768   // for QPX, which does have preinc r+r forms).
01769   if (VT.isVector()) {
01770     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
01771       return false;
01772     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
01773       AM = ISD::PRE_INC;
01774       return true;
01775     }
01776   }
01777 
01778   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
01779 
01780     // Common code will reject creating a pre-inc form if the base pointer
01781     // is a frame index, or if N is a store and the base pointer is either
01782     // the same as or a predecessor of the value being stored.  Check for
01783     // those situations here, and try with swapped Base/Offset instead.
01784     bool Swap = false;
01785 
01786     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
01787       Swap = true;
01788     else if (!isLoad) {
01789       SDValue Val = cast<StoreSDNode>(N)->getValue();
01790       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
01791         Swap = true;
01792     }
01793 
01794     if (Swap)
01795       std::swap(Base, Offset);
01796 
01797     AM = ISD::PRE_INC;
01798     return true;
01799   }
01800 
01801   // LDU/STU can only handle immediates that are a multiple of 4.
01802   if (VT != MVT::i64) {
01803     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
01804       return false;
01805   } else {
01806     // LDU/STU need an address with at least 4-byte alignment.
01807     if (Alignment < 4)
01808       return false;
01809 
01810     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
01811       return false;
01812   }
01813 
01814   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01815     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
01816     // sext i32 to i64 when addr mode is r+i.
01817     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
01818         LD->getExtensionType() == ISD::SEXTLOAD &&
01819         isa<ConstantSDNode>(Offset))
01820       return false;
01821   }
01822 
01823   AM = ISD::PRE_INC;
01824   return true;
01825 }
01826 
01827 //===----------------------------------------------------------------------===//
01828 //  LowerOperation implementation
01829 //===----------------------------------------------------------------------===//
01830 
01831 /// GetLabelAccessInfo - Return true if we should reference labels using a
01832 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
01833 static bool GetLabelAccessInfo(const TargetMachine &TM,
01834                                const PPCSubtarget &Subtarget,
01835                                unsigned &HiOpFlags, unsigned &LoOpFlags,
01836                                const GlobalValue *GV = nullptr) {
01837   HiOpFlags = PPCII::MO_HA;
01838   LoOpFlags = PPCII::MO_LO;
01839 
01840   // Don't use the pic base if not in PIC relocation model.
01841   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
01842 
01843   if (isPIC) {
01844     HiOpFlags |= PPCII::MO_PIC_FLAG;
01845     LoOpFlags |= PPCII::MO_PIC_FLAG;
01846   }
01847 
01848   // If this is a reference to a global value that requires a non-lazy-ptr, make
01849   // sure that instruction lowering adds it.
01850   if (GV && Subtarget.hasLazyResolverStub(GV)) {
01851     HiOpFlags |= PPCII::MO_NLP_FLAG;
01852     LoOpFlags |= PPCII::MO_NLP_FLAG;
01853 
01854     if (GV->hasHiddenVisibility()) {
01855       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
01856       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
01857     }
01858   }
01859 
01860   return isPIC;
01861 }
01862 
01863 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
01864                              SelectionDAG &DAG) {
01865   SDLoc DL(HiPart);
01866   EVT PtrVT = HiPart.getValueType();
01867   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
01868 
01869   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
01870   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
01871 
01872   // With PIC, the first instruction is actually "GR+hi(&G)".
01873   if (isPIC)
01874     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
01875                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
01876 
01877   // Generate non-pic code that has direct accesses to the constant pool.
01878   // The address of the global is just (hi(&g)+lo(&g)).
01879   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
01880 }
01881 
01882 static void setUsesTOCBasePtr(MachineFunction &MF) {
01883   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01884   FuncInfo->setUsesTOCBasePtr();
01885 }
01886 
01887 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
01888   setUsesTOCBasePtr(DAG.getMachineFunction());
01889 }
01890 
01891 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
01892                            SDValue GA) {
01893   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
01894   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
01895                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
01896 
01897   SDValue Ops[] = { GA, Reg };
01898   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
01899                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
01900                                  MachinePointerInfo::getGOT(), 0, false, true,
01901                                  false, 0);
01902 }
01903 
01904 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
01905                                              SelectionDAG &DAG) const {
01906   EVT PtrVT = Op.getValueType();
01907   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
01908   const Constant *C = CP->getConstVal();
01909 
01910   // 64-bit SVR4 ABI code is always position-independent.
01911   // The actual address of the GlobalValue is stored in the TOC.
01912   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01913     setUsesTOCBasePtr(DAG);
01914     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
01915     return getTOCEntry(DAG, SDLoc(CP), true, GA);
01916   }
01917 
01918   unsigned MOHiFlag, MOLoFlag;
01919   bool isPIC =
01920       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
01921 
01922   if (isPIC && Subtarget.isSVR4ABI()) {
01923     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
01924                                            PPCII::MO_PIC_FLAG);
01925     return getTOCEntry(DAG, SDLoc(CP), false, GA);
01926   }
01927 
01928   SDValue CPIHi =
01929     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
01930   SDValue CPILo =
01931     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
01932   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
01933 }
01934 
01935 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
01936   EVT PtrVT = Op.getValueType();
01937   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
01938 
01939   // 64-bit SVR4 ABI code is always position-independent.
01940   // The actual address of the GlobalValue is stored in the TOC.
01941   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01942     setUsesTOCBasePtr(DAG);
01943     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
01944     return getTOCEntry(DAG, SDLoc(JT), true, GA);
01945   }
01946 
01947   unsigned MOHiFlag, MOLoFlag;
01948   bool isPIC =
01949       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
01950 
01951   if (isPIC && Subtarget.isSVR4ABI()) {
01952     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
01953                                         PPCII::MO_PIC_FLAG);
01954     return getTOCEntry(DAG, SDLoc(GA), false, GA);
01955   }
01956 
01957   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
01958   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
01959   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
01960 }
01961 
01962 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
01963                                              SelectionDAG &DAG) const {
01964   EVT PtrVT = Op.getValueType();
01965   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
01966   const BlockAddress *BA = BASDN->getBlockAddress();
01967 
01968   // 64-bit SVR4 ABI code is always position-independent.
01969   // The actual BlockAddress is stored in the TOC.
01970   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01971     setUsesTOCBasePtr(DAG);
01972     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
01973     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
01974   }
01975 
01976   unsigned MOHiFlag, MOLoFlag;
01977   bool isPIC =
01978       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
01979   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
01980   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
01981   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
01982 }
01983 
01984 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
01985                                               SelectionDAG &DAG) const {
01986 
01987   // FIXME: TLS addresses currently use medium model code sequences,
01988   // which is the most useful form.  Eventually support for small and
01989   // large models could be added if users need it, at the cost of
01990   // additional complexity.
01991   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
01992   SDLoc dl(GA);
01993   const GlobalValue *GV = GA->getGlobal();
01994   EVT PtrVT = getPointerTy();
01995   bool is64bit = Subtarget.isPPC64();
01996   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
01997   PICLevel::Level picLevel = M->getPICLevel();
01998 
01999   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
02000 
02001   if (Model == TLSModel::LocalExec) {
02002     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
02003                                                PPCII::MO_TPREL_HA);
02004     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
02005                                                PPCII::MO_TPREL_LO);
02006     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
02007                                      is64bit ? MVT::i64 : MVT::i32);
02008     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
02009     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
02010   }
02011 
02012   if (Model == TLSModel::InitialExec) {
02013     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
02014     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
02015                                                 PPCII::MO_TLS);
02016     SDValue GOTPtr;
02017     if (is64bit) {
02018       setUsesTOCBasePtr(DAG);
02019       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
02020       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
02021                            PtrVT, GOTReg, TGA);
02022     } else
02023       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
02024     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
02025                                    PtrVT, TGA, GOTPtr);
02026     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
02027   }
02028 
02029   if (Model == TLSModel::GeneralDynamic) {
02030     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
02031     SDValue GOTPtr;
02032     if (is64bit) {
02033       setUsesTOCBasePtr(DAG);
02034       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
02035       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
02036                                    GOTReg, TGA);
02037     } else {
02038       if (picLevel == PICLevel::Small)
02039         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
02040       else
02041         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
02042     }
02043     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
02044                        GOTPtr, TGA, TGA);
02045   }
02046 
02047   if (Model == TLSModel::LocalDynamic) {
02048     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
02049     SDValue GOTPtr;
02050     if (is64bit) {
02051       setUsesTOCBasePtr(DAG);
02052       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
02053       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
02054                            GOTReg, TGA);
02055     } else {
02056       if (picLevel == PICLevel::Small)
02057         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
02058       else
02059         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
02060     }
02061     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
02062                                   PtrVT, GOTPtr, TGA, TGA);
02063     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
02064                                       PtrVT, TLSAddr, TGA);
02065     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
02066   }
02067 
02068   llvm_unreachable("Unknown TLS model!");
02069 }
02070 
02071 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
02072                                               SelectionDAG &DAG) const {
02073   EVT PtrVT = Op.getValueType();
02074   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
02075   SDLoc DL(GSDN);
02076   const GlobalValue *GV = GSDN->getGlobal();
02077 
02078   // 64-bit SVR4 ABI code is always position-independent.
02079   // The actual address of the GlobalValue is stored in the TOC.
02080   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
02081     setUsesTOCBasePtr(DAG);
02082     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
02083     return getTOCEntry(DAG, DL, true, GA);
02084   }
02085 
02086   unsigned MOHiFlag, MOLoFlag;
02087   bool isPIC =
02088       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
02089 
02090   if (isPIC && Subtarget.isSVR4ABI()) {
02091     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
02092                                             GSDN->getOffset(),
02093                                             PPCII::MO_PIC_FLAG);
02094     return getTOCEntry(DAG, DL, false, GA);
02095   }
02096 
02097   SDValue GAHi =
02098     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
02099   SDValue GALo =
02100     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
02101 
02102   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
02103 
02104   // If the global reference is actually to a non-lazy-pointer, we have to do an
02105   // extra load to get the address of the global.
02106   if (MOHiFlag & PPCII::MO_NLP_FLAG)
02107     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
02108                       false, false, false, 0);
02109   return Ptr;
02110 }
02111 
02112 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
02113   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
02114   SDLoc dl(Op);
02115 
02116   if (Op.getValueType() == MVT::v2i64) {
02117     // When the operands themselves are v2i64 values, we need to do something
02118     // special because VSX has no underlying comparison operations for these.
02119     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
02120       // Equality can be handled by casting to the legal type for Altivec
02121       // comparisons, everything else needs to be expanded.
02122       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
02123         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
02124                  DAG.getSetCC(dl, MVT::v4i32,
02125                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
02126                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
02127                    CC));
02128       }
02129 
02130       return SDValue();
02131     }
02132 
02133     // We handle most of these in the usual way.
02134     return Op;
02135   }
02136 
02137   // If we're comparing for equality to zero, expose the fact that this is
02138   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
02139   // fold the new nodes.
02140   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
02141     if (C->isNullValue() && CC == ISD::SETEQ) {
02142       EVT VT = Op.getOperand(0).getValueType();
02143       SDValue Zext = Op.getOperand(0);
02144       if (VT.bitsLT(MVT::i32)) {
02145         VT = MVT::i32;
02146         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
02147       }
02148       unsigned Log2b = Log2_32(VT.getSizeInBits());
02149       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
02150       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
02151                                 DAG.getConstant(Log2b, dl, MVT::i32));
02152       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
02153     }
02154     // Leave comparisons against 0 and -1 alone for now, since they're usually
02155     // optimized.  FIXME: revisit this when we can custom lower all setcc
02156     // optimizations.
02157     if (C->isAllOnesValue() || C->isNullValue())
02158       return SDValue();
02159   }
02160 
02161   // If we have an integer seteq/setne, turn it into a compare against zero
02162   // by xor'ing the rhs with the lhs, which is faster than setting a
02163   // condition register, reading it back out, and masking the correct bit.  The
02164   // normal approach here uses sub to do this instead of xor.  Using xor exposes
02165   // the result to other bit-twiddling opportunities.
02166   EVT LHSVT = Op.getOperand(0).getValueType();
02167   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
02168     EVT VT = Op.getValueType();
02169     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
02170                                 Op.getOperand(1));
02171     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
02172   }
02173   return SDValue();
02174 }
02175 
02176 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
02177                                       const PPCSubtarget &Subtarget) const {
02178   SDNode *Node = Op.getNode();
02179   EVT VT = Node->getValueType(0);
02180   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02181   SDValue InChain = Node->getOperand(0);
02182   SDValue VAListPtr = Node->getOperand(1);
02183   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
02184   SDLoc dl(Node);
02185 
02186   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
02187 
02188   // gpr_index
02189   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
02190                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
02191                                     false, false, false, 0);
02192   InChain = GprIndex.getValue(1);
02193 
02194   if (VT == MVT::i64) {
02195     // Check if GprIndex is even
02196     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
02197                                  DAG.getConstant(1, dl, MVT::i32));
02198     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
02199                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
02200     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
02201                                           DAG.getConstant(1, dl, MVT::i32));
02202     // Align GprIndex to be even if it isn't
02203     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
02204                            GprIndex);
02205   }
02206 
02207   // fpr index is 1 byte after gpr
02208   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
02209                                DAG.getConstant(1, dl, MVT::i32));
02210 
02211   // fpr
02212   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
02213                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
02214                                     false, false, false, 0);
02215   InChain = FprIndex.getValue(1);
02216 
02217   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
02218                                        DAG.getConstant(8, dl, MVT::i32));
02219 
02220   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
02221                                         DAG.getConstant(4, dl, MVT::i32));
02222 
02223   // areas
02224   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
02225                                      MachinePointerInfo(), false, false,
02226                                      false, 0);
02227   InChain = OverflowArea.getValue(1);
02228 
02229   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
02230                                     MachinePointerInfo(), false, false,
02231                                     false, 0);
02232   InChain = RegSaveArea.getValue(1);
02233 
02234   // select overflow_area if index > 8
02235   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
02236                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
02237 
02238   // adjustment constant gpr_index * 4/8
02239   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
02240                                     VT.isInteger() ? GprIndex : FprIndex,
02241                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
02242                                                     MVT::i32));
02243 
02244   // OurReg = RegSaveArea + RegConstant
02245   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
02246                                RegConstant);
02247 
02248   // Floating types are 32 bytes into RegSaveArea
02249   if (VT.isFloatingPoint())
02250     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
02251                          DAG.getConstant(32, dl, MVT::i32));
02252 
02253   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
02254   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
02255                                    VT.isInteger() ? GprIndex : FprIndex,
02256                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
02257                                                    MVT::i32));
02258 
02259   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
02260                               VT.isInteger() ? VAListPtr : FprPtr,
02261                               MachinePointerInfo(SV),
02262                               MVT::i8, false, false, 0);
02263 
02264   // determine if we should load from reg_save_area or overflow_area
02265   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
02266 
02267   // increase overflow_area by 4/8 if gpr/fpr > 8
02268   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
02269                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
02270                                           dl, MVT::i32));
02271 
02272   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
02273                              OverflowAreaPlusN);
02274 
02275   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
02276                               OverflowAreaPtr,
02277                               MachinePointerInfo(),
02278                               MVT::i32, false, false, 0);
02279 
02280   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
02281                      false, false, false, 0);
02282 }
02283 
02284 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
02285                                        const PPCSubtarget &Subtarget) const {
02286   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
02287 
02288   // We have to copy the entire va_list struct:
02289   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
02290   return DAG.getMemcpy(Op.getOperand(0), Op,
02291                        Op.getOperand(1), Op.getOperand(2),
02292                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
02293                        false, MachinePointerInfo(), MachinePointerInfo());
02294 }
02295 
02296 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
02297                                                   SelectionDAG &DAG) const {
02298   return Op.getOperand(0);
02299 }
02300 
02301 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
02302                                                 SelectionDAG &DAG) const {
02303   SDValue Chain = Op.getOperand(0);
02304   SDValue Trmp = Op.getOperand(1); // trampoline
02305   SDValue FPtr = Op.getOperand(2); // nested function
02306   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
02307   SDLoc dl(Op);
02308 
02309   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02310   bool isPPC64 = (PtrVT == MVT::i64);
02311   Type *IntPtrTy =
02312     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
02313                                                              *DAG.getContext());
02314 
02315   TargetLowering::ArgListTy Args;
02316   TargetLowering::ArgListEntry Entry;
02317 
02318   Entry.Ty = IntPtrTy;
02319   Entry.Node = Trmp; Args.push_back(Entry);
02320 
02321   // TrampSize == (isPPC64 ? 48 : 40);
02322   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
02323                                isPPC64 ? MVT::i64 : MVT::i32);
02324   Args.push_back(Entry);
02325 
02326   Entry.Node = FPtr; Args.push_back(Entry);
02327   Entry.Node = Nest; Args.push_back(Entry);
02328 
02329   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
02330   TargetLowering::CallLoweringInfo CLI(DAG);
02331   CLI.setDebugLoc(dl).setChain(Chain)
02332     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
02333                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
02334                std::move(Args), 0);
02335 
02336   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
02337   return CallResult.second;
02338 }
02339 
02340 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
02341                                         const PPCSubtarget &Subtarget) const {
02342   MachineFunction &MF = DAG.getMachineFunction();
02343   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02344 
02345   SDLoc dl(Op);
02346 
02347   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
02348     // vastart just stores the address of the VarArgsFrameIndex slot into the
02349     // memory location argument.
02350     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02351     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02352     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02353     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
02354                         MachinePointerInfo(SV),
02355                         false, false, 0);
02356   }
02357 
02358   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
02359   // We suppose the given va_list is already allocated.
02360   //
02361   // typedef struct {
02362   //  char gpr;     /* index into the array of 8 GPRs
02363   //                 * stored in the register save area
02364   //                 * gpr=0 corresponds to r3,
02365   //                 * gpr=1 to r4, etc.
02366   //                 */
02367   //  char fpr;     /* index into the array of 8 FPRs
02368   //                 * stored in the register save area
02369   //                 * fpr=0 corresponds to f1,
02370   //                 * fpr=1 to f2, etc.
02371   //                 */
02372   //  char *overflow_arg_area;
02373   //                /* location on stack that holds
02374   //                 * the next overflow argument
02375   //                 */
02376   //  char *reg_save_area;
02377   //               /* where r3:r10 and f1:f8 (if saved)
02378   //                * are stored
02379   //                */
02380   // } va_list[1];
02381 
02382 
02383   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
02384   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
02385 
02386 
02387   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02388 
02389   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
02390                                             PtrVT);
02391   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
02392                                  PtrVT);
02393 
02394   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
02395   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
02396 
02397   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
02398   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
02399 
02400   uint64_t FPROffset = 1;
02401   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
02402 
02403   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02404 
02405   // Store first byte : number of int regs
02406   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
02407                                          Op.getOperand(1),
02408                                          MachinePointerInfo(SV),
02409                                          MVT::i8, false, false, 0);
02410   uint64_t nextOffset = FPROffset;
02411   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
02412                                   ConstFPROffset);
02413 
02414   // Store second byte : number of float regs
02415   SDValue secondStore =
02416     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
02417                       MachinePointerInfo(SV, nextOffset), MVT::i8,
02418                       false, false, 0);
02419   nextOffset += StackOffset;
02420   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
02421 
02422   // Store second word : arguments given on stack
02423   SDValue thirdStore =
02424     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
02425                  MachinePointerInfo(SV, nextOffset),
02426                  false, false, 0);
02427   nextOffset += FrameOffset;
02428   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
02429 
02430   // Store third word : arguments given in registers
02431   return DAG.getStore(thirdStore, dl, FR, nextPtr,
02432                       MachinePointerInfo(SV, nextOffset),
02433                       false, false, 0);
02434 
02435 }
02436 
02437 #include "PPCGenCallingConv.inc"
02438 
02439 // Function whose sole purpose is to kill compiler warnings 
02440 // stemming from unused functions included from PPCGenCallingConv.inc.
02441 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
02442   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
02443 }
02444 
02445 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
02446                                       CCValAssign::LocInfo &LocInfo,
02447                                       ISD::ArgFlagsTy &ArgFlags,
02448                                       CCState &State) {
02449   return true;
02450 }
02451 
02452 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
02453                                              MVT &LocVT,
02454                                              CCValAssign::LocInfo &LocInfo,
02455                                              ISD::ArgFlagsTy &ArgFlags,
02456                                              CCState &State) {
02457   static const MCPhysReg ArgRegs[] = {
02458     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02459     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02460   };
02461   const unsigned NumArgRegs = array_lengthof(ArgRegs);
02462 
02463   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
02464 
02465   // Skip one register if the first unallocated register has an even register
02466   // number and there are still argument registers available which have not been
02467   // allocated yet. RegNum is actually an index into ArgRegs, which means we
02468   // need to skip a register if RegNum is odd.
02469   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
02470     State.AllocateReg(ArgRegs[RegNum]);
02471   }
02472 
02473   // Always return false here, as this function only makes sure that the first
02474   // unallocated register has an odd register number and does not actually
02475   // allocate a register for the current argument.
02476   return false;
02477 }
02478 
02479 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
02480                                                MVT &LocVT,
02481                                                CCValAssign::LocInfo &LocInfo,
02482                                                ISD::ArgFlagsTy &ArgFlags,
02483                                                CCState &State) {
02484   static const MCPhysReg ArgRegs[] = {
02485     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
02486     PPC::F8
02487   };
02488 
02489   const unsigned NumArgRegs = array_lengthof(ArgRegs);
02490 
02491   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
02492 
02493   // If there is only one Floating-point register left we need to put both f64
02494   // values of a split ppc_fp128 value on the stack.
02495   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
02496     State.AllocateReg(ArgRegs[RegNum]);
02497   }
02498 
02499   // Always return false here, as this function only makes sure that the two f64
02500   // values a ppc_fp128 value is split into are both passed in registers or both
02501   // passed on the stack and does not actually allocate a register for the
02502   // current argument.
02503   return false;
02504 }
02505 
02506 /// FPR - The set of FP registers that should be allocated for arguments,
02507 /// on Darwin.
02508 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
02509                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
02510                                 PPC::F11, PPC::F12, PPC::F13};
02511 
02512 /// QFPR - The set of QPX registers that should be allocated for arguments.
02513 static const MCPhysReg QFPR[] = {
02514     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
02515     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
02516 
02517 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
02518 /// the stack.
02519 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
02520                                        unsigned PtrByteSize) {
02521   unsigned ArgSize = ArgVT.getStoreSize();
02522   if (Flags.isByVal())
02523     ArgSize = Flags.getByValSize();
02524 
02525   // Round up to multiples of the pointer size, except for array members,
02526   // which are always packed.
02527   if (!Flags.isInConsecutiveRegs())
02528     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02529 
02530   return ArgSize;
02531 }
02532 
02533 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
02534 /// on the stack.
02535 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
02536                                             ISD::ArgFlagsTy Flags,
02537                                             unsigned PtrByteSize) {
02538   unsigned Align = PtrByteSize;
02539 
02540   // Altivec parameters are padded to a 16 byte boundary.
02541   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
02542       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
02543       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
02544       ArgVT == MVT::v1i128)
02545     Align = 16;
02546   // QPX vector types stored in double-precision are padded to a 32 byte
02547   // boundary.
02548   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
02549     Align = 32;
02550 
02551   // ByVal parameters are aligned as requested.
02552   if (Flags.isByVal()) {
02553     unsigned BVAlign = Flags.getByValAlign();
02554     if (BVAlign > PtrByteSize) {
02555       if (BVAlign % PtrByteSize != 0)
02556           llvm_unreachable(
02557             "ByVal alignment is not a multiple of the pointer size");
02558 
02559       Align = BVAlign;
02560     }
02561   }
02562 
02563   // Array members are always packed to their original alignment.
02564   if (Flags.isInConsecutiveRegs()) {
02565     // If the array member was split into multiple registers, the first
02566     // needs to be aligned to the size of the full type.  (Except for
02567     // ppcf128, which is only aligned as its f64 components.)
02568     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
02569       Align = OrigVT.getStoreSize();
02570     else
02571       Align = ArgVT.getStoreSize();
02572   }
02573 
02574   return Align;
02575 }
02576 
02577 /// CalculateStackSlotUsed - Return whether this argument will use its
02578 /// stack slot (instead of being passed in registers).  ArgOffset,
02579 /// AvailableFPRs, and AvailableVRs must hold the current argument
02580 /// position, and will be updated to account for this argument.
02581 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
02582                                    ISD::ArgFlagsTy Flags,
02583                                    unsigned PtrByteSize,
02584                                    unsigned LinkageSize,
02585                                    unsigned ParamAreaSize,
02586                                    unsigned &ArgOffset,
02587                                    unsigned &AvailableFPRs,
02588                                    unsigned &AvailableVRs, bool HasQPX) {
02589   bool UseMemory = false;
02590 
02591   // Respect alignment of argument on the stack.
02592   unsigned Align =
02593     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
02594   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
02595   // If there's no space left in the argument save area, we must
02596   // use memory (this check also catches zero-sized arguments).
02597   if (ArgOffset >= LinkageSize + ParamAreaSize)
02598     UseMemory = true;
02599 
02600   // Allocate argument on the stack.
02601   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
02602   if (Flags.isInConsecutiveRegsLast())
02603     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02604   // If we overran the argument save area, we must use memory
02605   // (this check catches arguments passed partially in memory)
02606   if (ArgOffset > LinkageSize + ParamAreaSize)
02607     UseMemory = true;
02608 
02609   // However, if the argument is actually passed in an FPR or a VR,
02610   // we don't use memory after all.
02611   if (!Flags.isByVal()) {
02612     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
02613         // QPX registers overlap with the scalar FP registers.
02614         (HasQPX && (ArgVT == MVT::v4f32 ||
02615                     ArgVT == MVT::v4f64 ||
02616                     ArgVT == MVT::v4i1)))
02617       if (AvailableFPRs > 0) {
02618         --AvailableFPRs;
02619         return false;
02620       }
02621     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
02622         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
02623         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
02624         ArgVT == MVT::v1i128)
02625       if (AvailableVRs > 0) {
02626         --AvailableVRs;
02627         return false;
02628       }
02629   }
02630 
02631   return UseMemory;
02632 }
02633 
02634 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
02635 /// ensure minimum alignment required for target.
02636 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
02637                                      unsigned NumBytes) {
02638   unsigned TargetAlign = Lowering->getStackAlignment();
02639   unsigned AlignMask = TargetAlign - 1;
02640   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
02641   return NumBytes;
02642 }
02643 
02644 SDValue
02645 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
02646                                         CallingConv::ID CallConv, bool isVarArg,
02647                                         const SmallVectorImpl<ISD::InputArg>
02648                                           &Ins,
02649                                         SDLoc dl, SelectionDAG &DAG,
02650                                         SmallVectorImpl<SDValue> &InVals)
02651                                           const {
02652   if (Subtarget.isSVR4ABI()) {
02653     if (Subtarget.isPPC64())
02654       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
02655                                          dl, DAG, InVals);
02656     else
02657       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
02658                                          dl, DAG, InVals);
02659   } else {
02660     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
02661                                        dl, DAG, InVals);
02662   }
02663 }
02664 
02665 SDValue
02666 PPCTargetLowering::LowerFormalArguments_32SVR4(
02667                                       SDValue Chain,
02668                                       CallingConv::ID CallConv, bool isVarArg,
02669                                       const SmallVectorImpl<ISD::InputArg>
02670                                         &Ins,
02671                                       SDLoc dl, SelectionDAG &DAG,
02672                                       SmallVectorImpl<SDValue> &InVals) const {
02673 
02674   // 32-bit SVR4 ABI Stack Frame Layout:
02675   //              +-----------------------------------+
02676   //        +-->  |            Back chain             |
02677   //        |     +-----------------------------------+
02678   //        |     | Floating-point register save area |
02679   //        |     +-----------------------------------+
02680   //        |     |    General register save area     |
02681   //        |     +-----------------------------------+
02682   //        |     |          CR save word             |
02683   //        |     +-----------------------------------+
02684   //        |     |         VRSAVE save word          |
02685   //        |     +-----------------------------------+
02686   //        |     |         Alignment padding         |
02687   //        |     +-----------------------------------+
02688   //        |     |     Vector register save area     |
02689   //        |     +-----------------------------------+
02690   //        |     |       Local variable space        |
02691   //        |     +-----------------------------------+
02692   //        |     |        Parameter list area        |
02693   //        |     +-----------------------------------+
02694   //        |     |           LR save word            |
02695   //        |     +-----------------------------------+
02696   // SP-->  +---  |            Back chain             |
02697   //              +-----------------------------------+
02698   //
02699   // Specifications:
02700   //   System V Application Binary Interface PowerPC Processor Supplement
02701   //   AltiVec Technology Programming Interface Manual
02702 
02703   MachineFunction &MF = DAG.getMachineFunction();
02704   MachineFrameInfo *MFI = MF.getFrameInfo();
02705   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02706 
02707   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02708   // Potential tail calls could cause overwriting of argument stack slots.
02709   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
02710                        (CallConv == CallingConv::Fast));
02711   unsigned PtrByteSize = 4;
02712 
02713   // Assign locations to all of the incoming arguments.
02714   SmallVector<CCValAssign, 16> ArgLocs;
02715   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
02716                  *DAG.getContext());
02717 
02718   // Reserve space for the linkage area on the stack.
02719   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
02720   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
02721 
02722   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
02723 
02724   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02725     CCValAssign &VA = ArgLocs[i];
02726 
02727     // Arguments stored in registers.
02728     if (VA.isRegLoc()) {
02729       const TargetRegisterClass *RC;
02730       EVT ValVT = VA.getValVT();
02731 
02732       switch (ValVT.getSimpleVT().SimpleTy) {
02733         default:
02734           llvm_unreachable("ValVT not supported by formal arguments Lowering");
02735         case MVT::i1:
02736         case MVT::i32:
02737           RC = &PPC::GPRCRegClass;
02738           break;
02739         case MVT::f32:
02740           if (Subtarget.hasP8Vector())
02741             RC = &PPC::VSSRCRegClass;
02742           else
02743             RC = &PPC::F4RCRegClass;
02744           break;
02745         case MVT::f64:
02746           if (Subtarget.hasVSX())
02747             RC = &PPC::VSFRCRegClass;
02748           else
02749             RC = &PPC::F8RCRegClass;
02750           break;
02751         case MVT::v16i8:
02752         case MVT::v8i16:
02753         case MVT::v4i32:
02754           RC = &PPC::VRRCRegClass;
02755           break;
02756         case MVT::v4f32:
02757           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
02758           break;
02759         case MVT::v2f64:
02760         case MVT::v2i64:
02761           RC = &PPC::VSHRCRegClass;
02762           break;
02763         case MVT::v4f64:
02764           RC = &PPC::QFRCRegClass;
02765           break;
02766         case MVT::v4i1:
02767           RC = &PPC::QBRCRegClass;
02768           break;
02769       }
02770 
02771       // Transform the arguments stored in physical registers into virtual ones.
02772       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
02773       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
02774                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
02775 
02776       if (ValVT == MVT::i1)
02777         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
02778 
02779       InVals.push_back(ArgValue);
02780     } else {
02781       // Argument stored in memory.
02782       assert(VA.isMemLoc());
02783 
02784       unsigned ArgSize = VA.getLocVT().getStoreSize();
02785       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
02786                                       isImmutable);
02787 
02788       // Create load nodes to retrieve arguments from the stack.
02789       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
02790       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
02791                                    MachinePointerInfo(),
02792                                    false, false, false, 0));
02793     }
02794   }
02795 
02796   // Assign locations to all of the incoming aggregate by value arguments.
02797   // Aggregates passed by value are stored in the local variable space of the
02798   // caller's stack frame, right above the parameter list area.
02799   SmallVector<CCValAssign, 16> ByValArgLocs;
02800   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
02801                       ByValArgLocs, *DAG.getContext());
02802 
02803   // Reserve stack space for the allocations in CCInfo.
02804   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
02805 
02806   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
02807 
02808   // Area that is at least reserved in the caller of this function.
02809   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
02810   MinReservedArea = std::max(MinReservedArea, LinkageSize);
02811 
02812   // Set the size that is at least reserved in caller of this function.  Tail
02813   // call optimized function's reserved stack space needs to be aligned so that
02814   // taking the difference between two stack areas will result in an aligned
02815   // stack.
02816   MinReservedArea =
02817       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
02818   FuncInfo->setMinReservedArea(MinReservedArea);
02819 
02820   SmallVector<SDValue, 8> MemOps;
02821 
02822   // If the function takes variable number of arguments, make a frame index for
02823   // the start of the first vararg value... for expansion of llvm.va_start.
02824   if (isVarArg) {
02825     static const MCPhysReg GPArgRegs[] = {
02826       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02827       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02828     };
02829     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
02830 
02831     static const MCPhysReg FPArgRegs[] = {
02832       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
02833       PPC::F8
02834     };
02835     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
02836     if (DisablePPCFloatInVariadic)
02837       NumFPArgRegs = 0;
02838 
02839     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
02840     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
02841 
02842     // Make room for NumGPArgRegs and NumFPArgRegs.
02843     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
02844                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
02845 
02846     FuncInfo->setVarArgsStackOffset(
02847       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
02848                              CCInfo.getNextStackOffset(), true));
02849 
02850     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
02851     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02852 
02853     // The fixed integer arguments of a variadic function are stored to the
02854     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
02855     // the result of va_next.
02856     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
02857       // Get an existing live-in vreg, or add a new one.
02858       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
02859       if (!VReg)
02860         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
02861 
02862       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
02863       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02864                                    MachinePointerInfo(), false, false, 0);
02865       MemOps.push_back(Store);
02866       // Increment the address by four for the next argument to store
02867       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
02868       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
02869     }
02870 
02871     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
02872     // is set.
02873     // The double arguments are stored to the VarArgsFrameIndex
02874     // on the stack.
02875     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
02876       // Get an existing live-in vreg, or add a new one.
02877       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
02878       if (!VReg)
02879         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
02880 
02881       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
02882       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02883                                    MachinePointerInfo(), false, false, 0);
02884       MemOps.push_back(Store);
02885       // Increment the address by eight for the next argument to store
02886       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
02887                                          PtrVT);
02888       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
02889     }
02890   }
02891 
02892   if (!MemOps.empty())
02893     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02894 
02895   return Chain;
02896 }
02897 
02898 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
02899 // value to MVT::i64 and then truncate to the correct register size.
02900 SDValue
02901 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
02902                                      SelectionDAG &DAG, SDValue ArgVal,
02903                                      SDLoc dl) const {
02904   if (Flags.isSExt())
02905     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
02906                          DAG.getValueType(ObjectVT));
02907   else if (Flags.isZExt())
02908     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
02909                          DAG.getValueType(ObjectVT));
02910 
02911   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
02912 }
02913 
02914 SDValue
02915 PPCTargetLowering::LowerFormalArguments_64SVR4(
02916                                       SDValue Chain,
02917                                       CallingConv::ID CallConv, bool isVarArg,
02918                                       const SmallVectorImpl<ISD::InputArg>
02919                                         &Ins,
02920                                       SDLoc dl, SelectionDAG &DAG,
02921                                       SmallVectorImpl<SDValue> &InVals) const {
02922   // TODO: add description of PPC stack frame format, or at least some docs.
02923   //
02924   bool isELFv2ABI = Subtarget.isELFv2ABI();
02925   bool isLittleEndian = Subtarget.isLittleEndian();
02926   MachineFunction &MF = DAG.getMachineFunction();
02927   MachineFrameInfo *MFI = MF.getFrameInfo();
02928   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02929 
02930   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
02931          "fastcc not supported on varargs functions");
02932 
02933   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02934   // Potential tail calls could cause overwriting of argument stack slots.
02935   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
02936                        (CallConv == CallingConv::Fast));
02937   unsigned PtrByteSize = 8;
02938   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
02939 
02940   static const MCPhysReg GPR[] = {
02941     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
02942     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
02943   };
02944   static const MCPhysReg VR[] = {
02945     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
02946     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
02947   };
02948   static const MCPhysReg VSRH[] = {
02949     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
02950     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
02951   };
02952 
02953   const unsigned Num_GPR_Regs = array_lengthof(GPR);
02954   const unsigned Num_FPR_Regs = 13;
02955   const unsigned Num_VR_Regs  = array_lengthof(VR);
02956   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
02957 
02958   // Do a first pass over the arguments to determine whether the ABI
02959   // guarantees that our caller has allocated the parameter save area
02960   // on its stack frame.  In the ELFv1 ABI, this is always the case;
02961   // in the ELFv2 ABI, it is true if this is a vararg function or if
02962   // any parameter is located in a stack slot.
02963 
02964   bool HasParameterArea = !isELFv2ABI || isVarArg;
02965   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
02966   unsigned NumBytes = LinkageSize;
02967   unsigned AvailableFPRs = Num_FPR_Regs;
02968   unsigned AvailableVRs = Num_VR_Regs;
02969   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
02970     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
02971                                PtrByteSize, LinkageSize, ParamAreaSize,
02972                                NumBytes, AvailableFPRs, AvailableVRs,
02973                                Subtarget.hasQPX()))
02974       HasParameterArea = true;
02975 
02976   // Add DAG nodes to load the arguments or copy them out of registers.  On
02977   // entry to a function on PPC, the arguments start after the linkage area,
02978   // although the first ones are often in registers.
02979 
02980   unsigned ArgOffset = LinkageSize;
02981   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
02982   unsigned &QFPR_idx = FPR_idx;
02983   SmallVector<SDValue, 8> MemOps;
02984   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
02985   unsigned CurArgIdx = 0;
02986   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
02987     SDValue ArgVal;
02988     bool needsLoad = false;
02989     EVT ObjectVT = Ins[ArgNo].VT;
02990     EVT OrigVT = Ins[ArgNo].ArgVT;
02991     unsigned ObjSize = ObjectVT.getStoreSize();
02992     unsigned ArgSize = ObjSize;
02993     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
02994     if (Ins[ArgNo].isOrigArg()) {
02995       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
02996       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
02997     }
02998     // We re-align the argument offset for each argument, except when using the
02999     // fast calling convention, when we need to make sure we do that only when
03000     // we'll actually use a stack slot.
03001     unsigned CurArgOffset, Align;
03002     auto ComputeArgOffset = [&]() {
03003       /* Respect alignment of argument on the stack.  */
03004       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
03005       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
03006       CurArgOffset = ArgOffset;
03007     };
03008 
03009     if (CallConv != CallingConv::Fast) {
03010       ComputeArgOffset();
03011 
03012       /* Compute GPR index associated with argument offset.  */
03013       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
03014       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
03015     }
03016 
03017     // FIXME the codegen can be much improved in some cases.
03018     // We do not have to keep everything in memory.
03019     if (Flags.isByVal()) {
03020       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
03021 
03022       if (CallConv == CallingConv::Fast)
03023         ComputeArgOffset();
03024 
03025       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
03026       ObjSize = Flags.getByValSize();
03027       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
03028       // Empty aggregate parameters do not take up registers.  Examples:
03029       //   struct { } a;
03030       //   union  { } b;
03031       //   int c[0];
03032       // etc.  However, we have to provide a place-holder in InVals, so
03033       // pretend we have an 8-byte item at the current address for that
03034       // purpose.
03035       if (!ObjSize) {
03036         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
03037         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03038         InVals.push_back(FIN);
03039         continue;
03040       }
03041 
03042       // Create a stack object covering all stack doublewords occupied
03043       // by the argument.  If the argument is (fully or partially) on
03044       // the stack, or if the argument is fully in registers but the
03045       // caller has allocated the parameter save anyway, we can refer
03046       // directly to the caller's stack frame.  Otherwise, create a
03047       // local copy in our own frame.
03048       int FI;
03049       if (HasParameterArea ||
03050           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
03051         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
03052       else
03053         FI = MFI->CreateStackObject(ArgSize, Align, false);
03054       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03055 
03056       // Handle aggregates smaller than 8 bytes.
03057       if (ObjSize < PtrByteSize) {
03058         // The value of the object is its address, which differs from the
03059         // address of the enclosing doubleword on big-endian systems.
03060         SDValue Arg = FIN;
03061         if (!isLittleEndian) {
03062           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
03063           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
03064         }
03065         InVals.push_back(Arg);
03066 
03067         if (GPR_idx != Num_GPR_Regs) {
03068           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
03069           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03070           SDValue Store;
03071 
03072           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
03073             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
03074                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
03075             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
03076                                       MachinePointerInfo(FuncArg),
03077                                       ObjType, false, false, 0);
03078           } else {
03079             // For sizes that don't fit a truncating store (3, 5, 6, 7),
03080             // store the whole register as-is to the parameter save area
03081             // slot.
03082             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03083                                  MachinePointerInfo(FuncArg),
03084                                  false, false, 0);
03085           }
03086 
03087           MemOps.push_back(Store);
03088         }
03089         // Whether we copied from a register or not, advance the offset
03090         // into the parameter save area by a full doubleword.
03091         ArgOffset += PtrByteSize;
03092         continue;
03093       }
03094 
03095       // The value of the object is its address, which is the address of
03096       // its first stack doubleword.
03097       InVals.push_back(FIN);
03098 
03099       // Store whatever pieces of the object are in registers to memory.
03100       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
03101         if (GPR_idx == Num_GPR_Regs)
03102           break;
03103 
03104         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03105         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03106         SDValue Addr = FIN;
03107         if (j) {
03108           SDValue Off = DAG.getConstant(j, dl, PtrVT);
03109           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
03110         }
03111         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
03112                                      MachinePointerInfo(FuncArg, j),
03113                                      false, false, 0);
03114         MemOps.push_back(Store);
03115         ++GPR_idx;
03116       }
03117       ArgOffset += ArgSize;
03118       continue;
03119     }
03120 
03121     switch (ObjectVT.getSimpleVT().SimpleTy) {
03122     default: llvm_unreachable("Unhandled argument type!");
03123     case MVT::i1:
03124     case MVT::i32:
03125     case MVT::i64:
03126       // These can be scalar arguments or elements of an integer array type
03127       // passed directly.  Clang may use those instead of "byval" aggregate
03128       // types to avoid forcing arguments to memory unnecessarily.
03129       if (GPR_idx != Num_GPR_Regs) {
03130         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
03131         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
03132 
03133         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
03134           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
03135           // value to MVT::i64 and then truncate to the correct register size.
03136           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
03137       } else {
03138         if (CallConv == CallingConv::Fast)
03139           ComputeArgOffset();
03140 
03141         needsLoad = true;
03142         ArgSize = PtrByteSize;
03143       }
03144       if (CallConv != CallingConv::Fast || needsLoad)
03145         ArgOffset += 8;
03146       break;
03147 
03148     case MVT::f32:
03149     case MVT::f64:
03150       // These can be scalar arguments or elements of a float array type
03151       // passed directly.  The latter are used to implement ELFv2 homogenous
03152       // float aggregates.
03153       if (FPR_idx != Num_FPR_Regs) {
03154         unsigned VReg;
03155 
03156         if (ObjectVT == MVT::f32)
03157           VReg = MF.addLiveIn(FPR[FPR_idx],
03158                               Subtarget.hasP8Vector()
03159                                   ? &PPC::VSSRCRegClass
03160                                   : &PPC::F4RCRegClass);
03161         else
03162           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
03163                                                 ? &PPC::VSFRCRegClass
03164                                                 : &PPC::F8RCRegClass);
03165 
03166         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03167         ++FPR_idx;
03168       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
03169         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
03170         // once we support fp <-> gpr moves.
03171 
03172         // This can only ever happen in the presence of f32 array types,
03173         // since otherwise we never run out of FPRs before running out
03174         // of GPRs.
03175         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
03176         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
03177 
03178         if (ObjectVT == MVT::f32) {
03179           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
03180             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
03181                                  DAG.getConstant(32, dl, MVT::i32));
03182           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
03183         }
03184 
03185         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
03186       } else {
03187         if (CallConv == CallingConv::Fast)
03188           ComputeArgOffset();
03189 
03190         needsLoad = true;
03191       }
03192 
03193       // When passing an array of floats, the array occupies consecutive
03194       // space in the argument area; only round up to the next doubleword
03195       // at the end of the array.  Otherwise, each float takes 8 bytes.
03196       if (CallConv != CallingConv::Fast || needsLoad) {
03197         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
03198         ArgOffset += ArgSize;
03199         if (Flags.isInConsecutiveRegsLast())
03200           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
03201       }
03202       break;
03203     case MVT::v4f32:
03204     case MVT::v4i32:
03205     case MVT::v8i16:
03206     case MVT::v16i8:
03207     case MVT::v2f64:
03208     case MVT::v2i64:
03209     case MVT::v1i128:
03210       if (!Subtarget.hasQPX()) {
03211       // These can be scalar arguments or elements of a vector array type
03212       // passed directly.  The latter are used to implement ELFv2 homogenous
03213       // vector aggregates.
03214       if (VR_idx != Num_VR_Regs) {
03215         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
03216                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
03217                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
03218         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03219         ++VR_idx;
03220       } else {
03221         if (CallConv == CallingConv::Fast)
03222           ComputeArgOffset();
03223 
03224         needsLoad = true;
03225       }
03226       if (CallConv != CallingConv::Fast || needsLoad)
03227         ArgOffset += 16;
03228       break;
03229       } // not QPX
03230 
03231       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
03232              "Invalid QPX parameter type");
03233       /* fall through */
03234 
03235     case MVT::v4f64:
03236     case MVT::v4i1:
03237       // QPX vectors are treated like their scalar floating-point subregisters
03238       // (except that they're larger).
03239       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
03240       if (QFPR_idx != Num_QFPR_Regs) {
03241         const TargetRegisterClass *RC;
03242         switch (ObjectVT.getSimpleVT().SimpleTy) {
03243         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
03244         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
03245         default:         RC = &PPC::QBRCRegClass; break;
03246         }
03247 
03248         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
03249         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03250         ++QFPR_idx;
03251       } else {
03252         if (CallConv == CallingConv::Fast)
03253           ComputeArgOffset();
03254         needsLoad = true;
03255       }
03256       if (CallConv != CallingConv::Fast || needsLoad)
03257         ArgOffset += Sz;
03258       break;
03259     }
03260 
03261     // We need to load the argument to a virtual register if we determined
03262     // above that we ran out of physical registers of the appropriate type.
03263     if (needsLoad) {
03264       if (ObjSize < ArgSize && !isLittleEndian)
03265         CurArgOffset += ArgSize - ObjSize;
03266       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
03267       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03268       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
03269                            false, false, false, 0);
03270     }
03271 
03272     InVals.push_back(ArgVal);
03273   }
03274 
03275   // Area that is at least reserved in the caller of this function.
03276   unsigned MinReservedArea;
03277   if (HasParameterArea)
03278     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
03279   else
03280     MinReservedArea = LinkageSize;
03281 
03282   // Set the size that is at least reserved in caller of this function.  Tail
03283   // call optimized functions' reserved stack space needs to be aligned so that
03284   // taking the difference between two stack areas will result in an aligned
03285   // stack.
03286   MinReservedArea =
03287       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
03288   FuncInfo->setMinReservedArea(MinReservedArea);
03289 
03290   // If the function takes variable number of arguments, make a frame index for
03291   // the start of the first vararg value... for expansion of llvm.va_start.
03292   if (isVarArg) {
03293     int Depth = ArgOffset;
03294 
03295     FuncInfo->setVarArgsFrameIndex(
03296       MFI->CreateFixedObject(PtrByteSize, Depth, true));
03297     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
03298 
03299     // If this function is vararg, store any remaining integer argument regs
03300     // to their spots on the stack so that they may be loaded by deferencing the
03301     // result of va_next.
03302     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
03303          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
03304       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03305       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03306       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03307                                    MachinePointerInfo(), false, false, 0);
03308       MemOps.push_back(Store);
03309       // Increment the address by four for the next argument to store
03310       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
03311       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
03312     }
03313   }
03314 
03315   if (!MemOps.empty())
03316     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
03317 
03318   return Chain;
03319 }
03320 
03321 SDValue
03322 PPCTargetLowering::LowerFormalArguments_Darwin(
03323                                       SDValue Chain,
03324                                       CallingConv::ID CallConv, bool isVarArg,
03325                                       const SmallVectorImpl<ISD::InputArg>
03326                                         &Ins,
03327                                       SDLoc dl, SelectionDAG &DAG,
03328                                       SmallVectorImpl<SDValue> &InVals) const {
03329   // TODO: add description of PPC stack frame format, or at least some docs.
03330   //
03331   MachineFunction &MF = DAG.getMachineFunction();
03332   MachineFrameInfo *MFI = MF.getFrameInfo();
03333   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
03334 
03335   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03336   bool isPPC64 = PtrVT == MVT::i64;
03337   // Potential tail calls could cause overwriting of argument stack slots.
03338   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
03339                        (CallConv == CallingConv::Fast));
03340   unsigned PtrByteSize = isPPC64 ? 8 : 4;
03341   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
03342   unsigned ArgOffset = LinkageSize;
03343   // Area that is at least reserved in caller of this function.
03344   unsigned MinReservedArea = ArgOffset;
03345 
03346   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
03347     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
03348     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
03349   };
03350   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
03351     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
03352     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
03353   };
03354   static const MCPhysReg VR[] = {
03355     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
03356     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
03357   };
03358 
03359   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
03360   const unsigned Num_FPR_Regs = 13;
03361   const unsigned Num_VR_Regs  = array_lengthof( VR);
03362 
03363   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
03364 
03365   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
03366 
03367   // In 32-bit non-varargs functions, the stack space for vectors is after the
03368   // stack space for non-vectors.  We do not use this space unless we have
03369   // too many vectors to fit in registers, something that only occurs in
03370   // constructed examples:), but we have to walk the arglist to figure
03371   // that out...for the pathological case, compute VecArgOffset as the
03372   // start of the vector parameter area.  Computing VecArgOffset is the
03373   // entire point of the following loop.
03374   unsigned VecArgOffset = ArgOffset;
03375   if (!isVarArg && !isPPC64) {
03376     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
03377          ++ArgNo) {
03378       EVT ObjectVT = Ins[ArgNo].VT;
03379       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
03380 
03381       if (Flags.isByVal()) {
03382         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
03383         unsigned ObjSize = Flags.getByValSize();
03384         unsigned ArgSize =
03385                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
03386         VecArgOffset += ArgSize;
03387         continue;
03388       }
03389 
03390       switch(ObjectVT.getSimpleVT().SimpleTy) {
03391       default: llvm_unreachable("Unhandled argument type!");
03392       case MVT::i1:
03393       case MVT::i32:
03394       case MVT::f32:
03395         VecArgOffset += 4;
03396         break;
03397       case MVT::i64:  // PPC64
03398       case MVT::f64:
03399         // FIXME: We are guaranteed to be !isPPC64 at this point.
03400         // Does MVT::i64 apply?
03401         VecArgOffset += 8;
03402         break;
03403       case MVT::v4f32:
03404       case MVT::v4i32:
03405       case MVT::v8i16:
03406       case MVT::v16i8:
03407         // Nothing to do, we're only looking at Nonvector args here.
03408         break;
03409       }
03410     }
03411   }
03412   // We've found where the vector parameter area in memory is.  Skip the
03413   // first 12 parameters; these don't use that memory.
03414   VecArgOffset = ((VecArgOffset+15)/16)*16;
03415   VecArgOffset += 12*16;
03416 
03417   // Add DAG nodes to load the arguments or copy them out of registers.  On
03418   // entry to a function on PPC, the arguments start after the linkage area,
03419   // although the first ones are often in registers.
03420 
03421   SmallVector<SDValue, 8> MemOps;
03422   unsigned nAltivecParamsAtEnd = 0;
03423   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
03424   unsigned CurArgIdx = 0;
03425   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
03426     SDValue ArgVal;
03427     bool needsLoad = false;
03428     EVT ObjectVT = Ins[ArgNo].VT;
03429     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
03430     unsigned ArgSize = ObjSize;
03431     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
03432     if (Ins[ArgNo].isOrigArg()) {
03433       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
03434       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
03435     }
03436     unsigned CurArgOffset = ArgOffset;
03437 
03438     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
03439     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
03440         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
03441       if (isVarArg || isPPC64) {
03442         MinReservedArea = ((MinReservedArea+15)/16)*16;
03443         MinReservedArea += CalculateStackSlotSize(ObjectVT,
03444                                                   Flags,
03445                                                   PtrByteSize);
03446       } else  nAltivecParamsAtEnd++;
03447     } else
03448       // Calculate min reserved area.
03449       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
03450                                                 Flags,
03451                                                 PtrByteSize);
03452 
03453     // FIXME the codegen can be much improved in some cases.
03454     // We do not have to keep everything in memory.
03455     if (Flags.isByVal()) {
03456       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
03457 
03458       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
03459       ObjSize = Flags.getByValSize();
03460       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
03461       // Objects of size 1 and 2 are right justified, everything else is
03462       // left justified.  This means the memory address is adjusted forwards.
03463       if (ObjSize==1 || ObjSize==2) {
03464         CurArgOffset = CurArgOffset + (4 - ObjSize);
03465       }
03466       // The value of the object is its address.
03467       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
03468       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03469       InVals.push_back(FIN);
03470       if (ObjSize==1 || ObjSize==2) {
03471         if (GPR_idx != Num_GPR_Regs) {
03472           unsigned VReg;
03473           if (isPPC64)
03474             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03475           else
03476             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03477           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03478           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
03479           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
03480                                             MachinePointerInfo(FuncArg),
03481                                             ObjType, false, false, 0);
03482           MemOps.push_back(Store);
03483           ++GPR_idx;
03484         }
03485 
03486         ArgOffset += PtrByteSize;
03487 
03488         continue;
03489       }
03490       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
03491         // Store whatever pieces of the object are in registers
03492         // to memory.  ArgOffset will be the address of the beginning
03493         // of the object.
03494         if (GPR_idx != Num_GPR_Regs) {
03495           unsigned VReg;
03496           if (isPPC64)
03497             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03498           else
03499             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03500           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
03501           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03502           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03503           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03504                                        MachinePointerInfo(FuncArg, j),
03505                                        false, false, 0);
03506           MemOps.push_back(Store);
03507           ++GPR_idx;
03508           ArgOffset += PtrByteSize;
03509         } else {
03510           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
03511           break;
03512         }
03513       }
03514       continue;
03515     }
03516 
03517     switch (ObjectVT.getSimpleVT().SimpleTy) {
03518     default: llvm_unreachable("Unhandled argument type!");
03519     case MVT::i1:
03520     case MVT::i32:
03521       if (!isPPC64) {
03522         if (GPR_idx != Num_GPR_Regs) {
03523           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03524           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
03525 
03526           if (ObjectVT == MVT::i1)
03527             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
03528 
03529           ++GPR_idx;
03530         } else {
03531           needsLoad = true;
03532           ArgSize = PtrByteSize;
03533         }
03534         // All int arguments reserve stack space in the Darwin ABI.
03535         ArgOffset += PtrByteSize;
03536         break;
03537       }
03538       // FALLTHROUGH
03539     case MVT::i64:  // PPC64
03540       if (GPR_idx != Num_GPR_Regs) {
03541         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03542         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
03543 
03544         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
03545           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
03546           // value to MVT::i64 and then truncate to the correct register size.
03547           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
03548 
03549         ++GPR_idx;
03550       } else {
03551         needsLoad = true;
03552         ArgSize = PtrByteSize;
03553       }
03554       // All int arguments reserve stack space in the Darwin ABI.
03555       ArgOffset += 8;
03556       break;
03557 
03558     case MVT::f32:
03559     case MVT::f64:
03560       // Every 4 bytes of argument space consumes one of the GPRs available for
03561       // argument passing.
03562       if (GPR_idx != Num_GPR_Regs) {
03563         ++GPR_idx;
03564         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
03565           ++GPR_idx;
03566       }
03567       if (FPR_idx != Num_FPR_Regs) {
03568         unsigned VReg;
03569 
03570         if (ObjectVT == MVT::f32)
03571           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
03572         else
03573           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
03574 
03575         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03576         ++FPR_idx;
03577       } else {
03578         needsLoad = true;
03579       }
03580 
03581       // All FP arguments reserve stack space in the Darwin ABI.
03582       ArgOffset += isPPC64 ? 8 : ObjSize;
03583       break;
03584     case MVT::v4f32:
03585     case MVT::v4i32:
03586     case MVT::v8i16:
03587     case MVT::v16i8:
03588       // Note that vector arguments in registers don't reserve stack space,
03589       // except in varargs functions.
03590       if (VR_idx != Num_VR_Regs) {
03591         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
03592         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03593         if (isVarArg) {
03594           while ((ArgOffset % 16) != 0) {
03595             ArgOffset += PtrByteSize;
03596             if (GPR_idx != Num_GPR_Regs)
03597               GPR_idx++;
03598           }
03599           ArgOffset += 16;
03600           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
03601         }
03602         ++VR_idx;
03603       } else {
03604         if (!isVarArg && !isPPC64) {
03605           // Vectors go after all the nonvectors.
03606           CurArgOffset = VecArgOffset;
03607           VecArgOffset += 16;
03608         } else {
03609           // Vectors are aligned.
03610           ArgOffset = ((ArgOffset+15)/16)*16;
03611           CurArgOffset = ArgOffset;
03612           ArgOffset += 16;
03613         }
03614         needsLoad = true;
03615       }
03616       break;
03617     }
03618 
03619     // We need to load the argument to a virtual register if we determined above
03620     // that we ran out of physical registers of the appropriate type.
03621     if (needsLoad) {
03622       int FI = MFI->CreateFixedObject(ObjSize,
03623                                       CurArgOffset + (ArgSize - ObjSize),
03624                                       isImmutable);
03625       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03626       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
03627                            false, false, false, 0);
03628     }
03629 
03630     InVals.push_back(ArgVal);
03631   }
03632 
03633   // Allow for Altivec parameters at the end, if needed.
03634   if (nAltivecParamsAtEnd) {
03635     MinReservedArea = ((MinReservedArea+15)/16)*16;
03636     MinReservedArea += 16*nAltivecParamsAtEnd;
03637   }
03638 
03639   // Area that is at least reserved in the caller of this function.
03640   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
03641 
03642   // Set the size that is at least reserved in caller of this function.  Tail
03643   // call optimized functions' reserved stack space needs to be aligned so that
03644   // taking the difference between two stack areas will result in an aligned
03645   // stack.
03646   MinReservedArea =
03647       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
03648   FuncInfo->setMinReservedArea(MinReservedArea);
03649 
03650   // If the function takes variable number of arguments, make a frame index for
03651   // the start of the first vararg value... for expansion of llvm.va_start.
03652   if (isVarArg) {
03653     int Depth = ArgOffset;
03654 
03655     FuncInfo->setVarArgsFrameIndex(
03656       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
03657                              Depth, true));
03658     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
03659 
03660     // If this function is vararg, store any remaining integer argument regs
03661     // to their spots on the stack so that they may be loaded by deferencing the
03662     // result of va_next.
03663     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
03664       unsigned VReg;
03665 
03666       if (isPPC64)
03667         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03668       else
03669         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03670 
03671       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03672       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03673                                    MachinePointerInfo(), false, false, 0);
03674       MemOps.push_back(Store);
03675       // Increment the address by four for the next argument to store
03676       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
03677       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
03678     }
03679   }
03680 
03681   if (!MemOps.empty())
03682     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
03683 
03684   return Chain;
03685 }
03686 
03687 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
03688 /// adjusted to accommodate the arguments for the tailcall.
03689 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
03690                                    unsigned ParamSize) {
03691 
03692   if (!isTailCall) return 0;
03693 
03694   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
03695   unsigned CallerMinReservedArea = FI->getMinReservedArea();
03696   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
03697   // Remember only if the new adjustement is bigger.
03698   if (SPDiff < FI->getTailCallSPDelta())
03699     FI->setTailCallSPDelta(SPDiff);
03700 
03701   return SPDiff;
03702 }
03703 
03704 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
03705 /// for tail call optimization. Targets which want to do tail call
03706 /// optimization should implement this function.
03707 bool
03708 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
03709                                                      CallingConv::ID CalleeCC,
03710                                                      bool isVarArg,
03711                                       const SmallVectorImpl<ISD::InputArg> &Ins,
03712                                                      SelectionDAG& DAG) const {
03713   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
03714     return false;
03715 
03716   // Variable argument functions are not supported.
03717   if (isVarArg)
03718     return false;
03719 
03720   MachineFunction &MF = DAG.getMachineFunction();
03721   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
03722   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
03723     // Functions containing by val parameters are not supported.
03724     for (unsigned i = 0; i != Ins.size(); i++) {
03725        ISD::ArgFlagsTy Flags = Ins[i].Flags;
03726        if (Flags.isByVal()) return false;
03727     }
03728 
03729     // Non-PIC/GOT tail calls are supported.
03730     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
03731       return true;
03732 
03733     // At the moment we can only do local tail calls (in same module, hidden
03734     // or protected) if we are generating PIC.
03735     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
03736       return G->getGlobal()->hasHiddenVisibility()
03737           || G->getGlobal()->hasProtectedVisibility();
03738   }
03739 
03740   return false;
03741 }
03742 
03743 /// isCallCompatibleAddress - Return the immediate to use if the specified
03744 /// 32-bit value is representable in the immediate field of a BxA instruction.
03745 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
03746   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
03747   if (!C) return nullptr;
03748 
03749   int Addr = C->getZExtValue();
03750   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
03751       SignExtend32<26>(Addr) != Addr)
03752     return nullptr;  // Top 6 bits have to be sext of immediate.
03753 
03754   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
03755                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
03756 }
03757 
03758 namespace {
03759 
03760 struct TailCallArgumentInfo {
03761   SDValue Arg;
03762   SDValue FrameIdxOp;
03763   int       FrameIdx;
03764 
03765   TailCallArgumentInfo() : FrameIdx(0) {}
03766 };
03767 
03768 }
03769 
03770 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
03771 static void
03772 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
03773                                            SDValue Chain,
03774                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
03775                    SmallVectorImpl<SDValue> &MemOpChains,
03776                    SDLoc dl) {
03777   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
03778     SDValue Arg = TailCallArgs[i].Arg;
03779     SDValue FIN = TailCallArgs[i].FrameIdxOp;
03780     int FI = TailCallArgs[i].FrameIdx;
03781     // Store relative to framepointer.
03782     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
03783                                        MachinePointerInfo::getFixedStack(FI),
03784                                        false, false, 0));
03785   }
03786 }
03787 
03788 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
03789 /// the appropriate stack slot for the tail call optimized function call.
03790 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
03791                                                MachineFunction &MF,
03792                                                SDValue Chain,
03793                                                SDValue OldRetAddr,
03794                                                SDValue OldFP,
03795                                                int SPDiff,
03796                                                bool isPPC64,
03797                                                bool isDarwinABI,
03798                                                SDLoc dl) {
03799   if (SPDiff) {
03800     // Calculate the new stack slot for the return address.
03801     int SlotSize = isPPC64 ? 8 : 4;
03802     const PPCFrameLowering *FL =
03803         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
03804     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
03805     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
03806                                                           NewRetAddrLoc, true);
03807     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
03808     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
03809     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
03810                          MachinePointerInfo::getFixedStack(NewRetAddr),
03811                          false, false, 0);
03812 
03813     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
03814     // slot as the FP is never overwritten.
03815     if (isDarwinABI) {
03816       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
03817       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
03818                                                           true);
03819       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
03820       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
03821                            MachinePointerInfo::getFixedStack(NewFPIdx),
03822                            false, false, 0);
03823     }
03824   }
03825   return Chain;
03826 }
03827 
03828 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
03829 /// the position of the argument.
03830 static void
03831 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
03832                          SDValue Arg, int SPDiff, unsigned ArgOffset,
03833                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
03834   int Offset = ArgOffset + SPDiff;
03835   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
03836   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
03837   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
03838   SDValue FIN = DAG.getFrameIndex(FI, VT);
03839   TailCallArgumentInfo Info;
03840   Info.Arg = Arg;
03841   Info.FrameIdxOp = FIN;
03842   Info.FrameIdx = FI;
03843   TailCallArguments.push_back(Info);
03844 }
03845 
03846 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
03847 /// stack slot. Returns the chain as result and the loaded frame pointers in
03848 /// LROpOut/FPOpout. Used when tail calling.
03849 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
03850                                                         int SPDiff,
03851                                                         SDValue Chain,
03852                                                         SDValue &LROpOut,
03853                                                         SDValue &FPOpOut,
03854                                                         bool isDarwinABI,
03855                                                         SDLoc dl) const {
03856   if (SPDiff) {
03857     // Load the LR and FP stack slot for later adjusting.
03858     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
03859     LROpOut = getReturnAddrFrameIndex(DAG);
03860     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
03861                           false, false, false, 0);
03862     Chain = SDValue(LROpOut.getNode(), 1);
03863 
03864     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
03865     // slot as the FP is never overwritten.
03866     if (isDarwinABI) {
03867       FPOpOut = getFramePointerFrameIndex(DAG);
03868       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
03869                             false, false, false, 0);
03870       Chain = SDValue(FPOpOut.getNode(), 1);
03871     }
03872   }
03873   return Chain;
03874 }
03875 
03876 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
03877 /// by "Src" to address "Dst" of size "Size".  Alignment information is
03878 /// specified by the specific parameter attribute. The copy will be passed as
03879 /// a byval function parameter.
03880 /// Sometimes what we are copying is the end of a larger object, the part that
03881 /// does not fit in registers.
03882 static SDValue
03883 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
03884                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
03885                           SDLoc dl) {
03886   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
03887   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
03888                        false, false, false, MachinePointerInfo(),
03889                        MachinePointerInfo());
03890 }
03891 
03892 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
03893 /// tail calls.
03894 static void
03895 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
03896                  SDValue Arg, SDValue PtrOff, int SPDiff,
03897                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
03898                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
03899                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
03900                  SDLoc dl) {
03901   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03902   if (!isTailCall) {
03903     if (isVector) {
03904       SDValue StackPtr;
03905       if (isPPC64)
03906         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
03907       else
03908         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
03909       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
03910                            DAG.getConstant(ArgOffset, dl, PtrVT));
03911     }
03912     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
03913                                        MachinePointerInfo(), false, false, 0));
03914   // Calculate and remember argument location.
03915   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
03916                                   TailCallArguments);
03917 }
03918 
03919 static
03920 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
03921                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
03922                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
03923                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
03924   MachineFunction &MF = DAG.getMachineFunction();
03925 
03926   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
03927   // might overwrite each other in case of tail call optimization.
03928   SmallVector<SDValue, 8> MemOpChains2;
03929   // Do not flag preceding copytoreg stuff together with the following stuff.
03930   InFlag = SDValue();
03931   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
03932                                     MemOpChains2, dl);
03933   if (!MemOpChains2.empty())
03934     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
03935 
03936   // Store the return address to the appropriate stack slot.
03937   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
03938                                         isPPC64, isDarwinABI, dl);
03939 
03940   // Emit callseq_end just before tailcall node.
03941   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
03942                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
03943   InFlag = Chain.getValue(1);
03944 }
03945 
03946 // Is this global address that of a function that can be called by name? (as
03947 // opposed to something that must hold a descriptor for an indirect call).
03948 static bool isFunctionGlobalAddress(SDValue Callee) {
03949   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
03950     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
03951         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
03952       return false;
03953 
03954     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
03955   }
03956 
03957   return false;
03958 }
03959 
03960 static
03961 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
03962                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
03963                      bool isTailCall, bool IsPatchPoint,
03964                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
03965                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
03966                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
03967 
03968   bool isPPC64 = Subtarget.isPPC64();
03969   bool isSVR4ABI = Subtarget.isSVR4ABI();
03970   bool isELFv2ABI = Subtarget.isELFv2ABI();
03971 
03972   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03973   NodeTys.push_back(MVT::Other);   // Returns a chain
03974   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
03975 
03976   unsigned CallOpc = PPCISD::CALL;
03977 
03978   bool needIndirectCall = true;
03979   if (!isSVR4ABI || !isPPC64)
03980     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
03981       // If this is an absolute destination address, use the munged value.
03982       Callee = SDValue(Dest, 0);
03983       needIndirectCall = false;
03984     }
03985 
03986   if (isFunctionGlobalAddress(Callee)) {
03987     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
03988     // A call to a TLS address is actually an indirect call to a
03989     // thread-specific pointer.
03990     unsigned OpFlags = 0;
03991     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
03992          (Subtarget.getTargetTriple().isMacOSX() &&
03993           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
03994          (G->getGlobal()->isDeclaration() ||
03995           G->getGlobal()->isWeakForLinker())) ||
03996         (Subtarget.isTargetELF() && !isPPC64 &&
03997          !G->getGlobal()->hasLocalLinkage() &&
03998          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
03999       // PC-relative references to external symbols should go through $stub,
04000       // unless we're building with the leopard linker or later, which
04001       // automatically synthesizes these stubs.
04002       OpFlags = PPCII::MO_PLT_OR_STUB;
04003     }
04004 
04005     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
04006     // every direct call is) turn it into a TargetGlobalAddress /
04007     // TargetExternalSymbol node so that legalize doesn't hack it.
04008     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
04009                                         Callee.getValueType(), 0, OpFlags);
04010     needIndirectCall = false;
04011   }
04012 
04013   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
04014     unsigned char OpFlags = 0;
04015 
04016     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
04017          (Subtarget.getTargetTriple().isMacOSX() &&
04018           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
04019         (Subtarget.isTargetELF() && !isPPC64 &&
04020          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
04021       // PC-relative references to external symbols should go through $stub,
04022       // unless we're building with the leopard linker or later, which
04023       // automatically synthesizes these stubs.
04024       OpFlags = PPCII::MO_PLT_OR_STUB;
04025     }
04026 
04027     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
04028                                          OpFlags);
04029     needIndirectCall = false;
04030   }
04031 
04032   if (IsPatchPoint) {
04033     // We'll form an invalid direct call when lowering a patchpoint; the full
04034     // sequence for an indirect call is complicated, and many of the
04035     // instructions introduced might have side effects (and, thus, can't be
04036     // removed later). The call itself will be removed as soon as the
04037     // argument/return lowering is complete, so the fact that it has the wrong
04038     // kind of operands should not really matter.
04039     needIndirectCall = false;
04040   }
04041 
04042   if (needIndirectCall) {
04043     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
04044     // to do the call, we can't use PPCISD::CALL.
04045     SDValue MTCTROps[] = {Chain, Callee, InFlag};
04046 
04047     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
04048       // Function pointers in the 64-bit SVR4 ABI do not point to the function
04049       // entry point, but to the function descriptor (the function entry point
04050       // address is part of the function descriptor though).
04051       // The function descriptor is a three doubleword structure with the
04052       // following fields: function entry point, TOC base address and
04053       // environment pointer.
04054       // Thus for a call through a function pointer, the following actions need
04055       // to be performed:
04056       //   1. Save the TOC of the caller in the TOC save area of its stack
04057       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
04058       //   2. Load the address of the function entry point from the function
04059       //      descriptor.
04060       //   3. Load the TOC of the callee from the function descriptor into r2.
04061       //   4. Load the environment pointer from the function descriptor into
04062       //      r11.
04063       //   5. Branch to the function entry point address.
04064       //   6. On return of the callee, the TOC of the caller needs to be
04065       //      restored (this is done in FinishCall()).
04066       //
04067       // The loads are scheduled at the beginning of the call sequence, and the
04068       // register copies are flagged together to ensure that no other
04069       // operations can be scheduled in between. E.g. without flagging the
04070       // copies together, a TOC access in the caller could be scheduled between
04071       // the assignment of the callee TOC and the branch to the callee, which
04072       // results in the TOC access going through the TOC of the callee instead
04073       // of going through the TOC of the caller, which leads to incorrect code.
04074 
04075       // Load the address of the function entry point from the function
04076       // descriptor.
04077       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
04078       if (LDChain.getValueType() == MVT::Glue)
04079         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
04080 
04081       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
04082 
04083       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
04084       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
04085                                         false, false, LoadsInv, 8);
04086 
04087       // Load environment pointer into r11.
04088       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
04089       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
04090       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
04091                                        MPI.getWithOffset(16), false, false,
04092                                        LoadsInv, 8);
04093 
04094       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
04095       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
04096       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
04097                                    MPI.getWithOffset(8), false, false,
04098                                    LoadsInv, 8);
04099 
04100       setUsesTOCBasePtr(DAG);
04101       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
04102                                         InFlag);
04103       Chain = TOCVal.getValue(0);
04104       InFlag = TOCVal.getValue(1);
04105 
04106       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
04107                                         InFlag);
04108 
04109       Chain = EnvVal.getValue(0);
04110       InFlag = EnvVal.getValue(1);
04111 
04112       MTCTROps[0] = Chain;
04113       MTCTROps[1] = LoadFuncPtr;
04114       MTCTROps[2] = InFlag;
04115     }
04116 
04117     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
04118                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
04119     InFlag = Chain.getValue(1);
04120 
04121     NodeTys.clear();
04122     NodeTys.push_back(MVT::Other);
04123     NodeTys.push_back(MVT::Glue);
04124     Ops.push_back(Chain);
04125     CallOpc = PPCISD::BCTRL;
04126     Callee.setNode(nullptr);
04127     // Add use of X11 (holding environment pointer)
04128     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
04129       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
04130     // Add CTR register as callee so a bctr can be emitted later.
04131     if (isTailCall)
04132       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
04133   }
04134 
04135   // If this is a direct call, pass the chain and the callee.
04136   if (Callee.getNode()) {
04137     Ops.push_back(Chain);
04138     Ops.push_back(Callee);
04139   }
04140   // If this is a tail call add stack pointer delta.
04141   if (isTailCall)
04142     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
04143 
04144   // Add argument registers to the end of the list so that they are known live
04145   // into the call.
04146   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
04147     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
04148                                   RegsToPass[i].second.getValueType()));
04149 
04150   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
04151   // into the call.
04152   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
04153     setUsesTOCBasePtr(DAG);
04154     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
04155   }
04156 
04157   return CallOpc;
04158 }
04159 
04160 static
04161 bool isLocalCall(const SDValue &Callee)
04162 {
04163   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
04164     return !G->getGlobal()->isDeclaration() &&
04165            !G->getGlobal()->isWeakForLinker();
04166   return false;
04167 }
04168 
04169 SDValue
04170 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
04171                                    CallingConv::ID CallConv, bool isVarArg,
04172                                    const SmallVectorImpl<ISD::InputArg> &Ins,
04173                                    SDLoc dl, SelectionDAG &DAG,
04174                                    SmallVectorImpl<SDValue> &InVals) const {
04175 
04176   SmallVector<CCValAssign, 16> RVLocs;
04177   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
04178                     *DAG.getContext());
04179   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
04180 
04181   // Copy all of the result registers out of their specified physreg.
04182   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
04183     CCValAssign &VA = RVLocs[i];
04184     assert(VA.isRegLoc() && "Can only return in registers!");
04185 
04186     SDValue Val = DAG.getCopyFromReg(Chain, dl,
04187                                      VA.getLocReg(), VA.getLocVT(), InFlag);
04188     Chain = Val.getValue(1);
04189     InFlag = Val.getValue(2);
04190 
04191     switch (VA.getLocInfo()) {
04192     default: llvm_unreachable("Unknown loc info!");
04193     case CCValAssign::Full: break;
04194     case CCValAssign::AExt:
04195       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
04196       break;
04197     case CCValAssign::ZExt:
04198       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
04199                         DAG.getValueType(VA.getValVT()));
04200       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
04201       break;
04202     case CCValAssign::SExt:
04203       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
04204                         DAG.getValueType(VA.getValVT()));
04205       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
04206       break;
04207     }
04208 
04209     InVals.push_back(Val);
04210   }
04211 
04212   return Chain;
04213 }
04214 
04215 SDValue
04216 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
04217                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
04218                               SelectionDAG &DAG,
04219                               SmallVector<std::pair<unsigned, SDValue>, 8>
04220                                 &RegsToPass,
04221                               SDValue InFlag, SDValue Chain,
04222                               SDValue CallSeqStart, SDValue &Callee,
04223                               int SPDiff, unsigned NumBytes,
04224                               const SmallVectorImpl<ISD::InputArg> &Ins,
04225                               SmallVectorImpl<SDValue> &InVals,
04226                               ImmutableCallSite *CS) const {
04227 
04228   std::vector<EVT> NodeTys;
04229   SmallVector<SDValue, 8> Ops;
04230   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
04231                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
04232                                  Ops, NodeTys, CS, Subtarget);
04233 
04234   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
04235   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
04236     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
04237 
04238   // When performing tail call optimization the callee pops its arguments off
04239   // the stack. Account for this here so these bytes can be pushed back on in
04240   // PPCFrameLowering::eliminateCallFramePseudoInstr.
04241   int BytesCalleePops =
04242     (CallConv == CallingConv::Fast &&
04243      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
04244 
04245   // Add a register mask operand representing the call-preserved registers.
04246   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
04247   const uint32_t *Mask =
04248       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
04249   assert(Mask && "Missing call preserved mask for calling convention");
04250   Ops.push_back(DAG.getRegisterMask(Mask));
04251 
04252   if (InFlag.getNode())
04253     Ops.push_back(InFlag);
04254 
04255   // Emit tail call.
04256   if (isTailCall) {
04257     assert(((Callee.getOpcode() == ISD::Register &&
04258              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
04259             Callee.getOpcode() == ISD::TargetExternalSymbol ||
04260             Callee.getOpcode() == ISD::TargetGlobalAddress ||
04261             isa<ConstantSDNode>(Callee)) &&
04262     "Expecting an global address, external symbol, absolute value or register");
04263 
04264     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
04265     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
04266   }
04267 
04268   // Add a NOP immediately after the branch instruction when using the 64-bit
04269   // SVR4 ABI. At link time, if caller and callee are in a different module and
04270   // thus have a different TOC, the call will be replaced with a call to a stub
04271   // function which saves the current TOC, loads the TOC of the callee and
04272   // branches to the callee. The NOP will be replaced with a load instruction
04273   // which restores the TOC of the caller from the TOC save slot of the current
04274   // stack frame. If caller and callee belong to the same module (and have the
04275   // same TOC), the NOP will remain unchanged.
04276 
04277   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
04278       !IsPatchPoint) {
04279     if (CallOpc == PPCISD::BCTRL) {
04280       // This is a call through a function pointer.
04281       // Restore the caller TOC from the save area into R2.
04282       // See PrepareCall() for more information about calls through function
04283       // pointers in the 64-bit SVR4 ABI.
04284       // We are using a target-specific load with r2 hard coded, because the
04285       // result of a target-independent load would never go directly into r2,
04286       // since r2 is a reserved register (which prevents the register allocator
04287       // from allocating it), resulting in an additional register being
04288       // allocated and an unnecessary move instruction being generated.
04289       CallOpc = PPCISD::BCTRL_LOAD_TOC;
04290 
04291       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
04292       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
04293       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
04294       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
04295       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
04296 
04297       // The address needs to go after the chain input but before the flag (or
04298       // any other variadic arguments).
04299       Ops.insert(std::next(Ops.begin()), AddTOC);
04300     } else if ((CallOpc == PPCISD::CALL) &&
04301                (!isLocalCall(Callee) ||
04302                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
04303       // Otherwise insert NOP for non-local calls.
04304       CallOpc = PPCISD::CALL_NOP;
04305   }
04306 
04307   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
04308   InFlag = Chain.getValue(1);
04309 
04310   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
04311                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
04312                              InFlag, dl);
04313   if (!Ins.empty())
04314     InFlag = Chain.getValue(1);
04315 
04316   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
04317                          Ins, dl, DAG, InVals);
04318 }
04319 
04320 SDValue
04321 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
04322                              SmallVectorImpl<SDValue> &InVals) const {
04323   SelectionDAG &DAG                     = CLI.DAG;
04324   SDLoc &dl                             = CLI.DL;
04325   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
04326   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
04327   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
04328   SDValue Chain                         = CLI.Chain;
04329   SDValue Callee                        = CLI.Callee;
04330   bool &isTailCall                      = CLI.IsTailCall;
04331   CallingConv::ID CallConv              = CLI.CallConv;
04332   bool isVarArg                         = CLI.IsVarArg;
04333   bool IsPatchPoint                     = CLI.IsPatchPoint;
04334   ImmutableCallSite *CS                 = CLI.CS;
04335 
04336   if (isTailCall)
04337     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
04338                                                    Ins, DAG);
04339 
04340   if (!isTailCall && CS && CS->isMustTailCall())
04341     report_fatal_error("failed to perform tail call elimination on a call "
04342                        "site marked musttail");
04343 
04344   if (Subtarget.isSVR4ABI()) {
04345     if (Subtarget.isPPC64())
04346       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
04347                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
04348                               dl, DAG, InVals, CS);
04349     else
04350       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
04351                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
04352                               dl, DAG, InVals, CS);
04353   }
04354 
04355   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
04356                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
04357                           dl, DAG, InVals, CS);
04358 }
04359 
04360 SDValue
04361 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
04362                                     CallingConv::ID CallConv, bool isVarArg,
04363                                     bool isTailCall, bool IsPatchPoint,
04364                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
04365                                     const SmallVectorImpl<SDValue> &OutVals,
04366                                     const SmallVectorImpl<ISD::InputArg> &Ins,
04367                                     SDLoc dl, SelectionDAG &DAG,
04368                                     SmallVectorImpl<SDValue> &InVals,
04369                                     ImmutableCallSite *CS) const {
04370   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
04371   // of the 32-bit SVR4 ABI stack frame layout.
04372 
04373   assert((CallConv == CallingConv::C ||
04374           CallConv == CallingConv::Fast) && "Unknown calling convention!");
04375 
04376   unsigned PtrByteSize = 4;
04377 
04378   MachineFunction &MF = DAG.getMachineFunction();
04379 
04380   // Mark this function as potentially containing a function that contains a
04381   // tail call. As a consequence the frame pointer will be used for dynamicalloc
04382   // and restoring the callers stack pointer in this functions epilog. This is
04383   // done because by tail calling the called function might overwrite the value
04384   // in this function's (MF) stack pointer stack slot 0(SP).
04385   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04386       CallConv == CallingConv::Fast)
04387     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
04388 
04389   // Count how many bytes are to be pushed on the stack, including the linkage
04390   // area, parameter list area and the part of the local variable space which
04391   // contains copies of aggregates which are passed by value.
04392 
04393   // Assign locations to all of the outgoing arguments.
04394   SmallVector<CCValAssign, 16> ArgLocs;
04395   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
04396                  *DAG.getContext());
04397 
04398   // Reserve space for the linkage area on the stack.
04399   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
04400                        PtrByteSize);
04401 
04402   if (isVarArg) {
04403     // Handle fixed and variable vector arguments differently.
04404     // Fixed vector arguments go into registers as long as registers are
04405     // available. Variable vector arguments always go into memory.
04406     unsigned NumArgs = Outs.size();
04407 
04408     for (unsigned i = 0; i != NumArgs; ++i) {
04409       MVT ArgVT = Outs[i].VT;
04410       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
04411       bool Result;
04412 
04413       if (Outs[i].IsFixed) {
04414         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
04415                                CCInfo);
04416       } else {
04417         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
04418                                       ArgFlags, CCInfo);
04419       }
04420 
04421       if (Result) {
04422 #ifndef NDEBUG
04423         errs() << "Call operand #" << i << " has unhandled type "
04424              << EVT(ArgVT).getEVTString() << "\n";
04425 #endif
04426         llvm_unreachable(nullptr);
04427       }
04428     }
04429   } else {
04430     // All arguments are treated the same.
04431     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
04432   }
04433 
04434   // Assign locations to all of the outgoing aggregate by value arguments.
04435   SmallVector<CCValAssign, 16> ByValArgLocs;
04436   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
04437                       ByValArgLocs, *DAG.getContext());
04438 
04439   // Reserve stack space for the allocations in CCInfo.
04440   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
04441 
04442   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
04443 
04444   // Size of the linkage area, parameter list area and the part of the local
04445   // space variable where copies of aggregates which are passed by value are
04446   // stored.
04447   unsigned NumBytes = CCByValInfo.getNextStackOffset();
04448 
04449   // Calculate by how many bytes the stack has to be adjusted in case of tail
04450   // call optimization.
04451   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
04452 
04453   // Adjust the stack pointer for the new arguments...
04454   // These operations are automatically eliminated by the prolog/epilog pass
04455   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
04456                                dl);
04457   SDValue CallSeqStart = Chain;
04458 
04459   // Load the return address and frame pointer so it can be moved somewhere else
04460   // later.
04461   SDValue LROp, FPOp;
04462   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
04463                                        dl);
04464 
04465   // Set up a copy of the stack pointer for use loading and storing any
04466   // arguments that may not fit in the registers available for argument
04467   // passing.
04468   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
04469 
04470   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
04471   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
04472   SmallVector<SDValue, 8> MemOpChains;
04473 
04474   bool seenFloatArg = false;
04475   // Walk the register/memloc assignments, inserting copies/loads.
04476   for (unsigned i = 0, j = 0, e = ArgLocs.size();
04477        i != e;
04478        ++i) {
04479     CCValAssign &VA = ArgLocs[i];
04480     SDValue Arg = OutVals[i];
04481     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04482 
04483     if (Flags.isByVal()) {
04484       // Argument is an aggregate which is passed by value, thus we need to
04485       // create a copy of it in the local variable space of the current stack
04486       // frame (which is the stack frame of the caller) and pass the address of
04487       // this copy to the callee.
04488       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
04489       CCValAssign &ByValVA = ByValArgLocs[j++];
04490       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
04491 
04492       // Memory reserved in the local variable space of the callers stack frame.
04493       unsigned LocMemOffset = ByValVA.getLocMemOffset();
04494 
04495       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
04496       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
04497 
04498       // Create a copy of the argument in the local area of the current
04499       // stack frame.
04500       SDValue MemcpyCall =
04501         CreateCopyOfByValArgument(Arg, PtrOff,
04502                                   CallSeqStart.getNode()->getOperand(0),
04503                                   Flags, DAG, dl);
04504 
04505       // This must go outside the CALLSEQ_START..END.
04506       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
04507                            CallSeqStart.getNode()->getOperand(1),
04508                            SDLoc(MemcpyCall));
04509       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
04510                              NewCallSeqStart.getNode());
04511       Chain = CallSeqStart = NewCallSeqStart;
04512 
04513       // Pass the address of the aggregate copy on the stack either in a
04514       // physical register or in the parameter list area of the current stack
04515       // frame to the callee.
04516       Arg = PtrOff;
04517     }
04518 
04519     if (VA.isRegLoc()) {
04520       if (Arg.getValueType() == MVT::i1)
04521         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
04522 
04523       seenFloatArg |= VA.getLocVT().isFloatingPoint();
04524       // Put argument in a physical register.
04525       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
04526     } else {
04527       // Put argument in the parameter list area of the current stack frame.
04528       assert(VA.isMemLoc());
04529       unsigned LocMemOffset = VA.getLocMemOffset();
04530 
04531       if (!isTailCall) {
04532         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
04533         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
04534 
04535         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
04536                                            MachinePointerInfo(),
04537                                            false, false, 0));
04538       } else {
04539         // Calculate and remember argument location.
04540         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
04541                                  TailCallArguments);
04542       }
04543     }
04544   }
04545 
04546   if (!MemOpChains.empty())
04547     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
04548 
04549   // Build a sequence of copy-to-reg nodes chained together with token chain
04550   // and flag operands which copy the outgoing args into the appropriate regs.
04551   SDValue InFlag;
04552   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
04553     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
04554                              RegsToPass[i].second, InFlag);
04555     InFlag = Chain.getValue(1);
04556   }
04557 
04558   // Set CR bit 6 to true if this is a vararg call with floating args passed in
04559   // registers.
04560   if (isVarArg) {
04561     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
04562     SDValue Ops[] = { Chain, InFlag };
04563 
04564     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
04565                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
04566 
04567     InFlag = Chain.getValue(1);
04568   }
04569 
04570   if (isTailCall)
04571     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
04572                     false, TailCallArguments);
04573 
04574   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
04575                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
04576                     NumBytes, Ins, InVals, CS);
04577 }
04578 
04579 // Copy an argument into memory, being careful to do this outside the
04580 // call sequence for the call to which the argument belongs.
04581 SDValue
04582 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
04583                                               SDValue CallSeqStart,
04584                                               ISD::ArgFlagsTy Flags,
04585                                               SelectionDAG &DAG,
04586                                               SDLoc dl) const {
04587   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
04588                         CallSeqStart.getNode()->getOperand(0),
04589                         Flags, DAG, dl);
04590   // The MEMCPY must go outside the CALLSEQ_START..END.
04591   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
04592                              CallSeqStart.getNode()->getOperand(1),
04593                              SDLoc(MemcpyCall));
04594   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
04595                          NewCallSeqStart.getNode());
04596   return NewCallSeqStart;
04597 }
04598 
04599 SDValue
04600 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
04601                                     CallingConv::ID CallConv, bool isVarArg,
04602                                     bool isTailCall, bool IsPatchPoint,
04603                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
04604                                     const SmallVectorImpl<SDValue> &OutVals,
04605                                     const SmallVectorImpl<ISD::InputArg> &Ins,
04606                                     SDLoc dl, SelectionDAG &DAG,
04607                                     SmallVectorImpl<SDValue> &InVals,
04608                                     ImmutableCallSite *CS) const {
04609 
04610   bool isELFv2ABI = Subtarget.isELFv2ABI();
04611   bool isLittleEndian = Subtarget.isLittleEndian();
04612   unsigned NumOps = Outs.size();
04613 
04614   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
04615   unsigned PtrByteSize = 8;
04616 
04617   MachineFunction &MF = DAG.getMachineFunction();
04618 
04619   // Mark this function as potentially containing a function that contains a
04620   // tail call. As a consequence the frame pointer will be used for dynamicalloc
04621   // and restoring the callers stack pointer in this functions epilog. This is
04622   // done because by tail calling the called function might overwrite the value
04623   // in this function's (MF) stack pointer stack slot 0(SP).
04624   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04625       CallConv == CallingConv::Fast)
04626     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
04627 
04628   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
04629          "fastcc not supported on varargs functions");
04630 
04631   // Count how many bytes are to be pushed on the stack, including the linkage
04632   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
04633   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
04634   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
04635   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
04636   unsigned NumBytes = LinkageSize;
04637   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
04638   unsigned &QFPR_idx = FPR_idx;
04639 
04640   static const MCPhysReg GPR[] = {
04641     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
04642     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
04643   };
04644   static const MCPhysReg VR[] = {
04645     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
04646     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
04647   };
04648   static const MCPhysReg VSRH[] = {
04649     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
04650     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
04651   };
04652 
04653   const unsigned NumGPRs = array_lengthof(GPR);
04654   const unsigned NumFPRs = 13;
04655   const unsigned NumVRs  = array_lengthof(VR);
04656   const unsigned NumQFPRs = NumFPRs;
04657 
04658   // When using the fast calling convention, we don't provide backing for
04659   // arguments that will be in registers.
04660   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
04661 
04662   // Add up all the space actually used.
04663   for (unsigned i = 0; i != NumOps; ++i) {
04664     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04665     EVT ArgVT = Outs[i].VT;
04666     EVT OrigVT = Outs[i].ArgVT;
04667 
04668     if (CallConv == CallingConv::Fast) {
04669       if (Flags.isByVal())
04670         NumGPRsUsed += (Flags.getByValSize()+7)/8;
04671       else
04672         switch (ArgVT.getSimpleVT().SimpleTy) {
04673         default: llvm_unreachable("Unexpected ValueType for argument!");
04674         case MVT::i1:
04675         case MVT::i32:
04676         case MVT::i64:
04677           if (++NumGPRsUsed <= NumGPRs)
04678             continue;
04679           break;
04680         case MVT::v4i32:
04681         case MVT::v8i16:
04682         case MVT::v16i8:
04683         case MVT::v2f64:
04684         case MVT::v2i64:
04685         case MVT::v1i128:
04686           if (++NumVRsUsed <= NumVRs)
04687             continue;
04688           break;
04689         case MVT::v4f32:
04690     // When using QPX, this is handled like a FP register, otherwise, it
04691     // is an Altivec register.
04692           if (Subtarget.hasQPX()) {
04693             if (++NumFPRsUsed <= NumFPRs)
04694               continue;
04695           } else {
04696             if (++NumVRsUsed <= NumVRs)
04697               continue;
04698           }
04699           break;
04700         case MVT::f32:
04701         case MVT::f64:
04702         case MVT::v4f64: // QPX
04703         case MVT::v4i1:  // QPX
04704           if (++NumFPRsUsed <= NumFPRs)
04705             continue;
04706           break;
04707         }
04708     }
04709 
04710     /* Respect alignment of argument on the stack.  */
04711     unsigned Align =
04712       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
04713     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
04714 
04715     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
04716     if (Flags.isInConsecutiveRegsLast())
04717       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
04718   }
04719 
04720   unsigned NumBytesActuallyUsed = NumBytes;
04721 
04722   // The prolog code of the callee may store up to 8 GPR argument registers to
04723   // the stack, allowing va_start to index over them in memory if its varargs.
04724   // Because we cannot tell if this is needed on the caller side, we have to
04725   // conservatively assume that it is needed.  As such, make sure we have at
04726   // least enough stack space for the caller to store the 8 GPRs.
04727   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
04728   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
04729 
04730   // Tail call needs the stack to be aligned.
04731   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04732       CallConv == CallingConv::Fast)
04733     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
04734 
04735   // Calculate by how many bytes the stack has to be adjusted in case of tail
04736   // call optimization.
04737   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
04738 
04739   // To protect arguments on the stack from being clobbered in a tail call,
04740   // force all the loads to happen before doing any other lowering.
04741   if (isTailCall)
04742     Chain = DAG.getStackArgumentTokenFactor(Chain);
04743 
04744   // Adjust the stack pointer for the new arguments...
04745   // These operations are automatically eliminated by the prolog/epilog pass
04746   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),