ArgumentPromotion.cpp revision 992e97eed344a141ff581838cfdacb76a1e9559a
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
20bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner// by default it refuses to scalarize aggregates which would require passing in more than
2155cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// three operands to the function, because passing thousands of operands for a
22bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner// large array or structure is unprofitable! This limit is can be configured or
23bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner// 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"
39ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
405eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner#include "llvm/Analysis/CallGraph.h"
41ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Target/TargetData.h"
42ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CallSite.h"
43ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CFG.h"
44551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/Debug.h"
45551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/DepthFirstIterator.h"
46551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/Statistic.h"
47551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/StringExtras.h"
489133fe28954d498fc4de13064c7d65bd811de02cReid Spencer#include "llvm/Support/Compiler.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  ///
609133fe28954d498fc4de13064c7d65bd811de02cReid Spencer  struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
61ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      AU.addRequired<AliasAnalysis>();
63ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      AU.addRequired<TargetData>();
645eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner      CallGraphSCCPass::getAnalysisUsage(AU);
65ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
66ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
675eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
68ecd94c804a563f2a86572dcf1d2e81f397e19daaNick Lewycky    static char ID; // Pass identification, replacement for typeid
69a72acf938902ea8ae2776cad7327257e88a63a54Nate Begeman    ArgPromotion(unsigned maxElements = 3) : CallGraphSCCPass((intptr_t)&ID),
70a72acf938902ea8ae2776cad7327257e88a63a54Nate Begeman                                             maxElements(maxElements) {}
71794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel
72ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  private:
735eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    bool PromoteArguments(CallGraphNode *CGN);
7440c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
75a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner    Function *DoPromotion(Function *F,
7610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                          SmallPtrSet<Argument*, 8> &ArgsToPromote,
7710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                          SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
78992e97eed344a141ff581838cfdacb76a1e9559aMatthijs Kooijman    /// The maximum number of elements to expand, or 0 for unlimited.
79992e97eed344a141ff581838cfdacb76a1e9559aMatthijs Kooijman    unsigned maxElements;
80ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  };
81ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
82ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
83844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar ArgPromotion::ID = 0;
84844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<ArgPromotion>
85844731a7f1909f55935e3514c9e713a62d67662eDan GohmanX("argpromotion", "Promote 'by reference' arguments to scalars");
86844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
87bcd203cf860269987f32b14737b200b84fc2b63eChris LattnerPass *llvm::createArgumentPromotionPass(unsigned maxElements) {
88bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner  return new ArgPromotion(maxElements);
89ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
90ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
915eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattnerbool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
925eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  bool Changed = false, LocalChange;
93ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
94f5afcabff887c2e9023f0c69c44f1de15b5c4347Chris Lattner  do {  // Iterate until we stop promoting from this SCC.
955eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    LocalChange = false;
965eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    // Attempt to promote arguments from all functions in this SCC.
975eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    for (unsigned i = 0, e = SCC.size(); i != e; ++i)
985eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner      LocalChange |= PromoteArguments(SCC[i]);
995eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    Changed |= LocalChange;               // Remember that we changed something.
1005eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  } while (LocalChange);
101fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
102ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return Changed;
103ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
104ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
1059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// PromoteArguments - This method checks the specified function to see if there
1069e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// are any promotable arguments and if it is safe to promote the function (for
1079e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// example, all callers are direct).  If safe to promote some arguments, it
1089e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// calls the DoPromotion method.
1099e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner///
1105eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattnerbool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
1115eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  Function *F = CGN->getFunction();
1125eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner
1135eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  // Make sure that it is local to this module.
1145eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  if (!F || !F->hasInternalLinkage()) return false;
115ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
116ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // First check: see if there are any pointer arguments!  If not, quick exit.
11740c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
11840c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  unsigned ArgNo = 0;
11940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
12040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner       I != E; ++I, ++ArgNo)
121ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (isa<PointerType>(I->getType()))
12240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner      PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
123ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  if (PointerArgs.empty()) return false;
124ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
125ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Second check: make sure that all callers are direct callers.  We can't
126ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transform functions that have indirect callers.
127ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
1287db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner       UI != E; ++UI) {
1297db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner    CallSite CS = CallSite::get(*UI);
1309e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    if (!CS.getInstruction())       // "Taking the address" of the function
1319e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      return false;
1329e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
1339e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Ensure that this call site is CALLING the function, not passing it as
1349e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // an argument.
135f1577014ddd13113c4a06d85bc75cd7b2dce71a9Chris Lattner    if (UI.getOperandNo() != 0)
136f1577014ddd13113c4a06d85bc75cd7b2dce71a9Chris Lattner      return false;
1377db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner  }
138ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
13940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // Check to see which arguments are promotable.  If an argument is promotable,
14040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // add it to ArgsToPromote.
14140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallPtrSet<Argument*, 8> ArgsToPromote;
14210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  SmallPtrSet<Argument*, 8> ByValArgsToTransform;
14340c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (unsigned i = 0; i != PointerArgs.size(); ++i) {
14410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, ParamAttr::ByVal);
14510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
14610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // If this is a byval argument, and if the aggregate type is small, just
14710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // pass the elements, which is always safe.
14810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    Argument *PtrArg = PointerArgs[i].first;
14910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isByVal) {
15010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
15110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (const StructType *STy = dyn_cast<StructType>(AgTy))
152bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner        if (maxElements > 0 && STy->getNumElements() > maxElements) {
153bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner          DOUT << "argpromotion disable promoting argument '"
154bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner               << PtrArg->getName() << "' because it would require adding more "
155bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner               << "than " << maxElements << " arguments to the function.\n";
156bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner        } else {
157399101a5990621b0357009ab1852cc00f410a6c6Dan Gohman          // If all the elements are single-value types, we can promote it.
15810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          bool AllSimple = true;
15910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
160399101a5990621b0357009ab1852cc00f410a6c6Dan Gohman            if (!STy->getElementType(i)->isSingleValueType()) {
16110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner              AllSimple = false;
16210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner              break;
16310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            }
16410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
16510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // Safe to transform, don't even bother trying to "promote" it.
16610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // Passing the elements as a scalar will allow scalarrepl to hack on
16710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // the new alloca we introduce.
16810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          if (AllSimple) {
16910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            ByValArgsToTransform.insert(PtrArg);
17010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            continue;
17110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          }
17210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
17310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
17410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
17510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, see if we can promote the pointer to its value.
17610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isSafeToPromoteArgument(PtrArg, isByVal))
17710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ArgsToPromote.insert(PtrArg);
17840c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  }
17940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner
180ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // No promotable pointer arguments.
18110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) return false;
182ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
18310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  Function *NewF = DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
1845eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner
185dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Update the call graph to know that the function has been transformed.
1865eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  getAnalysis<CallGraph>().changeFunction(F, NewF);
187ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
188ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
189ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
19011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
19111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// to load.
19211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattnerstatic bool IsAlwaysValidPointer(Value *V) {
19311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
19411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
19511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    return IsAlwaysValidPointer(GEP->getOperand(0));
19611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
19711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    if (CE->getOpcode() == Instruction::GetElementPtr)
19811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return IsAlwaysValidPointer(CE->getOperand(0));
19911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
20011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return false;
20111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
20211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
20311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
20411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// all callees pass in a valid pointer for the specified function argument.
20511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattnerstatic bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
20611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  Function *Callee = Arg->getParent();
20711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
20893e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  unsigned ArgNo = std::distance(Callee->arg_begin(),
20993e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner                                 Function::arg_iterator(Arg));
21011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
21111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Look at all call sites of the function.  At this pointer we know we only
21211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // have direct callees.
21311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
21411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner       UI != E; ++UI) {
21511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    CallSite CS = CallSite::get(*UI);
21611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    assert(CS.getInstruction() && "Should only have direct calls!");
21711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
21811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
21911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return false;
22011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  }
22111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return true;
22211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
22311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
2249e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
2259e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// isSafeToPromoteArgument - As you might guess from the name of this method,
2269e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// it checks to see if it is both safe and useful to promote the argument.
2279e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// This method limits promotion of aggregates to only promote up to three
2289e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// elements of the aggregate in order to avoid exploding the number of
2299e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// arguments passed in.
23040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattnerbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
2319440db886627161a8413e823797569fc7b10beafChris Lattner  // We can only promote this argument if all of the uses are loads, or are GEP
2329440db886627161a8413e823797569fc7b10beafChris Lattner  // instructions (with constant indices) that are subsequently loaded.
233170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
234170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // We can also only promote the load if we can guarantee that it will happen.
235170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // Promoting a load causes the load to be unconditionally executed in the
236170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // caller, so we can't turn a conditional load into an unconditional load in
237170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // general.
238170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  bool SafeToUnconditionallyLoad = false;
239170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  if (isByVal)   // ByVal arguments are always safe to load from.
240170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner    SafeToUnconditionallyLoad = true;
241170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
24211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  BasicBlock *EntryBlock = Arg->getParent()->begin();
243a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  SmallVector<LoadInst*, 16> Loads;
244a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
245ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
246ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner       UI != E; ++UI)
247ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
248ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      if (LI->isVolatile()) return false;  // Don't hack volatile loads
249ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Loads.push_back(LI);
250170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
251170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      // If this load occurs in the entry block, then the pointer is
252170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      // unconditionally loaded.
253170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
2549440db886627161a8413e823797569fc7b10beafChris Lattner    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
2559440db886627161a8413e823797569fc7b10beafChris Lattner      if (GEP->use_empty()) {
2569440db886627161a8413e823797569fc7b10beafChris Lattner        // Dead GEP's cause trouble later.  Just remove them if we run into
2579440db886627161a8413e823797569fc7b10beafChris Lattner        // them.
2589e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        getAnalysis<AliasAnalysis>().deleteValue(GEP);
25940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        GEP->eraseFromParent();
26040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        return isSafeToPromoteArgument(Arg, isByVal);
2619440db886627161a8413e823797569fc7b10beafChris Lattner      }
2629440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that all of the indices are constants.
263a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner      SmallVector<ConstantInt*, 8> Operands;
2649440db886627161a8413e823797569fc7b10beafChris Lattner      for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
265beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
2669440db886627161a8413e823797569fc7b10beafChris Lattner          Operands.push_back(C);
2679440db886627161a8413e823797569fc7b10beafChris Lattner        else
2689440db886627161a8413e823797569fc7b10beafChris Lattner          return false;  // Not a constant operand GEP!
2699440db886627161a8413e823797569fc7b10beafChris Lattner
2709440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that the only users of the GEP are load instructions.
2719440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
2729440db886627161a8413e823797569fc7b10beafChris Lattner           UI != E; ++UI)
2739440db886627161a8413e823797569fc7b10beafChris Lattner        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
2749440db886627161a8413e823797569fc7b10beafChris Lattner          if (LI->isVolatile()) return false;  // Don't hack volatile loads
2759440db886627161a8413e823797569fc7b10beafChris Lattner          Loads.push_back(LI);
276170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
277170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          // If this load occurs in the entry block, then the pointer is
278170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          // unconditionally loaded.
279170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
2809440db886627161a8413e823797569fc7b10beafChris Lattner        } else {
2819440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
2829440db886627161a8413e823797569fc7b10beafChris Lattner        }
283ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
2849e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // See if there is already a GEP with these indices.  If not, check to
2859e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // make sure that we aren't promoting too many elements.  If so, nothing
2869e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // to do.
2879440db886627161a8413e823797569fc7b10beafChris Lattner      if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
2889440db886627161a8413e823797569fc7b10beafChris Lattner          GEPIndices.end()) {
289bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner        if (maxElements > 0 && GEPIndices.size() == maxElements) {
2900a81aac4b46eed130d20714af5a1c01b05d0275eBill Wendling          DOUT << "argpromotion disable promoting argument '"
2910a81aac4b46eed130d20714af5a1c01b05d0275eBill Wendling               << Arg->getName() << "' because it would require adding more "
292bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner               << "than " << maxElements << " arguments to the function.\n";
293bcd203cf860269987f32b14737b200b84fc2b63eChris Lattner          // We limit aggregate promotion to only promoting up to a fixed number
294a72acf938902ea8ae2776cad7327257e88a63a54Nate Begeman          // of elements of the aggregate.
2959440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
2969440db886627161a8413e823797569fc7b10beafChris Lattner        }
2979440db886627161a8413e823797569fc7b10beafChris Lattner        GEPIndices.push_back(Operands);
2989440db886627161a8413e823797569fc7b10beafChris Lattner      }
2999440db886627161a8413e823797569fc7b10beafChris Lattner    } else {
3009440db886627161a8413e823797569fc7b10beafChris Lattner      return false;  // Not a load or a GEP.
3019440db886627161a8413e823797569fc7b10beafChris Lattner    }
302ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
3039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  if (Loads.empty()) return true;  // No users, this is a dead argument.
304ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
30511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // If we decide that we want to promote this argument, the value is going to
30611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // be unconditionally loaded in all callees.  This is only safe to do if the
30711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // pointer was going to be unconditionally loaded anyway (i.e. there is a load
30811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // of the pointer in the entry block of the function) or if we can prove that
30911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // all pointers passed in are always to legal locations (for example, no null
31011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // pointers are passed in, no pointers to free'd memory, etc).
311170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  if (!SafeToUnconditionallyLoad &&
312170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      !AllCalleesPassInValidPointerForArgument(Arg))
31311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    return false;   // Cannot prove that this is safe!!
31411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
31511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Okay, now we know that the argument is only used by load instructions and
31611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // it is safe to unconditionally load the pointer.  Use alias analysis to
31711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // check to see if the pointer is guaranteed to not be modified from entry of
31811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // the function to each of the load instructions.
319ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
320ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Because there could be several/many load instructions, remember which
321ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // blocks we know to be transparent to the load.
322e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
32346f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson
32446f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3259440db886627161a8413e823797569fc7b10beafChris Lattner  TargetData &TD = getAnalysis<TargetData>();
326ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
327ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
328ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Check to see if the load is invalidated from the start of the block to
329ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // the load itself.
330ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    LoadInst *Load = Loads[i];
331ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    BasicBlock *BB = Load->getParent();
3329440db886627161a8413e823797569fc7b10beafChris Lattner
3339440db886627161a8413e823797569fc7b10beafChris Lattner    const PointerType *LoadTy =
3349440db886627161a8413e823797569fc7b10beafChris Lattner      cast<PointerType>(Load->getOperand(0)->getType());
335514ab348fddcdffa8367685dc608b2f8d5de986dDuncan Sands    unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
3369440db886627161a8413e823797569fc7b10beafChris Lattner
337ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
338ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      return false;  // Pointer is invalidated!
339ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
340ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Now check every path from the entry block to the load for transparency.
341ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // To do this, we perform a depth first search on the inverse CFG from the
342ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // loading block.
343ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
344e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
345e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner             I = idf_ext_begin(*PI, TranspBlocks),
346ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner             E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
347ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        if (AA.canBasicBlockModify(**I, Arg, LoadSize))
348ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner          return false;
349ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
350ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
351ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // If the path from the entry of the function to each load is free of
352ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // instructions that potentially invalidate the load, we can make the
353ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transformation!
354ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
355ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
356ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
357beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattnernamespace {
358beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
359beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  /// elements are instances of ConstantInt.
360beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  ///
361beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  struct GEPIdxComparator {
362beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner    bool operator()(const std::vector<Value*> &LHS,
363beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner                    const std::vector<Value*> &RHS) const {
364beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      unsigned idx = 0;
365beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
366beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        if (LHS[idx] != RHS[idx]) {
367b83eb6447ba155342598f0fabe1f08f5baa9164aReid Spencer          return cast<ConstantInt>(LHS[idx])->getZExtValue() <
368b83eb6447ba155342598f0fabe1f08f5baa9164aReid Spencer                 cast<ConstantInt>(RHS[idx])->getZExtValue();
369beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        }
370beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      }
371beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
372beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      // Return less than if we ran out of stuff in LHS and we didn't run out of
373beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      // stuff in RHS.
374beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      return idx == LHS.size() && idx != RHS.size();
375beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner    }
376beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  };
377beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner}
378beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
379beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
3809e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// DoPromotion - This method actually performs the promotion of the specified
3815eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// arguments, and returns the new function.  At this point, we know that it's
3825eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// safe to do so.
3835eb6f6c829ddfe353f94623aa1009c72be930497Chris LattnerFunction *ArgPromotion::DoPromotion(Function *F,
38410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                    SmallPtrSet<Argument*, 8> &ArgsToPromote,
38510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                              SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
386fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
387ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Start by computing a new prototype for the function, which is the same as
388ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the old function, but has modified arguments.
389ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  const FunctionType *FTy = F->getFunctionType();
390ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  std::vector<const Type*> Params;
391ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
392beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
393beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
3949440db886627161a8413e823797569fc7b10beafChris Lattner  // ScalarizedElements - If we are promoting a pointer that has elements
3959440db886627161a8413e823797569fc7b10beafChris Lattner  // accessed out of it, keep track of which elements are accessed so that we
3969440db886627161a8413e823797569fc7b10beafChris Lattner  // can add one argument for each.
3979440db886627161a8413e823797569fc7b10beafChris Lattner  //
3989440db886627161a8413e823797569fc7b10beafChris Lattner  // Arguments that are directly loaded will have a zero element value here, to
3999440db886627161a8413e823797569fc7b10beafChris Lattner  // handle cases where there are both a direct load and GEP accesses.
4009440db886627161a8413e823797569fc7b10beafChris Lattner  //
401beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  std::map<Argument*, ScalarizeTable> ScalarizedElements;
4029440db886627161a8413e823797569fc7b10beafChris Lattner
4039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // OriginalLoads - Keep track of a representative load instruction from the
4049e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // original function so that we can tell the alias analysis implementation
4059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // what the new GEP/Load instructions we are inserting look like.
4069e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
4079e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
408dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // ParamAttrs - Keep track of the parameter attributes for the arguments
409dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // that we are *not* promoting. For the ones that we do promote, the parameter
410dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // attributes are lost
41158d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
41258d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  const PAListPtr &PAL = F->getParamAttrs();
413dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
414532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands  // Add any return attributes.
41558d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  if (ParameterAttributes attrs = PAL.getParamAttrs(0))
416532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
417532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
418ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  unsigned ArgIndex = 1;
419dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
420ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner       ++I, ++ArgIndex) {
42110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
42210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
42310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
42410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const StructType *STy = cast<StructType>(AgTy);
42510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
42610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Params.push_back(STy->getElementType(i));
42710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++NumByValArgsPromoted;
42810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    } else if (!ArgsToPromote.count(I)) {
429ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Params.push_back(I->getType());
43058d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      if (ParameterAttributes attrs = PAL.getParamAttrs(ArgIndex))
43110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
4329e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else if (I->use_empty()) {
4339e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      ++NumArgumentsDead;
4349e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else {
4359440db886627161a8413e823797569fc7b10beafChris Lattner      // Okay, this is being promoted.  Check to see if there are any GEP uses
4369440db886627161a8413e823797569fc7b10beafChris Lattner      // of the argument.
437beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      ScalarizeTable &ArgIndices = ScalarizedElements[I];
4389440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
4399440db886627161a8413e823797569fc7b10beafChris Lattner           ++UI) {
4409440db886627161a8413e823797569fc7b10beafChris Lattner        Instruction *User = cast<Instruction>(*UI);
44146f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
44246f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
44346f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        ArgIndices.insert(Indices);
44446f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        LoadInst *OrigLoad;
44546f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        if (LoadInst *L = dyn_cast<LoadInst>(User))
44646f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = L;
44746f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        else
44846f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = cast<LoadInst>(User->use_back());
44946f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        OriginalLoads[Indices] = OrigLoad;
4509440db886627161a8413e823797569fc7b10beafChris Lattner      }
4519440db886627161a8413e823797569fc7b10beafChris Lattner
4529440db886627161a8413e823797569fc7b10beafChris Lattner      // Add a parameter to the function for each element passed in.
453beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
4549440db886627161a8413e823797569fc7b10beafChris Lattner             E = ArgIndices.end(); SI != E; ++SI)
4551ccd185cb49d81465a2901622e58ceae046d1d83Chris Lattner        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
456b8f74793b9d161bc666fe27fc92fe112b6ec169bDavid Greene                                                           SI->begin(),
457b8f74793b9d161bc666fe27fc92fe112b6ec169bDavid Greene                                                           SI->end()));
4589440db886627161a8413e823797569fc7b10beafChris Lattner
4599440db886627161a8413e823797569fc7b10beafChris Lattner      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
4609440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumArgumentsPromoted;
4619440db886627161a8413e823797569fc7b10beafChris Lattner      else
4629440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumAggregatesPromoted;
463ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
46410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
465ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
466ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  const Type *RetTy = FTy->getReturnType();
467ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
468ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
469ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // have zero fixed arguments.
470ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  bool ExtraArgHack = false;
471ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  if (Params.empty() && FTy->isVarArg()) {
472ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    ExtraArgHack = true;
473c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer    Params.push_back(Type::Int32Ty);
474ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
475dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
476dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Construct the new function type using the new arguments.
477ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
478fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
479dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Create the new function body and insert it into the module...
480051a950000e21935165db56695e35bade668193bGabor Greif  Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
481f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner  NF->setCallingConv(F->getCallingConv());
482ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
483ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // Recompute the parameter attributes list based on the new arguments for
484ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // the function.
48558d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
48658d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  ParamAttrsVec.clear();
487ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
488194c90ed2a8e74b5a1c5184835f84c572d524dadGordon Henriksen  if (F->hasCollector())
489194c90ed2a8e74b5a1c5184835f84c572d524dadGordon Henriksen    NF->setCollector(F->getCollector());
490ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  F->getParent()->getFunctionList().insert(F, NF);
4912b3407f5b3d8626b924c532bcfea15daaf1bd3c0Zhou Sheng  NF->takeName(F);
4929e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
4939e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Get the alias analysis information that we need to update to reflect our
4949e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // changes.
4959e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4969e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
497ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over all of the callers of the function, transforming the call sites
498ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // to pass in the loaded pointers.
499ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
500ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  SmallVector<Value*, 16> Args;
501ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  while (!F->use_empty()) {
502ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite CS = CallSite::get(F->use_back());
503ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *Call = CS.getInstruction();
50458d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner    const PAListPtr &CallPAL = CS.getParamAttrs();
505ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
506532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    // Add any return attributes.
50758d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner    if (ParameterAttributes attrs = CallPAL.getParamAttrs(0))
508532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands      ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
509532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
5109e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Loop over the operands, inserting GEP and loads in the caller as
5119e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // appropriate.
512ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
513ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ArgIndex = 1;
514f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
515ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner         I != E; ++I, ++AI, ++ArgIndex)
51610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
517ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        Args.push_back(*AI);          // Unmodified argument
518ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
51958d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner        if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
520ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner          ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
521ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
52210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (ByValArgsToTransform.count(I)) {
52310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // Emit a GEP and load for each element of the struct.
52410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
52510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        const StructType *STy = cast<StructType>(AgTy);
52610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
52710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
52810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
529051a950000e21935165db56695e35bade668193bGabor Greif          Value *Idx = GetElementPtrInst::Create(*AI, Idxs, Idxs+2,
530051a950000e21935165db56695e35bade668193bGabor Greif                                                 (*AI)->getName()+"."+utostr(i),
531051a950000e21935165db56695e35bade668193bGabor Greif                                                 Call);
53210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // TODO: Tell AA about the new values?
53310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
53410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
53510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (!I->use_empty()) {
5369e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        // Non-dead argument: insert GEPs and loads as appropriate.
537beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        ScalarizeTable &ArgIndices = ScalarizedElements[I];
538beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
5399440db886627161a8413e823797569fc7b10beafChris Lattner               E = ArgIndices.end(); SI != E; ++SI) {
5409440db886627161a8413e823797569fc7b10beafChris Lattner          Value *V = *AI;
5419e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          LoadInst *OrigLoad = OriginalLoads[*SI];
5429e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          if (!SI->empty()) {
543051a950000e21935165db56695e35bade668193bGabor Greif            V = GetElementPtrInst::Create(V, SI->begin(), SI->end(),
544051a950000e21935165db56695e35bade668193bGabor Greif                                          V->getName()+".idx", Call);
5459e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner            AA.copyValue(OrigLoad->getOperand(0), V);
5469e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          }
5479440db886627161a8413e823797569fc7b10beafChris Lattner          Args.push_back(new LoadInst(V, V->getName()+".val", Call));
5489e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          AA.copyValue(OrigLoad, Args.back());
5499440db886627161a8413e823797569fc7b10beafChris Lattner        }
550ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
551ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
552ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (ExtraArgHack)
553c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer      Args.push_back(Constant::getNullValue(Type::Int32Ty));
554ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
555ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Push any varargs arguments on the list
556ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
557ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Args.push_back(*AI);
55858d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
559ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner        ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
560ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    }
561ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
562ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *New;
563ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
564051a950000e21935165db56695e35bade668193bGabor Greif      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
565051a950000e21935165db56695e35bade668193bGabor Greif                               Args.begin(), Args.end(), "", Call);
566f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
56758d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      cast<InvokeInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
56858d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner                                                          ParamAttrsVec.end()));
569ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    } else {
570051a950000e21935165db56695e35bade668193bGabor Greif      New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
571f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
57258d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      cast<CallInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
57358d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner                                                        ParamAttrsVec.end()));
5741430ef134d36888b99d2e6fedd2b025882593538Chris Lattner      if (cast<CallInst>(Call)->isTailCall())
5751430ef134d36888b99d2e6fedd2b025882593538Chris Lattner        cast<CallInst>(New)->setTailCall();
576ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
577ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Args.clear();
578ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ParamAttrsVec.clear();
579ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5809e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Update the alias analysis implementation to know that we are replacing
5819e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // the old call with a new one.
5829e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    AA.replaceWithNewValue(Call, New);
5839e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
584ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (!Call->use_empty()) {
585ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Call->replaceAllUsesWith(New);
586046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      New->takeName(Call);
587ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
588fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
589ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Finally, remove the old call from the program, reducing the use-count of
590ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // F.
59140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    Call->eraseFromParent();
592ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
593ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
594ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Since we have now created the new function, splice the body of the old
595ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function right into the new function, leaving the old rotting hulk of the
596ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function empty.
597ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
598ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
599ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over the argument list, transfering uses of the old arguments over to
600ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the new arguments, also transfering over the names as well.
601ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
60293e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
60310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner       I2 = NF->arg_begin(); I != E; ++I) {
60410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
605ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // If this is an unmodified argument, move the name and users over to the
606ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // new version.
607ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      I->replaceAllUsesWith(I2);
608046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      I2->takeName(I);
6099e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.replaceWithNewValue(I, I2);
610ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      ++I2;
61110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
61210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
61310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
61410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
61510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // In the callee, we create an alloca, and store each of the new incoming
61610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // arguments into the alloca.
61710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Instruction *InsertPt = NF->begin()->begin();
61810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
61910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
62010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
62110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
62210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const StructType *STy = cast<StructType>(AgTy);
62310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
62410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
62510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
62610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
627051a950000e21935165db56695e35bade668193bGabor Greif        Value *Idx = GetElementPtrInst::Create(TheAlloca, Idxs, Idxs+2,
628051a950000e21935165db56695e35bade668193bGabor Greif                                               TheAlloca->getName()+"."+utostr(i),
629051a950000e21935165db56695e35bade668193bGabor Greif                                               InsertPt);
63010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+"."+utostr(i));
63110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        new StoreInst(I2++, Idx, InsertPt);
63210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      }
63310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
63410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Anything that used the arg should now use the alloca.
63510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      I->replaceAllUsesWith(TheAlloca);
63610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      TheAlloca->takeName(I);
63710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      AA.replaceWithNewValue(I, TheAlloca);
63810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
63910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
64010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
64110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (I->use_empty()) {
6429e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.deleteValue(I);
64310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
64410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
64510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
64610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, if we promoted this argument, then all users are load
64710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // instructions, and all loads should be using the new argument that we
64810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // added.
64910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    ScalarizeTable &ArgIndices = ScalarizedElements[I];
65010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
65110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    while (!I->use_empty()) {
65210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
65310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        assert(ArgIndices.begin()->empty() &&
65410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner               "Load element should sort to front!");
65510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+".val");
65610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->replaceAllUsesWith(I2);
65710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.replaceWithNewValue(LI, I2);
65810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->eraseFromParent();
65910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        DOUT << "*** Promoted load of argument '" << I->getName()
66010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             << "' in function '" << F->getName() << "'\n";
66110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else {
66210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
66310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
66410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
66510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Function::arg_iterator TheArg = I2;
66610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (ScalarizeTable::iterator It = ArgIndices.begin();
66710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             *It != Operands; ++It, ++TheArg) {
66810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          assert(It != ArgIndices.end() && "GEP not handled??");
66910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
6709440db886627161a8413e823797569fc7b10beafChris Lattner
67110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::string NewName = I->getName();
67210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = Operands.size(); i != e; ++i)
67310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
67410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            NewName += "." + CI->getValue().toStringUnsigned(10);
67510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          else
67610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            NewName += ".x";
67710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        TheArg->setName(NewName+".val");
67810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
67910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        DOUT << "*** Promoted agg argument '" << TheArg->getName()
68010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             << "' of function '" << F->getName() << "'\n";
68110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
68210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // All of the uses must be load instructions.  Replace them all with
68310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // the argument specified by ArgNo.
68410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        while (!GEP->use_empty()) {
68510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          LoadInst *L = cast<LoadInst>(GEP->use_back());
68610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->replaceAllUsesWith(TheArg);
68710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          AA.replaceWithNewValue(L, TheArg);
68810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->eraseFromParent();
6899440db886627161a8413e823797569fc7b10beafChris Lattner        }
69010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.deleteValue(GEP);
69110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GEP->eraseFromParent();
692ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
693ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
694ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
69510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Increment I2 past all of the arguments added for this promoted pointer.
69610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
69710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++I2;
69810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
69910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
7009e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Notify the alias analysis implementation that we inserted a new argument.
7019e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  if (ExtraArgHack)
702c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer    AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
7039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
7049e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
7059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Tell the alias analysis that the old function is about to disappear.
7069e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AA.replaceWithNewValue(F, NF);
7079e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
708ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Now that the old function is dead, delete it.
70940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  F->eraseFromParent();
7105eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  return NF;
711ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
712