source: src/main.cc @ ecaeac6e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since ecaeac6e was ecaeac6e, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Better statistics formatting

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