source: src/main.cc @ 8f74a6a

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 8f74a6a was 8f74a6a, checked in by tdelisle <tdelisle@…>, 5 years ago

Added code to support generic statistic counters in the compiler

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