source: src/main.cc @ eba74ba

new-envwith_gc
Last change on this file since eba74ba was eba74ba, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge remote-tracking branch 'origin/master' into with_gc

  • Property mode set to 100644
File size: 19.9 KB
Line 
1
2//
3// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
4//
5// The contents of this file are covered under the licence agreement in the
6// file "LICENCE" distributed with Cforall.
7//
8// main.cc --
9//
10// Author           : Richard C. Bilson
11// Created On       : Fri May 15 23:12:02 2015
12// Last Modified By : Peter A. Buhr
13// Last Modified On : Mon May  7 14:35:57 2018
14// Update Count     : 492
15//
16
17#include <cxxabi.h>                         // for __cxa_demangle
18#include <execinfo.h>                       // for backtrace, backtrace_symbols
19#include <getopt.h>                         // for no_argument, optind, geto...
20#include <signal.h>                         // for signal, SIGABRT, SIGSEGV
21#include <cassert>                          // for assertf
22#include <cstdio>                           // for fopen, FILE, fclose, stdin
23#include <cstdlib>                          // for exit, free, abort, EXIT_F...
24#include <cstring>                          // for index
25#include <fstream>                          // for ofstream
26#include <iostream>                         // for operator<<, basic_ostream
27#include <iterator>                         // for back_inserter
28#include <list>                             // for list
29#include <string>                           // for char_traits, operator<<
30
31#include "../config.h"                      // for CFA_LIBDIR
32#include "CodeGen/FixMain.h"                // for FixMain
33#include "CodeGen/FixNames.h"               // for fixNames
34#include "CodeGen/Generate.h"               // for generate
35#include "CodeTools/DeclStats.h"            // for printDeclStats
36#include "CodeTools/TrackLoc.h"             // for fillLocations
37#include "Common/CompilerError.h"           // for CompilerError
38#include "Common/GC.h"                      // for GC
39#include "Common/Heap.h"
40#include "Common/PassVisitor.h"
41#include "Common/SemanticError.h"           // for SemanticError
42#include "Common/UnimplementedError.h"      // for UnimplementedError
43#include "Common/utility.h"                 // for deleteAll, filter, printAll
44#include "Concurrency/Waitfor.h"            // for generateWaitfor
45#include "ControlStruct/ExceptTranslate.h"  // for translateEHM
46#include "ControlStruct/Mutate.h"           // for mutate
47#include "GenPoly/Box.h"                    // for box
48#include "GenPoly/InstantiateGeneric.h"     // for instantiateGeneric
49#include "GenPoly/Lvalue.h"                 // for convertLvalue
50#include "GenPoly/Specialize.h"             // for convertSpecializations
51#include "InitTweak/FixInit.h"              // for fix
52#include "InitTweak/GenInit.h"              // for genInit
53#include "MakeLibCfa.h"                     // for makeLibCfa
54#include "Parser/LinkageSpec.h"             // for Spec, Cforall, Intrinsic
55#include "Parser/ParseNode.h"               // for DeclarationNode, buildList
56#include "Parser/TypedefTable.h"            // for TypedefTable
57#include "ResolvExpr/AlternativePrinter.h"  // for AlternativePrinter
58#include "ResolvExpr/Resolver.h"            // for resolve
59#include "SymTab/Validate.h"                // for validate
60#include "SynTree/Declaration.h"            // for Declaration
61#include "SynTree/GcTracer.h"               // for GC << TranslationUnit
62#include "SynTree/Visitor.h"                // for acceptAll
63#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
64#include "Virtual/ExpandCasts.h"            // for expandCasts
65
66using namespace std;
67
68#define PASS(name, pass)                   \
69        if ( errorp ) { cerr << name << endl; } \
70        HeapStats::newPass(name);               \
71        pass;
72
73LinkageSpec::Spec linkage = LinkageSpec::Cforall;
74TypedefTable typedefTable;
75DeclarationNode * parseTree = nullptr;                                  // program parse tree
76
77extern int yydebug;                                                                             // set for -g flag (Grammar)
78bool
79        astp = false,
80        bresolvep = false,
81        bboxp = false,
82        bcodegenp = false,
83        ctorinitp = false,
84        declstatsp = false,
85        exprp = false,
86        expraltp = false,
87        genericsp = false,
88        libcfap = false,
89        nopreludep = false,
90        noprotop = false,
91        nomainp = false,
92        parsep = false,
93        resolvep = false,                                                                       // used in AlternativeFinder
94        symtabp = false,
95        treep = false,
96        tuplep = false,
97        validp = false,
98        errorp = false,
99        codegenp = false,
100        prettycodegenp = false,
101        linemarks = false;
102
103static void parse_cmdline( int argc, char *argv[], const char *& filename );
104static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
105static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
106
107static void backtrace( int start ) {                                    // skip first N stack frames
108        enum { Frames = 50 };
109        void * array[Frames];
110        int size = ::backtrace( array, Frames );
111        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
112
113        *index( messages[0], '(' ) = '\0';                                      // find executable name
114        cerr << "Stack back trace for: " << messages[0] << endl;
115
116        // skip last 2 stack frames after main
117        for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
118                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
119                for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
120                        if ( *p == '(' ) {
121                                mangled_name = p;
122                        } else if ( *p == '+' ) {
123                                offset_begin = p;
124                        } else if ( *p == ')' ) {
125                                offset_end = p;
126                                break;
127                        } // if
128                } // for
129
130                // if line contains symbol, attempt to demangle
131                int frameNo = i - start;
132                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
133                        *mangled_name++ = '\0';                                         // delimit strings
134                        *offset_begin++ = '\0';
135                        *offset_end++ = '\0';
136
137                        int status;
138                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
139                        // bug in __cxa_demangle for single-character lower-case non-mangled names
140                        if ( status == 0 ) {                                            // demangling successful ?
141                                cerr << "(" << frameNo << ") " << messages[i] << " : "
142                                         << real_name << "+" << offset_begin << offset_end << endl;
143                        } else {                                                                        // otherwise, output mangled name
144                                cerr << "(" << frameNo << ") " << messages[i] << " : "
145                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
146                        } // if
147
148                        free( real_name );
149                } else {                                                                                // otherwise, print the whole line
150                        cerr << "(" << frameNo << ") " << messages[i] << endl;
151                } // if
152        } // for
153
154        free( messages );
155} // backtrace
156
157void sigSegvBusHandler( int sig_num ) {
158        cerr << "*CFA runtime error* program cfa-cpp terminated with "
159                 <<     (sig_num == SIGSEGV ? "segment fault" : "bus error")
160                 << "." << endl;
161        backtrace( 2 );                                                                         // skip first 2 stack frames
162        exit( EXIT_FAILURE );
163} // sigSegvBusHandler
164
165void sigAbortHandler( __attribute__((unused)) int sig_num ) {
166        backtrace( 6 );                                                                         // skip first 6 stack frames
167        signal( SIGABRT, SIG_DFL);                                                      // reset default signal handler
168    raise( SIGABRT );                                                                   // reraise SIGABRT
169} // sigAbortHandler
170
171
172int main( int argc, char * argv[] ) {
173        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
174        ostream *output = & cout;
175        const char *filename = nullptr;
176        list< Declaration * > translationUnit;
177
178        signal( SIGSEGV, sigSegvBusHandler );
179        signal( SIGBUS, sigSegvBusHandler );
180        signal( SIGABRT, sigAbortHandler );
181
182        parse_cmdline( argc, argv, filename );                          // process command-line arguments
183        CodeGen::FixMain::setReplaceMain( !nomainp );
184
185        try {
186                // choose to read the program from a file or stdin
187                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
188                        input = fopen( argv[ optind ], "r" );
189                        assertf( input, "cannot open %s\n", argv[ optind ] );
190                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
191                        if ( filename == nullptr ) filename = argv[ optind ];
192                        // prelude filename comes in differently
193                        if ( libcfap ) filename = "prelude.cf";
194                        optind += 1;
195                } else {                                                                                // no input file name
196                        input = stdin;
197                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
198                        // a fake name along
199                        if ( filename == nullptr ) filename = "stdin";
200                } // if
201
202                // read in the builtins, extras, and the prelude
203                if ( ! nopreludep ) {                                                   // include gcc builtins
204                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
205
206                        // Read to gcc builtins, if not generating the cfa library
207                        FILE * gcc_builtins = fopen( libcfap | treep ? "../prelude/gcc-builtins.cf" : CFA_LIBDIR "/gcc-builtins.cf", "r" );
208                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
209                        parse( gcc_builtins, LinkageSpec::Compiler );
210
211                        // read the extra prelude in, if not generating the cfa library
212                        FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
213                        assertf( extras, "cannot open extras.cf\n" );
214                        parse( extras, LinkageSpec::BuiltinC );
215
216                        if ( ! libcfap ) {
217                                // read the prelude in, if not generating the cfa library
218                                FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
219                                assertf( prelude, "cannot open prelude.cf\n" );
220                                parse( prelude, LinkageSpec::Intrinsic );
221
222                                // Read to cfa builtins, if not generating the cfa library
223                                FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
224                                assertf( builtins, "cannot open builtins.cf\n" );
225                                parse( builtins, LinkageSpec::BuiltinCFA );
226                        } // if
227                } // if
228
229                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
230
231                if ( parsep ) {
232                        parseTree->printList( cout );
233                        delete parseTree;
234                        return 0;
235                } // if
236
237                buildList( parseTree, translationUnit );
238                delete parseTree;
239                parseTree = nullptr;
240                collect( translationUnit );
241
242                if ( astp ) {
243                        dump( translationUnit );
244                        return 0;
245                } // if
246
247                // add the assignment statement after the initialization of a type parameter
248                PASS( "validate", SymTab::validate( translationUnit, symtabp ) );
249                if ( symtabp ) return 0;
250                collect( translationUnit );
251
252                if ( expraltp ) {
253                        PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
254                        acceptAll( translationUnit, printer );
255                        return 0;
256                } // if
257
258                if ( validp ) {
259                        dump( translationUnit );
260                        return 0;
261                } // if
262
263                PASS( "mutate", ControlStruct::mutate( translationUnit ) );
264                PASS( "fixNames", CodeGen::fixNames( translationUnit ) );
265                PASS( "genInit", InitTweak::genInit( translationUnit ) );
266                PASS( "expandMemberTuples" , Tuples::expandMemberTuples( translationUnit ) );
267                collect( translationUnit );
268                if ( libcfap ) {
269                        // generate the bodies of cfa library functions
270                        LibCfa::makeLibCfa( translationUnit );
271                } // if
272
273                if ( declstatsp ) {
274                        CodeTools::printDeclStats( translationUnit );
275                        return 0;
276                }
277
278                if ( bresolvep ) {
279                        dump( translationUnit );
280                        return 0;
281                } // if
282
283                CodeTools::fillLocations( translationUnit );
284
285                PASS( "resolve", ResolvExpr::resolve( translationUnit ) );
286                collect( translationUnit );
287                if ( exprp ) {
288                        dump( translationUnit );
289                        return 0;
290                } // if
291
292                // fix ObjectDecl - replaces ConstructorInit nodes
293                PASS( "fixInit", InitTweak::fix( translationUnit, filename, libcfap || treep ) );
294                collect( translationUnit );
295                if ( ctorinitp ) {
296                        dump ( translationUnit );
297                        return 0;
298                } // if
299
300                PASS( "expandUniqueExpr", 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
301
302                PASS( "translateEHM" , ControlStruct::translateEHM( translationUnit ) );
303
304                PASS( "generateWaitfor" , Concurrency::generateWaitFor( translationUnit ) );
305
306                PASS( "convertSpecializations",  GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
307
308                PASS( "expandTuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
309                collect( translationUnit );
310                if ( tuplep ) {
311                        dump( translationUnit );
312                        return 0;
313                }
314
315                PASS( "virtual expandCasts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
316
317                PASS( "instantiateGenerics", GenPoly::instantiateGeneric( translationUnit ) );
318                collect( translationUnit );
319                if ( genericsp ) {
320                        dump( translationUnit );
321                        return 0;
322                }
323                PASS( "convertLvalue", GenPoly::convertLvalue( translationUnit ) );
324                collect( translationUnit );
325                if ( bboxp ) {
326                        dump( translationUnit );
327                        return 0;
328                } // if
329                PASS( "box", GenPoly::box( translationUnit ) );
330                collect( translationUnit );
331                if ( bcodegenp ) {
332                        dump( translationUnit );
333                        return 0;
334                }
335
336                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
337                        output = new ofstream( argv[ optind ] );
338                } // if
339
340                CodeTools::fillLocations( translationUnit );
341                PASS( "codegen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );
342
343                CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
344                if ( output != &cout ) {
345                        delete output;
346                } // if
347        } catch ( SemanticErrorException &e ) {
348                if ( errorp ) {
349                        cerr << "---AST at error:---" << endl;
350                        dump( translationUnit, cerr );
351                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
352                } // if
353                e.print();
354                if ( output != &cout ) {
355                        delete output;
356                } // if
357                return 1;
358        } catch ( UnimplementedError &e ) {
359                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
360                if ( output != &cout ) {
361                        delete output;
362                } // if
363                return 1;
364        } catch ( CompilerError &e ) {
365                cerr << "Compiler Error: " << e.get_what() << endl;
366                cerr << "(please report bugs to [REDACTED])" << endl;
367                if ( output != &cout ) {
368                        delete output;
369                } // if
370                return 1;
371        } catch(...) {
372                std::exception_ptr eptr = std::current_exception();
373                try {
374                        if (eptr) {
375                                std::rethrow_exception(eptr);
376                        }
377                        else {
378                                std::cerr << "Exception Uncaught and Unkown" << std::endl;
379                        }
380                } catch(const std::exception& e) {
381                        std::cerr << "Unaught Exception \"" << e.what() << "\"\n";
382                }
383                return 1;
384        }// try
385
386        if(!libcfap && !treep) HeapStats::printStats();
387        return 0;
388} // main
389
390void parse_cmdline( int argc, char * argv[], const char *& filename ) {
391        enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
392
393        static struct option long_opts[] = {
394                { "ast", no_argument, 0, Ast },
395                { "before-box", no_argument, 0, Bbox },
396                { "before-resolver", no_argument, 0, Bresolver },
397                { "ctorinitfix", no_argument, 0, CtorInitFix },
398                { "decl-stats", no_argument, 0, DeclStats },
399                { "expr", no_argument, 0, Expr },
400                { "expralt", no_argument, 0, ExprAlt },
401                { "grammar", no_argument, 0, Grammar },
402                { "libcfa", no_argument, 0, LibCFA },
403                { "line-marks", no_argument, 0, Linemarks },
404                { "no-line-marks", no_argument, 0, Nolinemarks },
405                { "no-preamble", no_argument, 0, Nopreamble },
406                { "parse", no_argument, 0, Parse },
407                { "no-prototypes", no_argument, 0, Prototypes },
408                { "resolver", no_argument, 0, Resolver },
409                { "symbol", no_argument, 0, Symbol },
410                { "tree", no_argument, 0, Tree },
411                { "tuple-expansion", no_argument, 0, TupleExpansion },
412                { "validate", no_argument, 0, Validate },
413                { 0, 0, 0, 0 }
414        }; // long_opts
415        int long_index;
416
417        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
418
419        bool Wsuppress = false, Werror = false;
420        int c;
421        while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrstTvwW:yzZD:F:", long_opts, &long_index )) != -1 ) {
422                switch ( c ) {
423                  case Ast:
424                  case 'a':                                                                             // dump AST
425                        astp = true;
426                        break;
427                  case Bresolver:
428                  case 'b':                                                                             // print before resolver steps
429                        bresolvep = true;
430                        break;
431                  case 'B':                                                                             // print before box steps
432                        bboxp = true;
433                        break;
434                  case CtorInitFix:
435                  case 'c':                                                                             // print after constructors and destructors are replaced
436                        ctorinitp = true;
437                        break;
438                  case 'C':                                                                             // print before code generation
439                        bcodegenp = true;
440                        break;
441                  case DeclStats:
442                  case 'd':
443                    declstatsp = true;
444                        break;
445                  case Expr:
446                  case 'e':                                                                             // dump AST after expression analysis
447                        exprp = true;
448                        break;
449                  case ExprAlt:
450                  case 'f':                                                                             // print alternatives for expressions
451                        expraltp = true;
452                        break;
453                  case Grammar:
454                  case 'g':                                                                             // bison debugging info (grammar rules)
455                        yydebug = true;
456                        break;
457                  case 'G':                                                                             // dump AST after instantiate generics
458                        genericsp = true;
459                        break;
460                  case LibCFA:
461                  case 'l':                                                                             // generate libcfa.c
462                        libcfap = true;
463                        break;
464                  case Linemarks:
465                  case 'L':                                                                             // print lines marks
466                        linemarks = true;
467                        break;
468                  case Nopreamble:
469                  case 'n':                                                                             // do not read preamble
470                        nopreludep = true;
471                        break;
472                  case Nolinemarks:
473                  case 'N':                                                                             // suppress line marks
474                        linemarks = false;
475                        break;
476                  case Prototypes:
477                  case 'p':                                                                             // generate prototypes for preamble functions
478                        noprotop = true;
479                        break;
480                  case 'm':                                                                             // don't replace the main
481                        nomainp = true;
482                        break;
483                  case Parse:
484                  case 'q':                                                                             // dump parse tree
485                        parsep = true;
486                        break;
487                  case Resolver:
488                  case 'r':                                                                             // print resolver steps
489                        resolvep = true;
490                        break;
491                  case Symbol:
492                  case 's':                                                                             // print symbol table events
493                        symtabp = true;
494                        break;
495                  case Tree:
496                  case 't':                                                                             // build in tree
497                        treep = true;
498                        break;
499                  case TupleExpansion:
500                  case 'T':                                                                             // print after tuple expansion
501                        tuplep = true;
502                        break;
503                  case 'v':                                                                             // dump AST after decl validation pass
504                        validp = true;
505                        break;
506                  case 'w':
507                        Wsuppress = true;
508                        break;
509                  case 'W':
510                        if ( strcmp( optarg, "all" ) == 0 ) {
511                                SemanticWarning_EnableAll();
512                        } else if ( strcmp( optarg, "error" ) == 0 ) {
513                                Werror = true;
514                        } else {
515                                char * warning = optarg;
516                                Severity s;
517                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
518                                        warning += 3;
519                                        s = Severity::Suppress;
520                                } else {
521                                        s = Severity::Warn;
522                                } // if
523                                SemanticWarning_Set( warning, s );
524                        } // if
525                        break;
526                  case 'y':                                                                             // dump AST on error
527                        errorp = true;
528                        break;
529                  case 'z':                                                                             // dump as codegen rather than AST
530                        codegenp = true;
531                        break;
532                        case 'Z':                                                                       // prettyprint during codegen (i.e. print unmangled names, etc.)
533                        prettycodegenp = true;
534                        break;
535                  case 'D':                                                                             // ignore -Dxxx
536                        break;
537                  case 'F':                                                                             // source file-name without suffix
538                        filename = optarg;
539                        break;
540                  case '?':
541                        if ( optopt ) {                                                         // short option ?
542                                assertf( false, "Unknown option: -%c\n", (char)optopt );
543                        } else {
544                                assertf( false, "Unknown option: %s\n", argv[optind - 1] );
545                        } // if
546                        #if defined(__GNUC__) && __GNUC__ >= 7
547                                __attribute__((fallthrough));
548                        #endif
549                  default:
550                        abort();
551                } // switch
552        } // while
553
554        if ( Werror ) {
555                SemanticWarning_WarningAsError();
556        } // if
557        if ( Wsuppress ) {
558                SemanticWarning_SuppressAll();
559        } // if
560        // for ( const auto w : WarningFormats ) {
561        //      cout << w.name << ' ' << (int)w.severity << endl;
562        // } // for
563} // parse_cmdline
564
565static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
566        extern int yyparse( void );
567        extern FILE * yyin;
568        extern int yylineno;
569
570        ::linkage = linkage;                                                            // set globals
571        yyin = input;
572        yylineno = 1;
573        typedefTable.enterScope();
574        int parseStatus = yyparse();
575
576        fclose( input );
577        if ( shouldExit || parseStatus != 0 ) {
578                exit( parseStatus );
579        } // if
580} // parse
581
582static bool notPrelude( Declaration * decl ) {
583        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
584} // notPrelude
585
586static void dump( list< Declaration * > & translationUnit, ostream & out ) {
587        list< Declaration * > decls;
588
589        if ( noprotop ) {
590                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
591        } else {
592                decls = translationUnit;
593        } // if
594
595        // depending on commandline options, either generate code or dump the AST
596        if ( codegenp ) {
597                CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
598        } else {
599                printAll( decls, out );
600        }
601} // dump
602
603// Local Variables: //
604// tab-width: 4 //
605// mode: c++ //
606// compile-command: "make install" //
607// End:  //
Note: See TracBrowser for help on using the repository browser.