ArgumentPromotion.cpp revision d509d0b532ec2358b3f341d4a4cd1411cb8b5db2
19e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
3ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//                     The LLVM Compiler Infrastructure
4ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
8ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//===----------------------------------------------------------------------===//
9ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//
10ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner// This pass promotes "by reference" arguments to be "by value" arguments.  In
11ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner// practice, this means looking for internal functions that have pointer
1255cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// arguments.  If it can prove, through the use of alias analysis, that an
1355cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// argument is *only* loaded, then it can pass the value into the function
14ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner// instead of the address of the value.  This can cause recursive simplification
159e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner// of code and lead to the elimination of allocas (especially in C++ template
169e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner// code like the STL).
17ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//
189440db886627161a8413e823797569fc7b10beafChris Lattner// This pass also handles aggregate arguments that are passed into a function,
199440db886627161a8413e823797569fc7b10beafChris Lattner// scalarizing them if the elements of the aggregate are only loaded.  Note that
20477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman// by default it refuses to scalarize aggregates which would require passing in
21477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman// more than three operands to the function, because passing thousands of
224cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands// operands for a large array or structure is unprofitable! This limit can be
23477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman// configured or disabled, however.
249440db886627161a8413e823797569fc7b10beafChris Lattner//
25ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner// Note that this transformation could also be done for arguments that are only
2655cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// stored to (returning the value instead), but does not currently.  This case
2755cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// would be best handled when and if LLVM begins supporting multiple return
2855cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// values from functions.
29ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//
30ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//===----------------------------------------------------------------------===//
31ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
329e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner#define DEBUG_TYPE "argpromotion"
33ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Transforms/IPO.h"
34ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Constants.h"
35ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/DerivedTypes.h"
36ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Module.h"
375eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner#include "llvm/CallGraphSCCPass.h"
38ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Instructions.h"
3914ce9ef2e9013ba56e1daafebd91fe3ee1e8647eOwen Anderson#include "llvm/LLVMContext.h"
40ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
415eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner#include "llvm/Analysis/CallGraph.h"
42ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CallSite.h"
43ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CFG.h"
44551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/Debug.h"
45ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar#include "llvm/Support/raw_ostream.h"
46551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/DepthFirstIterator.h"
47551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/Statistic.h"
4823132b188ba651ba172380cd082cc286df73d440Chris Lattner#include "llvm/ADT/StringExtras.h"
49ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include <set>
50ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattnerusing namespace llvm;
51ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5286453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
5386453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
5410603e0c84d15f61443e8b17bc35f98cc46606d9Chris LattnerSTATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
5586453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
56ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5786453c52ba02e743d29c08456e51006500041456Chris Lattnernamespace {
58ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  ///
606726b6d75a8b679068a58cb954ba97cf9d1690baNick Lewycky  struct ArgPromotion : public CallGraphSCCPass {
61ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      AU.addRequired<AliasAnalysis>();
635eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner      CallGraphSCCPass::getAnalysisUsage(AU);
64ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
65ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
662decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattner    virtual bool runOnSCC(CallGraphSCC &SCC);
67ecd94c804a563f2a86572dcf1d2e81f397e19daaNick Lewycky    static char ID; // Pass identification, replacement for typeid
6838deef9ce58b33dba34515f23fb7dbde02164c77Dan Gohman    explicit ArgPromotion(unsigned maxElements = 3)
69081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson        : CallGraphSCCPass(ID), maxElements(maxElements) {
70081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson      initializeArgPromotionPass(*PassRegistry::getPassRegistry());
71081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson    }
724cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
73477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    /// A vector used to hold the indices of a single GEP instruction
74477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    typedef std::vector<uint64_t> IndicesVector;
75794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel
76ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  private:
775095e3d1d1caef8d573534d369e37277c623064cChris Lattner    CallGraphNode *PromoteArguments(CallGraphNode *CGN);
7840c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
795095e3d1d1caef8d573534d369e37277c623064cChris Lattner    CallGraphNode *DoPromotion(Function *F,
805095e3d1d1caef8d573534d369e37277c623064cChris Lattner                               SmallPtrSet<Argument*, 8> &ArgsToPromote,
815095e3d1d1caef8d573534d369e37277c623064cChris Lattner                               SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
82992e97eed344a141ff581838cfdacb76a1e9559aMatthijs Kooijman    /// The maximum number of elements to expand, or 0 for unlimited.
83992e97eed344a141ff581838cfdacb76a1e9559aMatthijs Kooijman    unsigned maxElements;
84ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  };
85ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
86ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
87844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar ArgPromotion::ID = 0;
882ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
892ab36d350293c77fc8941ce1023e4899df7e3a82Owen Anderson                "Promote 'by reference' arguments to scalars", false, false)
902ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
91ae0a7bc68303ce0c8721f0e981ae602601390e68Owen AndersonINITIALIZE_AG_DEPENDENCY(CallGraph)
922ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_END(ArgPromotion, "argpromotion",
93ce665bd2e2b581ab0858d1afe359192bac96b868Owen Anderson                "Promote 'by reference' arguments to scalars", false, false)
94844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
95bcd203cf860269987f32b14737b200b84fc2b63eChris LattnerPass *llvm::createArgumentPromotionPass(unsigned maxElements) {
96bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner  return new ArgPromotion(maxElements);
97ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
98ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
992decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattnerbool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
1005eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  bool Changed = false, LocalChange;
101ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
102f5afcabff887c2e9023f0c69c44f1de15b5c4347Chris Lattner  do {  // Iterate until we stop promoting from this SCC.
1035eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    LocalChange = false;
1045eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    // Attempt to promote arguments from all functions in this SCC.
1052decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattner    for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1062decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattner      if (CallGraphNode *CGN = PromoteArguments(*I)) {
1075095e3d1d1caef8d573534d369e37277c623064cChris Lattner        LocalChange = true;
1082decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattner        SCC.ReplaceNode(*I, CGN);
1095095e3d1d1caef8d573534d369e37277c623064cChris Lattner      }
1102decb22222cac46bb1d9163e7b89d7e5be8ef65fChris Lattner    }
1115eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    Changed |= LocalChange;               // Remember that we changed something.
1125eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  } while (LocalChange);
113eae220259fca393adc874ed41e3930011047beb7Chris Lattner
114ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return Changed;
115ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
116ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
1179e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// PromoteArguments - This method checks the specified function to see if there
1189e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// are any promotable arguments and if it is safe to promote the function (for
1199e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// example, all callers are direct).  If safe to promote some arguments, it
1209e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// calls the DoPromotion method.
1219e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner///
1225095e3d1d1caef8d573534d369e37277c623064cChris LattnerCallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
1235eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  Function *F = CGN->getFunction();
1245eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner
1255eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  // Make sure that it is local to this module.
1265095e3d1d1caef8d573534d369e37277c623064cChris Lattner  if (!F || !F->hasLocalLinkage()) return 0;
127ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
128ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // First check: see if there are any pointer arguments!  If not, quick exit.
12940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
13040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  unsigned ArgNo = 0;
13140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
13240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner       I != E; ++I, ++ArgNo)
1331df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands    if (I->getType()->isPointerTy())
13440c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner      PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
1355095e3d1d1caef8d573534d369e37277c623064cChris Lattner  if (PointerArgs.empty()) return 0;
136ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
137ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Second check: make sure that all callers are direct callers.  We can't
13828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  // transform functions that have indirect callers.  Also see if the function
13928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  // is self-recursive.
14028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  bool isSelfRecursive = false;
14128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
14228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner       UI != E; ++UI) {
14328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    CallSite CS(*UI);
14428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // Must be a direct call.
14528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (CS.getInstruction() == 0 || !CS.isCallee(UI)) return 0;
14628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
14728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (CS.getInstruction()->getParent()->getParent() == F)
14828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner      isSelfRecursive = true;
14928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  }
15028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
15140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // Check to see which arguments are promotable.  If an argument is promotable,
15240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // add it to ArgsToPromote.
15340c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallPtrSet<Argument*, 8> ArgsToPromote;
15410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  SmallPtrSet<Argument*, 8> ByValArgsToTransform;
15540c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (unsigned i = 0; i != PointerArgs.size(); ++i) {
1560598866c052147c31b808391f58434ce3dbfb838Devang Patel    bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, Attribute::ByVal);
15728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    Argument *PtrArg = PointerArgs[i].first;
158db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
1594cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
16010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // If this is a byval argument, and if the aggregate type is small, just
16110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // pass the elements, which is always safe.
16210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isByVal) {
163db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
164bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner        if (maxElements > 0 && STy->getNumElements() > maxElements) {
1655ededf7d42417379d230c92fc73912ebb650ede9David Greene          DEBUG(dbgs() << "argpromotion disable promoting argument '"
166ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar                << PtrArg->getName() << "' because it would require adding more"
167ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar                << " than " << maxElements << " arguments to the function.\n");
16828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
16928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
17028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
17128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // If all the elements are single-value types, we can promote it.
17228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        bool AllSimple = true;
17328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
17428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          if (!STy->getElementType(i)->isSingleValueType()) {
17528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            AllSimple = false;
17628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            break;
17710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          }
17810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
17928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
18028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // Safe to transform, don't even bother trying to "promote" it.
18128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // Passing the elements as a scalar will allow scalarrepl to hack on
18228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // the new alloca we introduce.
18328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        if (AllSimple) {
18428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          ByValArgsToTransform.insert(PtrArg);
18528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
18628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
18743e2a035309f4e353a8bd5547d10125414597e74Duncan Sands      }
18810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
1894cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
19028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // If the argument is a recursive type and we're in a recursive
19128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // function, we could end up infinitely peeling the function argument.
19228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (isSelfRecursive) {
193db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
19428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        bool RecursiveType = false;
19528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
19628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          if (STy->getElementType(i) == PtrArg->getType()) {
19728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            RecursiveType = true;
19828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            break;
19928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          }
20028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
20128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        if (RecursiveType)
20228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
20328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner      }
20428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    }
20528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
20610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, see if we can promote the pointer to its value.
20710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isSafeToPromoteArgument(PtrArg, isByVal))
20810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ArgsToPromote.insert(PtrArg);
20940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  }
2104cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
211ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // No promotable pointer arguments.
2125095e3d1d1caef8d573534d369e37277c623064cChris Lattner  if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
2135095e3d1d1caef8d573534d369e37277c623064cChris Lattner    return 0;
214ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
2155095e3d1d1caef8d573534d369e37277c623064cChris Lattner  return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
216ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
217ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
21828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner/// AllCallersPassInValidPointerForArgument - Return true if we can prove that
21911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// all callees pass in a valid pointer for the specified function argument.
22028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattnerstatic bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
22111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  Function *Callee = Arg->getParent();
22211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
22393e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  unsigned ArgNo = std::distance(Callee->arg_begin(),
22493e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner                                 Function::arg_iterator(Arg));
22511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
22611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Look at all call sites of the function.  At this pointer we know we only
22711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // have direct callees.
22811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
22911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner       UI != E; ++UI) {
2307d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    CallSite CS(*UI);
2317d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    assert(CS && "Should only have direct calls!");
23211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
2334d70a2949007edeaad4662d5cdcb2d272cb2b2ffDan Gohman    if (!CS.getArgument(ArgNo)->isDereferenceablePointer())
23411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return false;
23511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  }
23611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return true;
23711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
23811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
239477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// Returns true if Prefix is a prefix of longer. That means, Longer has a size
240477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// that is greater than or equal to the size of prefix, and each of the
241477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// elements in Prefix is the same as the corresponding elements in Longer.
242477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman///
243477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// This means it also returns true when Prefix and Longer are equal!
244477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
245477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                     const ArgPromotion::IndicesVector &Longer) {
246477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Prefix.size() > Longer.size())
247477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return false;
248477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  for (unsigned i = 0, e = Prefix.size(); i != e; ++i)
249477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (Prefix[i] != Longer[i])
250477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      return false;
251477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  return true;
252477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
253477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
254477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
255477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// Checks if Indices, or a prefix of Indices, is in Set.
256477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
257477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                     std::set<ArgPromotion::IndicesVector> &Set) {
258477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    std::set<ArgPromotion::IndicesVector>::iterator Low;
259477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Low = Set.upper_bound(Indices);
260477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (Low != Set.begin())
261477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Low--;
262477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Low is now the last element smaller than or equal to Indices. This means
263477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // it points to a prefix of Indices (possibly Indices itself), if such
264477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // prefix exists.
265477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    //
266477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // This load is safe if any prefix of its operands is safe to load.
267477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return Low != Set.end() && IsPrefix(*Low, Indices);
268477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
269477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
270f451cb870efcf9e0302d25ed05f4cac6bb494e42Dan Gohman/// Mark the given indices (ToMark) as safe in the given set of indices
271477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
272477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// is already a prefix of Indices in Safe, Indices are implicitely marked safe
273477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// already. Furthermore, any indices that Indices is itself a prefix of, are
274477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// removed from Safe (since they are implicitely safe because of Indices now).
275477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
276477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                            std::set<ArgPromotion::IndicesVector> &Safe) {
277477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::set<ArgPromotion::IndicesVector>::iterator Low;
278477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  Low = Safe.upper_bound(ToMark);
279477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Guard against the case where Safe is empty
280477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Low != Safe.begin())
281477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Low--;
282477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Low is now the last element smaller than or equal to Indices. This
283477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // means it points to a prefix of Indices (possibly Indices itself), if
284477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // such prefix exists.
285477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Low != Safe.end()) {
286477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (IsPrefix(*Low, ToMark))
287477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // If there is already a prefix of these indices (or exactly these
288477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // indices) marked a safe, don't bother adding these indices
289477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      return;
290477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
291477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Increment Low, so we can use it as a "insert before" hint
2924cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands    ++Low;
293477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
2944cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands  // Insert
295477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  Low = Safe.insert(Low, ToMark);
296477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  ++Low;
297477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // If there we're a prefix of longer index list(s), remove those
298477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
299477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  while (Low != End && IsPrefix(ToMark, *Low)) {
300477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
301477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    ++Low;
302477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Safe.erase(Remove);
303477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
304477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
3059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
3069e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// isSafeToPromoteArgument - As you might guess from the name of this method,
3079e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// it checks to see if it is both safe and useful to promote the argument.
3089e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// This method limits promotion of aggregates to only promote up to three
3099e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// elements of the aggregate in order to avoid exploding the number of
3109e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// arguments passed in.
31140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattnerbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
312477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  typedef std::set<IndicesVector> GEPIndicesSet;
313477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
314477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Quick exit for unused arguments
315477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Arg->use_empty())
316477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return true;
317477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
3189440db886627161a8413e823797569fc7b10beafChris Lattner  // We can only promote this argument if all of the uses are loads, or are GEP
3199440db886627161a8413e823797569fc7b10beafChris Lattner  // instructions (with constant indices) that are subsequently loaded.
320477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  //
321477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Promoting the argument causes it to be loaded in the caller
322477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // unconditionally. This is only safe if we can prove that either the load
323477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // would have happened in the callee anyway (ie, there is a load in the entry
324477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // block) or the pointer passed in at every call site is guaranteed to be
325477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // valid.
326477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // In the former case, invalid loads can happen, but would have happened
327477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // anyway, in the latter case, invalid loads won't happen. This prevents us
328477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // from introducing an invalid load that wouldn't have happened in the
329477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // original code.
330477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  //
331477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This set will contain all sets of indices that are loaded in the entry
332477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // block, and thus are safe to unconditionally load in the caller.
333477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  GEPIndicesSet SafeToUnconditionallyLoad;
334170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
335477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This set contains all the sets of indices that we are planning to promote.
336477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This makes it possible to limit the number of arguments added.
337477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  GEPIndicesSet ToPromote;
3384cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
339477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // If the pointer is always valid, any load with first index 0 is valid.
34028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  if (isByVal || AllCallersPassInValidPointerForArgument(Arg))
341477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
342477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
343477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // First, iterate the entry block and mark loads of (geps of) arguments as
344477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // safe.
34511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  BasicBlock *EntryBlock = Arg->getParent()->begin();
346477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Declare this here so we can reuse it
347477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  IndicesVector Indices;
348477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
349477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman       I != E; ++I)
350477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
351477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Value *V = LI->getPointerOperand();
352477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
353477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        V = GEP->getPointerOperand();
354477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (V == Arg) {
355477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // This load actually loads (part of) Arg? Check the indices then.
356477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.reserve(GEP->getNumIndices());
357477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
358477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman               II != IE; ++II)
359477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
360477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              Indices.push_back(CI->getSExtValue());
361477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            else
362477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // We found a non-constant GEP index for this argument? Bail out
363477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // right away, can't promote this argument at all.
364477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              return false;
365477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
366477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Indices checked out, mark them as safe
367477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
368477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.clear();
369477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        }
370477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      } else if (V == Arg) {
371477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Direct loads are equivalent to a GEP with a single 0 index.
372477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
373477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
374477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    }
375477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
376477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Now, iterate all uses of the argument to see if there are any uses that are
377477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
378a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  SmallVector<LoadInst*, 16> Loads;
379477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  IndicesVector Operands;
380ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
381477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman       UI != E; ++UI) {
382a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    User *U = *UI;
383477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Operands.clear();
384a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
3853d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman      // Don't hack volatile/atomic loads
3863d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman      if (!LI->isSimple()) return false;
387ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Loads.push_back(LI);
388477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Direct loads are equivalent to a GEP with a zero index and then a load.
389477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Operands.push_back(0);
390a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
3919440db886627161a8413e823797569fc7b10beafChris Lattner      if (GEP->use_empty()) {
3929440db886627161a8413e823797569fc7b10beafChris Lattner        // Dead GEP's cause trouble later.  Just remove them if we run into
3939440db886627161a8413e823797569fc7b10beafChris Lattner        // them.
3949e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        getAnalysis<AliasAnalysis>().deleteValue(GEP);
39540c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        GEP->eraseFromParent();
396a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif        // TODO: This runs the above loop over and over again for dead GEPs
397477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Couldn't we just do increment the UI iterator earlier and erase the
398477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // use?
39940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        return isSafeToPromoteArgument(Arg, isByVal);
4009440db886627161a8413e823797569fc7b10beafChris Lattner      }
401477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
4029440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that all of the indices are constants.
403477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
404477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        i != e; ++i)
4055e46321d665d6b1f445aff70d8eabb4870a6cf0eGabor Greif        if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
406477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.push_back(C->getSExtValue());
4079440db886627161a8413e823797569fc7b10beafChris Lattner        else
4089440db886627161a8413e823797569fc7b10beafChris Lattner          return false;  // Not a constant operand GEP!
4099440db886627161a8413e823797569fc7b10beafChris Lattner
4109440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that the only users of the GEP are load instructions.
4119440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
4129440db886627161a8413e823797569fc7b10beafChris Lattner           UI != E; ++UI)
4139440db886627161a8413e823797569fc7b10beafChris Lattner        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
4143d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman          // Don't hack volatile/atomic loads
4153d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman          if (!LI->isSimple()) return false;
4169440db886627161a8413e823797569fc7b10beafChris Lattner          Loads.push_back(LI);
4179440db886627161a8413e823797569fc7b10beafChris Lattner        } else {
418477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Other uses than load?
4199440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
4209440db886627161a8413e823797569fc7b10beafChris Lattner        }
4219440db886627161a8413e823797569fc7b10beafChris Lattner    } else {
4229440db886627161a8413e823797569fc7b10beafChris Lattner      return false;  // Not a load or a GEP.
4239440db886627161a8413e823797569fc7b10beafChris Lattner    }
4244cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
425477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Now, see if it is safe to promote this load / loads of this GEP. Loading
426477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // is safe if Operands, or a prefix of Operands, is marked as safe.
427477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
428477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      return false;
429ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
430477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // See if we are already promoting a load with these indices. If not, check
431477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // to make sure that we aren't promoting too many elements.  If so, nothing
432477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // to do.
433477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (ToPromote.find(Operands) == ToPromote.end()) {
434477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      if (maxElements > 0 && ToPromote.size() == maxElements) {
4355ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "argpromotion not promoting argument '"
436ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << Arg->getName() << "' because it would require adding more "
437ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "than " << maxElements << " arguments to the function.\n");
438477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // We limit aggregate promotion to only promoting up to a fixed number
439477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // of elements of the aggregate.
440477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        return false;
441477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
442477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      ToPromote.insert(Operands);
443477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    }
444477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
445ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
446477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Loads.empty()) return true;  // No users, this is a dead argument.
44711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
44811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Okay, now we know that the argument is only used by load instructions and
449477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // it is safe to unconditionally perform all of them. Use alias analysis to
45011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // check to see if the pointer is guaranteed to not be modified from entry of
45111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // the function to each of the load instructions.
452ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
453ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Because there could be several/many load instructions, remember which
454ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // blocks we know to be transparent to the load.
455e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
45646f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson
45746f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
458ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
459ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
460ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Check to see if the load is invalidated from the start of the block to
461ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // the load itself.
462ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    LoadInst *Load = Loads[i];
463ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    BasicBlock *BB = Load->getParent();
4649440db886627161a8413e823797569fc7b10beafChris Lattner
4656d8eb156e6be727570b300bac7712f745a318c7dDan Gohman    AliasAnalysis::Location Loc = AA.getLocation(Load);
46656653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman    if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
467ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      return false;  // Pointer is invalidated!
468ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
469ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Now check every path from the entry block to the load for transparency.
470ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // To do this, we perform a depth first search on the inverse CFG from the
471ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // loading block.
472a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
473a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif      BasicBlock *P = *PI;
474e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
475a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif             I = idf_ext_begin(P, TranspBlocks),
476a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif             E = idf_ext_end(P, TranspBlocks); I != E; ++I)
47756653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman        if (AA.canBasicBlockModify(**I, Loc))
478ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner          return false;
479a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    }
480ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
481ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
482ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // If the path from the entry of the function to each load is free of
483ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // instructions that potentially invalidate the load, we can make the
484ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transformation!
485ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
486ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
487ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
4889e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// DoPromotion - This method actually performs the promotion of the specified
4895eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// arguments, and returns the new function.  At this point, we know that it's
4905eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// safe to do so.
4915095e3d1d1caef8d573534d369e37277c623064cChris LattnerCallGraphNode *ArgPromotion::DoPromotion(Function *F,
4925095e3d1d1caef8d573534d369e37277c623064cChris Lattner                               SmallPtrSet<Argument*, 8> &ArgsToPromote,
49310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                              SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
494fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
495ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Start by computing a new prototype for the function, which is the same as
496ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the old function, but has modified arguments.
497db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  FunctionType *FTy = F->getFunctionType();
4985fdd6c8793462549e3593890ec61573da06e3346Jay Foad  std::vector<Type*> Params;
499ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
500477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  typedef std::set<IndicesVector> ScalarizeTable;
501beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
5029440db886627161a8413e823797569fc7b10beafChris Lattner  // ScalarizedElements - If we are promoting a pointer that has elements
5039440db886627161a8413e823797569fc7b10beafChris Lattner  // accessed out of it, keep track of which elements are accessed so that we
5049440db886627161a8413e823797569fc7b10beafChris Lattner  // can add one argument for each.
5059440db886627161a8413e823797569fc7b10beafChris Lattner  //
5069440db886627161a8413e823797569fc7b10beafChris Lattner  // Arguments that are directly loaded will have a zero element value here, to
5079440db886627161a8413e823797569fc7b10beafChris Lattner  // handle cases where there are both a direct load and GEP accesses.
5089440db886627161a8413e823797569fc7b10beafChris Lattner  //
509beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  std::map<Argument*, ScalarizeTable> ScalarizedElements;
5109440db886627161a8413e823797569fc7b10beafChris Lattner
5119e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // OriginalLoads - Keep track of a representative load instruction from the
5129e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // original function so that we can tell the alias analysis implementation
5139e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // what the new GEP/Load instructions we are inserting look like.
514477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::map<IndicesVector, LoadInst*> OriginalLoads;
5159e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
5160598866c052147c31b808391f58434ce3dbfb838Devang Patel  // Attributes - Keep track of the parameter attributes for the arguments
517dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // that we are *not* promoting. For the ones that we do promote, the parameter
518dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // attributes are lost
5190598866c052147c31b808391f58434ce3dbfb838Devang Patel  SmallVector<AttributeWithIndex, 8> AttributesVec;
5200598866c052147c31b808391f58434ce3dbfb838Devang Patel  const AttrListPtr &PAL = F->getAttributes();
521dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
522532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands  // Add any return attributes.
52319c874638d9478a5d5028854817a5ee72293bb2bDevang Patel  if (Attributes attrs = PAL.getRetAttributes())
5240598866c052147c31b808391f58434ce3dbfb838Devang Patel    AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
5254cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
526477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // First, determine the new argument list
527ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  unsigned ArgIndex = 1;
528dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
529ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner       ++I, ++ArgIndex) {
53010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
531477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Simple byval argument? Just add all the struct element types.
532db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
533db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      StructType *STy = cast<StructType>(AgTy);
53410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
53510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Params.push_back(STy->getElementType(i));
53610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++NumByValArgsPromoted;
53710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    } else if (!ArgsToPromote.count(I)) {
538477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Unchanged argument
539ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Params.push_back(I->getType());
54019c874638d9478a5d5028854817a5ee72293bb2bDevang Patel      if (Attributes attrs = PAL.getParamAttributes(ArgIndex))
5410598866c052147c31b808391f58434ce3dbfb838Devang Patel        AttributesVec.push_back(AttributeWithIndex::get(Params.size(), attrs));
5429e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else if (I->use_empty()) {
543477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Dead argument (which are always marked as promotable)
5449e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      ++NumArgumentsDead;
5459e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else {
546477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Okay, this is being promoted. This means that the only uses are loads
547477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // or GEPs which are only used by loads
548477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
549477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // In this table, we will track which indices are loaded from the argument
550477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // (where direct loads are tracked as no indices).
551beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      ScalarizeTable &ArgIndices = ScalarizedElements[I];
5529440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
5539440db886627161a8413e823797569fc7b10beafChris Lattner           ++UI) {
5549440db886627161a8413e823797569fc7b10beafChris Lattner        Instruction *User = cast<Instruction>(*UI);
55546f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
556477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        IndicesVector Indices;
557477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        Indices.reserve(User->getNumOperands() - 1);
558477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Since loads will only have a single operand, and GEPs only a single
559477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // non-index operand, this will record direct loads without any indices,
560477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // and gep+loads with the GEP indices.
561477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (User::op_iterator II = User->op_begin() + 1, IE = User->op_end();
562477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             II != IE; ++II)
563477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
564477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // GEPs with a single 0 index can be merged with direct loads
565477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (Indices.size() == 1 && Indices.front() == 0)
566477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.clear();
56746f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        ArgIndices.insert(Indices);
56846f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        LoadInst *OrigLoad;
56946f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        if (LoadInst *L = dyn_cast<LoadInst>(User))
57046f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = L;
57146f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        else
572477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Take any load, we will use it only to update Alias Analysis
57346f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = cast<LoadInst>(User->use_back());
57446f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        OriginalLoads[Indices] = OrigLoad;
5759440db886627161a8413e823797569fc7b10beafChris Lattner      }
5769440db886627161a8413e823797569fc7b10beafChris Lattner
5779440db886627161a8413e823797569fc7b10beafChris Lattner      // Add a parameter to the function for each element passed in.
578beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
579477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             E = ArgIndices.end(); SI != E; ++SI) {
580b079a391c8b85d088dabce715d99be5917af88faTorok Edwin        // not allowed to dereference ->begin() if size() is 0
581a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
582477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        assert(Params.back());
583477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
5849440db886627161a8413e823797569fc7b10beafChris Lattner
5859440db886627161a8413e823797569fc7b10beafChris Lattner      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
5869440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumArgumentsPromoted;
5879440db886627161a8413e823797569fc7b10beafChris Lattner      else
5889440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumAggregatesPromoted;
589ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
59010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
591ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
59219c874638d9478a5d5028854817a5ee72293bb2bDevang Patel  // Add any function attributes.
59319c874638d9478a5d5028854817a5ee72293bb2bDevang Patel  if (Attributes attrs = PAL.getFnAttributes())
59419c874638d9478a5d5028854817a5ee72293bb2bDevang Patel    AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
59519c874638d9478a5d5028854817a5ee72293bb2bDevang Patel
596db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *RetTy = FTy->getReturnType();
597ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
598ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
599ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // have zero fixed arguments.
600ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  bool ExtraArgHack = false;
601ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  if (Params.empty() && FTy->isVarArg()) {
602ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    ExtraArgHack = true;
6031d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    Params.push_back(Type::getInt32Ty(F->getContext()));
604ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
605dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
606dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Construct the new function type using the new arguments.
607debcb01b0f0a15f568ca69e8f288fade4bfc7297Owen Anderson  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
608fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
609a51c39cc3265f5d0d5de87b4a3ef9332c83556e1Chris Lattner  // Create the new function body and insert it into the module.
610051a950000e21935165db56695e35bade668193bGabor Greif  Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
61128c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  NF->copyAttributesFrom(F);
612ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
613a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner
6145ededf7d42417379d230c92fc73912ebb650ede9David Greene  DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
615a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner        << "From: " << *F);
616a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner
617ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // Recompute the parameter attributes list based on the new arguments for
618ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // the function.
619d509d0b532ec2358b3f341d4a4cd1411cb8b5db2Chris Lattner  NF->setAttributes(AttrListPtr::get(AttributesVec));
6200598866c052147c31b808391f58434ce3dbfb838Devang Patel  AttributesVec.clear();
62128c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands
622ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  F->getParent()->getFunctionList().insert(F, NF);
6232b3407f5b3d8626b924c532bcfea15daaf1bd3c0Zhou Sheng  NF->takeName(F);
6249e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
6259e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Get the alias analysis information that we need to update to reflect our
6269e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // changes.
6279e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
6289e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
62934c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  // Get the callgraph information that we need to update to reflect our
63034c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  // changes.
63134c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  CallGraph &CG = getAnalysis<CallGraph>();
6325095e3d1d1caef8d573534d369e37277c623064cChris Lattner
6335095e3d1d1caef8d573534d369e37277c623064cChris Lattner  // Get a new callgraph node for NF.
6345095e3d1d1caef8d573534d369e37277c623064cChris Lattner  CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
63534c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands
636ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over all of the callers of the function, transforming the call sites
637ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // to pass in the loaded pointers.
638ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
639ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  SmallVector<Value*, 16> Args;
640ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  while (!F->use_empty()) {
6417d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    CallSite CS(F->use_back());
6420054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif    assert(CS.getCalledFunction() == F);
643ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *Call = CS.getInstruction();
6440598866c052147c31b808391f58434ce3dbfb838Devang Patel    const AttrListPtr &CallPAL = CS.getAttributes();
6454cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
646532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    // Add any return attributes.
64719c874638d9478a5d5028854817a5ee72293bb2bDevang Patel    if (Attributes attrs = CallPAL.getRetAttributes())
6480598866c052147c31b808391f58434ce3dbfb838Devang Patel      AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
649532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
6509e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Loop over the operands, inserting GEP and loads in the caller as
6519e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // appropriate.
652ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
653ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ArgIndex = 1;
654f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
655ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner         I != E; ++I, ++AI, ++ArgIndex)
65610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
657ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        Args.push_back(*AI);          // Unmodified argument
6584cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
65919c874638d9478a5d5028854817a5ee72293bb2bDevang Patel        if (Attributes Attrs = CallPAL.getParamAttributes(ArgIndex))
6600598866c052147c31b808391f58434ce3dbfb838Devang Patel          AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
6614cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
66210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (ByValArgsToTransform.count(I)) {
66310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // Emit a GEP and load for each element of the struct.
664db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner        Type *AgTy = cast<PointerType>(I->getType())->getElementType();
665db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner        StructType *STy = cast<StructType>(AgTy);
6661d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Value *Idxs[2] = {
6671d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
66810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6691d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
670a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad          Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
671051a950000e21935165db56695e35bade668193bGabor Greif                                                 (*AI)->getName()+"."+utostr(i),
672051a950000e21935165db56695e35bade668193bGabor Greif                                                 Call);
67310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // TODO: Tell AA about the new values?
67410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
6754cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands        }
67610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (!I->use_empty()) {
6779e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        // Non-dead argument: insert GEPs and loads as appropriate.
678beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        ScalarizeTable &ArgIndices = ScalarizedElements[I];
679477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Store the Value* version of the indices in here, but declare it now
6800054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif        // for reuse.
681477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        std::vector<Value*> Ops;
682beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
6839440db886627161a8413e823797569fc7b10beafChris Lattner               E = ArgIndices.end(); SI != E; ++SI) {
6849440db886627161a8413e823797569fc7b10beafChris Lattner          Value *V = *AI;
6859e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          LoadInst *OrigLoad = OriginalLoads[*SI];
6869e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          if (!SI->empty()) {
687477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            Ops.reserve(SI->size());
688db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner            Type *ElTy = V->getType();
6894cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands            for (IndicesVector::const_iterator II = SI->begin(),
690477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                 IE = SI->end(); II != IE; ++II) {
691477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // Use i32 to index structs, and i64 for others (pointers/arrays).
692477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // This satisfies GEP constraints.
693db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner              Type *IdxTy = (ElTy->isStructTy() ?
6941d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                    Type::getInt32Ty(F->getContext()) :
6951d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                    Type::getInt64Ty(F->getContext()));
696eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson              Ops.push_back(ConstantInt::get(IdxTy, *II));
6970054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif              // Keep track of the type we're currently indexing.
698477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
699477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            }
7000054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif            // And create a GEP to extract those indices.
701a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad            V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
702477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            Ops.clear();
7039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner            AA.copyValue(OrigLoad->getOperand(0), V);
7049e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          }
7056fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          // Since we're replacing a load make sure we take the alignment
7066fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          // of the previous load.
7076fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
7086fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          newLoad->setAlignment(OrigLoad->getAlignment());
70956653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman          // Transfer the TBAA info too.
71056653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman          newLoad->setMetadata(LLVMContext::MD_tbaa,
71156653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman                               OrigLoad->getMetadata(LLVMContext::MD_tbaa));
7126fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          Args.push_back(newLoad);
7139e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          AA.copyValue(OrigLoad, Args.back());
7149440db886627161a8413e823797569fc7b10beafChris Lattner        }
715ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
716ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
717ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (ExtraArgHack)
7181d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      Args.push_back(Constant::getNullValue(Type::getInt32Ty(F->getContext())));
719ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7200054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif    // Push any varargs arguments on the list.
721ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
722ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Args.push_back(*AI);
72319c874638d9478a5d5028854817a5ee72293bb2bDevang Patel      if (Attributes Attrs = CallPAL.getParamAttributes(ArgIndex))
7240598866c052147c31b808391f58434ce3dbfb838Devang Patel        AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
725ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    }
726ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
72719c874638d9478a5d5028854817a5ee72293bb2bDevang Patel    // Add any function attributes.
72819c874638d9478a5d5028854817a5ee72293bb2bDevang Patel    if (Attributes attrs = CallPAL.getFnAttributes())
72919c874638d9478a5d5028854817a5ee72293bb2bDevang Patel      AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
73019c874638d9478a5d5028854817a5ee72293bb2bDevang Patel
731ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *New;
732ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
733051a950000e21935165db56695e35bade668193bGabor Greif      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
734a3efbb15ddd5aa9006564cd79086723640084878Jay Foad                               Args, "", Call);
735f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
736d509d0b532ec2358b3f341d4a4cd1411cb8b5db2Chris Lattner      cast<InvokeInst>(New)->setAttributes(AttrListPtr::get(AttributesVec));
737ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    } else {
738a3efbb15ddd5aa9006564cd79086723640084878Jay Foad      New = CallInst::Create(NF, Args, "", Call);
739f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
740d509d0b532ec2358b3f341d4a4cd1411cb8b5db2Chris Lattner      cast<CallInst>(New)->setAttributes(AttrListPtr::get(AttributesVec));
7411430ef134d36888b99d2e6fedd2b025882593538Chris Lattner      if (cast<CallInst>(Call)->isTailCall())
7421430ef134d36888b99d2e6fedd2b025882593538Chris Lattner        cast<CallInst>(New)->setTailCall();
743ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
744ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Args.clear();
7450598866c052147c31b808391f58434ce3dbfb838Devang Patel    AttributesVec.clear();
746ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7479e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Update the alias analysis implementation to know that we are replacing
7489e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // the old call with a new one.
7499e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    AA.replaceWithNewValue(Call, New);
7509e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
75134c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands    // Update the callgraph to know that the callsite has been transformed.
752da230cb876edf0d4fa8eefc289b8addfb722cd07Chris Lattner    CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
753a51c39cc3265f5d0d5de87b4a3ef9332c83556e1Chris Lattner    CalleeNode->replaceCallEdge(Call, New, NF_CGN);
75434c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands
755ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (!Call->use_empty()) {
756ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Call->replaceAllUsesWith(New);
757046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      New->takeName(Call);
758ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
759fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
760ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Finally, remove the old call from the program, reducing the use-count of
761ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // F.
76240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    Call->eraseFromParent();
763ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
764ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
765ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Since we have now created the new function, splice the body of the old
766ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function right into the new function, leaving the old rotting hulk of the
767ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function empty.
768ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
769ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7707a2bdde0a0eebcd2125055e0eacaca040f0b766cChris Lattner  // Loop over the argument list, transferring uses of the old arguments over to
7717a2bdde0a0eebcd2125055e0eacaca040f0b766cChris Lattner  // the new arguments, also transferring over the names as well.
772ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
77393e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
77410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner       I2 = NF->arg_begin(); I != E; ++I) {
77510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
776ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // If this is an unmodified argument, move the name and users over to the
777ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // new version.
778ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      I->replaceAllUsesWith(I2);
779046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      I2->takeName(I);
7809e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.replaceWithNewValue(I, I2);
781ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      ++I2;
78210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
78310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
7844cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
78510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
78610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // In the callee, we create an alloca, and store each of the new incoming
78710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // arguments into the alloca.
78810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Instruction *InsertPt = NF->begin()->begin();
7894cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
79010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
791db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
79250dead06ffc107edb7e84857baaeeb09039c631cOwen Anderson      Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
793db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      StructType *STy = cast<StructType>(AgTy);
7941d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      Value *Idxs[2] = {
7951d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
7964cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
79710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
7981d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
799dfd3b647839d3f944b5d8bffd6e9a2ec022d3507Daniel Dunbar        Value *Idx =
800a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad          GetElementPtrInst::Create(TheAlloca, Idxs,
801fe09b2098ac483f6d6ce6ea4ab237a9539bdb6b9Daniel Dunbar                                    TheAlloca->getName()+"."+Twine(i),
802dfd3b647839d3f944b5d8bffd6e9a2ec022d3507Daniel Dunbar                                    InsertPt);
803fe09b2098ac483f6d6ce6ea4ab237a9539bdb6b9Daniel Dunbar        I2->setName(I->getName()+"."+Twine(i));
80410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        new StoreInst(I2++, Idx, InsertPt);
80510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      }
8064cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
80710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Anything that used the arg should now use the alloca.
80810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      I->replaceAllUsesWith(TheAlloca);
80910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      TheAlloca->takeName(I);
81010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      AA.replaceWithNewValue(I, TheAlloca);
81110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
8124cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands    }
8134cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
81410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (I->use_empty()) {
8159e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.deleteValue(I);
81610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
81710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
8184cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
81910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, if we promoted this argument, then all users are load
820477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // instructions (or GEPs with only load users), and all loads should be
821477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // using the new argument that we added.
82210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    ScalarizeTable &ArgIndices = ScalarizedElements[I];
82310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
82410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    while (!I->use_empty()) {
82510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
82610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        assert(ArgIndices.begin()->empty() &&
82710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner               "Load element should sort to front!");
82810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+".val");
82910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->replaceAllUsesWith(I2);
83010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.replaceWithNewValue(LI, I2);
83110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->eraseFromParent();
8325ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
833ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "' in function '" << F->getName() << "'\n");
83410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else {
83510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
836477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        IndicesVector Operands;
837477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        Operands.reserve(GEP->getNumIndices());
838477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
839477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             II != IE; ++II)
840477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
841477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
842477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // GEPs with a single 0 index can be merged with direct loads
843477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (Operands.size() == 1 && Operands.front() == 0)
844477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.clear();
84510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
84610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Function::arg_iterator TheArg = I2;
84710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (ScalarizeTable::iterator It = ArgIndices.begin();
84810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             *It != Operands; ++It, ++TheArg) {
84910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          assert(It != ArgIndices.end() && "GEP not handled??");
85010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
8519440db886627161a8413e823797569fc7b10beafChris Lattner
85210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::string NewName = I->getName();
853477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
854477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            NewName += "." + utostr(Operands[i]);
855477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        }
856477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        NewName += ".val";
857477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        TheArg->setName(NewName);
85810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
8595ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
860ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "' of function '" << NF->getName() << "'\n");
86110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
86210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // All of the uses must be load instructions.  Replace them all with
86310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // the argument specified by ArgNo.
86410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        while (!GEP->use_empty()) {
86510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          LoadInst *L = cast<LoadInst>(GEP->use_back());
86610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->replaceAllUsesWith(TheArg);
86710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          AA.replaceWithNewValue(L, TheArg);
86810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->eraseFromParent();
8699440db886627161a8413e823797569fc7b10beafChris Lattner        }
87010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.deleteValue(GEP);
87110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GEP->eraseFromParent();
872ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
873ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
874ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
87510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Increment I2 past all of the arguments added for this promoted pointer.
87610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
87710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++I2;
87810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
87910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
8809e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Notify the alias analysis implementation that we inserted a new argument.
8819e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  if (ExtraArgHack)
8821d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    AA.copyValue(Constant::getNullValue(Type::getInt32Ty(F->getContext())),
8831d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                 NF->arg_begin());
8849e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
8859e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
8869e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Tell the alias analysis that the old function is about to disappear.
8879e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AA.replaceWithNewValue(F, NF);
8889e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
8895095e3d1d1caef8d573534d369e37277c623064cChris Lattner
8905095e3d1d1caef8d573534d369e37277c623064cChris Lattner  NF_CGN->stealCalledFunctionsFrom(CG[F]);
8915095e3d1d1caef8d573534d369e37277c623064cChris Lattner
892eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // Now that the old function is dead, delete it.  If there is a dangling
893eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // reference to the CallgraphNode, just leave the dead function around for
894eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // someone else to nuke.
895eae220259fca393adc874ed41e3930011047beb7Chris Lattner  CallGraphNode *CGN = CG[F];
896eae220259fca393adc874ed41e3930011047beb7Chris Lattner  if (CGN->getNumReferences() == 0)
897eae220259fca393adc874ed41e3930011047beb7Chris Lattner    delete CG.removeFunctionFromModule(CGN);
898eae220259fca393adc874ed41e3930011047beb7Chris Lattner  else
899eae220259fca393adc874ed41e3930011047beb7Chris Lattner    F->setLinkage(Function::ExternalLinkage);
9005095e3d1d1caef8d573534d369e37277c623064cChris Lattner
9015095e3d1d1caef8d573534d369e37277c623064cChris Lattner  return NF_CGN;
902ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
903