source: src/main.cc@ 3bb4f85

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

Translation of Validate F; and some improvements in some helpers.

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