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