source: src/main.cc@ 4e7171f

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

Translated the first half of validate-D. HoistControlStruct is pretty much the same, Autogen has changed a lot due to the changes in the AST.

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