[cfe-dev] CFGElement to CFGStmt

David Blaikie dblaikie at gmail.com
Sun Mar 24 22:04:51 PDT 2013

On Sun, Mar 24, 2013 at 9:29 PM, anikau31 <amkaushi at uwaterloo.ca> wrote:
> Hi,
> I am trying to cast CFGElement* to CFGStmt*. I remember using the following
> code a while back:
> CFGStmt *cs = bit->getAs<CFGStmt>()

The code looked more like this, I believe:

-  if (CFGStmt CS = E.getAs<CFGStmt>()) {
-    const Stmt *S = CS.getStmt();
+  if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
+    const Stmt *S = CS->getStmt();

Notice in the old code you didn't convert to a pointer, you converted
to a concrete CFGStmt value.

> where bit is a const_iterator (I am
> iterating through the elements of a CFG block). I get the following error
> "error: cannot convert ‘llvm::Optional<clang::CFGStmt>’ to ‘const
> clang::CFGStmt*’ in initialization". I remember the above code used to work
> fine a while back. Is there a work around and why the change?


There were several issues that lead to this:

1) the llvm::cast machinery was being abused for value conversions
rather than pointer/reference conversions - this created undefined
behavior (casting pointers/references to base objects to derived types
& then calling derived copy ctors with those base objects)
2) CFG* types were boolean testable to check for the "invalid" state.
It was better to enshrine this invalid state in the type system
explicitly through the use of Optional<T> rather than to let every
CFG* object be potentially invalid

More information about the cfe-dev mailing list