How do I implement AssemblyAnnotationWriter to print metadata - llvm

I am learning how to write passes in llvm. I am trying to implement
virtual void emitFunctionAnnot(const Function *, formatted_raw_ostream &){}
as given at http://llvm.org/doxygen/AssemblyAnnotationWriter_8h_source.html
to print #[uses]=1 before start of a function.
The code below works if I manually call emitFunctionAnnot(&F, ferrs()); inside runOnFunction() method, which(emitFunctionAnnot) I have overridden. However shouldn't it work without calling it manullay because that's the whole point of overriding it. I believe I am doing something wrong while overriding. I have spent countless hours trying to debug it. I would appreciate any help.
This is what I have so far.
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/DebugInfo.h"
#include "llvm/Assembly/AssemblyAnnotationWriter.h"
#include <ostream>
#include <fstream>
#include <iostream>
#include <stdlib.h>
using namespace llvm;
namespace {
class CommentWriter : public AssemblyAnnotationWriter {
public:
virtual void emitFunctionAnnot(const Function *F,
formatted_raw_ostream &OS) {
OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
OS << '\n';
}
};
class FunctionInfo : public FunctionPass, public AssemblyAnnotationWriter{
public:
static char ID;
FunctionInfo() : FunctionPass(ID) {}
void emitFunctionAnnot(const Function *F, formatted_raw_ostream &OS) {
errs() << "CALLED";
OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
OS << '\n';
}
virtual bool runOnFunction(Function &F) {
// emitFunctionAnnot(&F, ferrs());
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I){
Instruction &II = *I;
errs() << *I;
}
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
char FunctionInfo::ID = 0;
// clang -c -Xclang -load -Xclang ./FunctionInfo.so loop.c
static void registerMyPass(const PassManagerBuilder &,
PassManagerBase &PM) {
PM.add(new FunctionInfo());
}
RegisterStandardPasses
RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
registerMyPass);
RegisterPass<FunctionInfo> X("function-info", "Function Information");
}

Annotations exist only as comments in an LLVM IR printout. They are not actually a part of the IR, and consequently they are not something you "add" in a pass.
The way to use an AssemblyAnnotationWriter is to pass it as the 2nd argument to a print function (e.g. Module::print). You can do that inside a pass, but it's not something that is done automatically for you. Specifically, making the pass inherit from AssemblyAnnotationWriter is nonsensical - the first approach you've shown in your question, inheriting from it in a separate class, is the correct approach.
In short, if you want a printout of the module in your pass, call print on it. If you want to add comments to the printout, call the same print but pass an instance of your CommentWriter as the 2nd argument.

Related

Access variable from another class (in C++)

This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.

cannot call member function without object for vector of shared_ptr of object

#include <boost/ref.hpp>
//#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/mem_fn.hpp>
using namespace std;
using namespace boost::lambda;
class Base {
public:
Base () {}
bool toBeRemoved() const {
return true;
}
};
class status : public Base {
std::string name_;
bool ok_;
public:
status(const std::string& name):name_(name),ok_(true) {}
void break_it() {
ok_=false;
}
bool is_broken() const {
return ok_;
}
void report() const {
std::cout << name_ << " is " <<
(ok_ ? "working nominally":"terribly broken") << '\n';
}
std::string getStatus() const {
return ok_ ? "1" : "0";
}
};
class some_class {
public:
int test() {
std::vector<boost::shared_ptr<status> > s_statuses = getStatus(); //some func
std::set<string> s;
std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::lambda::bind(boost::mem_fn(&status::getStatus), boost::ref(*_1)));
// approach #2
// std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::lambda::bind(boost::mem_fn(&status::getStatus), boost::ref(*_1), _1));
// approach #3
// std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::bind(&status::getStatus), _1));
std::copy(s.begin(), s.end(), ostream_iterator<string>(std::cout, "-"));
std::cout << endl;
return 0;
}
}
For all the approaches above, I am getting the error "can call member function without object" on the line containing the bind call. I have tried using boost::lambda::bind and boost::bind as well. Though this way of using bind works if objects are defined, for example in main function. I assume I am making some silly mistake here, but I am not able to figure out why these all approaches working, or it could be the case that this is not the right way of doing at all.
Could someone please help me resolve this on how to properly use boost bind for non-static member of class which are stored in stl containers ?
Thanks,
You should just need to use boost::mem_fn. (Note, you could also use std::mem_fn if available.)
std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), std::mem_fn(&status::getStatus));

