source: src/main.cc@ 06bdba4

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 06bdba4 was 72e76fd, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Converted the last pass in validate B (linkReferenceToTypes). Cleaned up a related test.

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