Reputation: 8727
I have successfully build the sample code
Now my I have a requirement that if I have a sample code like below:
int inc(int& p)
{
p++;
printf("In inc [%d]\n", p);
return p;
}
int main()
{
int i = 0;
int y,z;
if(y == 0)
print(inc(i) , inc(i));
else
{
print(inc(i) , inc(i));
}
printf("y = [%d] z = [%d]\n", y , z);
return 0;
}
The code should transform to
int inc(int& p)
{
p++;
printf("%s %d", __FILE__, __LINE__);
printf("In inc [%d]\n", p);
printf("%s %d", __FILE__, __LINE__);
return p;
}
int main()
{
int i = 0;
printf("%s %d", __FILE__, __LINE__);
int y,z;
printf("%s %d", __FILE__, __LINE__);
if(y == 0)
print(inc(i) , inc(i));
else
{
print(inc(i) , inc(i));
printf("%s %d", __FILE__, __LINE__);
}
printf("y = [%d] z = [%d]\n", y , z);
printf("%s %d", __FILE__, __LINE__);
return 0;
}
I tried with following code changes:
bool VisitStmt(Stmt *s) {
// Only care about If statements.
if (isa<CompoundStmt>(s)) {
CompoundStmt *Statement = cast<CompoundStmt>(s);
TheRewriter.InsertText(Statement->getLocStart(),
"printf(\"%s %d\", __FILE__, __LINE__);\n",
true, true);
}
But the output comes as :
// Begin function inc returning int
int inc(int& p)
printf("%s %d", __FILE__, __LINE__);
{
p++;
printf("In inc [%d]\n", p);
return p;
}
// End function inc
// Begin function main returning int
int main()
printf("%s %d", __FILE__, __LINE__);
{
int i = 0;
int y,z;
if(y == 0)
print(inc(i) , inc(i));
else
{
print(inc(i) , inc(i));
}
printf("y = [%d] z = [%d]\n", y , z);
return 0;
}
// End function main
Please let me know how can I achieve the objective?
I also get output like:
test.cpp:4:26: error: use of undeclared identifier 'p'
printf("In inc [%d]\n", p);
^
test.cpp:5:9: error: use of undeclared identifier 'p'
return p;
How can I stop the code rendering the same? Its just that the statements in compound block should add extra statements.
Upvotes: 3
Views: 1531
Reputation: 153
If i understand correctly, and to add to @vonbrand, you should not use the Compound statement's start and end as they represent the block of statements. Instead, you should just replace the above with inserting the text (Print statements) in the generic VisitStmt body. Note that i am unclear as to what you are trying to accomplish, since you do not have a Print statement immediately after your if/else statement. I think it would help if you just listed down which statements you want to process, and then have "isa" conditionals in your visitor implementation deal with each case. That way, you are actually using the visitor pattern correctly. Hope that helps!
Upvotes: 0
Reputation: 11831
If you look at the generated code, it is a illegal mess. A wonder the compiler doesn't scream your ears off ;-)
Clearly LLVM (with your VisitStmt) considers just "{...}" as "compound statement", and the output happens before the statement itself. Check carefully when such interspersed actions are done (I suspect either just before or just after, not in the middle).
Upvotes: 1