Performance of stdext::hash_value() defined in std::hash_set

Firstly,I want to inform you that my overall/main target is to execute certain functions using their function name(string) as an argument,I defined a function as below:
(I want to generate a unique number for each string data that I inserted as argument to a function)
#include <iostream>
#include <string>
#include <hash_set>
using namespace std;
void Func_Execution(string &s){
int k=stdext::hash_value(s);
#if(_MSC_VER ==1500)
switch (k)
{
case -336300864: GETBATTERYCALLSIGNS();
break;
case -1859542241:GETGUNIDS();
break;
case 323320073:Foo(); // here int k=323320073 for string s="Foo"
break;
case 478877555:Bar();
break;
defalut :Exit();
break;
}
#endif
}
Here I call Func_Execution function as below:
void main(){
string s="Foo";
Func_Execution(s);
}
I want to know that is there any efficient(considering perfomance/time consuming) and effective mechanism to generate a unique numerical value for certain string(character pattern) rather than using stdext::hash_value() function?(Also notice I want to implement switch-case too)
Have you considered something like
#include <functional>
#include <iostream>
#include <unordered_map>
#include <string>
using std::cout;
using std::endl;
using std::function;
using std::string;
using std::unordered_map;
class Registry {
public:
static void Execute(const string& function) {
if (functions_.find(function) != functions_.end()) {
functions_[function]();
}
}
static int Register(const string& function_name, function<void()> f) {
functions_.emplace(function_name, f);
return functions_.size();
}
static void Dump() {
for (auto& i : functions_) {
cout << i.first << endl;
}
}
private:
Registry() {};
static unordered_map<string, function<void()>> functions_;
};
unordered_map<string, function<void()>> Registry::functions_;
#define REGISTER_FUNCTION(F) \
namespace { \
const int REGISTERED__##F = Registry::Register(#F, &F); \
}
void foo() {
cout << "foo" << endl;
}
REGISTER_FUNCTION(foo);
void bar() {
cout << "bar" << endl;
}
REGISTER_FUNCTION(bar);
int main() {
Registry::Execute("foo");
Registry::Execute("foo");
Registry::Execute("unknown");
Registry::Dump();
return 0;
}
It should serve well for your use case. I just hacked it together, there's probably a bug somewhere, but it compiles and runs (c++11).
Don't use hash_value() for fingerprinting (which is what you are describing). If you really know all your possible strings ahead of time, use your own perfect hash function and then measure the results to see if it is worth it.

A pointer to a bound function may only be used to call the function

I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.

Print the type of a parameter (ParmVarDecl) with clang API

I need to print the type of a parameter in a C++ source file using the clang API.
If I have a parameter representation in clang (ParmVarDecl* param) I can print the name of the parameter using param->getNameAsString(). I would need a method param->getTypeAsString(), but there is no such method. So is there another way to do this task?
Got the answer to my question in the llvm irc:
There is a method std::string clang::QualType::getAsString(SplitQualType split)
So this does work for me:
ParmVarDecl* param = *someParameter;
cout << QualType::getAsString(param->getType().split()) << endl;
You can use typeid to get the name of any type. Although it will vary from compiler to compiler, and may not be a pretty name.
#include <iostream>
#include <typeinfo>
struct MyStruct { };
int main()
{
std::cout << typeid(MyStruct).name() << std::endl;
}
If you need to do this for a lot of classes, you could make the call part of a base class, then any class that needs the functionality can just inherit from it.
#include <iostream>
#include <typeinfo>
class NamedClass
{
public:
virtual ~NamedClass() { }
std::string getNameAsString()
{
return typeid(*this).name();
}
};
class MyStruct : public NamedClass
{
};
int main()
{
MyStruct ms;
std::cout << ms.getNameAsString() << std::endl;
}