1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
3 // This pass is used to promote memory references to be register references. A
4 // simple example of the transformation performed by this pass is:
7 // %X = alloca int, uint 1 ret int 42
8 // store int 42, int *%X
12 // To do this transformation, a simple analysis is done to ensure it is safe.
13 // Currently this just loops over all alloca instructions, looking for
14 // instructions that are only used in simple load and stores.
16 // After this, the code is transformed by...
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Method.h"
25 #include "llvm/Assembly/Writer.h" // For debugging
27 class PromotePass : public MethodPass {
29 // runOnMethod - To run this pass, first we calculate the alloca instructions
30 // that are safe for promotion, then we promote each one.
32 virtual bool runOnMethod(Method *M) {
33 std::vector<AllocaInst*> Allocas;
34 findSafeAllocas(M, Allocas); // Calculate safe allocas
36 // Transform each alloca in turn...
37 for (std::vector<AllocaInst*>::iterator I = Allocas.begin(),
38 E = Allocas.end(); I != E; ++I)
41 return !Allocas.empty();
44 // findSafeAllocas - Find allocas that are safe to promote
46 void findSafeAllocas(Method *M, std::vector<AllocaInst*> &Allocas) const;
48 // promoteAlloca - Convert the use chain of an alloca instruction into
49 // register references.
51 void promoteAlloca(AllocaInst *AI);
55 // findSafeAllocas - Find allocas that are safe to promote
57 void PromotePass::findSafeAllocas(Method *M,
58 std::vector<AllocaInst*> &Allocas) const {
59 BasicBlock *BB = M->front(); // Get the entry node for the method
61 // Look at all instructions in the entry node
62 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
63 if (AllocaInst *AI = dyn_cast<AllocaInst>(*I)) // Is it an alloca?
64 if (!AI->isArrayAllocation()) {
66 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
67 UI != UE; ++UI) { // Loop over all of the uses of the alloca
68 // Only allow nonindexed memory access instructions...
69 if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
70 if (MAI->hasIndices()) { isSafe = false; break; } // indexed?
72 isSafe = false; break; // Not a load or store?
76 if (isSafe) // If all checks pass, add alloca to safe list
77 Allocas.push_back(AI);
82 // promoteAlloca - Convert the use chain of an alloca instruction into
83 // register references.
85 void PromotePass::promoteAlloca(AllocaInst *AI) {
86 cerr << "TODO: Should process: " << AI;
91 Pass *newPromoteMemoryToRegister() {
92 return new PromotePass();