MEGAPATCH checkin.
[oota-llvm.git] / lib / Transforms / IPO / MutateStructTypes.cpp
1 //===- MutateStructTypes.cpp - Change struct defns --------------------------=//
2 //
3 // This pass is used to change structure accesses and type definitions in some
4 // way.  It can be used to arbitrarily permute structure fields, safely, without
5 // breaking code.  A transformation may only be done on a type if that type has
6 // been found to be "safe" by the 'FindUnsafePointerTypes' pass.  This pass will
7 // assert and die if you try to do an illegal transformation.
8 //
9 // This is an interprocedural pass that requires the entire program to do a
10 // transformation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/IPO/MutateStructTypes.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Function.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Argument.h"
26 #include "llvm/Constants.h"
27 #include "Support/STLExtras.h"
28 #include "Support/StatisticReporter.h"
29 #include <algorithm>
30 using std::map;
31 using std::vector;
32
33 // ValuePlaceHolder - A stupid little marker value.  It appears as an
34 // instruction of type Instruction::UserOp1.
35 //
36 struct ValuePlaceHolder : public Instruction {
37   ValuePlaceHolder(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
38
39   virtual Instruction *clone() const { abort(); return 0; }
40   virtual const char *getOpcodeName() const { return "placeholder"; }
41 };
42
43
44 // ConvertType - Convert from the old type system to the new one...
45 const Type *MutateStructTypes::ConvertType(const Type *Ty) {
46   if (Ty->isPrimitiveType() ||
47       isa<OpaqueType>(Ty)) return Ty;  // Don't convert primitives
48
49   map<const Type *, PATypeHolder>::iterator I = TypeMap.find(Ty);
50   if (I != TypeMap.end()) return I->second;
51
52   const Type *DestTy = 0;
53
54   PATypeHolder PlaceHolder = OpaqueType::get();
55   TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
56
57   switch (Ty->getPrimitiveID()) {
58   case Type::FunctionTyID: {
59     const FunctionType *MT = cast<FunctionType>(Ty);
60     const Type *RetTy = ConvertType(MT->getReturnType());
61     vector<const Type*> ArgTypes;
62
63     for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
64            E = MT->getParamTypes().end(); I != E; ++I)
65       ArgTypes.push_back(ConvertType(*I));
66     
67     DestTy = FunctionType::get(RetTy, ArgTypes, MT->isVarArg());
68     break;
69   }
70   case Type::StructTyID: {
71     const StructType *ST = cast<StructType>(Ty);
72     const StructType::ElementTypes &El = ST->getElementTypes();
73     vector<const Type *> Types;
74
75     for (StructType::ElementTypes::const_iterator I = El.begin(), E = El.end();
76          I != E; ++I)
77       Types.push_back(ConvertType(*I));
78     DestTy = StructType::get(Types);
79     break;
80   }
81   case Type::ArrayTyID:
82     DestTy = ArrayType::get(ConvertType(cast<ArrayType>(Ty)->getElementType()),
83                             cast<ArrayType>(Ty)->getNumElements());
84     break;
85
86   case Type::PointerTyID:
87     DestTy = PointerType::get(
88                  ConvertType(cast<PointerType>(Ty)->getElementType()));
89     break;
90   default:
91     assert(0 && "Unknown type!");
92     return 0;
93   }
94
95   assert(DestTy && "Type didn't get created!?!?");
96
97   // Refine our little placeholder value into a real type...
98   ((DerivedType*)PlaceHolder.get())->refineAbstractTypeTo(DestTy);
99   TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
100
101   return PlaceHolder.get();
102 }
103
104
105 // AdjustIndices - Convert the indexes specifed by Idx to the new changed form
106 // using the specified OldTy as the base type being indexed into.
107 //
108 void MutateStructTypes::AdjustIndices(const CompositeType *OldTy,
109                                       vector<Value*> &Idx,
110                                       unsigned i = 0) {
111   assert(i < Idx.size() && "i out of range!");
112   const CompositeType *NewCT = cast<CompositeType>(ConvertType(OldTy));
113   if (NewCT == OldTy) return;  // No adjustment unless type changes
114
115   if (const StructType *OldST = dyn_cast<StructType>(OldTy)) {
116     // Figure out what the current index is...
117     unsigned ElNum = cast<ConstantUInt>(Idx[i])->getValue();
118     assert(ElNum < OldST->getElementTypes().size());
119
120     map<const StructType*, TransformType>::iterator I = Transforms.find(OldST);
121     if (I != Transforms.end()) {
122       assert(ElNum < I->second.second.size());
123       // Apply the XForm specified by Transforms map...
124       unsigned NewElNum = I->second.second[ElNum];
125       Idx[i] = ConstantUInt::get(Type::UByteTy, NewElNum);
126     }
127   }
128
129   // Recursively process subtypes...
130   if (i+1 < Idx.size())
131     AdjustIndices(cast<CompositeType>(OldTy->getTypeAtIndex(Idx[i])), Idx, i+1);
132 }
133
134
135 // ConvertValue - Convert from the old value in the old type system to the new
136 // type system.
137 //
138 Value *MutateStructTypes::ConvertValue(const Value *V) {
139   // Ignore null values and simple constants..
140   if (V == 0) return 0;
141
142   if (const Constant *CPV = dyn_cast<Constant>(V)) {
143     if (V->getType()->isPrimitiveType())
144       return (Value*)CPV;
145
146     if (isa<ConstantPointerNull>(CPV))
147       return ConstantPointerNull::get(
148                       cast<PointerType>(ConvertType(V->getType())));
149     assert(0 && "Unable to convert constpool val of this type!");
150   }
151
152   // Check to see if this is an out of function reference first...
153   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
154     // Check to see if the value is in the map...
155     map<const GlobalValue*, GlobalValue*>::iterator I = GlobalMap.find(GV);
156     if (I == GlobalMap.end())
157       return (Value*)GV;  // Not mapped, just return value itself
158     return I->second;
159   }
160   
161   map<const Value*, Value*>::iterator I = LocalValueMap.find(V);
162   if (I != LocalValueMap.end()) return I->second;
163
164   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
165     // Create placeholder block to represent the basic block we haven't seen yet
166     // This will be used when the block gets created.
167     //
168     return LocalValueMap[V] = new BasicBlock(BB->getName());
169   }
170
171   DEBUG(cerr << "NPH: " << V << "\n");
172
173   // Otherwise make a constant to represent it
174   return LocalValueMap[V] = new ValuePlaceHolder(ConvertType(V->getType()));
175 }
176
177
178 // setTransforms - Take a map that specifies what transformation to do for each
179 // field of the specified structure types.  There is one element of the vector
180 // for each field of the structure.  The value specified indicates which slot of
181 // the destination structure the field should end up in.  A negative value 
182 // indicates that the field should be deleted entirely.
183 //
184 void MutateStructTypes::setTransforms(const TransformsType &XForm) {
185
186   // Loop over the types and insert dummy entries into the type map so that 
187   // recursive types are resolved properly...
188   for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
189          E = XForm.end(); I != E; ++I) {
190     const StructType *OldTy = I->first;
191     TypeMap.insert(std::make_pair(OldTy, OpaqueType::get()));
192   }
193
194   // Loop over the type specified and figure out what types they should become
195   for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
196          E = XForm.end(); I != E; ++I) {
197     const StructType  *OldTy = I->first;
198     const vector<int> &InVec = I->second;
199
200     assert(OldTy->getElementTypes().size() == InVec.size() &&
201            "Action not specified for every element of structure type!");
202
203     vector<const Type *> NewType;
204
205     // Convert the elements of the type over, including the new position mapping
206     int Idx = 0;
207     vector<int>::const_iterator TI = find(InVec.begin(), InVec.end(), Idx);
208     while (TI != InVec.end()) {
209       unsigned Offset = TI-InVec.begin();
210       const Type *NewEl = ConvertType(OldTy->getContainedType(Offset));
211       assert(NewEl && "Element not found!");
212       NewType.push_back(NewEl);
213
214       TI = find(InVec.begin(), InVec.end(), ++Idx);
215     }
216
217     // Create a new type that corresponds to the destination type
218     PATypeHolder NSTy = StructType::get(NewType);
219
220     // Refine the old opaque type to the new type to properly handle recursive
221     // types...
222     //
223     const Type *OldTypeStub = TypeMap.find(OldTy)->second.get();
224     ((DerivedType*)OldTypeStub)->refineAbstractTypeTo(NSTy);
225
226     // Add the transformation to the Transforms map.
227     Transforms.insert(std::make_pair(OldTy,
228                        std::make_pair(cast<StructType>(NSTy.get()), InVec)));
229
230     DEBUG(cerr << "Mutate " << OldTy << "\nTo " << NSTy << "\n");
231   }
232 }
233
234 void MutateStructTypes::clearTransforms() {
235   Transforms.clear();
236   TypeMap.clear();
237   GlobalMap.clear();
238   assert(LocalValueMap.empty() &&
239          "Local Value Map should always be empty between transformations!");
240 }
241
242 // processGlobals - This loops over global constants defined in the
243 // module, converting them to their new type.
244 //
245 void MutateStructTypes::processGlobals(Module &M) {
246   // Loop through the functions in the module and create a new version of the
247   // function to contained the transformed code.  Also, be careful to not
248   // process the values that we add.
249   //
250   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
251     if (!I->isExternal()) {
252       const FunctionType *NewMTy = 
253         cast<FunctionType>(ConvertType(I->getFunctionType()));
254       
255       // Create a new function to put stuff into...
256       Function *NewMeth = new Function(NewMTy, I->hasInternalLinkage(),
257                                        I->getName());
258       if (I->hasName())
259         I->setName("OLD."+I->getName());
260
261       // Insert the new function into the function list... to be filled in later
262       M.getFunctionList().push_back(NewMeth);
263       
264       // Keep track of the association...
265       GlobalMap[I] = NewMeth;
266     }
267
268   // TODO: HANDLE GLOBAL VARIABLES
269
270   // Remap the symbol table to refer to the types in a nice way
271   //
272   if (SymbolTable *ST = M.getSymbolTable()) {    
273     SymbolTable::iterator I = ST->find(Type::TypeTy);
274     if (I != ST->end()) {    // Get the type plane for Type's
275       SymbolTable::VarMap &Plane = I->second;
276       for (SymbolTable::type_iterator TI = Plane.begin(), TE = Plane.end();
277            TI != TE; ++TI) {
278         // FIXME: This is gross, I'm reaching right into a symbol table and
279         // mucking around with it's internals... but oh well.
280         //
281         TI->second = (Value*)cast<Type>(ConvertType(cast<Type>(TI->second)));
282       }
283     }
284   }
285 }
286
287
288 // removeDeadGlobals - For this pass, all this does is remove the old versions
289 // of the functions and global variables that we no longer need.
290 void MutateStructTypes::removeDeadGlobals(Module &M) {
291   // Prepare for deletion of globals by dropping their interdependencies...
292   for(Module::iterator I = M.begin(); I != M.end(); ++I) {
293     if (GlobalMap.find(I) != GlobalMap.end())
294       I->dropAllReferences();
295   }
296
297   // Run through and delete the functions and global variables...
298 #if 0  // TODO: HANDLE GLOBAL VARIABLES
299   M->getGlobalList().delete_span(M.gbegin(), M.gbegin()+NumGVars/2);
300 #endif
301   for(Module::iterator I = M.begin(); I != M.end();) {
302     if (GlobalMap.find(I) != GlobalMap.end())
303       I = M.getFunctionList().erase(I);
304     else
305       ++I;
306   }
307 }
308
309
310
311 // transformFunction - This transforms the instructions of the function to use
312 // the new types.
313 //
314 void MutateStructTypes::transformFunction(Function *m) {
315   const Function *M = m;
316   map<const GlobalValue*, GlobalValue*>::iterator GMI = GlobalMap.find(M);
317   if (GMI == GlobalMap.end())
318     return;  // Do not affect one of our new functions that we are creating
319
320   Function *NewMeth = cast<Function>(GMI->second);
321
322   // Okay, first order of business, create the arguments...
323   for (Function::aiterator I = m->abegin(), E = m->aend(); I != E; ++I) {
324     Argument *NFA = new Argument(ConvertType(I->getType()), I->getName());
325     NewMeth->getArgumentList().push_back(NFA);
326     LocalValueMap[I] = NFA; // Keep track of value mapping
327   }
328
329
330   // Loop over all of the basic blocks copying instructions over...
331   for (Function::const_iterator BB = M->begin(), BBE = M->end(); BB != BBE;
332        ++BB) {
333     // Create a new basic block and establish a mapping between the old and new
334     BasicBlock *NewBB = cast<BasicBlock>(ConvertValue(BB));
335     NewMeth->getBasicBlockList().push_back(NewBB);  // Add block to function
336
337     // Copy over all of the instructions in the basic block...
338     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
339          II != IE; ++II) {
340
341       const Instruction &I = *II;   // Get the current instruction...
342       Instruction *NewI = 0;
343
344       switch (I.getOpcode()) {
345         // Terminator Instructions
346       case Instruction::Ret:
347         NewI = new ReturnInst(
348                    ConvertValue(cast<ReturnInst>(I).getReturnValue()));
349         break;
350       case Instruction::Br: {
351         const BranchInst &BI = cast<BranchInst>(I);
352         if (BI.isConditional()) {
353           NewI =
354               new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))),
355                              cast<BasicBlock>(ConvertValue(BI.getSuccessor(1))),
356                              ConvertValue(BI.getCondition()));
357         } else {
358           NewI = 
359             new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))));
360         }
361         break;
362       }
363       case Instruction::Switch:
364       case Instruction::Invoke:
365         assert(0 && "Insn not implemented!");
366
367         // Unary Instructions
368       case Instruction::Not:
369         NewI = UnaryOperator::create((Instruction::UnaryOps)I.getOpcode(),
370                                      ConvertValue(I.getOperand(0)));
371         break;
372
373         // Binary Instructions
374       case Instruction::Add:
375       case Instruction::Sub:
376       case Instruction::Mul:
377       case Instruction::Div:
378       case Instruction::Rem:
379         // Logical Operations
380       case Instruction::And:
381       case Instruction::Or:
382       case Instruction::Xor:
383
384         // Binary Comparison Instructions
385       case Instruction::SetEQ:
386       case Instruction::SetNE:
387       case Instruction::SetLE:
388       case Instruction::SetGE:
389       case Instruction::SetLT:
390       case Instruction::SetGT:
391         NewI = BinaryOperator::create((Instruction::BinaryOps)I.getOpcode(),
392                                       ConvertValue(I.getOperand(0)),
393                                       ConvertValue(I.getOperand(1)));
394         break;
395
396       case Instruction::Shr:
397       case Instruction::Shl:
398         NewI = new ShiftInst(cast<ShiftInst>(I).getOpcode(),
399                              ConvertValue(I.getOperand(0)),
400                              ConvertValue(I.getOperand(1)));
401         break;
402
403
404         // Memory Instructions
405       case Instruction::Alloca:
406         NewI = 
407           new AllocaInst(ConvertType(I.getType()),
408                          I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
409         break;
410       case Instruction::Malloc:
411         NewI = 
412           new MallocInst(ConvertType(I.getType()),
413                          I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
414         break;
415
416       case Instruction::Free:
417         NewI = new FreeInst(ConvertValue(I.getOperand(0)));
418         break;
419
420       case Instruction::Load:
421       case Instruction::Store:
422       case Instruction::GetElementPtr: {
423         const MemAccessInst &MAI = cast<MemAccessInst>(I);
424         vector<Value*> Indices(MAI.idx_begin(), MAI.idx_end());
425         const Value *Ptr = MAI.getPointerOperand();
426         Value *NewPtr = ConvertValue(Ptr);
427         if (!Indices.empty()) {
428           const Type *PTy = cast<PointerType>(Ptr->getType())->getElementType();
429           AdjustIndices(cast<CompositeType>(PTy), Indices);
430         }
431
432         if (isa<LoadInst>(I)) {
433           NewI = new LoadInst(NewPtr, Indices);
434         } else if (isa<StoreInst>(I)) {
435           NewI = new StoreInst(ConvertValue(I.getOperand(0)), NewPtr, Indices);
436         } else if (isa<GetElementPtrInst>(I)) {
437           NewI = new GetElementPtrInst(NewPtr, Indices);
438         } else {
439           assert(0 && "Unknown memory access inst!!!");
440         }
441         break;
442       }
443
444         // Miscellaneous Instructions
445       case Instruction::PHINode: {
446         const PHINode &OldPN = cast<PHINode>(I);
447         PHINode *PN = new PHINode(ConvertType(OldPN.getType()));
448         for (unsigned i = 0; i < OldPN.getNumIncomingValues(); ++i)
449           PN->addIncoming(ConvertValue(OldPN.getIncomingValue(i)),
450                     cast<BasicBlock>(ConvertValue(OldPN.getIncomingBlock(i))));
451         NewI = PN;
452         break;
453       }
454       case Instruction::Cast:
455         NewI = new CastInst(ConvertValue(I.getOperand(0)),
456                             ConvertType(I.getType()));
457         break;
458       case Instruction::Call: {
459         Value *Meth = ConvertValue(I.getOperand(0));
460         vector<Value*> Operands;
461         for (unsigned i = 1; i < I.getNumOperands(); ++i)
462           Operands.push_back(ConvertValue(I.getOperand(i)));
463         NewI = new CallInst(Meth, Operands);
464         break;
465       }
466         
467       default:
468         assert(0 && "UNKNOWN INSTRUCTION ENCOUNTERED!\n");
469         break;
470       }
471
472       NewI->setName(I.getName());
473       NewBB->getInstList().push_back(NewI);
474
475       // Check to see if we had to make a placeholder for this value...
476       map<const Value*,Value*>::iterator LVMI = LocalValueMap.find(&I);
477       if (LVMI != LocalValueMap.end()) {
478         // Yup, make sure it's a placeholder...
479         Instruction *I = cast<Instruction>(LVMI->second);
480         assert(I->getOpcode() == Instruction::UserOp1 && "Not a placeholder!");
481
482         // Replace all uses of the place holder with the real deal...
483         I->replaceAllUsesWith(NewI);
484         delete I;                    // And free the placeholder memory
485       }
486
487       // Keep track of the fact the the local implementation of this instruction
488       // is NewI.
489       LocalValueMap[&I] = NewI;
490     }
491   }
492
493   LocalValueMap.clear();
494 }
495
496
497 bool MutateStructTypes::run(Module &M) {
498   processGlobals(M);
499
500   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
501     transformFunction(I);
502
503   removeDeadGlobals(M);
504   return true;
505 }
506