source: src/main.cc@ c42b8a1

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since c42b8a1 was 4f6dda0, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Converted Implement Concurrent Keywords to the new AST. Includes updates to various helpers, including the virtual table and a lot of examine helpers.

  • Property mode set to 100644
File size: 31.6 KB
RevLine 
[b87a5ed]1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
[71f4e4f]7// main.cc --
[b87a5ed]8//
[3e96559]9// Author : Peter Buhr and Rob Schluntz
[b87a5ed]10// Created On : Fri May 15 23:12:02 2015
[68fe946e]11// Last Modified By : Andrew Beach
[4f6dda0]12// Last Modified On : Fri Mar 11 10:39:00 2022
13// Update Count : 671
[b87a5ed]14//
15
[bf2438c]16#include <cxxabi.h> // for __cxa_demangle
17#include <execinfo.h> // for backtrace, backtrace_symbols
18#include <getopt.h> // for no_argument, optind, geto...
[08fc48f]19#include <cassert> // for assertf
[bf2438c]20#include <cstdio> // for fopen, FILE, fclose, stdin
21#include <cstdlib> // for exit, free, abort, EXIT_F...
[bffcd66]22#include <csignal> // for signal, SIGABRT, SIGSEGV
[bf2438c]23#include <cstring> // for index
[be9288a]24#include <fstream> // for ofstream
[bf2438c]25#include <iostream> // for operator<<, basic_ostream
[62ce290]26#include <iomanip>
[bf2438c]27#include <iterator> // for back_inserter
28#include <list> // for list
[08fc48f]29#include <string> // for char_traits, operator<<
[e6955b1]30
[bffcd66]31using namespace std;
32
[9ea38de]33#include "AST/Convert.hpp"
[9490621]34#include "AST/Print.hpp"
[7f38b67a]35#include "CompilationState.h"
[bf2438c]36#include "../config.h" // for CFA_LIBDIR
37#include "CodeGen/FixMain.h" // for FixMain
38#include "CodeGen/FixNames.h" // for fixNames
39#include "CodeGen/Generate.h" // for generate
[aff7e86]40#include "CodeGen/LinkOnce.h" // for translateLinkOnce
[bf2438c]41#include "CodeTools/DeclStats.h" // for printDeclStats
[3b3491b6]42#include "CodeTools/ResolvProtoDump.h" // for dumpAsResolvProto
[bf2438c]43#include "CodeTools/TrackLoc.h" // for fillLocations
[f57faf6f]44#include "Common/CodeLocationTools.hpp" // for forceFillCodeLocations
[bf2438c]45#include "Common/CompilerError.h" // for CompilerError
[55cbff8]46#include "Common/DeclStats.hpp" // for printDeclStats
47#include "Common/ResolvProtoDump.hpp" // for dumpAsResolverProto
[7abee38]48#include "Common/Stats.h"
[cbbd5b48]49#include "Common/PassVisitor.h"
[bf2438c]50#include "Common/SemanticError.h" // for SemanticError
51#include "Common/UnimplementedError.h" // for UnimplementedError
52#include "Common/utility.h" // for deleteAll, filter, printAll
[2cf3b87]53#include "Concurrency/Keywords.h" // for implementMutex, implement...
[9f5ecf5]54#include "Concurrency/Waitfor.h" // for generateWaitfor
[0c730d9]55#include "ControlStruct/ExceptDecl.h" // for translateExcept
[bf2438c]56#include "ControlStruct/ExceptTranslate.h" // for translateEHM
[b8ab91a]57#include "ControlStruct/FixLabels.hpp" // for fixLabels
[a488783]58#include "ControlStruct/HoistControlDecls.hpp" // hoistControlDecls
[bf2438c]59#include "ControlStruct/Mutate.h" // for mutate
60#include "GenPoly/Box.h" // for box
61#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
62#include "GenPoly/Lvalue.h" // for convertLvalue
63#include "GenPoly/Specialize.h" // for convertSpecializations
64#include "InitTweak/FixInit.h" // for fix
65#include "InitTweak/GenInit.h" // for genInit
66#include "MakeLibCfa.h" // for makeLibCfa
67#include "Parser/ParseNode.h" // for DeclarationNode, buildList
68#include "Parser/TypedefTable.h" // for TypedefTable
69#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
[1622af5]70#include "ResolvExpr/CandidatePrinter.hpp" // for printCandidates
[bf2438c]71#include "ResolvExpr/Resolver.h" // for resolve
72#include "SymTab/Validate.h" // for validate
[bffcd66]73#include "SynTree/LinkageSpec.h" // for Spec, Cforall, Intrinsic
[bf2438c]74#include "SynTree/Declaration.h" // for Declaration
75#include "SynTree/Visitor.h" // for acceptAll
76#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
[a488783]77#include "Validate/Autogen.hpp" // for autogenerateRoutines
[ce36b55]78#include "Validate/FindSpecialDecls.h" // for findGlobalDecls
[9490621]79#include "Validate/ForallPointerDecay.hpp" // for decayForallPointers
[2cf3b87]80#include "Validate/CompoundLiteral.hpp" // for handleCompoundLiterals
[ce36b55]81#include "Validate/InitializerLength.hpp" // for setLengthFromInitializer
82#include "Validate/LabelAddressFixer.hpp" // for fixLabelAddresses
[a5f0529]83#include "Virtual/ExpandCasts.h" // for expandCasts
[51b73452]84
[3e96559]85static void NewPass( const char * const name ) {
86 Stats::Heap::newPass( name );
[1cb7fab2]87 using namespace Stats::Counters;
[b8665e3]88 {
[3e96559]89 static auto group = build<CounterGroup>( "Pass Visitor" );
90 auto pass = build<CounterGroup>( name, group );
[b8665e3]91 pass_visitor_stats.depth = 0;
[3e96559]92 pass_visitor_stats.avg = build<AverageCounter<double>>( "Average Depth", pass );
93 pass_visitor_stats.max = build<MaxCounter<double>>( "Max Depth", pass );
[b8665e3]94 }
95 {
[3e96559]96 static auto group = build<CounterGroup>( "Syntax Node" );
97 auto pass = build<CounterGroup>( name, group );
98 BaseSyntaxNode::new_nodes = build<SimpleCounter>( "Allocs", pass );
[b8665e3]99 }
[675716e]100}
101
[3e96559]102#define PASS( name, pass ) \
[ecaeac6e]103 if ( errorp ) { cerr << name << endl; } \
[675716e]104 NewPass(name); \
[4f97937]105 Stats::Time::StartBlock(name); \
106 pass; \
107 Stats::Time::StopBlock();
[0da3e2c]108
[8b7ee09]109LinkageSpec::Spec linkage = LinkageSpec::Cforall;
[0da3e2c]110TypedefTable typedefTable;
[cbaee0d]111DeclarationNode * parseTree = nullptr; // program parse tree
[81419b5]112
[ef22ad6]113static bool waiting_for_gdb = false; // flag to set cfa-cpp to wait for gdb on start
[dee1f89]114
[bffcd66]115static string PreludeDirector = "";
[4dcaed2]116
[77d601f]117static void parse_cmdline( int argc, char * argv[] );
[8b7ee09]118static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
[e6955b1]119static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
[e499381]120static void dump( ast::TranslationUnit && transUnit, ostream & out = cout );
[e6955b1]121
[0afffee]122static void backtrace( int start ) { // skip first N stack frames
[74330e7]123 enum { Frames = 50, }; // maximum number of stack frames
[e6955b1]124 void * array[Frames];
[74330e7]125 size_t size = ::backtrace( array, Frames );
[0afffee]126 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
127
128 *index( messages[0], '(' ) = '\0'; // find executable name
129 cerr << "Stack back trace for: " << messages[0] << endl;
[e6955b1]130
[b542bfb]131 // skip last 2 stack frames after main
[74330e7]132 for ( unsigned int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
[e6955b1]133 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
[7006ba5]134
135 for ( char * p = messages[i]; *p; p += 1 ) { // find parantheses and +offset
[0afffee]136 if ( *p == '(' ) {
[46f6134]137 mangled_name = p;
[0afffee]138 } else if ( *p == '+' ) {
[e6955b1]139 offset_begin = p;
[0afffee]140 } else if ( *p == ')' ) {
[e6955b1]141 offset_end = p;
142 break;
143 } // if
144 } // for
145
146 // if line contains symbol, attempt to demangle
[b542bfb]147 int frameNo = i - start;
[e6955b1]148 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
[0afffee]149 *mangled_name++ = '\0'; // delimit strings
[e6955b1]150 *offset_begin++ = '\0';
151 *offset_end++ = '\0';
152
[0afffee]153 int status;
[e6955b1]154 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
[0afffee]155 // bug in __cxa_demangle for single-character lower-case non-mangled names
[e6955b1]156 if ( status == 0 ) { // demangling successful ?
[b542bfb]157 cerr << "(" << frameNo << ") " << messages[i] << " : "
[e6955b1]158 << real_name << "+" << offset_begin << offset_end << endl;
159 } else { // otherwise, output mangled name
[b542bfb]160 cerr << "(" << frameNo << ") " << messages[i] << " : "
[0afffee]161 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
[e6955b1]162 } // if
[0afffee]163
[e6955b1]164 free( real_name );
165 } else { // otherwise, print the whole line
[b542bfb]166 cerr << "(" << frameNo << ") " << messages[i] << endl;
[e6955b1]167 } // if
168 } // for
[b542bfb]169
[e6955b1]170 free( messages );
[b542bfb]171} // backtrace
172
[bffcd66]173#define SIGPARMS int sig __attribute__(( unused )), siginfo_t * sfp __attribute__(( unused )), ucontext_t * cxt __attribute__(( unused ))
174
[1f68d5d]175static void _Signal(struct sigaction & act, int sig, int flags ) {
[bffcd66]176 act.sa_flags = flags;
177
178 if ( sigaction( sig, &act, nullptr ) == -1 ) {
[77d601f]179 cerr << "*cfa-cpp compilation error* problem installing signal handler, error(" << errno << ") " << strerror( errno ) << endl;
[bffcd66]180 _exit( EXIT_FAILURE );
181 } // if
[1f68d5d]182}
183
184static void Signal( int sig, void (* handler)(SIGPARMS), int flags ) {
185 struct sigaction act;
186 act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
187 _Signal(act, sig, flags);
188} // Signal
189
190static void Signal( int sig, void (* handler)(int), int flags ) {
191 struct sigaction act;
192 act.sa_handler = handler;
193 _Signal(act, sig, flags);
[bffcd66]194} // Signal
195
196static void sigSegvBusHandler( SIGPARMS ) {
197 if ( sfp->si_addr == nullptr ) {
198 cerr << "Null pointer (nullptr) dereference." << endl;
199 } else {
200 cerr << (sig == SIGSEGV ? "Segment fault" : "Bus error") << " at memory location " << sfp->si_addr << "." << endl
201 << "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript." << endl;
202 } // if
[b542bfb]203 backtrace( 2 ); // skip first 2 stack frames
[3e96559]204 abort(); // cause core dump for debugging
[e6955b1]205} // sigSegvBusHandler
[0da3e2c]206
[74330e7]207static void sigFpeHandler( SIGPARMS ) {
208 const char * msg;
209
210 switch ( sfp->si_code ) {
211 case FPE_INTDIV: case FPE_FLTDIV: msg = "divide by zero"; break;
212 case FPE_FLTOVF: msg = "overflow"; break;
213 case FPE_FLTUND: msg = "underflow"; break;
214 case FPE_FLTRES: msg = "inexact result"; break;
215 case FPE_FLTINV: msg = "invalid operation"; break;
216 default: msg = "unknown";
217 } // choose
218 cerr << "Computation error " << msg << " at location " << sfp->si_addr << endl
219 << "Possible cause is constant-expression evaluation invalid." << endl;
220 backtrace( 2 ); // skip first 2 stack frames
221 abort(); // cause core dump for debugging
222} // sigFpeHandler
223
[bffcd66]224static void sigAbortHandler( SIGPARMS ) {
[b542bfb]225 backtrace( 6 ); // skip first 6 stack frames
[1f68d5d]226 Signal( SIGABRT, SIG_DFL, SA_SIGINFO ); // reset default signal handler
[9be45a2]227 raise( SIGABRT ); // reraise SIGABRT
[b542bfb]228} // sigAbortHandler
229
[cbaee0d]230int main( int argc, char * argv[] ) {
[3b8e52c]231 FILE * input; // use FILE rather than istream because yyin is FILE
[d08beee]232 ostream * output = & cout;
[e6955b1]233 list< Declaration * > translationUnit;
234
[bffcd66]235 Signal( SIGSEGV, sigSegvBusHandler, SA_SIGINFO );
236 Signal( SIGBUS, sigSegvBusHandler, SA_SIGINFO );
[74330e7]237 Signal( SIGFPE, sigFpeHandler, SA_SIGINFO );
[bffcd66]238 Signal( SIGABRT, sigAbortHandler, SA_SIGINFO );
[b87a5ed]239
[bffcd66]240 // cout << "main" << endl;
[44bca7f]241 // for ( int i = 0; i < argc; i += 1 ) {
[bffcd66]242 // cout << '\t' << argv[i] << endl;
[44bca7f]243 // } // for
244
[e0bd0f9]245 parse_cmdline( argc, argv ); // process command-line arguments
[13de47bc]246 CodeGen::FixMain::setReplaceMain( !nomainp );
[b87a5ed]247
[ef22ad6]248 if ( waiting_for_gdb ) {
[bffcd66]249 cerr << "Waiting for gdb" << endl;
250 cerr << "run :" << endl;
251 cerr << " gdb attach " << getpid() << endl;
[dee1f89]252 raise(SIGSTOP);
[ef22ad6]253 } // if
[dee1f89]254
[b87a5ed]255 try {
[81419b5]256 // choose to read the program from a file or stdin
[3b8e52c]257 if ( optind < argc ) { // any commands after the flags ? => input file name
[b87a5ed]258 input = fopen( argv[ optind ], "r" );
[e0bd0f9]259 assertf( input, "cannot open %s because %s\n", argv[ optind ], strerror( errno ) );
[b87a5ed]260 optind += 1;
[3b8e52c]261 } else { // no input file name
[b87a5ed]262 input = stdin;
263 } // if
264
[79eaeb7]265 Stats::Time::StartGlobal();
[3c0d4cd]266 NewPass("Parse");
267 Stats::Time::StartBlock("Parse");
[675716e]268
[159c62e]269 // read in the builtins, extras, and the prelude
[de62360d]270 if ( ! nopreludep ) { // include gcc builtins
[faf8857]271 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
[807ce84]272
[37fe352]273 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
[4dcaed2]274
[807ce84]275 // Read to gcc builtins, if not generating the cfa library
[37fe352]276 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
[6ce3ae9]277 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
278 parse( gcc_builtins, LinkageSpec::Compiler );
[81419b5]279
[159c62e]280 // read the extra prelude in, if not generating the cfa library
[37fe352]281 FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
[3b8e52c]282 assertf( extras, "cannot open extras.cf\n" );
[f0994a1]283 parse( extras, LinkageSpec::BuiltinC );
[159c62e]284
[81419b5]285 if ( ! libcfap ) {
[faf8857]286 // read the prelude in, if not generating the cfa library
[e523b07]287 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
288 assertf( prelude, "cannot open prelude.cfa\n" );
[35304009]289 parse( prelude, LinkageSpec::Intrinsic );
[fa4805f]290
291 // Read to cfa builtins, if not generating the cfa library
[37fe352]292 FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
[fa4805f]293 assertf( builtins, "cannot open builtins.cf\n" );
[54d714e]294 parse( builtins, LinkageSpec::BuiltinCFA );
[b87a5ed]295 } // if
296 } // if
[81419b5]297
[926af74]298 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
[71f4e4f]299
[b87a5ed]300 if ( parsep ) {
[e6955b1]301 parseTree->printList( cout );
[0da3e2c]302 delete parseTree;
[3e96559]303 return EXIT_SUCCESS;
[b87a5ed]304 } // if
305
[0da3e2c]306 buildList( parseTree, translationUnit );
307 delete parseTree;
[cbaee0d]308 parseTree = nullptr;
[b87a5ed]309
310 if ( astp ) {
[1ab4ce2]311 dump( translationUnit );
[3e96559]312 return EXIT_SUCCESS;
[b87a5ed]313 } // if
314
[036dd5f]315 // Temporary: fill locations after parsing so that every node has a location, for early error messages.
316 // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
317 // works okay for now.
318 CodeTools::fillLocations( translationUnit );
[3c0d4cd]319 Stats::Time::StopBlock();
[036dd5f]320
[0c730d9]321 PASS( "Translate Exception Declarations", ControlStruct::translateExcept( translationUnit ) );
[00da199]322 if ( exdeclp ) {
323 dump( translationUnit );
324 return EXIT_SUCCESS;
325 } // if
[0c730d9]326
[839ccbb]327 // add the assignment statement after the initialization of a type parameter
[5dcb881]328 PASS( "Validate-A", SymTab::validate_A( translationUnit ) );
329 PASS( "Validate-B", SymTab::validate_B( translationUnit ) );
330 PASS( "Validate-C", SymTab::validate_C( translationUnit ) );
[b87a5ed]331
[76b378d]332 CodeTools::fillLocations( translationUnit );
333
[4a8f150]334 if( useNewAST ) {
[a488783]335 CodeTools::fillLocations( translationUnit );
336
[3746f777]337 if (Stats::Counters::enabled) {
338 ast::pass_visitor_stats.avg = Stats::Counters::build<Stats::Counters::AverageCounter<double>>("Average Depth - New");
339 ast::pass_visitor_stats.max = Stats::Counters::build<Stats::Counters::MaxCounter<double>>("Max depth - New");
340 }
[9ea38de]341 auto transUnit = convert( move( translationUnit ) );
[9f5a19fa]342
[68fe946e]343 forceFillCodeLocations( transUnit );
344
[4f6dda0]345 PASS( "Implement Concurrent Keywords", Concurrency::implementKeywords( transUnit ) );
346
[9490621]347 // Must be after implement concurrent keywords; because uniqueIds
348 // must be set on declaration before resolution.
349 // Must happen before autogen routines are added.
350 PASS( "Forall Pointer Decay", Validate::decayForallPointers( transUnit ) );
351
[a488783]352 // Must happen before autogen routines are added.
353 PASS( "Hoist Control Declarations", ControlStruct::hoistControlDecls( transUnit ) );
354
355 // Must be after enum and pointer decay.
356 // Must be before compound literals.
357 PASS( "Generate Autogen Routines", Validate::autogenerateRoutines( transUnit ) );
358
[2cf3b87]359 PASS( "Implement Mutex", Concurrency::implementMutex( transUnit ) );
360 PASS( "Implement Thread Start", Concurrency::implementThreadStarter( transUnit ) );
361 PASS( "Compound Literal", Validate::handleCompoundLiterals( transUnit ) );
[ce36b55]362 PASS( "Set Length From Initializer", Validate::setLengthFromInitializer( transUnit ) );
363 PASS( "Find Global Decls", Validate::findGlobalDecls( transUnit ) );
364 PASS( "Fix Label Address", Validate::fixLabelAddresses( transUnit ) );
365
[1622af5]366 if ( symtabp ) {
367 return EXIT_SUCCESS;
368 } // if
369
370 if ( expraltp ) {
371 ResolvExpr::printCandidates( transUnit );
372 return EXIT_SUCCESS;
373 } // if
374
375 if ( validp ) {
376 dump( move( transUnit ) );
377 return EXIT_SUCCESS;
378 } // if
379
[5ee153d]380 PASS( "Translate Throws", ControlStruct::translateThrows( transUnit ) );
[b8ab91a]381 PASS( "Fix Labels", ControlStruct::fixLabels( transUnit ) );
[0c577f7]382 PASS( "Fix Names", CodeGen::fixNames( transUnit ) );
[a36eb2d]383 PASS( "Gen Init", InitTweak::genInit( transUnit ) );
[9f5a19fa]384 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( transUnit ) );
[68fe946e]385
[da6396f]386 if ( libcfap ) {
387 // Generate the bodies of cfa library functions.
388 LibCfa::makeLibCfa( transUnit );
389 } // if
[68fe946e]390
391 if ( declstatsp ) {
392 printDeclStats( transUnit );
393 return EXIT_SUCCESS;
394 } // if
395
396 if ( bresolvep ) {
397 dump( move( transUnit ) );
398 return EXIT_SUCCESS;
399 } // if
400
401 if ( resolvprotop ) {
[55cbff8]402 dumpAsResolverProto( transUnit );
[68fe946e]403 return EXIT_SUCCESS;
404 } // if
405
[9ea38de]406 PASS( "Resolve", ResolvExpr::resolve( transUnit ) );
[490fb92e]407 if ( exprp ) {
[e499381]408 dump( move( transUnit ) );
[490fb92e]409 return EXIT_SUCCESS;
410 } // if
411
[f57faf6f]412 forceFillCodeLocations( transUnit );
[4a8f150]413
[490fb92e]414 PASS( "Fix Init", InitTweak::fix(transUnit, buildingLibrary()));
[da6396f]415
[01d433e]416 // fix ObjectDecl - replaces ConstructorInit nodes
417 if ( ctorinitp ) {
418 dump( move( transUnit ) );
419 return EXIT_SUCCESS;
420 } // if
421
422 // Currently not working due to unresolved issues with UniqueExpr
423 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( transUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent passes don't need to worry about double-visiting a unique expr - needs to go after InitTweak::fix so that copy constructed return declarations are reused
[5f3ba11]424
425 PASS( "Translate Tries" , ControlStruct::translateTries( transUnit ) );
426
[9ea38de]427 translationUnit = convert( move( transUnit ) );
[a77257be]428 } else {
[a488783]429 PASS( "Validate-D", SymTab::validate_D( translationUnit ) );
[2cf3b87]430 PASS( "Validate-E", SymTab::validate_E( translationUnit ) );
[ce36b55]431 PASS( "Validate-F", SymTab::validate_F( translationUnit ) );
432
[1622af5]433 if ( symtabp ) {
434 deleteAll( translationUnit );
435 return EXIT_SUCCESS;
436 } // if
437
438 if ( expraltp ) {
439 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
440 acceptAll( translationUnit, printer );
441 return EXIT_SUCCESS;
442 } // if
443
444 if ( validp ) {
445 dump( translationUnit );
446 return EXIT_SUCCESS;
447 } // if
448
[5ee153d]449 PASS( "Translate Throws", ControlStruct::translateThrows( translationUnit ) );
[b8ab91a]450 PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
[0c577f7]451 PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
[a36eb2d]452 PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
[9f5a19fa]453 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
454
[da6396f]455 if ( libcfap ) {
456 // Generate the bodies of cfa library functions.
457 LibCfa::makeLibCfa( translationUnit );
458 } // if
[68fe946e]459
460 if ( declstatsp ) {
461 CodeTools::printDeclStats( translationUnit );
462 deleteAll( translationUnit );
463 return EXIT_SUCCESS;
464 } // if
465
466 if ( bresolvep ) {
467 dump( translationUnit );
468 return EXIT_SUCCESS;
469 } // if
470
471 CodeTools::fillLocations( translationUnit );
472
473 if ( resolvprotop ) {
474 CodeTools::dumpAsResolvProto( translationUnit );
475 return EXIT_SUCCESS;
476 } // if
477
[a77257be]478 PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
[490fb92e]479 if ( exprp ) {
480 dump( translationUnit );
481 return EXIT_SUCCESS;
482 }
[4615ac8]483
[490fb92e]484 PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
[81419b5]485
[01d433e]486 // fix ObjectDecl - replaces ConstructorInit nodes
487 if ( ctorinitp ) {
488 dump ( translationUnit );
489 return EXIT_SUCCESS;
490 } // if
[71f4e4f]491
[01d433e]492 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( translationUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent passes don't need to worry about double-visiting a unique expr - needs to go after InitTweak::fix so that copy constructed return declarations are reused
[5f3ba11]493
494 PASS( "Translate Tries" , ControlStruct::translateTries( translationUnit ) );
[01d433e]495 }
[626dbc10]496
[675716e]497 PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
[307a732]498
[675716e]499 PASS( "Convert Specializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
[9f5ecf5]500
[675716e]501 PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
[626dbc10]502
503 if ( tuplep ) {
504 dump( translationUnit );
[3e96559]505 return EXIT_SUCCESS;
506 } // if
[141b786]507
[675716e]508 PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
[a5f0529]509
[675716e]510 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
[53d3ab4b]511 if ( genericsp ) {
512 dump( translationUnit );
[3e96559]513 return EXIT_SUCCESS;
514 } // if
[b4f8808]515
[675716e]516 PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
[53d3ab4b]517
[fea7ca7]518 if ( bboxp ) {
519 dump( translationUnit );
[3e96559]520 return EXIT_SUCCESS;
[926af74]521 } // if
[675716e]522 PASS( "Box", GenPoly::box( translationUnit ) );
[81419b5]523
[aff7e86]524 PASS( "Link-Once", CodeGen::translateLinkOnce( translationUnit ) );
525
526 // Code has been lowered to C, now we can start generation.
527
[8905f56]528 if ( bcodegenp ) {
529 dump( translationUnit );
[3e96559]530 return EXIT_SUCCESS;
531 } // if
[8905f56]532
[13de47bc]533 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
534 output = new ofstream( argv[ optind ] );
535 } // if
[0270824]536
[7b15d7a]537 CodeTools::fillLocations( translationUnit );
[62ce290]538 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
[0270824]539
[8e48fca4]540 CodeGen::FixMain::fix( translationUnit, *output,
541 (PreludeDirector + "/bootloader.c").c_str() );
[e6955b1]542 if ( output != &cout ) {
[b87a5ed]543 delete output;
544 } // if
[77d601f]545 } catch ( SemanticErrorException & e ) {
[b87a5ed]546 if ( errorp ) {
[e6955b1]547 cerr << "---AST at error:---" << endl;
548 dump( translationUnit, cerr );
549 cerr << endl << "---End of AST, begin error message:---\n" << endl;
[926af74]550 } // if
[d55d7a6]551 e.print();
[e6955b1]552 if ( output != &cout ) {
[b87a5ed]553 delete output;
554 } // if
[3e96559]555 return EXIT_FAILURE;
[77d601f]556 } catch ( UnimplementedError & e ) {
[e6955b1]557 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
558 if ( output != &cout ) {
[b87a5ed]559 delete output;
560 } // if
[3e96559]561 return EXIT_FAILURE;
[77d601f]562 } catch ( CompilerError & e ) {
[e6955b1]563 cerr << "Compiler Error: " << e.get_what() << endl;
[c850687]564 cerr << "(please report bugs to [REDACTED])" << endl;
[e6955b1]565 if ( output != &cout ) {
[b87a5ed]566 delete output;
567 } // if
[3e96559]568 return EXIT_FAILURE;
[77d601f]569 } catch ( std::bad_alloc & ) {
570 cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
571 backtrace( 1 );
572 abort();
[3e96559]573 } catch ( ... ) {
[bffcd66]574 exception_ptr eptr = current_exception();
[4990812]575 try {
576 if (eptr) {
[bffcd66]577 rethrow_exception(eptr);
[3e96559]578 } else {
[77d601f]579 cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
[3e96559]580 } // if
[77d601f]581 } catch( const exception & e ) {
582 cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
[3e96559]583 } // try
584 return EXIT_FAILURE;
585 } // try
[b87a5ed]586
[39786813]587 deleteAll( translationUnit );
[1cb7fab2]588 Stats::print();
[3e96559]589 return EXIT_SUCCESS;
[d9a0e76]590} // main
[51b73452]591
[0da3e2c]592
[3e9de01]593static const char optstring[] = ":c:ghlLmNnpdOAP:S:twW:D:";
[3e96559]594
[62ce290]595enum { PreludeDir = 128 };
[3e96559]596static struct option long_opts[] = {
[1a69a90]597 { "colors", required_argument, nullptr, 'c' },
598 { "gdb", no_argument, nullptr, 'g' },
[3e96559]599 { "help", no_argument, nullptr, 'h' },
600 { "libcfa", no_argument, nullptr, 'l' },
[62ce290]601 { "linemarks", no_argument, nullptr, 'L' },
[3e96559]602 { "no-main", no_argument, 0, 'm' },
[62ce290]603 { "no-linemarks", no_argument, nullptr, 'N' },
604 { "no-prelude", no_argument, nullptr, 'n' },
[3e96559]605 { "prototypes", no_argument, nullptr, 'p' },
[7215000]606 { "deterministic-out", no_argument, nullptr, 'd' },
[a77257be]607 { "old-ast", no_argument, nullptr, 'O'},
608 { "new-ast", no_argument, nullptr, 'A'},
[62ce290]609 { "print", required_argument, nullptr, 'P' },
610 { "prelude-dir", required_argument, nullptr, PreludeDir },
611 { "statistics", required_argument, nullptr, 'S' },
[3e96559]612 { "tree", no_argument, nullptr, 't' },
613 { "", no_argument, nullptr, 0 }, // -w
614 { "", no_argument, nullptr, 0 }, // -W
615 { "", no_argument, nullptr, 0 }, // -D
616 { nullptr, 0, nullptr, 0 }
617}; // long_opts
618
619static const char * description[] = {
[aa88cb9a]620 "diagnostic color: never, always, auto", // -c
[3e9de01]621 "wait for gdb to attach", // -g
[aa88cb9a]622 "print translator help message", // -h
[3e9de01]623 "generate libcfa.c", // -l
624 "generate line marks", // -L
625 "do not replace main", // -m
626 "do not generate line marks", // -N
627 "do not read prelude", // -n
[aa88cb9a]628 "do not generate prelude prototypes => prelude not printed", // -p
[3e9de01]629 "only print deterministic output", // -d
630 "Use the old-ast", // -O
631 "Use the new-ast", // -A
632 "print", // -P
[62ce290]633 "<directory> prelude directory for debug/nodebug", // no flag
[aa88cb9a]634 "<option-list> enable profiling information: counters, heap, time, all, none", // -S
[3e9de01]635 "building cfa standard lib", // -t
636 "", // -w
637 "", // -W
638 "", // -D
[3e96559]639}; // description
640
[0c0f548]641static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
[62ce290]642
643static struct Printopts {
644 const char * name;
645 int & flag;
646 int val;
647 const char * descript;
648} printopts[] = {
[0e464f6]649 { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
650 { "asterr", errorp, true, "print AST on error" },
[62ce290]651 { "declstats", declstatsp, true, "code property statistics" },
652 { "parse", yydebug, true, "yacc (parsing) debug information" },
653 { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
654 { "rproto", resolvprotop, true, "resolver-proto instance" },
[0e464f6]655 { "rsteps", resolvep, true, "print resolver steps" },
656 { "tree", parsep, true, "print parse tree" },
657 // code dumps
658 { "ast", astp, true, "print AST after parsing" },
[00da199]659 { "exdecl", exdeclp, true, "print AST after translating exception decls" },
[0e464f6]660 { "symevt", symtabp, true, "print AST after symbol table events" },
661 { "altexpr", expraltp, true, "print alternatives for expressions" },
662 { "astdecl", validp, true, "print AST after declaration validation pass" },
663 { "resolver", bresolvep, true, "print AST before resolver step" },
664 { "astexpr", exprp, true, "print AST after expression analysis" },
665 { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
666 { "tuple", tuplep, true, "print AST after tuple expansion" },
667 { "astgen", genericsp, true, "print AST after instantiate generics" },
668 { "box", bboxp, true, "print AST before box step" },
669 { "codegen", bcodegenp, true, "print AST before code generation" },
[62ce290]670};
671enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
672
[77d601f]673static void usage( char * argv[] ) {
[e0bd0f9]674 cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
[3e96559]675 int i = 0, j = 1; // j skips starting colon
676 for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
677 if ( long_opts[i].name[0] != '\0' ) { // hidden option, internal usage only
[62ce290]678 if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
679 cout << " -" << optstring[j] << ",";
680 } else { // no flag
681 j -= 1; // compensate
682 cout << " ";
683 } // if
684 cout << " --" << left << setw(12) << long_opts[i].name << " ";
685 if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
686 cout << "one of: " << endl;
687 for ( int i = 0; i < printoptsSize; i += 1 ) {
688 cout << setw(10) << " " << left << setw(10) << printopts[i].name << " " << printopts[i].descript << endl;
689 } // for
690 } else {
691 cout << description[i] << endl;
692 } // if
[3e96559]693 } // if
[62ce290]694 if ( optstring[j + 1] == ':' ) j += 1;
[3e96559]695 } // for
696 if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
697 exit( EXIT_FAILURE );
698} // usage
699
[e0bd0f9]700static void parse_cmdline( int argc, char * argv[] ) {
[0da3e2c]701 opterr = 0; // (global) prevent getopt from printing error messages
702
[c5e5109]703 bool Wsuppress = false, Werror = false;
[0da3e2c]704 int c;
[3e96559]705 while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
[0da3e2c]706 switch ( c ) {
[1a69a90]707 case 'c': // diagnostic colors
708 if ( strcmp( optarg, "always" ) == 0 ) {
709 ErrorHelpers::colors = ErrorHelpers::Colors::Always;
710 } else if ( strcmp( optarg, "never" ) == 0 ) {
711 ErrorHelpers::colors = ErrorHelpers::Colors::Never;
712 } else if ( strcmp( optarg, "auto" ) == 0 ) {
713 ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
714 } // if
715 break;
[3e96559]716 case 'h': // help message
717 usage( argv ); // no return
[53d3ab4b]718 break;
[3e96559]719 case 'l': // generate libcfa.c
[0da3e2c]720 libcfap = true;
721 break;
[62ce290]722 case 'L': // generate line marks
[6de43b6]723 linemarks = true;
[c850687]724 break;
[3e96559]725 case 'm': // do not replace main
726 nomainp = true;
[0da3e2c]727 break;
[62ce290]728 case 'N': // do not generate line marks
[6de43b6]729 linemarks = false;
[c59bde6]730 break;
[62ce290]731 case 'n': // do not read prelude
[3e96559]732 nopreludep = true;
[0da3e2c]733 break;
[62ce290]734 case 'p': // generate prototypes for prelude functions
735 genproto = true;
[0da3e2c]736 break;
[7215000]737 case 'd': // don't print non-deterministic output
[a77257be]738 deterministic_output = true;
739 break;
740 case 'O': // don't print non-deterministic output
741 useNewAST = false;
742 break;
743 case 'A': // don't print non-deterministic output
744 useNewAST = true;
[7215000]745 break;
[62ce290]746 case 'P': // print options
747 for ( int i = 0;; i += 1 ) {
748 if ( i == printoptsSize ) {
749 cout << "Unknown --print option " << optarg << endl;
750 goto Default;
751 } // if
752 if ( strcmp( optarg, printopts[i].name ) == 0 ) {
753 printopts[i].flag = printopts[i].val;
754 break;
755 } // if
756 } // for
[0da3e2c]757 break;
[62ce290]758 case PreludeDir: // prelude directory for debug/nodebug, hidden
759 PreludeDirector = optarg;
[3b3491b6]760 break;
[3e96559]761 case 'S': // enable profiling information, argument comma separated list of names
762 Stats::parse_params( optarg );
[ebcc940]763 break;
[dee1f89]764 case 't': // building cfa stdlib
[0da3e2c]765 treep = true;
766 break;
[dee1f89]767 case 'g': // wait for gdb
768 waiting_for_gdb = true;
769 break;
[3e96559]770 case 'w': // suppress all warnings, hidden
[c5e5109]771 Wsuppress = true;
[44bca7f]772 break;
[3e96559]773 case 'W': // coordinate gcc -W with CFA, hidden
[44bca7f]774 if ( strcmp( optarg, "all" ) == 0 ) {
[68e9ace]775 SemanticWarning_EnableAll();
[44bca7f]776 } else if ( strcmp( optarg, "error" ) == 0 ) {
777 Werror = true;
778 } else {
779 char * warning = optarg;
780 Severity s;
781 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
782 warning += 3;
783 s = Severity::Suppress;
784 } else {
785 s = Severity::Warn;
786 } // if
[68e9ace]787 SemanticWarning_Set( warning, s );
[44bca7f]788 } // if
789 break;
[3e96559]790 case 'D': // ignore -Dxxx, forwarded by cpp, hidden
[0da3e2c]791 break;
[3e96559]792 case '?': // unknown option
793 if ( optopt ) { // short option ?
794 cout << "Unknown option -" << (char)optopt << endl;
795 } else {
796 cout << "Unknown option " << argv[optind - 1] << endl;
797 } // if
798 goto Default;
799 case ':': // missing option
[ae47a23]800 if ( optopt ) { // short option ?
[3e96559]801 cout << "Missing option for -" << (char)optopt << endl;
[ae47a23]802 } else {
[3e96559]803 cout << "Missing option for " << argv[optind - 1] << endl;
[ae47a23]804 } // if
[3e96559]805 goto Default;
806 Default:
807 default:
808 usage( argv ); // no return
[0da3e2c]809 } // switch
810 } // while
[44bca7f]811
812 if ( Werror ) {
[68e9ace]813 SemanticWarning_WarningAsError();
[44bca7f]814 } // if
[c5e5109]815 if ( Wsuppress ) {
816 SemanticWarning_SuppressAll();
817 } // if
[44bca7f]818 // for ( const auto w : WarningFormats ) {
819 // cout << w.name << ' ' << (int)w.severity << endl;
820 // } // for
[0da3e2c]821} // parse_cmdline
822
[8b7ee09]823static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
[0da3e2c]824 extern int yyparse( void );
[cbaee0d]825 extern FILE * yyin;
[0da3e2c]826 extern int yylineno;
827
[8b7ee09]828 ::linkage = linkage; // set globals
[0da3e2c]829 yyin = input;
830 yylineno = 1;
831 int parseStatus = yyparse();
[81419b5]832
833 fclose( input );
[0da3e2c]834 if ( shouldExit || parseStatus != 0 ) {
835 exit( parseStatus );
[81419b5]836 } // if
[0da3e2c]837} // parse
[81419b5]838
[1ab4ce2]839static bool notPrelude( Declaration * decl ) {
840 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
[0da3e2c]841} // notPrelude
[1ab4ce2]842
[e6955b1]843static void dump( list< Declaration * > & translationUnit, ostream & out ) {
844 list< Declaration * > decls;
[926af74]845
[62ce290]846 if ( genproto ) {
[e6955b1]847 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
[1ab4ce2]848 } else {
849 decls = translationUnit;
[926af74]850 } // if
[1ab4ce2]851
[e39241b]852 // depending on commandline options, either generate code or dump the AST
853 if ( codegenp ) {
[62ce290]854 CodeGen::generate( decls, out, ! genproto, prettycodegenp );
[e39241b]855 } else {
856 printAll( decls, out );
[3e96559]857 } // if
[7f5566b]858 deleteAll( translationUnit );
[0da3e2c]859} // dump
[1ab4ce2]860
[e499381]861static void dump( ast::TranslationUnit && transUnit, ostream & out ) {
862 std::list< Declaration * > translationUnit = convert( move( transUnit ) );
863 dump( translationUnit, out );
864}
865
[51b73452]866// Local Variables: //
[b87a5ed]867// tab-width: 4 //
868// mode: c++ //
869// compile-command: "make install" //
[51b73452]870// End: //
Note: See TracBrowser for help on using the repository browser.