source: src/main.cc @ 05e6eb5

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 05e6eb5 was 05e6eb5, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Warn about constructor/destructor priorities 101-200 only when not building the library

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