1 //===-- EmitFunctions.cpp - interface to insert instrumentation -----------===//
3 // This inserts a global constant table with function pointers all along
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/Module.h"
10 #include "llvm/Pass.h"
11 #include "llvm/Support/CFG.h"
20 struct EmitFunctionTable : public Pass {
24 RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
27 char doDFS(BasicBlock * node,std::map<BasicBlock *, Color > &color){
30 for(succ_iterator vl = succ_begin(node), ve = succ_end(node); vl != ve; ++vl){
34 if(color[BB]!=GREY && color[BB]!=BLACK){
35 if(!doDFS(BB, color)){
41 else if(color[BB]==GREY)
50 char hasBackEdge(Function *F){
51 std::map<BasicBlock *, Color > color;
52 return doDFS(F->begin(), color);
55 // Per Module pass for inserting function table
56 bool EmitFunctionTable::run(Module &M){
57 std::vector<const Type*> vType;
59 std::vector<Constant *> vConsts;
60 std::vector<Constant *> sBCons;
62 unsigned int counter = 0;
63 for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
64 if (!MI->isExternal()) {
65 vType.push_back(MI->getType());
69 vConsts.push_back(ConstantPointerRef::get(MI));
70 sBCons.push_back(ConstantInt::get(Type::SByteTy, hasBackEdge(MI)));
75 StructType *sttype = StructType::get(vType);
76 ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
78 GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
79 GlobalValue::ExternalLinkage,
80 cstruct, "llvmFunctionTable");
81 M.getGlobalList().push_back(gb);
83 ConstantArray *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
87 GlobalVariable *funcArray = new GlobalVariable(constArray->getType(), true,
88 GlobalValue::ExternalLinkage,
89 constArray, "llvmSimpleFunction");
91 M.getGlobalList().push_back(funcArray);
93 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
94 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
95 GlobalValue::ExternalLinkage,
96 cnst, "llvmFunctionCount");
97 M.getGlobalList().push_back(fnCount);
98 return true; // Always modifies program