1 //===- MutateStructTypes.cpp - Change struct defns --------------------------=//
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.
9 // This is an interprocedural pass that requires the entire program to do a
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/MutateStructTypes.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iOther.h"
22 #include "llvm/Constants.h"
23 #include "Support/STLExtras.h"
24 #include "Support/Statistic.h"
30 // ValuePlaceHolder - A stupid little marker value. It appears as an
31 // instruction of type Instruction::UserOp1.
33 struct ValuePlaceHolder : public Instruction {
34 ValuePlaceHolder(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
36 virtual Instruction *clone() const { abort(); return 0; }
37 virtual const char *getOpcodeName() const { return "placeholder"; }
41 // ConvertType - Convert from the old type system to the new one...
42 const Type *MutateStructTypes::ConvertType(const Type *Ty) {
43 if (Ty->isPrimitiveType() ||
44 isa<OpaqueType>(Ty)) return Ty; // Don't convert primitives
46 map<const Type *, PATypeHolder>::iterator I = TypeMap.find(Ty);
47 if (I != TypeMap.end()) return I->second;
49 const Type *DestTy = 0;
51 PATypeHolder PlaceHolder = OpaqueType::get();
52 TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
54 switch (Ty->getPrimitiveID()) {
55 case Type::FunctionTyID: {
56 const FunctionType *MT = cast<FunctionType>(Ty);
57 const Type *RetTy = ConvertType(MT->getReturnType());
58 vector<const Type*> ArgTypes;
60 for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
61 E = MT->getParamTypes().end(); I != E; ++I)
62 ArgTypes.push_back(ConvertType(*I));
64 DestTy = FunctionType::get(RetTy, ArgTypes, MT->isVarArg());
67 case Type::StructTyID: {
68 const StructType *ST = cast<StructType>(Ty);
69 const StructType::ElementTypes &El = ST->getElementTypes();
70 vector<const Type *> Types;
72 for (StructType::ElementTypes::const_iterator I = El.begin(), E = El.end();
74 Types.push_back(ConvertType(*I));
75 DestTy = StructType::get(Types);
79 DestTy = ArrayType::get(ConvertType(cast<ArrayType>(Ty)->getElementType()),
80 cast<ArrayType>(Ty)->getNumElements());
83 case Type::PointerTyID:
84 DestTy = PointerType::get(
85 ConvertType(cast<PointerType>(Ty)->getElementType()));
88 assert(0 && "Unknown type!");
92 assert(DestTy && "Type didn't get created!?!?");
94 // Refine our little placeholder value into a real type...
95 ((DerivedType*)PlaceHolder.get())->refineAbstractTypeTo(DestTy);
96 TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
98 return PlaceHolder.get();
102 // AdjustIndices - Convert the indexes specifed by Idx to the new changed form
103 // using the specified OldTy as the base type being indexed into.
105 void MutateStructTypes::AdjustIndices(const CompositeType *OldTy,
108 assert(i < Idx.size() && "i out of range!");
109 const CompositeType *NewCT = cast<CompositeType>(ConvertType(OldTy));
110 if (NewCT == OldTy) return; // No adjustment unless type changes
112 if (const StructType *OldST = dyn_cast<StructType>(OldTy)) {
113 // Figure out what the current index is...
114 unsigned ElNum = cast<ConstantUInt>(Idx[i])->getValue();
115 assert(ElNum < OldST->getElementTypes().size());
117 map<const StructType*, TransformType>::iterator I = Transforms.find(OldST);
118 if (I != Transforms.end()) {
119 assert(ElNum < I->second.second.size());
120 // Apply the XForm specified by Transforms map...
121 unsigned NewElNum = I->second.second[ElNum];
122 Idx[i] = ConstantUInt::get(Type::UByteTy, NewElNum);
126 // Recursively process subtypes...
127 if (i+1 < Idx.size())
128 AdjustIndices(cast<CompositeType>(OldTy->getTypeAtIndex(Idx[i])), Idx, i+1);
132 // ConvertValue - Convert from the old value in the old type system to the new
135 Value *MutateStructTypes::ConvertValue(const Value *V) {
136 // Ignore null values and simple constants..
137 if (V == 0) return 0;
139 if (const Constant *CPV = dyn_cast<Constant>(V)) {
140 if (V->getType()->isPrimitiveType())
143 if (isa<ConstantPointerNull>(CPV))
144 return ConstantPointerNull::get(
145 cast<PointerType>(ConvertType(V->getType())));
146 assert(0 && "Unable to convert constpool val of this type!");
149 // Check to see if this is an out of function reference first...
150 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
151 // Check to see if the value is in the map...
152 map<const GlobalValue*, GlobalValue*>::iterator I = GlobalMap.find(GV);
153 if (I == GlobalMap.end())
154 return (Value*)GV; // Not mapped, just return value itself
158 map<const Value*, Value*>::iterator I = LocalValueMap.find(V);
159 if (I != LocalValueMap.end()) return I->second;
161 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
162 // Create placeholder block to represent the basic block we haven't seen yet
163 // This will be used when the block gets created.
165 return LocalValueMap[V] = new BasicBlock(BB->getName());
168 DEBUG(std::cerr << "NPH: " << V << "\n");
170 // Otherwise make a constant to represent it
171 return LocalValueMap[V] = new ValuePlaceHolder(ConvertType(V->getType()));
175 // setTransforms - Take a map that specifies what transformation to do for each
176 // field of the specified structure types. There is one element of the vector
177 // for each field of the structure. The value specified indicates which slot of
178 // the destination structure the field should end up in. A negative value
179 // indicates that the field should be deleted entirely.
181 void MutateStructTypes::setTransforms(const TransformsType &XForm) {
183 // Loop over the types and insert dummy entries into the type map so that
184 // recursive types are resolved properly...
185 for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
186 E = XForm.end(); I != E; ++I) {
187 const StructType *OldTy = I->first;
188 TypeMap.insert(std::make_pair(OldTy, OpaqueType::get()));
191 // Loop over the type specified and figure out what types they should become
192 for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
193 E = XForm.end(); I != E; ++I) {
194 const StructType *OldTy = I->first;
195 const vector<int> &InVec = I->second;
197 assert(OldTy->getElementTypes().size() == InVec.size() &&
198 "Action not specified for every element of structure type!");
200 vector<const Type *> NewType;
202 // Convert the elements of the type over, including the new position mapping
204 vector<int>::const_iterator TI = find(InVec.begin(), InVec.end(), Idx);
205 while (TI != InVec.end()) {
206 unsigned Offset = TI-InVec.begin();
207 const Type *NewEl = ConvertType(OldTy->getContainedType(Offset));
208 assert(NewEl && "Element not found!");
209 NewType.push_back(NewEl);
211 TI = find(InVec.begin(), InVec.end(), ++Idx);
214 // Create a new type that corresponds to the destination type
215 PATypeHolder NSTy = StructType::get(NewType);
217 // Refine the old opaque type to the new type to properly handle recursive
220 const Type *OldTypeStub = TypeMap.find(OldTy)->second.get();
221 ((DerivedType*)OldTypeStub)->refineAbstractTypeTo(NSTy);
223 // Add the transformation to the Transforms map.
224 Transforms.insert(std::make_pair(OldTy,
225 std::make_pair(cast<StructType>(NSTy.get()), InVec)));
227 DEBUG(std::cerr << "Mutate " << OldTy << "\nTo " << NSTy << "\n");
231 void MutateStructTypes::clearTransforms() {
235 assert(LocalValueMap.empty() &&
236 "Local Value Map should always be empty between transformations!");
239 // processGlobals - This loops over global constants defined in the
240 // module, converting them to their new type.
242 void MutateStructTypes::processGlobals(Module &M) {
243 // Loop through the functions in the module and create a new version of the
244 // function to contained the transformed code. Also, be careful to not
245 // process the values that we add.
247 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
248 if (!I->isExternal()) {
249 const FunctionType *NewMTy =
250 cast<FunctionType>(ConvertType(I->getFunctionType()));
252 // Create a new function to put stuff into...
253 Function *NewMeth = new Function(NewMTy, I->getLinkage(), I->getName());
255 I->setName("OLD."+I->getName());
257 // Insert the new function into the function list... to be filled in later
258 M.getFunctionList().push_back(NewMeth);
260 // Keep track of the association...
261 GlobalMap[I] = NewMeth;
264 // TODO: HANDLE GLOBAL VARIABLES
266 // Remap the symbol table to refer to the types in a nice way
268 SymbolTable &ST = M.getSymbolTable();
269 SymbolTable::iterator I = ST.find(Type::TypeTy);
270 if (I != ST.end()) { // Get the type plane for Type's
271 SymbolTable::VarMap &Plane = I->second;
272 for (SymbolTable::type_iterator TI = Plane.begin(), TE = Plane.end();
274 // FIXME: This is gross, I'm reaching right into a symbol table and
275 // mucking around with it's internals... but oh well.
277 TI->second = (Value*)cast<Type>(ConvertType(cast<Type>(TI->second)));
283 // removeDeadGlobals - For this pass, all this does is remove the old versions
284 // of the functions and global variables that we no longer need.
285 void MutateStructTypes::removeDeadGlobals(Module &M) {
286 // Prepare for deletion of globals by dropping their interdependencies...
287 for(Module::iterator I = M.begin(); I != M.end(); ++I) {
288 if (GlobalMap.find(I) != GlobalMap.end())
289 I->dropAllReferences();
292 // Run through and delete the functions and global variables...
293 #if 0 // TODO: HANDLE GLOBAL VARIABLES
294 M->getGlobalList().delete_span(M.gbegin(), M.gbegin()+NumGVars/2);
296 for(Module::iterator I = M.begin(); I != M.end();) {
297 if (GlobalMap.find(I) != GlobalMap.end())
298 I = M.getFunctionList().erase(I);
306 // transformFunction - This transforms the instructions of the function to use
309 void MutateStructTypes::transformFunction(Function *m) {
310 const Function *M = m;
311 map<const GlobalValue*, GlobalValue*>::iterator GMI = GlobalMap.find(M);
312 if (GMI == GlobalMap.end())
313 return; // Do not affect one of our new functions that we are creating
315 Function *NewMeth = cast<Function>(GMI->second);
317 // Okay, first order of business, create the arguments...
318 for (Function::aiterator I = m->abegin(), E = m->aend(),
319 DI = NewMeth->abegin(); I != E; ++I, ++DI) {
320 DI->setName(I->getName());
321 LocalValueMap[I] = DI; // Keep track of value mapping
325 // Loop over all of the basic blocks copying instructions over...
326 for (Function::const_iterator BB = M->begin(), BBE = M->end(); BB != BBE;
328 // Create a new basic block and establish a mapping between the old and new
329 BasicBlock *NewBB = cast<BasicBlock>(ConvertValue(BB));
330 NewMeth->getBasicBlockList().push_back(NewBB); // Add block to function
332 // Copy over all of the instructions in the basic block...
333 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
336 const Instruction &I = *II; // Get the current instruction...
337 Instruction *NewI = 0;
339 switch (I.getOpcode()) {
340 // Terminator Instructions
341 case Instruction::Ret:
342 NewI = new ReturnInst(
343 ConvertValue(cast<ReturnInst>(I).getReturnValue()));
345 case Instruction::Br: {
346 const BranchInst &BI = cast<BranchInst>(I);
347 if (BI.isConditional()) {
349 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))),
350 cast<BasicBlock>(ConvertValue(BI.getSuccessor(1))),
351 ConvertValue(BI.getCondition()));
354 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))));
358 case Instruction::Switch:
359 case Instruction::Invoke:
360 assert(0 && "Insn not implemented!");
362 // Binary Instructions
363 case Instruction::Add:
364 case Instruction::Sub:
365 case Instruction::Mul:
366 case Instruction::Div:
367 case Instruction::Rem:
368 // Logical Operations
369 case Instruction::And:
370 case Instruction::Or:
371 case Instruction::Xor:
373 // Binary Comparison Instructions
374 case Instruction::SetEQ:
375 case Instruction::SetNE:
376 case Instruction::SetLE:
377 case Instruction::SetGE:
378 case Instruction::SetLT:
379 case Instruction::SetGT:
380 NewI = BinaryOperator::create((Instruction::BinaryOps)I.getOpcode(),
381 ConvertValue(I.getOperand(0)),
382 ConvertValue(I.getOperand(1)));
385 case Instruction::Shr:
386 case Instruction::Shl:
387 NewI = new ShiftInst(cast<ShiftInst>(I).getOpcode(),
388 ConvertValue(I.getOperand(0)),
389 ConvertValue(I.getOperand(1)));
393 // Memory Instructions
394 case Instruction::Alloca:
397 ConvertType(cast<PointerType>(I.getType())->getElementType()),
398 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
400 case Instruction::Malloc:
403 ConvertType(cast<PointerType>(I.getType())->getElementType()),
404 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
407 case Instruction::Free:
408 NewI = new FreeInst(ConvertValue(I.getOperand(0)));
411 case Instruction::Load:
412 NewI = new LoadInst(ConvertValue(I.getOperand(0)));
414 case Instruction::Store:
415 NewI = new StoreInst(ConvertValue(I.getOperand(0)),
416 ConvertValue(I.getOperand(1)));
418 case Instruction::GetElementPtr: {
419 const GetElementPtrInst &GEP = cast<GetElementPtrInst>(I);
420 vector<Value*> Indices(GEP.idx_begin(), GEP.idx_end());
421 if (!Indices.empty()) {
423 cast<PointerType>(GEP.getOperand(0)->getType())->getElementType();
424 AdjustIndices(cast<CompositeType>(PTy), Indices);
427 NewI = new GetElementPtrInst(ConvertValue(GEP.getOperand(0)), Indices);
431 // Miscellaneous Instructions
432 case Instruction::PHINode: {
433 const PHINode &OldPN = cast<PHINode>(I);
434 PHINode *PN = new PHINode(ConvertType(OldPN.getType()));
435 for (unsigned i = 0; i < OldPN.getNumIncomingValues(); ++i)
436 PN->addIncoming(ConvertValue(OldPN.getIncomingValue(i)),
437 cast<BasicBlock>(ConvertValue(OldPN.getIncomingBlock(i))));
441 case Instruction::Cast:
442 NewI = new CastInst(ConvertValue(I.getOperand(0)),
443 ConvertType(I.getType()));
445 case Instruction::Call: {
446 Value *Meth = ConvertValue(I.getOperand(0));
447 vector<Value*> Operands;
448 for (unsigned i = 1; i < I.getNumOperands(); ++i)
449 Operands.push_back(ConvertValue(I.getOperand(i)));
450 NewI = new CallInst(Meth, Operands);
455 assert(0 && "UNKNOWN INSTRUCTION ENCOUNTERED!\n");
459 NewI->setName(I.getName());
460 NewBB->getInstList().push_back(NewI);
462 // Check to see if we had to make a placeholder for this value...
463 map<const Value*,Value*>::iterator LVMI = LocalValueMap.find(&I);
464 if (LVMI != LocalValueMap.end()) {
465 // Yup, make sure it's a placeholder...
466 Instruction *I = cast<Instruction>(LVMI->second);
467 assert(I->getOpcode() == Instruction::UserOp1 && "Not a placeholder!");
469 // Replace all uses of the place holder with the real deal...
470 I->replaceAllUsesWith(NewI);
471 delete I; // And free the placeholder memory
474 // Keep track of the fact the the local implementation of this instruction
476 LocalValueMap[&I] = NewI;
480 LocalValueMap.clear();
484 bool MutateStructTypes::run(Module &M) {
487 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
488 transformFunction(I);
490 removeDeadGlobals(M);