1 //===-- EmitFunctions.cpp - interface to insert instrumentation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This inserts a global constant table with function pointers all along
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Support/CFG.h"
29 struct EmitFunctionTable : public Pass {
33 RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
36 char doDFS(BasicBlock * node,std::map<BasicBlock *, Color > &color){
39 for(succ_iterator vl = succ_begin(node), ve = succ_end(node); vl != ve; ++vl){
43 if(color[BB]!=GREY && color[BB]!=BLACK){
44 if(!doDFS(BB, color)){
50 else if(color[BB]==GREY)
59 char hasBackEdge(Function *F){
60 std::map<BasicBlock *, Color > color;
61 return doDFS(F->begin(), color);
64 // Per Module pass for inserting function table
65 bool EmitFunctionTable::run(Module &M){
66 std::vector<const Type*> vType;
68 std::vector<Constant *> vConsts;
69 std::vector<Constant *> sBCons;
71 unsigned int counter = 0;
72 for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
73 if (!MI->isExternal()) {
74 vType.push_back(MI->getType());
78 vConsts.push_back(ConstantPointerRef::get(MI));
79 sBCons.push_back(ConstantInt::get(Type::SByteTy, hasBackEdge(MI)));
84 StructType *sttype = StructType::get(vType);
85 ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
87 GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
88 GlobalValue::ExternalLinkage,
89 cstruct, "llvmFunctionTable");
90 M.getGlobalList().push_back(gb);
92 ConstantArray *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
96 GlobalVariable *funcArray = new GlobalVariable(constArray->getType(), true,
97 GlobalValue::ExternalLinkage,
98 constArray, "llvmSimpleFunction");
100 M.getGlobalList().push_back(funcArray);
102 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
103 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
104 GlobalValue::ExternalLinkage,
105 cnst, "llvmFunctionCount");
106 M.getGlobalList().push_back(fnCount);
107 return true; // Always modifies program
110 } // End llvm namespace