LLVM API Documentation

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