2012-09-05 09:37:39 +00:00
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
# include "IncrementalParser.h"
# include "ASTDumper.h"
# include "ASTNodeEraser.h"
# include "DeclCollector.h"
# include "DeclExtractor.h"
# include "DynamicLookup.h"
2012-10-15 13:42:09 +00:00
# include "ReturnSynthesizer.h"
2012-09-05 09:37:39 +00:00
# include "ValuePrinterSynthesizer.h"
# include "cling/Interpreter/CIFactory.h"
# include "cling/Interpreter/Interpreter.h"
2012-10-02 10:30:25 +00:00
# include "cling/Interpreter/InterpreterCallbacks.h"
2012-10-02 10:34:22 +00:00
# include "cling/Interpreter/Transaction.h"
2012-09-05 09:37:39 +00:00
# include "clang/AST/ASTContext.h"
# include "clang/AST/Decl.h"
# include "clang/AST/DeclGroup.h"
# include "clang/Basic/FileManager.h"
# include "clang/CodeGen/ModuleBuilder.h"
# include "clang/Parse/Parser.h"
# include "clang/Lex/Preprocessor.h"
# include "clang/Frontend/CompilerInstance.h"
# include "clang/Serialization/ASTWriter.h"
# include "llvm/LLVMContext.h"
# include "llvm/Module.h"
# include "llvm/Support/CrashRecoveryContext.h"
# include "llvm/Support/MemoryBuffer.h"
# include "llvm/Support/raw_os_ostream.h"
# include <ctime>
# include <iostream>
# include <stdio.h>
# include <sstream>
using namespace clang ;
namespace cling {
IncrementalParser : : IncrementalParser ( Interpreter * interp ,
int argc , const char * const * argv ,
const char * llvmdir ) :
2012-10-19 14:17:20 +00:00
m_Interpreter ( interp ) , m_Consumer ( 0 ) , m_FirstTransaction ( 0 ) ,
m_LastTransaction ( 0 ) {
2012-09-05 09:37:39 +00:00
CompilerInstance * CI
= CIFactory : : createCI ( llvm : : MemoryBuffer : : getMemBuffer ( " " , " CLING " ) ,
argc , argv , llvmdir ) ;
assert ( CI & & " CompilerInstance is (null)! " ) ;
m_Consumer = dyn_cast < DeclCollector > ( & CI - > getASTConsumer ( ) ) ;
assert ( m_Consumer & & " Expected ChainedConsumer! " ) ;
m_CI . reset ( CI ) ;
if ( CI - > getFrontendOpts ( ) . ProgramAction ! = clang : : frontend : : ParseSyntaxOnly ) {
m_CodeGen . reset ( CreateLLVMCodeGen ( CI - > getDiagnostics ( ) , " cling input " ,
CI - > getCodeGenOpts ( ) ,
* m_Interpreter - > getLLVMContext ( )
) ) ;
}
CreateSLocOffsetGenerator ( ) ;
// Add transformers to the IncrementalParser, which owns them
2012-09-18 12:46:30 +00:00
m_TTransformers . push_back ( new EvaluateTSynthesizer ( & CI - > getSema ( ) ) ) ;
2012-09-05 09:37:39 +00:00
2012-09-18 13:13:22 +00:00
m_TTransformers . push_back ( new ValuePrinterSynthesizer ( & CI - > getSema ( ) , 0 ) ) ;
2012-10-15 13:42:09 +00:00
m_TTransformers . push_back ( new ReturnSynthesizer ( & CI - > getSema ( ) ) ) ;
2012-09-05 09:37:39 +00:00
m_TTransformers . push_back ( new ASTDumper ( ) ) ;
2012-10-19 10:46:53 +00:00
m_TTransformers . push_back ( new DeclExtractor ( & getCI ( ) - > getSema ( ) ) ) ;
2012-09-05 09:37:39 +00:00
m_Parser . reset ( new Parser ( CI - > getPreprocessor ( ) , CI - > getSema ( ) ,
false /*skipFuncBodies*/ ) ) ;
CI - > getPreprocessor ( ) . EnterMainSourceFile ( ) ;
// Initialize the parser after we have entered the main source file.
m_Parser - > Initialize ( ) ;
// Perform initialization that occurs after the parser has been initialized
// but before it parses anything. Initializes the consumers too.
CI - > getSema ( ) . Initialize ( ) ;
}
IncrementalParser : : ~ IncrementalParser ( ) {
2012-11-20 13:21:00 +00:00
if ( hasCodeGenerator ( ) ) {
getCodeGenerator ( ) - > ReleaseModule ( ) ;
}
const Transaction * T = getFirstTransaction ( ) ;
const Transaction * nextT = 0 ;
while ( T ) {
nextT = T - > getNext ( ) ;
delete T ;
T = nextT ;
}
for ( size_t i = 0 ; i < m_TTransformers . size ( ) ; + + i )
delete m_TTransformers [ i ] ;
2012-09-05 09:37:39 +00:00
}
2012-11-14 22:06:58 +00:00
Transaction * IncrementalParser : : beginTransaction ( const CompilationOptions &
Opts ) {
2012-09-05 09:37:39 +00:00
llvm : : Module * M = 0 ;
if ( hasCodeGenerator ( ) )
M = getCodeGenerator ( ) - > GetModule ( ) ;
Transaction * NewCurT = new Transaction ( Opts , M ) ;
Transaction * OldCurT = m_Consumer - > getTransaction ( ) ;
m_Consumer - > setTransaction ( NewCurT ) ;
// If we are in the middle of transaction and we see another begin
// transaction - it must be nested transaction.
if ( OldCurT & & ! OldCurT - > isCompleted ( ) ) {
OldCurT - > addNestedTransaction ( NewCurT ) ; // takes the ownership
2012-11-14 22:06:58 +00:00
return NewCurT ;
2012-09-05 09:37:39 +00:00
}
2012-10-19 14:17:20 +00:00
if ( ! m_FirstTransaction ) {
m_FirstTransaction = NewCurT ;
m_LastTransaction = NewCurT ;
}
else {
m_LastTransaction - > setNext ( NewCurT ) ;
m_LastTransaction = NewCurT ;
}
2012-11-14 22:06:58 +00:00
return NewCurT ;
2012-09-05 09:37:39 +00:00
}
2012-11-14 22:06:58 +00:00
Transaction * IncrementalParser : : endTransaction ( ) const {
2012-09-05 09:37:39 +00:00
Transaction * CurT = m_Consumer - > getTransaction ( ) ;
CurT - > setCompleted ( ) ;
const DiagnosticsEngine & Diags = getCI ( ) - > getSema ( ) . getDiagnostics ( ) ;
//TODO: Make the enum orable.
if ( Diags . getNumWarnings ( ) > 0 )
CurT - > setIssuedDiags ( Transaction : : kWarnings ) ;
if ( Diags . hasErrorOccurred ( ) | | Diags . hasFatalErrorOccurred ( ) )
CurT - > setIssuedDiags ( Transaction : : kErrors ) ;
2012-11-13 23:52:30 +00:00
if ( CurT - > hasNestedTransactions ( ) ) {
for ( Transaction : : const_nested_iterator I = CurT - > nested_decls_begin ( ) ,
E = CurT - > nested_decls_end ( ) ; I ! = E ; + + I )
2012-11-14 22:06:58 +00:00
assert ( ( * I ) - > isCompleted ( ) & & " Nested transaction not completed!? " ) ;
2012-11-13 23:52:30 +00:00
}
2012-09-05 09:37:39 +00:00
if ( CurT - > isNestedTransaction ( ) ) {
2012-11-13 23:52:30 +00:00
// TODO: Add proper logic in the case where there are multiple nested
// transaction. This now won't handle the case where there are more than
// one level 1 nested transactions.
m_Consumer - > setTransaction ( CurT - > getParent ( ) ) ;
2012-09-05 09:37:39 +00:00
}
2012-11-14 22:06:58 +00:00
return CurT ;
2012-09-05 09:37:39 +00:00
}
2012-11-14 22:06:58 +00:00
void IncrementalParser : : commitTransaction ( Transaction * T ) {
//Transaction* CurT = m_Consumer->getTransaction();
assert ( T - > isCompleted ( ) & & " Transaction not ended!? " ) ;
2012-09-05 09:37:39 +00:00
// Check for errors...
2012-11-14 22:06:58 +00:00
if ( T - > getIssuedDiags ( ) = = Transaction : : kErrors ) {
rollbackTransaction ( T ) ;
2012-09-05 09:37:39 +00:00
return ;
}
2012-11-14 22:06:58 +00:00
if ( T - > hasNestedTransactions ( ) ) {
for ( Transaction : : const_nested_iterator I = T - > nested_decls_begin ( ) ,
E = T - > nested_decls_end ( ) ; I ! = E ; + + I )
commitTransaction ( * I ) ;
}
2012-09-05 09:37:39 +00:00
// We are sure it's safe to pipe it through the transformers
2012-10-26 10:08:00 +00:00
bool success = true ;
2012-10-27 21:41:21 +00:00
for ( size_t i = 0 ; i < m_TTransformers . size ( ) ; + + i ) {
2012-11-14 22:06:58 +00:00
success = m_TTransformers [ i ] - > TransformTransaction ( * T ) ;
2012-10-27 21:41:21 +00:00
if ( ! success ) {
2012-10-26 10:08:00 +00:00
break ;
2012-09-05 09:37:39 +00:00
}
2012-10-27 21:41:21 +00:00
}
2012-09-05 09:37:39 +00:00
2012-10-26 10:08:00 +00:00
m_CI - > getDiagnostics ( ) . Reset ( ) ; // FIXME: Should be in rollback transaction.
if ( ! success ) {
// Roll back on error in a transformer
2012-11-14 22:06:58 +00:00
rollbackTransaction ( T ) ;
2012-10-26 10:08:00 +00:00
return ;
}
2012-09-05 09:37:39 +00:00
// Pull all template instantiations in that came from the consumers.
getCI ( ) - > getSema ( ) . PerformPendingInstantiations ( ) ;
m_Consumer - > HandleTranslationUnit ( getCI ( ) - > getASTContext ( ) ) ;
2012-11-14 22:06:58 +00:00
if ( T - > getCompilationOpts ( ) . CodeGeneration & & hasCodeGenerator ( ) ) {
2012-09-05 09:37:39 +00:00
// Reset the module builder to clean up global initializers, c'tors, d'tors
getCodeGenerator ( ) - > Initialize ( getCI ( ) - > getASTContext ( ) ) ;
// codegen the transaction
2012-11-18 22:57:52 +00:00
// We assume that there is no ordering of the calls to HandleXYZ, because
// in clang they can happen in different order too, eg. coming from
// template instatiator and so on.
2012-12-03 16:28:24 +00:00
for ( Transaction : : iterator I = T - > decls_begin ( ) , E = T - > decls_end ( ) ;
I ! = E ; + + I ) {
switch ( I - > m_Call ) {
case Transaction : : kCCIHandleTopLevelDecl :
getCodeGenerator ( ) - > HandleTopLevelDecl ( I - > m_DGR ) ;
break ;
case Transaction : : kCCIHandleInterestingDecl :
getCodeGenerator ( ) - > HandleInterestingDecl ( I - > m_DGR ) ;
break ;
case Transaction : : kCCIHandleTagDeclDefinition : {
TagDecl * TD = cast < TagDecl > ( I - > m_DGR . getSingleDecl ( ) ) ;
getCodeGenerator ( ) - > HandleTagDeclDefinition ( TD ) ;
break ;
}
case Transaction : : kCCIHandleVTable : {
CXXRecordDecl * CXXRD = cast < CXXRecordDecl > ( I - > m_DGR . getSingleDecl ( ) ) ;
getCodeGenerator ( ) - > HandleVTable ( CXXRD , /*isRequired*/ true ) ;
break ;
}
2012-12-04 10:53:44 +00:00
default :
llvm_unreachable ( " We shouldn't have decl without call info. " ) ;
2012-12-03 16:28:24 +00:00
}
2012-09-05 09:37:39 +00:00
}
getCodeGenerator ( ) - > HandleTranslationUnit ( getCI ( ) - > getASTContext ( ) ) ;
// run the static initializers that came from codegenning
2012-11-20 16:24:02 +00:00
if ( m_Interpreter - > runStaticInitializersOnce ( )
> = Interpreter : : kExeFirstError ) {
2012-12-03 16:28:24 +00:00
// Roll back on error in a transformer
rollbackTransaction ( T ) ;
return ;
2012-11-20 16:24:02 +00:00
}
2012-09-05 09:37:39 +00:00
}
2012-11-14 22:06:58 +00:00
T - > setState ( Transaction : : kCommitted ) ;
2012-10-02 10:30:25 +00:00
InterpreterCallbacks * callbacks = m_Interpreter - > getCallbacks ( ) ;
2012-10-27 21:41:21 +00:00
2012-10-10 14:50:45 +00:00
if ( callbacks )
2012-11-14 22:06:58 +00:00
callbacks - > TransactionCommitted ( * T ) ;
2012-09-05 09:37:39 +00:00
}
void IncrementalParser : : rollbackTransaction ( Transaction * T ) const {
ASTNodeEraser NodeEraser ( & getCI ( ) - > getSema ( ) ) ;
if ( NodeEraser . RevertTransaction ( T ) )
T - > setState ( Transaction : : kRolledBack ) ;
else
T - > setState ( Transaction : : kRolledBackWithErrors ) ;
}
2012-11-14 22:06:58 +00:00
std : : vector < const Transaction * > IncrementalParser : : getAllTransactions ( ) {
std : : vector < const Transaction * > result ;
const cling : : Transaction * T = getFirstTransaction ( ) ;
while ( T ) {
result . push_back ( T ) ;
T = T - > getNext ( ) ;
}
return result ;
}
2012-09-05 09:37:39 +00:00
// Each input line is contained in separate memory buffer. The SourceManager
// assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry
// for the MemoryBuffer's FileID. That in turn is problem because invalid
// SourceLocations are given to the diagnostics. Thus the diagnostics cannot
// order the overloads, for example
//
// Our work-around is creating a virtual file, which doesn't exist on the disk
// with enormous size (no allocation is done). That file has valid FileEntry
// and so on... We use it for generating valid SourceLocations with valid
// offsets so that it doesn't cause any troubles to the diagnostics.
//
// +---------------------+
// | Main memory buffer |
// +---------------------+
// | Virtual file SLoc |
// | address space |<-----------------+
// | ... |<------------+ |
// | ... | | |
// | ... |<----+ | |
// | ... | | | |
// +~~~~~~~~~~~~~~~~~~~~~+ | | |
// | input_line_1 | ....+.......+..--+
// +---------------------+ | |
// | input_line_2 | ....+.....--+
// +---------------------+ |
// | ... | |
// +---------------------+ |
// | input_line_N | ..--+
// +---------------------+
//
void IncrementalParser : : CreateSLocOffsetGenerator ( ) {
SourceManager & SM = getCI ( ) - > getSourceManager ( ) ;
FileManager & FM = SM . getFileManager ( ) ;
const FileEntry * FE
2012-10-16 12:50:21 +00:00
= FM . getVirtualFile ( " InteractiveInputLineIncluder.h " , 1U < < 15U , time ( 0 ) ) ;
2012-09-05 09:37:39 +00:00
m_VirtualFileID = SM . createFileID ( FE , SourceLocation ( ) , SrcMgr : : C_User ) ;
assert ( ! m_VirtualFileID . isInvalid ( ) & & " No VirtualFileID created? " ) ;
}
2012-11-20 03:26:52 +00:00
Transaction * IncrementalParser : : Compile ( llvm : : StringRef input ,
const CompilationOptions & Opts ) {
2012-09-05 09:37:39 +00:00
2012-11-20 03:26:52 +00:00
Transaction * CurT = beginTransaction ( Opts ) ;
EParseResult ParseRes = ParseInternal ( input ) ;
2012-09-05 09:37:39 +00:00
2012-11-20 03:26:52 +00:00
if ( ParseRes = = kSuccessWithWarnings )
CurT - > setIssuedDiags ( Transaction : : kWarnings ) ;
else if ( ParseRes = = kFailed )
CurT - > setIssuedDiags ( Transaction : : kErrors ) ;
endTransaction ( ) ;
commitTransaction ( CurT ) ;
return CurT ;
2012-09-05 09:37:39 +00:00
}
2012-10-15 13:42:09 +00:00
Transaction * IncrementalParser : : Parse ( llvm : : StringRef input ,
const CompilationOptions & Opts ) {
beginTransaction ( Opts ) ;
2012-09-05 09:37:39 +00:00
ParseInternal ( input ) ;
2012-11-14 22:06:58 +00:00
return endTransaction ( ) ;
2012-09-05 09:37:39 +00:00
}
// Add the input to the memory buffer, parse it, and add it to the AST.
IncrementalParser : : EParseResult
IncrementalParser : : ParseInternal ( llvm : : StringRef input ) {
if ( input . empty ( ) ) return IncrementalParser : : kSuccess ;
PrettyStackTraceParserEntry CrashInfo ( * m_Parser . get ( ) ) ;
// Recover resources if we crash before exiting this method.
llvm : : CrashRecoveryContextCleanupRegistrar < Parser >
CleanupParser ( m_Parser . get ( ) ) ;
Sema & S = getCI ( ) - > getSema ( ) ;
// Recover resources if we crash before exiting this method.
llvm : : CrashRecoveryContextCleanupRegistrar < Sema > CleanupSema ( & S ) ;
Preprocessor & PP = m_CI - > getPreprocessor ( ) ;
if ( ! PP . getCurrentLexer ( ) ) {
PP . EnterSourceFile ( m_CI - > getSourceManager ( ) . getMainFileID ( ) ,
0 , SourceLocation ( ) ) ;
}
2012-10-04 13:09:52 +00:00
assert ( PP . isIncrementalProcessingEnabled ( ) & & " Not in incremental mode!? " ) ;
2012-09-05 09:37:39 +00:00
PP . enableIncrementalProcessing ( ) ;
std : : ostringstream source_name ;
source_name < < " input_line_ " < < ( m_MemoryBuffers . size ( ) + 1 ) ;
// Create an uninitialized memory buffer, copy code in and append "\n"
size_t InputSize = input . size ( ) ; // don't include trailing 0
// MemBuffer size should *not* include terminating zero
llvm : : MemoryBuffer * MB
= llvm : : MemoryBuffer : : getNewUninitMemBuffer ( InputSize + 1 ,
source_name . str ( ) ) ;
char * MBStart = const_cast < char * > ( MB - > getBufferStart ( ) ) ;
memcpy ( MBStart , input . data ( ) , InputSize ) ;
memcpy ( MBStart + InputSize , " \n " , 2 ) ;
m_MemoryBuffers . push_back ( MB ) ;
SourceManager & SM = getCI ( ) - > getSourceManager ( ) ;
// Create SourceLocation, which will allow clang to order the overload
// candidates for example
SourceLocation NewLoc = SM . getLocForStartOfFile ( m_VirtualFileID ) ;
NewLoc = NewLoc . getLocWithOffset ( m_MemoryBuffers . size ( ) + 1 ) ;
// Create FileID for the current buffer
FileID FID = SM . createFileIDForMemBuffer ( m_MemoryBuffers . back ( ) ,
/*LoadedID*/ 0 ,
/*LoadedOffset*/ 0 , NewLoc ) ;
PP . EnterSourceFile ( FID , /*DirLookup*/ 0 , NewLoc ) ;
Parser : : DeclGroupPtrTy ADecl ;
while ( ! m_Parser - > ParseTopLevelDecl ( ADecl ) ) {
// If we got a null return and something *was* parsed, ignore it. This
// is due to a top-level semicolon, an action override, or a parse error
// skipping something.
if ( ADecl )
m_Consumer - > HandleTopLevelDecl ( ADecl . getAsVal < DeclGroupRef > ( ) ) ;
} ;
// Process any TopLevelDecls generated by #pragma weak.
for ( llvm : : SmallVector < Decl * , 2 > : : iterator I = S . WeakTopLevelDecls ( ) . begin ( ) ,
E = S . WeakTopLevelDecls ( ) . end ( ) ; I ! = E ; + + I ) {
m_Consumer - > HandleTopLevelDecl ( DeclGroupRef ( * I ) ) ;
}
DiagnosticsEngine & Diag = S . getDiagnostics ( ) ;
if ( Diag . hasErrorOccurred ( ) )
return IncrementalParser : : kFailed ;
else if ( Diag . getNumWarnings ( ) )
return IncrementalParser : : kSuccessWithWarnings ;
return IncrementalParser : : kSuccess ;
}
void IncrementalParser : : unloadTransaction ( Transaction * T ) {
if ( ! T )
T = getLastTransaction ( ) ;
assert ( T - > getState ( ) = = Transaction : : kCommitted & &
" Unloading not commited transaction? " ) ;
assert ( T - > getModule ( ) & &
" Trying to uncodegen transaction taken in syntax only mode. " ) ;
ASTNodeEraser NodeEraser ( & getCI ( ) - > getSema ( ) ) ;
NodeEraser . RevertTransaction ( T ) ;
2012-10-02 10:30:25 +00:00
InterpreterCallbacks * callbacks = m_Interpreter - > getCallbacks ( ) ;
2012-10-10 14:50:45 +00:00
if ( callbacks )
2012-10-02 10:30:25 +00:00
callbacks - > TransactionUnloaded ( * T ) ;
2012-09-05 09:37:39 +00:00
}
} // namespace cling