ArgumentPromotion.cpp revision 58d74910c6b82e622ecbb57d6644d48fec5a5c0f
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
2055cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// 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
2255cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// large array or structure is unprofitable!
239440db886627161a8413e823797569fc7b10beafChris Lattner//
24ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner// Note that this transformation could also be done for arguments that are only
2555cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// stored to (returning the value instead), but does not currently.  This case
2655cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// would be best handled when and if LLVM begins supporting multiple return
2755cbec317d9c30c8ae1d35eaa008ca63d1f2fce9Gordon Henriksen// values from functions.
28ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//
29ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner//===----------------------------------------------------------------------===//
30ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
319e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner#define DEBUG_TYPE "argpromotion"
32ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Transforms/IPO.h"
33ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Constants.h"
34ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/DerivedTypes.h"
35ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Module.h"
365eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner#include "llvm/CallGraphSCCPass.h"
37ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Instructions.h"
38ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
395eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner#include "llvm/Analysis/CallGraph.h"
40ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Target/TargetData.h"
41ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CallSite.h"
42ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include "llvm/Support/CFG.h"
43551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/Debug.h"
44551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/DepthFirstIterator.h"
45551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/Statistic.h"
46551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/StringExtras.h"
479133fe28954d498fc4de13064c7d65bd811de02cReid Spencer#include "llvm/Support/Compiler.h"
48ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner#include <set>
49ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattnerusing namespace llvm;
50ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5186453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
5286453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
5310603e0c84d15f61443e8b17bc35f98cc46606d9Chris LattnerSTATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
5486453c52ba02e743d29c08456e51006500041456Chris LattnerSTATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
55ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5686453c52ba02e743d29c08456e51006500041456Chris Lattnernamespace {
57ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  ///
599133fe28954d498fc4de13064c7d65bd811de02cReid Spencer  struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
60ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      AU.addRequired<AliasAnalysis>();
62ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      AU.addRequired<TargetData>();
635eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner      CallGraphSCCPass::getAnalysisUsage(AU);
64ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
65ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
665eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
67ecd94c804a563f2a86572dcf1d2e81f397e19daaNick Lewycky    static char ID; // Pass identification, replacement for typeid
68794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel    ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
69794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel
70ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  private:
715eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    bool PromoteArguments(CallGraphNode *CGN);
7240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
73a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner    Function *DoPromotion(Function *F,
7410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                          SmallPtrSet<Argument*, 8> &ArgsToPromote,
7510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                          SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
76ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  };
77ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
781997473cf72957d0e70322e2fe6fe2ab141c58a6Devang Patel  char ArgPromotion::ID = 0;
797f8897f22e88271cfa114998a4d6088e7c8e8e11Chris Lattner  RegisterPass<ArgPromotion> X("argpromotion",
807f8897f22e88271cfa114998a4d6088e7c8e8e11Chris Lattner                               "Promote 'by reference' arguments to scalars");
81ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
82ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
83c71ca3cdd2d7a08b043ebb717cad0beadaf47450Devang PatelPass *llvm::createArgumentPromotionPass() {
84ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return new ArgPromotion();
85ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
86ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
875eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattnerbool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
885eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  bool Changed = false, LocalChange;
89ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
90f5afcabff887c2e9023f0c69c44f1de15b5c4347Chris Lattner  do {  // Iterate until we stop promoting from this SCC.
915eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    LocalChange = false;
925eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    // Attempt to promote arguments from all functions in this SCC.
935eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    for (unsigned i = 0, e = SCC.size(); i != e; ++i)
945eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner      LocalChange |= PromoteArguments(SCC[i]);
955eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner    Changed |= LocalChange;               // Remember that we changed something.
965eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  } while (LocalChange);
97fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
98ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return Changed;
99ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
100ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
1019e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// PromoteArguments - This method checks the specified function to see if there
1029e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// are any promotable arguments and if it is safe to promote the function (for
1039e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// example, all callers are direct).  If safe to promote some arguments, it
1049e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// calls the DoPromotion method.
1059e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner///
1065eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattnerbool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
1075eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  Function *F = CGN->getFunction();
1085eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner
1095eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  // Make sure that it is local to this module.
1105eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  if (!F || !F->hasInternalLinkage()) return false;
111ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
112ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // First check: see if there are any pointer arguments!  If not, quick exit.
11340c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
11440c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  unsigned ArgNo = 0;
11540c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
11640c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner       I != E; ++I, ++ArgNo)
117ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (isa<PointerType>(I->getType()))
11840c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner      PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
119ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  if (PointerArgs.empty()) return false;
120ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
121ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Second check: make sure that all callers are direct callers.  We can't
122ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transform functions that have indirect callers.
123ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
1247db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner       UI != E; ++UI) {
1257db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner    CallSite CS = CallSite::get(*UI);
1269e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    if (!CS.getInstruction())       // "Taking the address" of the function
1279e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      return false;
1289e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
1299e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Ensure that this call site is CALLING the function, not passing it as
1309e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // an argument.
131f1577014ddd13113c4a06d85bc75cd7b2dce71a9Chris Lattner    if (UI.getOperandNo() != 0)
132f1577014ddd13113c4a06d85bc75cd7b2dce71a9Chris Lattner      return false;
1337db5a6df78749bf0cd37870fcefe08b8849e38e6Chris Lattner  }
134ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
13540c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // Check to see which arguments are promotable.  If an argument is promotable,
13640c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  // add it to ArgsToPromote.
13740c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  SmallPtrSet<Argument*, 8> ArgsToPromote;
13810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  SmallPtrSet<Argument*, 8> ByValArgsToTransform;
13940c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  for (unsigned i = 0; i != PointerArgs.size(); ++i) {
14010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, ParamAttr::ByVal);
14110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
14210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // If this is a byval argument, and if the aggregate type is small, just
14310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // pass the elements, which is always safe.
14410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    Argument *PtrArg = PointerArgs[i].first;
14510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isByVal) {
14610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
14710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (const StructType *STy = dyn_cast<StructType>(AgTy))
14810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        if (STy->getNumElements() <= 3) {
14910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // If all the elements are first class types, we can promote it.
15010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          bool AllSimple = true;
15110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
15210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            if (!STy->getElementType(i)->isFirstClassType()) {
15310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner              AllSimple = false;
15410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner              break;
15510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            }
15610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
15710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // Safe to transform, don't even bother trying to "promote" it.
15810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // Passing the elements as a scalar will allow scalarrepl to hack on
15910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // the new alloca we introduce.
16010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          if (AllSimple) {
16110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            ByValArgsToTransform.insert(PtrArg);
16210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            continue;
16310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          }
16410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
16510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
16610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
16710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, see if we can promote the pointer to its value.
16810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (isSafeToPromoteArgument(PtrArg, isByVal))
16910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ArgsToPromote.insert(PtrArg);
17040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  }
17140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner
172ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // No promotable pointer arguments.
17310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) return false;
174ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
17510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  Function *NewF = DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
1765eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner
177dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Update the call graph to know that the function has been transformed.
1785eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  getAnalysis<CallGraph>().changeFunction(F, NewF);
179ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
180ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
181ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
18211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
18311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// to load.
18411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattnerstatic bool IsAlwaysValidPointer(Value *V) {
18511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
18611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
18711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    return IsAlwaysValidPointer(GEP->getOperand(0));
18811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
18911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    if (CE->getOpcode() == Instruction::GetElementPtr)
19011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return IsAlwaysValidPointer(CE->getOperand(0));
19111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
19211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return false;
19311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
19411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
19511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
19611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner/// all callees pass in a valid pointer for the specified function argument.
19711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattnerstatic bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
19811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  Function *Callee = Arg->getParent();
19911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
20093e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  unsigned ArgNo = std::distance(Callee->arg_begin(),
20193e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner                                 Function::arg_iterator(Arg));
20211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
20311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Look at all call sites of the function.  At this pointer we know we only
20411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // have direct callees.
20511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
20611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner       UI != E; ++UI) {
20711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    CallSite CS = CallSite::get(*UI);
20811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    assert(CS.getInstruction() && "Should only have direct calls!");
20911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
21011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
21111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner      return false;
21211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  }
21311a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  return true;
21411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner}
21511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
2169e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
2179e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// isSafeToPromoteArgument - As you might guess from the name of this method,
2189e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// it checks to see if it is both safe and useful to promote the argument.
2199e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// This method limits promotion of aggregates to only promote up to three
2209e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// elements of the aggregate in order to avoid exploding the number of
2219e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// arguments passed in.
22240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattnerbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
2239440db886627161a8413e823797569fc7b10beafChris Lattner  // We can only promote this argument if all of the uses are loads, or are GEP
2249440db886627161a8413e823797569fc7b10beafChris Lattner  // instructions (with constant indices) that are subsequently loaded.
225170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
226170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // We can also only promote the load if we can guarantee that it will happen.
227170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // Promoting a load causes the load to be unconditionally executed in the
228170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // caller, so we can't turn a conditional load into an unconditional load in
229170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  // general.
230170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  bool SafeToUnconditionallyLoad = false;
231170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  if (isByVal)   // ByVal arguments are always safe to load from.
232170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner    SafeToUnconditionallyLoad = true;
233170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
23411a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  BasicBlock *EntryBlock = Arg->getParent()->begin();
235a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  SmallVector<LoadInst*, 16> Loads;
236a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner  std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
237ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
238ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner       UI != E; ++UI)
239ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
240ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      if (LI->isVolatile()) return false;  // Don't hack volatile loads
241ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Loads.push_back(LI);
242170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
243170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      // If this load occurs in the entry block, then the pointer is
244170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      // unconditionally loaded.
245170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
2469440db886627161a8413e823797569fc7b10beafChris Lattner    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
2479440db886627161a8413e823797569fc7b10beafChris Lattner      if (GEP->use_empty()) {
2489440db886627161a8413e823797569fc7b10beafChris Lattner        // Dead GEP's cause trouble later.  Just remove them if we run into
2499440db886627161a8413e823797569fc7b10beafChris Lattner        // them.
2509e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        getAnalysis<AliasAnalysis>().deleteValue(GEP);
25140c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        GEP->eraseFromParent();
25240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner        return isSafeToPromoteArgument(Arg, isByVal);
2539440db886627161a8413e823797569fc7b10beafChris Lattner      }
2549440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that all of the indices are constants.
255a10145fdf6325c5c528689e8952ad7e4e2a1a6b5Chris Lattner      SmallVector<ConstantInt*, 8> Operands;
2569440db886627161a8413e823797569fc7b10beafChris Lattner      for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
257beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
2589440db886627161a8413e823797569fc7b10beafChris Lattner          Operands.push_back(C);
2599440db886627161a8413e823797569fc7b10beafChris Lattner        else
2609440db886627161a8413e823797569fc7b10beafChris Lattner          return false;  // Not a constant operand GEP!
2619440db886627161a8413e823797569fc7b10beafChris Lattner
2629440db886627161a8413e823797569fc7b10beafChris Lattner      // Ensure that the only users of the GEP are load instructions.
2639440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
2649440db886627161a8413e823797569fc7b10beafChris Lattner           UI != E; ++UI)
2659440db886627161a8413e823797569fc7b10beafChris Lattner        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
2669440db886627161a8413e823797569fc7b10beafChris Lattner          if (LI->isVolatile()) return false;  // Don't hack volatile loads
2679440db886627161a8413e823797569fc7b10beafChris Lattner          Loads.push_back(LI);
268170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner
269170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          // If this load occurs in the entry block, then the pointer is
270170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          // unconditionally loaded.
271170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner          SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
2729440db886627161a8413e823797569fc7b10beafChris Lattner        } else {
2739440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
2749440db886627161a8413e823797569fc7b10beafChris Lattner        }
275ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
2769e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // See if there is already a GEP with these indices.  If not, check to
2779e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // make sure that we aren't promoting too many elements.  If so, nothing
2789e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      // to do.
2799440db886627161a8413e823797569fc7b10beafChris Lattner      if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
2809440db886627161a8413e823797569fc7b10beafChris Lattner          GEPIndices.end()) {
2819440db886627161a8413e823797569fc7b10beafChris Lattner        if (GEPIndices.size() == 3) {
2820a81aac4b46eed130d20714af5a1c01b05d0275eBill Wendling          DOUT << "argpromotion disable promoting argument '"
2830a81aac4b46eed130d20714af5a1c01b05d0275eBill Wendling               << Arg->getName() << "' because it would require adding more "
2840a81aac4b46eed130d20714af5a1c01b05d0275eBill Wendling               << "than 3 arguments to the function.\n";
2859440db886627161a8413e823797569fc7b10beafChris Lattner          // We limit aggregate promotion to only promoting up to three elements
2869440db886627161a8413e823797569fc7b10beafChris Lattner          // of the aggregate.
2879440db886627161a8413e823797569fc7b10beafChris Lattner          return false;
2889440db886627161a8413e823797569fc7b10beafChris Lattner        }
2899440db886627161a8413e823797569fc7b10beafChris Lattner        GEPIndices.push_back(Operands);
2909440db886627161a8413e823797569fc7b10beafChris Lattner      }
2919440db886627161a8413e823797569fc7b10beafChris Lattner    } else {
2929440db886627161a8413e823797569fc7b10beafChris Lattner      return false;  // Not a load or a GEP.
2939440db886627161a8413e823797569fc7b10beafChris Lattner    }
294ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
2959e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  if (Loads.empty()) return true;  // No users, this is a dead argument.
296ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
29711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // If we decide that we want to promote this argument, the value is going to
29811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // be unconditionally loaded in all callees.  This is only safe to do if the
29911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // pointer was going to be unconditionally loaded anyway (i.e. there is a load
30011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // of the pointer in the entry block of the function) or if we can prove that
30111a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // all pointers passed in are always to legal locations (for example, no null
30211a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // pointers are passed in, no pointers to free'd memory, etc).
303170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner  if (!SafeToUnconditionallyLoad &&
304170b1816b2cd6f02a8d0d5f1e13d9bda2f247012Chris Lattner      !AllCalleesPassInValidPointerForArgument(Arg))
30511a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner    return false;   // Cannot prove that this is safe!!
30611a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner
30711a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // Okay, now we know that the argument is only used by load instructions and
30811a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // it is safe to unconditionally load the pointer.  Use alias analysis to
30911a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // check to see if the pointer is guaranteed to not be modified from entry of
31011a3d7b7ddd10659b72ed248d878fa0d90ddcb45Chris Lattner  // the function to each of the load instructions.
311ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
312ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Because there could be several/many load instructions, remember which
313ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // blocks we know to be transparent to the load.
314e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
31546f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson
31646f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3179440db886627161a8413e823797569fc7b10beafChris Lattner  TargetData &TD = getAnalysis<TargetData>();
318ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
319ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
320ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Check to see if the load is invalidated from the start of the block to
321ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // the load itself.
322ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    LoadInst *Load = Loads[i];
323ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    BasicBlock *BB = Load->getParent();
3249440db886627161a8413e823797569fc7b10beafChris Lattner
3259440db886627161a8413e823797569fc7b10beafChris Lattner    const PointerType *LoadTy =
3269440db886627161a8413e823797569fc7b10beafChris Lattner      cast<PointerType>(Load->getOperand(0)->getType());
327514ab348fddcdffa8367685dc608b2f8d5de986dDuncan Sands    unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
3289440db886627161a8413e823797569fc7b10beafChris Lattner
329ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
330ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      return false;  // Pointer is invalidated!
331ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
332ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Now check every path from the entry block to the load for transparency.
333ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // To do this, we perform a depth first search on the inverse CFG from the
334ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // loading block.
335ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
336e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
337e027efa21816dbd2350d137fdfa181c24cbe8c49Chris Lattner             I = idf_ext_begin(*PI, TranspBlocks),
338ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner             E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
339ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        if (AA.canBasicBlockModify(**I, Arg, LoadSize))
340ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner          return false;
341ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
342ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
343ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // If the path from the entry of the function to each load is free of
344ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // instructions that potentially invalidate the load, we can make the
345ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // transformation!
346ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  return true;
347ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
348ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
349beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattnernamespace {
350beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
351beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  /// elements are instances of ConstantInt.
352beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  ///
353beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  struct GEPIdxComparator {
354beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner    bool operator()(const std::vector<Value*> &LHS,
355beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner                    const std::vector<Value*> &RHS) const {
356beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      unsigned idx = 0;
357beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
358beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        if (LHS[idx] != RHS[idx]) {
359b83eb6447ba155342598f0fabe1f08f5baa9164aReid Spencer          return cast<ConstantInt>(LHS[idx])->getZExtValue() <
360b83eb6447ba155342598f0fabe1f08f5baa9164aReid Spencer                 cast<ConstantInt>(RHS[idx])->getZExtValue();
361beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        }
362beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      }
363beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
364beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      // Return less than if we ran out of stuff in LHS and we didn't run out of
365beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      // stuff in RHS.
366beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      return idx == LHS.size() && idx != RHS.size();
367beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner    }
368beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  };
369beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner}
370beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
371beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
3729e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner/// DoPromotion - This method actually performs the promotion of the specified
3735eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// arguments, and returns the new function.  At this point, we know that it's
3745eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner/// safe to do so.
3755eb6f6c829ddfe353f94623aa1009c72be930497Chris LattnerFunction *ArgPromotion::DoPromotion(Function *F,
37610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                    SmallPtrSet<Argument*, 8> &ArgsToPromote,
37710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                              SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
378fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
379ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Start by computing a new prototype for the function, which is the same as
380ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the old function, but has modified arguments.
381ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  const FunctionType *FTy = F->getFunctionType();
382ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  std::vector<const Type*> Params;
383ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
384beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
385beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner
3869440db886627161a8413e823797569fc7b10beafChris Lattner  // ScalarizedElements - If we are promoting a pointer that has elements
3879440db886627161a8413e823797569fc7b10beafChris Lattner  // accessed out of it, keep track of which elements are accessed so that we
3889440db886627161a8413e823797569fc7b10beafChris Lattner  // can add one argument for each.
3899440db886627161a8413e823797569fc7b10beafChris Lattner  //
3909440db886627161a8413e823797569fc7b10beafChris Lattner  // Arguments that are directly loaded will have a zero element value here, to
3919440db886627161a8413e823797569fc7b10beafChris Lattner  // handle cases where there are both a direct load and GEP accesses.
3929440db886627161a8413e823797569fc7b10beafChris Lattner  //
393beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner  std::map<Argument*, ScalarizeTable> ScalarizedElements;
3949440db886627161a8413e823797569fc7b10beafChris Lattner
3959e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // OriginalLoads - Keep track of a representative load instruction from the
3969e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // original function so that we can tell the alias analysis implementation
3979e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // what the new GEP/Load instructions we are inserting look like.
3989e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
3999e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
400dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // ParamAttrs - Keep track of the parameter attributes for the arguments
401dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // that we are *not* promoting. For the ones that we do promote, the parameter
402dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // attributes are lost
40358d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
40458d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  const PAListPtr &PAL = F->getParamAttrs();
405dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
406532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands  // Add any return attributes.
40758d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  if (ParameterAttributes attrs = PAL.getParamAttrs(0))
408532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
409532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
410ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  unsigned ArgIndex = 1;
411dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
412ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner       ++I, ++ArgIndex) {
41310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
41410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
41510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
41610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const StructType *STy = cast<StructType>(AgTy);
41710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
41810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Params.push_back(STy->getElementType(i));
41910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++NumByValArgsPromoted;
42010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    } else if (!ArgsToPromote.count(I)) {
421ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Params.push_back(I->getType());
42258d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      if (ParameterAttributes attrs = PAL.getParamAttrs(ArgIndex))
42310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
4249e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else if (I->use_empty()) {
4259e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      ++NumArgumentsDead;
4269e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    } else {
4279440db886627161a8413e823797569fc7b10beafChris Lattner      // Okay, this is being promoted.  Check to see if there are any GEP uses
4289440db886627161a8413e823797569fc7b10beafChris Lattner      // of the argument.
429beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      ScalarizeTable &ArgIndices = ScalarizedElements[I];
4309440db886627161a8413e823797569fc7b10beafChris Lattner      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
4319440db886627161a8413e823797569fc7b10beafChris Lattner           ++UI) {
4329440db886627161a8413e823797569fc7b10beafChris Lattner        Instruction *User = cast<Instruction>(*UI);
43346f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
43446f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
43546f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        ArgIndices.insert(Indices);
43646f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        LoadInst *OrigLoad;
43746f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        if (LoadInst *L = dyn_cast<LoadInst>(User))
43846f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = L;
43946f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        else
44046f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson          OrigLoad = cast<LoadInst>(User->use_back());
44146f022a7f105211d5ea2c394e406d1943b80908cOwen Anderson        OriginalLoads[Indices] = OrigLoad;
4429440db886627161a8413e823797569fc7b10beafChris Lattner      }
4439440db886627161a8413e823797569fc7b10beafChris Lattner
4449440db886627161a8413e823797569fc7b10beafChris Lattner      // Add a parameter to the function for each element passed in.
445beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
4469440db886627161a8413e823797569fc7b10beafChris Lattner             E = ArgIndices.end(); SI != E; ++SI)
4471ccd185cb49d81465a2901622e58ceae046d1d83Chris Lattner        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
448b8f74793b9d161bc666fe27fc92fe112b6ec169bDavid Greene                                                           SI->begin(),
449b8f74793b9d161bc666fe27fc92fe112b6ec169bDavid Greene                                                           SI->end()));
4509440db886627161a8413e823797569fc7b10beafChris Lattner
4519440db886627161a8413e823797569fc7b10beafChris Lattner      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
4529440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumArgumentsPromoted;
4539440db886627161a8413e823797569fc7b10beafChris Lattner      else
4549440db886627161a8413e823797569fc7b10beafChris Lattner        ++NumAggregatesPromoted;
455ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
45610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
457ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
458ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  const Type *RetTy = FTy->getReturnType();
459ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
460ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
461ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // have zero fixed arguments.
462ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  bool ExtraArgHack = false;
463ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  if (Params.empty() && FTy->isVarArg()) {
464ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    ExtraArgHack = true;
465c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer    Params.push_back(Type::Int32Ty);
466ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
467dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands
468dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Construct the new function type using the new arguments.
469ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
470fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
471dc024674ff96820d6020757b48d47f46d4c07db2Duncan Sands  // Create the new function body and insert it into the module...
472ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
473f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner  NF->setCallingConv(F->getCallingConv());
474ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
475ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // Recompute the parameter attributes list based on the new arguments for
476ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  // the function.
47758d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
47858d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner  ParamAttrsVec.clear();
479ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
480194c90ed2a8e74b5a1c5184835f84c572d524dadGordon Henriksen  if (F->hasCollector())
481194c90ed2a8e74b5a1c5184835f84c572d524dadGordon Henriksen    NF->setCollector(F->getCollector());
482ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  F->getParent()->getFunctionList().insert(F, NF);
4839e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
4849e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Get the alias analysis information that we need to update to reflect our
4859e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // changes.
4869e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4879e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
488ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over all of the callers of the function, transforming the call sites
489ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // to pass in the loaded pointers.
490ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
491ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner  SmallVector<Value*, 16> Args;
492ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  while (!F->use_empty()) {
493ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite CS = CallSite::get(F->use_back());
494ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *Call = CS.getInstruction();
49558d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner    const PAListPtr &CallPAL = CS.getParamAttrs();
496ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
497532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands    // Add any return attributes.
49858d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner    if (ParameterAttributes attrs = CallPAL.getParamAttrs(0))
499532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands      ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
500532d022794beabceae09c7fcc222a6e4e929c748Duncan Sands
5019e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Loop over the operands, inserting GEP and loads in the caller as
5029e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // appropriate.
503ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
504ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ArgIndex = 1;
505f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
506ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner         I != E; ++I, ++AI, ++ArgIndex)
50710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
508ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner        Args.push_back(*AI);          // Unmodified argument
509ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
51058d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner        if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
511ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner          ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
512ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner
51310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (ByValArgsToTransform.count(I)) {
51410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // Emit a GEP and load for each element of the struct.
51510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
51610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        const StructType *STy = cast<StructType>(AgTy);
51710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
51810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
51910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
52010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Value *Idx = new GetElementPtrInst(*AI, Idxs, Idxs+2,
52110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                             (*AI)->getName()+"."+utostr(i),
52210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                             Call);
52310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          // TODO: Tell AA about the new values?
52410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
52510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
52610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else if (!I->use_empty()) {
5279e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner        // Non-dead argument: insert GEPs and loads as appropriate.
528beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        ScalarizeTable &ArgIndices = ScalarizedElements[I];
529beabf45a6923b1748edae40d53e2b2c4362cc32fChris Lattner        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
5309440db886627161a8413e823797569fc7b10beafChris Lattner               E = ArgIndices.end(); SI != E; ++SI) {
5319440db886627161a8413e823797569fc7b10beafChris Lattner          Value *V = *AI;
5329e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          LoadInst *OrigLoad = OriginalLoads[*SI];
5339e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          if (!SI->empty()) {
534b8f74793b9d161bc666fe27fc92fe112b6ec169bDavid Greene            V = new GetElementPtrInst(V, SI->begin(), SI->end(),
5351ccd185cb49d81465a2901622e58ceae046d1d83Chris Lattner                                      V->getName()+".idx", Call);
5369e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner            AA.copyValue(OrigLoad->getOperand(0), V);
5379e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          }
5389440db886627161a8413e823797569fc7b10beafChris Lattner          Args.push_back(new LoadInst(V, V->getName()+".val", Call));
5399e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner          AA.copyValue(OrigLoad, Args.back());
5409440db886627161a8413e823797569fc7b10beafChris Lattner        }
541ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
542ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
543ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (ExtraArgHack)
544c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer      Args.push_back(Constant::getNullValue(Type::Int32Ty));
545ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
546ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Push any varargs arguments on the list
547ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
548ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Args.push_back(*AI);
54958d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
550ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner        ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
551ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    }
552ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
553ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Instruction *New;
554ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
555ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
556f1355a55f8d815f5385e9a4432195f03b65f3a42David Greene                           Args.begin(), Args.end(), "", Call);
557f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
55858d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      cast<InvokeInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
55958d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner                                                          ParamAttrsVec.end()));
560ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    } else {
56152eec548206d0b135b55ba52dd0e82e978f15ae5David Greene      New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
562f201dbc1a4a638659ec3916785196e2c204c7755Chris Lattner      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
56358d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner      cast<CallInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
56458d74910c6b82e622ecbb57d6644d48fec5a5c0fChris Lattner                                                        ParamAttrsVec.end()));
5651430ef134d36888b99d2e6fedd2b025882593538Chris Lattner      if (cast<CallInst>(Call)->isTailCall())
5661430ef134d36888b99d2e6fedd2b025882593538Chris Lattner        cast<CallInst>(New)->setTailCall();
567ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
568ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    Args.clear();
569ab04e13a1f017c2b0a82344b4c083d92139ee2ccChris Lattner    ParamAttrsVec.clear();
570ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
5719e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // Update the alias analysis implementation to know that we are replacing
5729e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    // the old call with a new one.
5739e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner    AA.replaceWithNewValue(Call, New);
5749e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
575ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    if (!Call->use_empty()) {
576ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      Call->replaceAllUsesWith(New);
577046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      New->takeName(Call);
578ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
579fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
580ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // Finally, remove the old call from the program, reducing the use-count of
581ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    // F.
58240c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner    Call->eraseFromParent();
583ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  }
584ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
585ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Since we have now created the new function, splice the body of the old
586ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function right into the new function, leaving the old rotting hulk of the
587ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // function empty.
588ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
589ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
590ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Loop over the argument list, transfering uses of the old arguments over to
591ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // the new arguments, also transfering over the names as well.
592ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  //
59393e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
59410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner       I2 = NF->arg_begin(); I != E; ++I) {
59510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
596ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // If this is an unmodified argument, move the name and users over to the
597ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      // new version.
598ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      I->replaceAllUsesWith(I2);
599046800a7125cd497613efc0e1ea15cb595666585Chris Lattner      I2->takeName(I);
6009e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.replaceWithNewValue(I, I2);
601ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      ++I2;
60210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
60310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
60410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
60510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (ByValArgsToTransform.count(I)) {
60610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // In the callee, we create an alloca, and store each of the new incoming
60710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // arguments into the alloca.
60810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Instruction *InsertPt = NF->begin()->begin();
60910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
61010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Just add all the struct element types.
61110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
61210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
61310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      const StructType *STy = cast<StructType>(AgTy);
61410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
61510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
61610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
61710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
61810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Value *Idx = new GetElementPtrInst(TheAlloca, Idxs, Idxs+2,
61910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                           TheAlloca->getName()+"."+utostr(i),
62010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner                                           InsertPt);
62110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+"."+utostr(i));
62210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        new StoreInst(I2++, Idx, InsertPt);
62310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      }
62410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
62510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      // Anything that used the arg should now use the alloca.
62610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      I->replaceAllUsesWith(TheAlloca);
62710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      TheAlloca->takeName(I);
62810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      AA.replaceWithNewValue(I, TheAlloca);
62910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
63010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
63110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
63210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    if (I->use_empty()) {
6339e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner      AA.deleteValue(I);
63410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      continue;
63510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    }
63610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
63710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Otherwise, if we promoted this argument, then all users are load
63810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // instructions, and all loads should be using the new argument that we
63910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // added.
64010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    ScalarizeTable &ArgIndices = ScalarizedElements[I];
64110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
64210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    while (!I->use_empty()) {
64310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
64410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        assert(ArgIndices.begin()->empty() &&
64510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner               "Load element should sort to front!");
64610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        I2->setName(I->getName()+".val");
64710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->replaceAllUsesWith(I2);
64810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.replaceWithNewValue(LI, I2);
64910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        LI->eraseFromParent();
65010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        DOUT << "*** Promoted load of argument '" << I->getName()
65110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             << "' in function '" << F->getName() << "'\n";
65210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      } else {
65310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
65410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
65510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
65610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        Function::arg_iterator TheArg = I2;
65710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (ScalarizeTable::iterator It = ArgIndices.begin();
65810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             *It != Operands; ++It, ++TheArg) {
65910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          assert(It != ArgIndices.end() && "GEP not handled??");
66010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        }
6619440db886627161a8413e823797569fc7b10beafChris Lattner
66210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        std::string NewName = I->getName();
66310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        for (unsigned i = 0, e = Operands.size(); i != e; ++i)
66410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
66510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            NewName += "." + CI->getValue().toStringUnsigned(10);
66610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          else
66710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner            NewName += ".x";
66810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        TheArg->setName(NewName+".val");
66910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
67010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        DOUT << "*** Promoted agg argument '" << TheArg->getName()
67110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner             << "' of function '" << F->getName() << "'\n";
67210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
67310603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // All of the uses must be load instructions.  Replace them all with
67410603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        // the argument specified by ArgNo.
67510603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        while (!GEP->use_empty()) {
67610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          LoadInst *L = cast<LoadInst>(GEP->use_back());
67710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->replaceAllUsesWith(TheArg);
67810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          AA.replaceWithNewValue(L, TheArg);
67910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner          L->eraseFromParent();
6809440db886627161a8413e823797569fc7b10beafChris Lattner        }
68110603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        AA.deleteValue(GEP);
68210603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner        GEP->eraseFromParent();
683ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner      }
684ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner    }
685ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner
68610603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    // Increment I2 past all of the arguments added for this promoted pointer.
68710603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner    for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
68810603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner      ++I2;
68910603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner  }
69010603e0c84d15f61443e8b17bc35f98cc46606d9Chris Lattner
6919e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Notify the alias analysis implementation that we inserted a new argument.
6929e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  if (ExtraArgHack)
693c5b206b6be61d0d933b98b6af5e22f42edd48ad1Reid Spencer    AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
6949e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
6959e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
6969e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  // Tell the alias analysis that the old function is about to disappear.
6979e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner  AA.replaceWithNewValue(F, NF);
6989e7cc2f0d42aa4127e3b8406e25907a96ce9ada0Chris Lattner
699ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner  // Now that the old function is dead, delete it.
70040c14be5bc9ba900f01c408b65aca57e053788e1Chris Lattner  F->eraseFromParent();
7015eb6f6c829ddfe353f94623aa1009c72be930497Chris Lattner  return NF;
702ed570a7dca45e001a6223e2a25d034b838934f88Chris Lattner}
703