source: src/main.cc @ 767a8ef

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since 767a8ef was 9939dc3, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Reduced the number of object files linked into the demangler. Some of the divisions are rather odd, Lvalue2 and FixMain2, but they should be a better base to work from. Also improved the calling of the impurity detector visitors slightly.

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