[cfe-dev] Clang does not rewrite expressions with NULL
Douglas Gregor
dgregor at apple.com
Mon Jun 27 09:02:36 PDT 2011
On Jun 26, 2011, at 3:44 PM, Andrey Tarasevich wrote:
> Hello!
>
> I'm currently doing some source-to-source manipulations mainly on C
> code. I found a problem with NULL macro. I'm using Ubuntu 10.04 64bit.
>
> Here is a simple code I'm parsing
>
> #include <stdlib.h>
>
> int main()
> {
> int n;
> int* p;
> if(p == NULL)
> n = 0;
> else
> n = 1;
> }
>
>
> I initialize the compiler in the following way
>
> void startProcessing(string inFile, string outFile)
> {
> auto_ptr<CompilerInstance> compiler(new CompilerInstance);
> compiler->createDiagnostics(0, NULL);
>
> const char *args[] =
> {
> "-cc1",
> "/home/sevich/master/list.c"
> };
>
> clang::CompilerInvocation::CreateFromArgs(
> compiler->getInvocation(),
> args,
> args + 2,
> compiler->getDiagnostics());
>
> llvm::OwningPtr<clang::ASTFrontendAction> action(new ASTMutationAction(inFile,
> outFile));
> compiler->ExecuteAction(*action);
> }
>
> The ASTConsumer I use is a modified version of the RewriteOBjC class.
> The main work it does is negation of the if statement condition in the
> following way
>
> void RewriteIfStatement(clang::IfStmt *is)
> {
> Expr* oldCond = is->getCond();
> ParenExpr* pe = new (context) ParenExpr(is->getLocStart(),
> is->getLocEnd(), oldCond);
> Expr* uo = new (context) UnaryOperator(pe, UO_LNot,
> context->getPointerType(pe->getType()),
> VK_RValue,
> OK_Ordinary,
> SourceLocation());
> bool result = rewriter.ReplaceStmt(oldCond, uo);
> }
>
> So the problem is whenever I meet the NULL in the if condition it
> never gets rewritten. I found out, that source range of the condition
> expression with NULL is wrong, for instance It starts with 373 and
> ends at 2147677727, what is obviously wrong and rewriter does not do
> anything. Clang didn't signalize any errors for this code sample.
>
> So my question is following. Am I doing something wrong or this is a
> problem of the clang?
Neither. Clang's source locations keep track of macro instantiation history. The 2147677727 location is the encoding for a macro instantiation; see the SourceManager class and (especially) SourceManager::getInstantiationLoc().
> And one more question also. Is it possible to force clang to process
> code as C-code? Since I only saw a options for C++ and ObjC.
-x c
- Doug
More information about the cfe-dev
mailing list