source: src/main.cc@ 5cd0742

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

Converted validate C, including adding DimensionExpr to the new ast.

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