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"
34d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/DepthFirstIterator.h"
35d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/Statistic.h"
36d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/StringExtras.h"
37d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/AliasAnalysis.h"
38d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/CallGraph.h"
393251e81d793a293b78f4914be6093b405c24fc2aChandler Carruth#include "llvm/Analysis/CallGraphSCCPass.h"
400b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
410b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
420b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
430b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/LLVMContext.h"
440b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Module.h"
45ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CFG.h"
46d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Support/CallSite.h"
47551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/Debug.h"
48ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar#include "llvm/Support/raw_ostream.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.
129b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky  SmallVector<Argument*, 16> PointerArgs;
130b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1311df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands    if (I->getType()->isPointerTy())
132b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky      PointerArgs.push_back(I);
1335095e3d1d1caef8d573534d369e37277c623064cChris Lattner  if (PointerArgs.empty()) return 0;
134ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
135ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Second check: make sure that all callers are direct callers.  We can't
13628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  // transform functions that have indirect callers.  Also see if the function
13728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  // is self-recursive.
13828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  bool isSelfRecursive = false;
13928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
14028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner       UI != E; ++UI) {
14128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    CallSite CS(*UI);
14228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // Must be a direct call.
14328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (CS.getInstruction() == 0 || !CS.isCallee(UI)) return 0;
14428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
14528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (CS.getInstruction()->getParent()->getParent() == F)
14628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner      isSelfRecursive = true;
14728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  }
14828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
14940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // Check to see which arguments are promotable.  If an argument is promotable,
15040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // add it to ArgsToPromote.
15140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallPtrSet<Argument*, 8> ArgsToPromote;
15210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  SmallPtrSet<Argument*, 8> ByValArgsToTransform;
153b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky  for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
154b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky    Argument *PtrArg = PointerArgs[i];
155db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
1564cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
15710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // If this is a byval argument, and if the aggregate type is small, just
15810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // pass the elements, which is always safe.
159b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky    if (PtrArg->hasByValAttr()) {
160db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
161bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner        if (maxElements > 0 && STy->getNumElements() > maxElements) {
1625ededf7d42417379d230c92fc73912ebb650ede9David Greene          DEBUG(dbgs() << "argpromotion disable promoting argument '"
163ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar                << PtrArg->getName() << "' because it would require adding more"
164ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar                << " than " << maxElements << " arguments to the function.\n");
16528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
16628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
16728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
16828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // If all the elements are single-value types, we can promote it.
16928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        bool AllSimple = true;
17028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
17128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          if (!STy->getElementType(i)->isSingleValueType()) {
17228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            AllSimple = false;
17328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            break;
17410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          }
17510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
17628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
17728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // Safe to transform, don't even bother trying to "promote" it.
17828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // Passing the elements as a scalar will allow scalarrepl to hack on
17928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        // the new alloca we introduce.
18028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        if (AllSimple) {
18128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          ByValArgsToTransform.insert(PtrArg);
18228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
18328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
18443e2a035309f4e353a8bd5547d10125414597e74Duncan Sands      }
18510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
1864cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
18728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // If the argument is a recursive type and we're in a recursive
18828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    // function, we could end up infinitely peeling the function argument.
18928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    if (isSelfRecursive) {
190db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
19128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        bool RecursiveType = false;
19228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
19328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          if (STy->getElementType(i) == PtrArg->getType()) {
19428252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            RecursiveType = true;
19528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner            break;
19628252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          }
19728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        }
19828252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner        if (RecursiveType)
19928252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner          continue;
20028252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner      }
20128252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner    }
20228252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner
20310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, see if we can promote the pointer to its value.
204b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky    if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValAttr()))
20510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ArgsToPromote.insert(PtrArg);
20640c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  }
2074cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
208ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // No promotable pointer arguments.
2095095e3d1d1caef8d573534d369e37277c623064cChris Lattner  if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
2105095e3d1d1caef8d573534d369e37277c623064cChris Lattner    return 0;
211ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
2125095e3d1d1caef8d573534d369e37277c623064cChris Lattner  return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
213ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
214ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
21528252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner/// AllCallersPassInValidPointerForArgument - Return true if we can prove that
21611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// all callees pass in a valid pointer for the specified function argument.
21728252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattnerstatic bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
21811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  Function *Callee = Arg->getParent();
21911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
220b05ad799e7dc19d7c88576820b1cf16b43a4de9eNick Lewycky  unsigned ArgNo = Arg->getArgNo();
22111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
22211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Look at all call sites of the function.  At this pointer we know we only
22311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // have direct callees.
22411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
22511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner       UI != E; ++UI) {
2267d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    CallSite CS(*UI);
2277d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    assert(CS && "Should only have direct calls!");
22811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
2294d70a2949007edeaad4662d5cdcb2d272cb2b2ffDan Gohman    if (!CS.getArgument(ArgNo)->isDereferenceablePointer())
23011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return false;
23111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  }
23211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return true;
23311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
23411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
235477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// Returns true if Prefix is a prefix of longer. That means, Longer has a size
236477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// that is greater than or equal to the size of prefix, and each of the
237477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// elements in Prefix is the same as the corresponding elements in Longer.
238477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman///
239477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// This means it also returns true when Prefix and Longer are equal!
240477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
241477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                     const ArgPromotion::IndicesVector &Longer) {
242477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Prefix.size() > Longer.size())
243477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return false;
244b26e2916c937d03bc2d7e273b2df4ffccdb061b4Benjamin Kramer  return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
245477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
246477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
247477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
248477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// Checks if Indices, or a prefix of Indices, is in Set.
249477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
250477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                     std::set<ArgPromotion::IndicesVector> &Set) {
251477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    std::set<ArgPromotion::IndicesVector>::iterator Low;
252477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Low = Set.upper_bound(Indices);
253477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (Low != Set.begin())
254477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Low--;
255477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Low is now the last element smaller than or equal to Indices. This means
256477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // it points to a prefix of Indices (possibly Indices itself), if such
257477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // prefix exists.
258477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    //
259477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // This load is safe if any prefix of its operands is safe to load.
260477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return Low != Set.end() && IsPrefix(*Low, Indices);
261477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
262477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
263f451cb870efcf9e0302d25ed05f4cac6bb494e42Dan Gohman/// Mark the given indices (ToMark) as safe in the given set of indices
264477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
265477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// is already a prefix of Indices in Safe, Indices are implicitely marked safe
266477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// already. Furthermore, any indices that Indices is itself a prefix of, are
267477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman/// removed from Safe (since they are implicitely safe because of Indices now).
268477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijmanstatic void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
269477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                            std::set<ArgPromotion::IndicesVector> &Safe) {
270477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::set<ArgPromotion::IndicesVector>::iterator Low;
271477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  Low = Safe.upper_bound(ToMark);
272477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Guard against the case where Safe is empty
273477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Low != Safe.begin())
274477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Low--;
275477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Low is now the last element smaller than or equal to Indices. This
276477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // means it points to a prefix of Indices (possibly Indices itself), if
277477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // such prefix exists.
278477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Low != Safe.end()) {
279477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (IsPrefix(*Low, ToMark))
280477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // If there is already a prefix of these indices (or exactly these
281477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // indices) marked a safe, don't bother adding these indices
282477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      return;
283477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
284477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Increment Low, so we can use it as a "insert before" hint
2854cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands    ++Low;
286477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
2874cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands  // Insert
288477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  Low = Safe.insert(Low, ToMark);
289477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  ++Low;
290477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // If there we're a prefix of longer index list(s), remove those
291477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
292477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  while (Low != End && IsPrefix(ToMark, *Low)) {
293477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
294477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    ++Low;
295477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Safe.erase(Remove);
296477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
297477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman}
2989e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
2999e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// isSafeToPromoteArgument - As you might guess from the name of this method,
3009e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// it checks to see if it is both safe and useful to promote the argument.
3019e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// This method limits promotion of aggregates to only promote up to three
3029e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// elements of the aggregate in order to avoid exploding the number of
3039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// arguments passed in.
30440c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattnerbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
305477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  typedef std::set<IndicesVector> GEPIndicesSet;
306477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
307477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Quick exit for unused arguments
308477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Arg->use_empty())
309477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    return true;
310477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
3119440db886627161a8413e823797569fc7b10beafChris Lattner  // We can only promote this argument if all of the uses are loads, or are GEP
3129440db886627161a8413e823797569fc7b10beafChris Lattner  // instructions (with constant indices) that are subsequently loaded.
313477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  //
314477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Promoting the argument causes it to be loaded in the caller
315477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // unconditionally. This is only safe if we can prove that either the load
316477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // would have happened in the callee anyway (ie, there is a load in the entry
317477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // block) or the pointer passed in at every call site is guaranteed to be
318477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // valid.
319477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // In the former case, invalid loads can happen, but would have happened
320477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // anyway, in the latter case, invalid loads won't happen. This prevents us
321477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // from introducing an invalid load that wouldn't have happened in the
322477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // original code.
323477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  //
324477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This set will contain all sets of indices that are loaded in the entry
325477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // block, and thus are safe to unconditionally load in the caller.
326477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  GEPIndicesSet SafeToUnconditionallyLoad;
327170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
328477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This set contains all the sets of indices that we are planning to promote.
329477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // This makes it possible to limit the number of arguments added.
330477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  GEPIndicesSet ToPromote;
3314cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
332477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // If the pointer is always valid, any load with first index 0 is valid.
33328252b6f0a483ffb0ead991c7a1ead14e3cd2fc1Chris Lattner  if (isByVal || AllCallersPassInValidPointerForArgument(Arg))
334477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
335477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
336477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // First, iterate the entry block and mark loads of (geps of) arguments as
337477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // safe.
33811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  BasicBlock *EntryBlock = Arg->getParent()->begin();
339477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Declare this here so we can reuse it
340477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  IndicesVector Indices;
341477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
342477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman       I != E; ++I)
343477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
344477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Value *V = LI->getPointerOperand();
345477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
346477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        V = GEP->getPointerOperand();
347477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (V == Arg) {
348477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // This load actually loads (part of) Arg? Check the indices then.
349477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.reserve(GEP->getNumIndices());
350477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
351477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman               II != IE; ++II)
352477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
353477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              Indices.push_back(CI->getSExtValue());
354477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            else
355477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // We found a non-constant GEP index for this argument? Bail out
356477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // right away, can't promote this argument at all.
357477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              return false;
358477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
359477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Indices checked out, mark them as safe
360477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
361477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.clear();
362477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        }
363477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      } else if (V == Arg) {
364477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Direct loads are equivalent to a GEP with a single 0 index.
365477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
366477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
367477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    }
368477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
369477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // Now, iterate all uses of the argument to see if there are any uses that are
370477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
371a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  SmallVector<LoadInst*, 16> Loads;
372477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  IndicesVector Operands;
373ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
374477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman       UI != E; ++UI) {
375a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    User *U = *UI;
376477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    Operands.clear();
377a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
3783d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman      // Don't hack volatile/atomic loads
3793d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman      if (!LI->isSimple()) return false;
380ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Loads.push_back(LI);
381477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Direct loads are equivalent to a GEP with a zero index and then a load.
382477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      Operands.push_back(0);
383a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
3849440db886627161a8413e823797569fc7b10beafChris Lattner      if (GEP->use_empty()) {
3859440db886627161a8413e823797569fc7b10beafChris Lattner        // Dead GEP's cause trouble later.  Just remove them if we run into
3869440db886627161a8413e823797569fc7b10beafChris Lattner        // them.
3879e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        getAnalysis<AliasAnalysis>().deleteValue(GEP);
38840c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        GEP->eraseFromParent();
389a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif        // TODO: This runs the above loop over and over again for dead GEPs
390477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Couldn't we just do increment the UI iterator earlier and erase the
391477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // use?
39240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        return isSafeToPromoteArgument(Arg, isByVal);
3939440db886627161a8413e823797569fc7b10beafChris Lattner      }
394477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
3959440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that all of the indices are constants.
396477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
397477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        i != e; ++i)
3985e46321d665d6b1f445aff70d8eabb4870a6cf0eGabor Greif        if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
399477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.push_back(C->getSExtValue());
4009440db886627161a8413e823797569fc7b10beafChris Lattner        else
4019440db886627161a8413e823797569fc7b10beafChris Lattner          return false;  // Not a constant operand GEP!
4029440db886627161a8413e823797569fc7b10beafChris Lattner
4039440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that the only users of the GEP are load instructions.
4049440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
4059440db886627161a8413e823797569fc7b10beafChris Lattner           UI != E; ++UI)
4069440db886627161a8413e823797569fc7b10beafChris Lattner        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
4073d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman          // Don't hack volatile/atomic loads
4083d30b435e2b3d0e7480019577f48472b51133c21Eli Friedman          if (!LI->isSimple()) return false;
4099440db886627161a8413e823797569fc7b10beafChris Lattner          Loads.push_back(LI);
4109440db886627161a8413e823797569fc7b10beafChris Lattner        } else {
411477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Other uses than load?
4129440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
4139440db886627161a8413e823797569fc7b10beafChris Lattner        }
4149440db886627161a8413e823797569fc7b10beafChris Lattner    } else {
4159440db886627161a8413e823797569fc7b10beafChris Lattner      return false;  // Not a load or a GEP.
4169440db886627161a8413e823797569fc7b10beafChris Lattner    }
4174cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
418477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // Now, see if it is safe to promote this load / loads of this GEP. Loading
419477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // is safe if Operands, or a prefix of Operands, is marked as safe.
420477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
421477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      return false;
422ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
423477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // See if we are already promoting a load with these indices. If not, check
424477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // to make sure that we aren't promoting too many elements.  If so, nothing
425477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // to do.
426477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    if (ToPromote.find(Operands) == ToPromote.end()) {
427477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      if (maxElements > 0 && ToPromote.size() == maxElements) {
4285ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "argpromotion not promoting argument '"
429ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << Arg->getName() << "' because it would require adding more "
430ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "than " << maxElements << " arguments to the function.\n");
431477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // We limit aggregate promotion to only promoting up to a fixed number
432477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // of elements of the aggregate.
433477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        return false;
434477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
435477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      ToPromote.insert(Operands);
436477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    }
437477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  }
438ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
439477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  if (Loads.empty()) return true;  // No users, this is a dead argument.
44011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
44111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Okay, now we know that the argument is only used by load instructions and
442477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // it is safe to unconditionally perform all of them. Use alias analysis to
44311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // check to see if the pointer is guaranteed to not be modified from entry of
44411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // the function to each of the load instructions.
445ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
446ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Because there could be several/many load instructions, remember which
447ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // blocks we know to be transparent to the load.
448e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
44946f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson
45046f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
451ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
452ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
453ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Check to see if the load is invalidated from the start of the block to
454ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // the load itself.
455ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    LoadInst *Load = Loads[i];
456ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    BasicBlock *BB = Load->getParent();
4579440db886627161a8413e823797569fc7b10beafChris Lattner
4586d8eb156e6be727570b300bac7712f745a318c7dDan Gohman    AliasAnalysis::Location Loc = AA.getLocation(Load);
45956653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman    if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
460ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      return false;  // Pointer is invalidated!
461ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
462ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Now check every path from the entry block to the load for transparency.
463ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // To do this, we perform a depth first search on the inverse CFG from the
464ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // loading block.
465a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
466a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif      BasicBlock *P = *PI;
467e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
468a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif             I = idf_ext_begin(P, TranspBlocks),
469a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif             E = idf_ext_end(P, TranspBlocks); I != E; ++I)
47056653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman        if (AA.canBasicBlockModify(**I, Loc))
471ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner          return false;
472a53029b1fcc71b1482863a7031ddb0c48d7a1177Gabor Greif    }
473ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
474ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
475ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // If the path from the entry of the function to each load is free of
476ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // instructions that potentially invalidate the load, we can make the
477ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transformation!
478ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
479ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
480ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
4819e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// DoPromotion - This method actually performs the promotion of the specified
4825eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// arguments, and returns the new function.  At this point, we know that it's
4835eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// safe to do so.
4845095e3d1d1caef8d573534d369e37277c623064cChris LattnerCallGraphNode *ArgPromotion::DoPromotion(Function *F,
4855095e3d1d1caef8d573534d369e37277c623064cChris Lattner                               SmallPtrSet<Argument*, 8> &ArgsToPromote,
48610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                              SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
487fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
488ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Start by computing a new prototype for the function, which is the same as
489ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the old function, but has modified arguments.
490db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  FunctionType *FTy = F->getFunctionType();
4915fdd6c8793462549e3593890ec61573da06e3346Jay Foad  std::vector<Type*> Params;
492ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
493477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  typedef std::set<IndicesVector> ScalarizeTable;
494beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
4959440db886627161a8413e823797569fc7b10beafChris Lattner  // ScalarizedElements - If we are promoting a pointer that has elements
4969440db886627161a8413e823797569fc7b10beafChris Lattner  // accessed out of it, keep track of which elements are accessed so that we
4979440db886627161a8413e823797569fc7b10beafChris Lattner  // can add one argument for each.
4989440db886627161a8413e823797569fc7b10beafChris Lattner  //
4999440db886627161a8413e823797569fc7b10beafChris Lattner  // Arguments that are directly loaded will have a zero element value here, to
5009440db886627161a8413e823797569fc7b10beafChris Lattner  // handle cases where there are both a direct load and GEP accesses.
5019440db886627161a8413e823797569fc7b10beafChris Lattner  //
502beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  std::map<Argument*, ScalarizeTable> ScalarizedElements;
5039440db886627161a8413e823797569fc7b10beafChris Lattner
5049e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // OriginalLoads - Keep track of a representative load instruction from the
5059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // original function so that we can tell the alias analysis implementation
5069e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // what the new GEP/Load instructions we are inserting look like.
507477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  std::map<IndicesVector, LoadInst*> OriginalLoads;
5089e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
509034b94b17006f51722886b0f2283fb6fb19aca1fBill Wendling  // Attribute - Keep track of the parameter attributes for the arguments
510dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // that we are *not* promoting. For the ones that we do promote, the parameter
511dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // attributes are lost
512b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling  SmallVector<AttributeSet, 8> AttributesVec;
51399faa3b4ec6d03ac7808fe4ff3fbf3d04e375502Bill Wendling  const AttributeSet &PAL = F->getAttributes();
514dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
515532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands  // Add any return attributes.
5161b0c54f1c5dd61e56cb7cbc435fcb3319cff628fBill Wendling  if (PAL.hasAttributes(AttributeSet::ReturnIndex))
517b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling    AttributesVec.push_back(AttributeSet::get(F->getContext(),
518b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling                                              PAL.getRetAttributes()));
5194cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
520477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman  // First, determine the new argument list
521ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  unsigned ArgIndex = 1;
522dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
523ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner       ++I, ++ArgIndex) {
52410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
525477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Simple byval argument? Just add all the struct element types.
526db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
527db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      StructType *STy = cast<StructType>(AgTy);
52810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
52910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Params.push_back(STy->getElementType(i));
53010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++NumByValArgsPromoted;
53110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    } else if (!ArgsToPromote.count(I)) {
532477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Unchanged argument
533ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Params.push_back(I->getType());
53428d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling      AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
53528d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling      if (attrs.hasAttributes(ArgIndex)) {
536b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling        AttrBuilder B(attrs, ArgIndex);
53728d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling        AttributesVec.
538b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling          push_back(AttributeSet::get(F->getContext(), Params.size(), B));
53928d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling      }
5409e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else if (I->use_empty()) {
541477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Dead argument (which are always marked as promotable)
5429e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      ++NumArgumentsDead;
5439e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else {
544477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // Okay, this is being promoted. This means that the only uses are loads
545477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // or GEPs which are only used by loads
546477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
547477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // In this table, we will track which indices are loaded from the argument
548477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      // (where direct loads are tracked as no indices).
549beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      ScalarizeTable &ArgIndices = ScalarizedElements[I];
5509440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
5519440db886627161a8413e823797569fc7b10beafChris Lattner           ++UI) {
5529440db886627161a8413e823797569fc7b10beafChris Lattner        Instruction *User = cast<Instruction>(*UI);
55346f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
554477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        IndicesVector Indices;
555477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        Indices.reserve(User->getNumOperands() - 1);
556477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Since loads will only have a single operand, and GEPs only a single
557477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // non-index operand, this will record direct loads without any indices,
558477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // and gep+loads with the GEP indices.
559477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (User::op_iterator II = User->op_begin() + 1, IE = User->op_end();
560477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             II != IE; ++II)
561477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
562477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // GEPs with a single 0 index can be merged with direct loads
563477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (Indices.size() == 1 && Indices.front() == 0)
564477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Indices.clear();
56546f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        ArgIndices.insert(Indices);
56646f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        LoadInst *OrigLoad;
56746f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        if (LoadInst *L = dyn_cast<LoadInst>(User))
56846f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = L;
56946f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        else
570477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          // Take any load, we will use it only to update Alias Analysis
57146f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = cast<LoadInst>(User->use_back());
57246f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        OriginalLoads[Indices] = OrigLoad;
5739440db886627161a8413e823797569fc7b10beafChris Lattner      }
5749440db886627161a8413e823797569fc7b10beafChris Lattner
5759440db886627161a8413e823797569fc7b10beafChris Lattner      // Add a parameter to the function for each element passed in.
576beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
577477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             E = ArgIndices.end(); SI != E; ++SI) {
578b079a391c8b85d088dabce715d99be5917af88faTorok Edwin        // not allowed to dereference ->begin() if size() is 0
579a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
580477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        assert(Params.back());
581477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman      }
5829440db886627161a8413e823797569fc7b10beafChris Lattner
5839440db886627161a8413e823797569fc7b10beafChris Lattner      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
5849440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumArgumentsPromoted;
5859440db886627161a8413e823797569fc7b10beafChris Lattner      else
5869440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumAggregatesPromoted;
587ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
58810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
589ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
59019c874638d9478a5d5028854817a5ee72293bb2bDevang Patel  // Add any function attributes.
591956f13440a4aa0297606a4412f4aa091d931592aBill Wendling  if (PAL.hasAttributes(AttributeSet::FunctionIndex))
592b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling    AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
593b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling                                              PAL.getFnAttributes()));
59419c874638d9478a5d5028854817a5ee72293bb2bDevang Patel
595db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *RetTy = FTy->getReturnType();
596ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
597dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Construct the new function type using the new arguments.
598debcb01b0f0a15f568ca69e8f288fade4bfc7297Owen Anderson  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
599fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
600a51c39cc3265f5d0d5de87b4a3ef9332c83556e1Chris Lattner  // Create the new function body and insert it into the module.
601051a950000e21935165db56695e35bade668193bGabor Greif  Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
60228c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  NF->copyAttributesFrom(F);
603ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
604a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner
6055ededf7d42417379d230c92fc73912ebb650ede9David Greene  DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
606a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner        << "From: " << *F);
607a3512bd589ad9269ddaa4e9c008da43c36b4a1b8Chris Lattner
608ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // Recompute the parameter attributes list based on the new arguments for
609ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // the function.
61099faa3b4ec6d03ac7808fe4ff3fbf3d04e375502Bill Wendling  NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
6110598866c052147c31b808391f58434ce3dbfb838Devang Patel  AttributesVec.clear();
61228c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands
613ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  F->getParent()->getFunctionList().insert(F, NF);
6142b3407f5b3d8626b924c532bcfea15daaf1bd3c0Zhou Sheng  NF->takeName(F);
6159e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
6169e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Get the alias analysis information that we need to update to reflect our
6179e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // changes.
6189e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
6199e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
62034c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  // Get the callgraph information that we need to update to reflect our
62134c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  // changes.
62234c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands  CallGraph &CG = getAnalysis<CallGraph>();
6235095e3d1d1caef8d573534d369e37277c623064cChris Lattner
6245095e3d1d1caef8d573534d369e37277c623064cChris Lattner  // Get a new callgraph node for NF.
6255095e3d1d1caef8d573534d369e37277c623064cChris Lattner  CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
62634c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands
627ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over all of the callers of the function, transforming the call sites
628ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // to pass in the loaded pointers.
629ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
630ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  SmallVector<Value*, 16> Args;
631ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  while (!F->use_empty()) {
6327d3056b16038a6a09c452c0dfcc3c8f4e421506aGabor Greif    CallSite CS(F->use_back());
6330054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif    assert(CS.getCalledFunction() == F);
634ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *Call = CS.getInstruction();
63599faa3b4ec6d03ac7808fe4ff3fbf3d04e375502Bill Wendling    const AttributeSet &CallPAL = CS.getAttributes();
6364cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
637532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    // Add any return attributes.
6381b0c54f1c5dd61e56cb7cbc435fcb3319cff628fBill Wendling    if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
639b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling      AttributesVec.push_back(AttributeSet::get(F->getContext(),
640b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling                                                CallPAL.getRetAttributes()));
641532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
6429e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Loop over the operands, inserting GEP and loads in the caller as
6439e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // appropriate.
644ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
645ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ArgIndex = 1;
646f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
647ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner         I != E; ++I, ++AI, ++ArgIndex)
64810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
649ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        Args.push_back(*AI);          // Unmodified argument
6504cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
65128d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling        if (CallPAL.hasAttributes(ArgIndex)) {
652b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling          AttrBuilder B(CallPAL, ArgIndex);
65328d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling          AttributesVec.
654b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling            push_back(AttributeSet::get(F->getContext(), Args.size(), B));
65528d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling        }
65610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (ByValArgsToTransform.count(I)) {
65710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // Emit a GEP and load for each element of the struct.
658db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner        Type *AgTy = cast<PointerType>(I->getType())->getElementType();
659db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner        StructType *STy = cast<StructType>(AgTy);
6601d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Value *Idxs[2] = {
6611d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
66210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6631d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
664a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad          Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
665051a950000e21935165db56695e35bade668193bGabor Greif                                                 (*AI)->getName()+"."+utostr(i),
666051a950000e21935165db56695e35bade668193bGabor Greif                                                 Call);
66710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // TODO: Tell AA about the new values?
66810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
6694cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands        }
67010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (!I->use_empty()) {
6719e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        // Non-dead argument: insert GEPs and loads as appropriate.
672beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        ScalarizeTable &ArgIndices = ScalarizedElements[I];
673477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // Store the Value* version of the indices in here, but declare it now
6740054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif        // for reuse.
675477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        std::vector<Value*> Ops;
676beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
6779440db886627161a8413e823797569fc7b10beafChris Lattner               E = ArgIndices.end(); SI != E; ++SI) {
6789440db886627161a8413e823797569fc7b10beafChris Lattner          Value *V = *AI;
6799e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          LoadInst *OrigLoad = OriginalLoads[*SI];
6809e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          if (!SI->empty()) {
681477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            Ops.reserve(SI->size());
682db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner            Type *ElTy = V->getType();
6834cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands            for (IndicesVector::const_iterator II = SI->begin(),
684477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman                 IE = SI->end(); II != IE; ++II) {
685477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // Use i32 to index structs, and i64 for others (pointers/arrays).
686477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              // This satisfies GEP constraints.
687db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner              Type *IdxTy = (ElTy->isStructTy() ?
6881d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                    Type::getInt32Ty(F->getContext()) :
6891d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                    Type::getInt64Ty(F->getContext()));
690eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson              Ops.push_back(ConstantInt::get(IdxTy, *II));
6910054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif              // Keep track of the type we're currently indexing.
692477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman              ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
693477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            }
6940054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif            // And create a GEP to extract those indices.
695a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad            V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
696477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            Ops.clear();
6979e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner            AA.copyValue(OrigLoad->getOperand(0), V);
6989e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          }
6996fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          // Since we're replacing a load make sure we take the alignment
7006fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          // of the previous load.
7016fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
7026fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          newLoad->setAlignment(OrigLoad->getAlignment());
70356653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman          // Transfer the TBAA info too.
70456653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman          newLoad->setMetadata(LLVMContext::MD_tbaa,
70556653f0df85f8e4ee60941a6ca31c17ca6f936ffDan Gohman                               OrigLoad->getMetadata(LLVMContext::MD_tbaa));
7066fde0bd39b1b431b7be30aaf9221ce6c60b0a5f0Eric Christopher          Args.push_back(newLoad);
7079e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          AA.copyValue(OrigLoad, Args.back());
7089440db886627161a8413e823797569fc7b10beafChris Lattner        }
709ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
710ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7110054c7a867f85f52fdcc11279d696160de92c9f8Gabor Greif    // Push any varargs arguments on the list.
712ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
713ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Args.push_back(*AI);
71428d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling      if (CallPAL.hasAttributes(ArgIndex)) {
715b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling        AttrBuilder B(CallPAL, ArgIndex);
71628d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling        AttributesVec.
717b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling          push_back(AttributeSet::get(F->getContext(), Args.size(), B));
71828d65722d6f283b327b5815914382077fe9c0ab4Bill Wendling      }
719ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    }
720ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
72119c874638d9478a5d5028854817a5ee72293bb2bDevang Patel    // Add any function attributes.
722956f13440a4aa0297606a4412f4aa091d931592aBill Wendling    if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
723b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling      AttributesVec.push_back(AttributeSet::get(Call->getContext(),
724b2484b4332ffe385421e338de21372ea8a9dc5cfBill Wendling                                                CallPAL.getFnAttributes()));
72519c874638d9478a5d5028854817a5ee72293bb2bDevang Patel
726ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *New;
727ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
728051a950000e21935165db56695e35bade668193bGabor Greif      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
729a3efbb15ddd5aa9006564cd79086723640084878Jay Foad                               Args, "", Call);
730f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
73199faa3b4ec6d03ac7808fe4ff3fbf3d04e375502Bill Wendling      cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
7320976e00fd1cbf4128daeb72efd8957d00383fda9Bill Wendling                                                            AttributesVec));
733ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    } else {
734a3efbb15ddd5aa9006564cd79086723640084878Jay Foad      New = CallInst::Create(NF, Args, "", Call);
735f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
73699faa3b4ec6d03ac7808fe4ff3fbf3d04e375502Bill Wendling      cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
7370976e00fd1cbf4128daeb72efd8957d00383fda9Bill Wendling                                                          AttributesVec));
7381430ef134d36888b99d2e6fedd2b025882593538Chris Lattner      if (cast<CallInst>(Call)->isTailCall())
7391430ef134d36888b99d2e6fedd2b025882593538Chris Lattner        cast<CallInst>(New)->setTailCall();
740ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
741ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Args.clear();
7420598866c052147c31b808391f58434ce3dbfb838Devang Patel    AttributesVec.clear();
743ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7449e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Update the alias analysis implementation to know that we are replacing
7459e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // the old call with a new one.
7469e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    AA.replaceWithNewValue(Call, New);
7479e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
74834c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands    // Update the callgraph to know that the callsite has been transformed.
749da230cb876edf0d4fa8eefc289b8addfb722cd07Chris Lattner    CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
750a51c39cc3265f5d0d5de87b4a3ef9332c83556e1Chris Lattner    CalleeNode->replaceCallEdge(Call, New, NF_CGN);
75134c8847b2d27433ec7b81c824b66771e7665873aDuncan Sands
752ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (!Call->use_empty()) {
753ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Call->replaceAllUsesWith(New);
754046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      New->takeName(Call);
755ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
756fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
757ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Finally, remove the old call from the program, reducing the use-count of
758ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // F.
75940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    Call->eraseFromParent();
760ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
761ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
762ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Since we have now created the new function, splice the body of the old
763ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function right into the new function, leaving the old rotting hulk of the
764ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function empty.
765ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
766ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
7677a2bdde0a0eebcd2125055e0eacaca040f0b766cChris Lattner  // Loop over the argument list, transferring uses of the old arguments over to
7687a2bdde0a0eebcd2125055e0eacaca040f0b766cChris Lattner  // the new arguments, also transferring over the names as well.
769ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
77093e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
77110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner       I2 = NF->arg_begin(); I != E; ++I) {
77210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
773ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // If this is an unmodified argument, move the name and users over to the
774ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // new version.
775ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      I->replaceAllUsesWith(I2);
776046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      I2->takeName(I);
7779e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.replaceWithNewValue(I, I2);
778ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      ++I2;
77910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
78010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
7814cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
78210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
78310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // In the callee, we create an alloca, and store each of the new incoming
78410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // arguments into the alloca.
78510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Instruction *InsertPt = NF->begin()->begin();
7864cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
78710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
788db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
78950dead06ffc107edb7e84857baaeeb09039c631cOwen Anderson      Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
790db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      StructType *STy = cast<StructType>(AgTy);
7911d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      Value *Idxs[2] = {
7921d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
7934cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
79410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
7951d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
796dfd3b647839d3f944b5d8bffd6e9a2ec022d3507Daniel Dunbar        Value *Idx =
797a9203109f4ac95aa7e9624f2838e3d89623ec902Jay Foad          GetElementPtrInst::Create(TheAlloca, Idxs,
798fe09b2098ac483f6d6ce6ea4ab237a9539bdb6b9Daniel Dunbar                                    TheAlloca->getName()+"."+Twine(i),
799dfd3b647839d3f944b5d8bffd6e9a2ec022d3507Daniel Dunbar                                    InsertPt);
800fe09b2098ac483f6d6ce6ea4ab237a9539bdb6b9Daniel Dunbar        I2->setName(I->getName()+"."+Twine(i));
80110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        new StoreInst(I2++, Idx, InsertPt);
80210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      }
8034cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
80410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Anything that used the arg should now use the alloca.
80510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      I->replaceAllUsesWith(TheAlloca);
80610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      TheAlloca->takeName(I);
80710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      AA.replaceWithNewValue(I, TheAlloca);
80810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
8094cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands    }
8104cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
81110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (I->use_empty()) {
8129e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.deleteValue(I);
81310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
81410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
8154cddaf77c4f2482e7d3e7cc1c80895523dcfb68eDuncan Sands
81610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, if we promoted this argument, then all users are load
817477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // instructions (or GEPs with only load users), and all loads should be
818477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman    // using the new argument that we added.
81910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    ScalarizeTable &ArgIndices = ScalarizedElements[I];
82010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
82110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    while (!I->use_empty()) {
82210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
82310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        assert(ArgIndices.begin()->empty() &&
82410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner               "Load element should sort to front!");
82510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+".val");
82610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->replaceAllUsesWith(I2);
82710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.replaceWithNewValue(LI, I2);
82810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->eraseFromParent();
8295ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
830ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "' in function '" << F->getName() << "'\n");
83110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else {
83210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
833477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        IndicesVector Operands;
834477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        Operands.reserve(GEP->getNumIndices());
835477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
836477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman             II != IE; ++II)
837477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
838477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman
839477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        // GEPs with a single 0 index can be merged with direct loads
840477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        if (Operands.size() == 1 && Operands.front() == 0)
841477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman          Operands.clear();
84210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
84310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Function::arg_iterator TheArg = I2;
84410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (ScalarizeTable::iterator It = ArgIndices.begin();
84510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             *It != Operands; ++It, ++TheArg) {
84610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          assert(It != ArgIndices.end() && "GEP not handled??");
84710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
8489440db886627161a8413e823797569fc7b10beafChris Lattner
84910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::string NewName = I->getName();
850477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
851477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman            NewName += "." + utostr(Operands[i]);
852477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        }
853477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        NewName += ".val";
854477f5a2f11a0383b4ecfcb0db2913027ed38ee39Matthijs Kooijman        TheArg->setName(NewName);
85510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
8565ededf7d42417379d230c92fc73912ebb650ede9David Greene        DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
857ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar              << "' of function '" << NF->getName() << "'\n");
85810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
85910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // All of the uses must be load instructions.  Replace them all with
86010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // the argument specified by ArgNo.
86110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        while (!GEP->use_empty()) {
86210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          LoadInst *L = cast<LoadInst>(GEP->use_back());
86310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->replaceAllUsesWith(TheArg);
86410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          AA.replaceWithNewValue(L, TheArg);
86510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->eraseFromParent();
8669440db886627161a8413e823797569fc7b10beafChris Lattner        }
86710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.deleteValue(GEP);
86810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GEP->eraseFromParent();
869ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
870ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
871ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
87210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Increment I2 past all of the arguments added for this promoted pointer.
87372f0976c1b91c7ba50dce4d0ad0289dc14d37f81Benjamin Kramer    std::advance(I2, ArgIndices.size());
87410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
87510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
8769e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Tell the alias analysis that the old function is about to disappear.
8779e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AA.replaceWithNewValue(F, NF);
8789e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
8795095e3d1d1caef8d573534d369e37277c623064cChris Lattner
8805095e3d1d1caef8d573534d369e37277c623064cChris Lattner  NF_CGN->stealCalledFunctionsFrom(CG[F]);
8815095e3d1d1caef8d573534d369e37277c623064cChris Lattner
882eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // Now that the old function is dead, delete it.  If there is a dangling
883eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // reference to the CallgraphNode, just leave the dead function around for
884eae220259fca393adc874ed41e3930011047beb7Chris Lattner  // someone else to nuke.
885eae220259fca393adc874ed41e3930011047beb7Chris Lattner  CallGraphNode *CGN = CG[F];
886eae220259fca393adc874ed41e3930011047beb7Chris Lattner  if (CGN->getNumReferences() == 0)
887eae220259fca393adc874ed41e3930011047beb7Chris Lattner    delete CG.removeFunctionFromModule(CGN);
888eae220259fca393adc874ed41e3930011047beb7Chris Lattner  else
889eae220259fca393adc874ed41e3930011047beb7Chris Lattner    F->setLinkage(Function::ExternalLinkage);
8905095e3d1d1caef8d573534d369e37277c623064cChris Lattner
8915095e3d1d1caef8d573534d369e37277c623064cChris Lattner  return NF_CGN;
892ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
893