source: src/main.cc@ 70056ed

ADT ast-experimental
Last change on this file since 70056ed was 3830c84, checked in by caparsons <caparson@…>, 3 years ago

cleaned up actor pass and added virtual destructor pass

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