source: src/main.cc@ 5dcb881

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

Split up the validate pass. (Some statistics code is repeated, but this does not effect regular runs.)

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