source: src/main.cc@ b110bcc

ADT
Last change on this file since b110bcc was 52f9804, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Update macros in main. DUMP is now a macro to save space/noise and the PASS macro now runs checkInvariants afterwards if --invariant is on.

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