source: src/main.cc @ 3fe34ae

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

Added bootloader.cf which contains the main that wraps the user main

  • Property mode set to 100644
File size: 14.7 KB
RevLine 
[b87a5ed]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//
[71f4e4f]7// main.cc --
[b87a5ed]8//
[843054c2]9// Author           : Richard C. Bilson
[b87a5ed]10// Created On       : Fri May 15 23:12:02 2015
[dd51906]11// Last Modified By : Peter A. Buhr
[375a068]12// Last Modified On : Wed Dec 14 14:35:54 2016
13// Update Count     : 436
[b87a5ed]14//
15
[0270824]16#include <memory>
[51b7345]17#include <iostream>
18#include <fstream>
[e6955b1]19#include <signal.h>                                                                             // signal
20#include <getopt.h>                                                                             // getopt
[0afffee]21#include <execinfo.h>                                                                   // backtrace, backtrace_symbols
[e6955b1]22#include <cxxabi.h>                                                                             // __cxa_demangle
[0afffee]23#include <cstring>                                                                              // index
[e6955b1]24
25using namespace std;
26
[0da3e2c]27#include "Parser/lex.h"
28#include "Parser/parser.h"
29#include "Parser/TypedefTable.h"
[51b7345]30#include "GenPoly/Lvalue.h"
31#include "GenPoly/Specialize.h"
32#include "GenPoly/Box.h"
33#include "GenPoly/CopyParams.h"
[ea5daeb]34#include "GenPoly/InstantiateGeneric.h"
[51b7345]35#include "CodeGen/Generate.h"
36#include "CodeGen/FixNames.h"
37#include "ControlStruct/Mutate.h"
38#include "SymTab/Validate.h"
39#include "ResolvExpr/AlternativePrinter.h"
40#include "ResolvExpr/Resolver.h"
41#include "MakeLibCfa.h"
[a0fdbd5]42#include "InitTweak/GenInit.h"
[71f4e4f]43#include "InitTweak/FixInit.h"
[d3b7937]44#include "Common/UnimplementedError.h"
[51b7345]45#include "../config.h"
[6eb8948]46#include "Tuples/Tuples.h"
[51b7345]47
48using namespace std;
49
[e6955b1]50#define OPTPRINT(x) if ( errorp ) cerr << x << endl;
[81419b5]51
[0da3e2c]52
[8b7ee09]53LinkageSpec::Spec linkage = LinkageSpec::Cforall;
[0da3e2c]54TypedefTable typedefTable;
[cbaee0d]55DeclarationNode * parseTree = nullptr;                                  // program parse tree
[81419b5]56
[926af74]57extern int yydebug;                                                                             // set for -g flag (Grammar)
[b87a5ed]58bool
59        astp = false,
[de62360d]60        bresolvep = false,
[fea7ca7]61        bboxp = false,
[ca1c11f]62        ctorinitp = false,
[b87a5ed]63        exprp = false,
64        expraltp = false,
65        libcfap = false,
[de62360d]66        nopreludep = false,
[1ab4ce2]67        noprotop = false,
[3fe34ae]68        nomainp = false,
[de62360d]69        parsep = false,
[b87a5ed]70        resolvep = false,                                                                       // used in AlternativeFinder
71        symtabp = false,
[d3b7937]72        treep = false,
[626dbc10]73        tuplep = false,
[b87a5ed]74        validp = false,
[de62360d]75        errorp = false,
76        codegenp = false;
[b87a5ed]77
[926af74]78static void parse_cmdline( int argc, char *argv[], const char *& filename );
[8b7ee09]79static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
[e6955b1]80static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
81
[3fe34ae]82bool translation_unit_nomain = true;
[0270824]83std::unique_ptr<FunctionDecl> translation_unit_main_signature = nullptr;
84
[0afffee]85static void backtrace( int start ) {                                    // skip first N stack frames
[e6955b1]86        enum { Frames = 50 };
87        void * array[Frames];
[0afffee]88        int size = ::backtrace( array, Frames );
89        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
90
91        *index( messages[0], '(' ) = '\0';                                      // find executable name
92        cerr << "Stack back trace for: " << messages[0] << endl;
[e6955b1]93
[b542bfb]94        // skip last 2 stack frames after main
95        for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
[e6955b1]96                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
97                for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
[0afffee]98                        if ( *p == '(' ) {
[46f6134]99                                mangled_name = p;
[0afffee]100                        } else if ( *p == '+' ) {
[e6955b1]101                                offset_begin = p;
[0afffee]102                        } else if ( *p == ')' ) {
[e6955b1]103                                offset_end = p;
104                                break;
105                        } // if
106                } // for
107
108                // if line contains symbol, attempt to demangle
[b542bfb]109                int frameNo = i - start;
[e6955b1]110                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
[0afffee]111                        *mangled_name++ = '\0';                                         // delimit strings
[e6955b1]112                        *offset_begin++ = '\0';
113                        *offset_end++ = '\0';
114
[0afffee]115                        int status;
[e6955b1]116                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
[0afffee]117                        // bug in __cxa_demangle for single-character lower-case non-mangled names
[e6955b1]118                        if ( status == 0 ) {                                            // demangling successful ?
[b542bfb]119                                cerr << "(" << frameNo << ") " << messages[i] << " : "
[e6955b1]120                                         << real_name << "+" << offset_begin << offset_end << endl;
121                        } else {                                                                        // otherwise, output mangled name
[b542bfb]122                                cerr << "(" << frameNo << ") " << messages[i] << " : "
[0afffee]123                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
[e6955b1]124                        } // if
[0afffee]125
[e6955b1]126                        free( real_name );
127                } else {                                                                                // otherwise, print the whole line
[b542bfb]128                        cerr << "(" << frameNo << ") " << messages[i] << endl;
[e6955b1]129                } // if
130        } // for
[b542bfb]131
[e6955b1]132        free( messages );
[b542bfb]133} // backtrace
134
135void sigSegvBusHandler( int sig_num ) {
136        cerr << "*CFA runtime error* program cfa-cpp terminated with "
137                 <<     (sig_num == SIGSEGV ? "segment fault" : "bus error")
[0afffee]138                 << "." << endl;
[b542bfb]139        backtrace( 2 );                                                                         // skip first 2 stack frames
[e6955b1]140        exit( EXIT_FAILURE );
141} // sigSegvBusHandler
[0da3e2c]142
[b542bfb]143void sigAbortHandler( int sig_num ) {
144        backtrace( 6 );                                                                         // skip first 6 stack frames
145        signal( SIGABRT, SIG_DFL);                                                      // reset default signal handler
146    raise( SIGABRT );                                                                   // reraise SIGABRT
147} // sigAbortHandler
148
149
[cbaee0d]150int main( int argc, char * argv[] ) {
[3b8e52c]151        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
[e6955b1]152        ostream *output = & cout;
[926af74]153        const char *filename = nullptr;
[e6955b1]154        list< Declaration * > translationUnit;
155
156        signal( SIGSEGV, sigSegvBusHandler );
157        signal( SIGBUS, sigSegvBusHandler );
[b542bfb]158        signal( SIGABRT, sigAbortHandler );
[b87a5ed]159
[0da3e2c]160        parse_cmdline( argc, argv, filename );                          // process command-line arguments
[3fe34ae]161        translation_unit_nomain = nomainp;
[b87a5ed]162
163        try {
[81419b5]164                // choose to read the program from a file or stdin
[3b8e52c]165                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
[b87a5ed]166                        input = fopen( argv[ optind ], "r" );
[3b8e52c]167                        assertf( input, "cannot open %s\n", argv[ optind ] );
[d029162]168                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
[926af74]169                        if ( filename == nullptr ) filename = argv[ optind ];
[37024fd]170                        // prelude filename comes in differently
171                        if ( libcfap ) filename = "prelude.cf";
[b87a5ed]172                        optind += 1;
[3b8e52c]173                } else {                                                                                // no input file name
[b87a5ed]174                        input = stdin;
[2a7e29b]175                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
176                        // a fake name along
[926af74]177                        if ( filename == nullptr ) filename = "stdin";
[b87a5ed]178                } // if
179
[3b8e52c]180                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
[b87a5ed]181                        output = new ofstream( argv[ optind ] );
182                } // if
[71f4e4f]183
[159c62e]184                // read in the builtins, extras, and the prelude
[de62360d]185                if ( ! nopreludep ) {                                                   // include gcc builtins
[faf8857]186                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
[375a068]187                        FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
[3b8e52c]188                        assertf( builtins, "cannot open builtins.cf\n" );
[81419b5]189                        parse( builtins, LinkageSpec::Compiler );
190
[159c62e]191                        // read the extra prelude in, if not generating the cfa library
[375a068]192                        FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
[3b8e52c]193                        assertf( extras, "cannot open extras.cf\n" );
[159c62e]194                        parse( extras, LinkageSpec::C );
195
[81419b5]196                        if ( ! libcfap ) {
[faf8857]197                                // read the prelude in, if not generating the cfa library
[375a068]198                                FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
[3b8e52c]199                                assertf( prelude, "cannot open prelude.cf\n" );
[35304009]200                                parse( prelude, LinkageSpec::Intrinsic );
[b87a5ed]201                        } // if
202                } // if
[81419b5]203
[926af74]204                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
[71f4e4f]205
[b87a5ed]206                if ( parsep ) {
[e6955b1]207                        parseTree->printList( cout );
[0da3e2c]208                        delete parseTree;
[b87a5ed]209                        return 0;
210                } // if
211
[0da3e2c]212                buildList( parseTree, translationUnit );
213                delete parseTree;
[cbaee0d]214                parseTree = nullptr;
[b87a5ed]215
216                if ( astp ) {
[1ab4ce2]217                        dump( translationUnit );
[b87a5ed]218                        return 0;
219                } // if
220
[839ccbb]221                // add the assignment statement after the initialization of a type parameter
[81419b5]222                OPTPRINT( "validate" )
223                SymTab::validate( translationUnit, symtabp );
224                if ( symtabp ) {
[46f6134]225                        deleteAll( translationUnit );
[b87a5ed]226                        return 0;
227                } // if
228
[81419b5]229                if ( expraltp ) {
[e6955b1]230                        ResolvExpr::AlternativePrinter printer( cout );
[81419b5]231                        acceptAll( translationUnit, printer );
[b87a5ed]232                        return 0;
233                } // if
234
235                if ( validp ) {
[1ab4ce2]236                        dump( translationUnit );
[b87a5ed]237                        return 0;
238                } // if
239
[81419b5]240                OPTPRINT( "mutate" )
241                ControlStruct::mutate( translationUnit );
[71f4e4f]242                OPTPRINT( "fixNames" )
[81419b5]243                CodeGen::fixNames( translationUnit );
[f1e012b]244                OPTPRINT( "tweakInit" )
[a0fdbd5]245                InitTweak::genInit( translationUnit );
[bf32bb8]246                OPTPRINT( "expandMemberTuples" );
247                Tuples::expandMemberTuples( translationUnit );
[81419b5]248                if ( libcfap ) {
249                        // generate the bodies of cfa library functions
250                        LibCfa::makeLibCfa( translationUnit );
[b87a5ed]251                } // if
252
[de62360d]253                if ( bresolvep ) {
[1ab4ce2]254                        dump( translationUnit );
[de62360d]255                        return 0;
256                } // if
257
[81419b5]258                OPTPRINT( "resolve" )
[b87a5ed]259                ResolvExpr::resolve( translationUnit );
[81419b5]260                if ( exprp ) {
[1ab4ce2]261                        dump( translationUnit );
[ca1c11f]262                        return 0;
[926af74]263                } // if
[81419b5]264
[71f4e4f]265                // fix ObjectDecl - replaces ConstructorInit nodes
[6cf27a07]266                OPTPRINT( "fixInit" )
267                InitTweak::fix( translationUnit, filename, libcfap || treep );
[ca1c11f]268                if ( ctorinitp ) {
269                        dump ( translationUnit );
270                        return 0;
[926af74]271                } // if
[71f4e4f]272
[141b786]273                OPTPRINT( "expandUniqueExpr" ); // xxx - is this the right place for this? want to expand ASAP so that subsequent 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
274                Tuples::expandUniqueExpr( translationUnit );
[626dbc10]275
276                OPTPRINT( "convertSpecializations" ) // needs to happen before tuple types are expanded
277                GenPoly::convertSpecializations( translationUnit );
278
[d9fa60a]279                OPTPRINT( "expandTuples" ); // xxx - is this the right place for this?
280                Tuples::expandTuples( translationUnit );
[626dbc10]281                if ( tuplep ) {
282                        dump( translationUnit );
283                        return 0;
284                }
[141b786]285
[ea5daeb]286                OPTPRINT("instantiateGenerics")
287                GenPoly::instantiateGeneric( translationUnit );
[81419b5]288                OPTPRINT( "copyParams" );
[b87a5ed]289                GenPoly::copyParams( translationUnit );
[81419b5]290                OPTPRINT( "convertLvalue" )
[b87a5ed]291                GenPoly::convertLvalue( translationUnit );
[fea7ca7]292
293                if ( bboxp ) {
294                        dump( translationUnit );
295                        return 0;
[926af74]296                } // if
[81419b5]297                OPTPRINT( "box" )
[b87a5ed]298                GenPoly::box( translationUnit );
[81419b5]299
[2871210]300                // print tree right before code generation
[81419b5]301                if ( codegenp ) {
[1ab4ce2]302                        dump( translationUnit );
[81419b5]303                        return 0;
304                } // if
[b87a5ed]305
[1ab4ce2]306                CodeGen::generate( translationUnit, *output, ! noprotop );
[b87a5ed]307
[0270824]308                if( translation_unit_main_signature ) {
309                        *output << "int main(int argc, char** argv) { return ";
310
311                        *output << translation_unit_main_signature->get_scopedMangleName() << "(";
312                        if(translation_unit_main_signature->get_functionType()->get_parameters().size() != 0){
313                                *output << "argc, argv";
314                        }
315                        *output << ");";
316
317                        *output << " }\n";
318                }
319
[e6955b1]320                if ( output != &cout ) {
[b87a5ed]321                        delete output;
322                } // if
323        } catch ( SemanticError &e ) {
324                if ( errorp ) {
[e6955b1]325                        cerr << "---AST at error:---" << endl;
326                        dump( translationUnit, cerr );
327                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
[926af74]328                } // if
[e6955b1]329                e.print( cerr );
330                if ( output != &cout ) {
[b87a5ed]331                        delete output;
332                } // if
333                return 1;
334        } catch ( UnimplementedError &e ) {
[e6955b1]335                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
336                if ( output != &cout ) {
[b87a5ed]337                        delete output;
338                } // if
339                return 1;
340        } catch ( CompilerError &e ) {
[e6955b1]341                cerr << "Compiler Error: " << e.get_what() << endl;
342                cerr << "(please report bugs to " << endl;
343                if ( output != &cout ) {
[b87a5ed]344                        delete output;
345                } // if
346                return 1;
347        } // try
348
[39786813]349        deleteAll( translationUnit );
[b87a5ed]350        return 0;
[d9a0e76]351} // main
[51b7345]352
[cbaee0d]353void parse_cmdline( int argc, char * argv[], const char *& filename ) {
[626dbc10]354        enum { Ast, Bbox, Bresolver, CtorInitFix, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
[0da3e2c]355
356        static struct option long_opts[] = {
357                { "ast", no_argument, 0, Ast },
358                { "before-box", no_argument, 0, Bbox },
359                { "before-resolver", no_argument, 0, Bresolver },
360                { "ctorinitfix", no_argument, 0, CtorInitFix },
361                { "expr", no_argument, 0, Expr },
362                { "expralt", no_argument, 0, ExprAlt },
363                { "grammar", no_argument, 0, Grammar },
364                { "libcfa", no_argument, 0, LibCFA },
365                { "no-preamble", no_argument, 0, Nopreamble },
366                { "parse", no_argument, 0, Parse },
367                { "no-prototypes", no_argument, 0, Prototypes },
368                { "resolver", no_argument, 0, Resolver },
369                { "symbol", no_argument, 0, Symbol },
370                { "tree", no_argument, 0, Tree },
[626dbc10]371                { "tuple-expansion", no_argument, 0, TupleExpansion },
[0da3e2c]372                { "validate", no_argument, 0, Validate },
373                { 0, 0, 0, 0 }
374        }; // long_opts
375        int long_index;
376
377        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
378
379        int c;
[3fe34ae]380        while ( (c = getopt_long( argc, argv, "abBcefglmnpqrstTvyzD:F:", long_opts, &long_index )) != -1 ) {
[0da3e2c]381                switch ( c ) {
382                  case Ast:
383                  case 'a':                                                                             // dump AST
384                        astp = true;
385                        break;
386                  case Bresolver:
387                  case 'b':                                                                             // print before resolver steps
388                        bresolvep = true;
389                        break;
[626dbc10]390                  case 'B':                                                                             // print before box steps
[0da3e2c]391                        bboxp = true;
392                        break;
393                  case CtorInitFix:
394                  case 'c':
395                        ctorinitp = true;
396                        break;
397                  case Expr:
398                  case 'e':                                                                             // dump AST after expression analysis
399                        exprp = true;
400                        break;
401                  case ExprAlt:
402                  case 'f':                                                                             // print alternatives for expressions
403                        expraltp = true;
404                        break;
405                  case Grammar:
406                  case 'g':                                                                             // bison debugging info (grammar rules)
[926af74]407                        yydebug = true;
[0da3e2c]408                        break;
409                  case LibCFA:
410                  case 'l':                                                                             // generate libcfa.c
411                        libcfap = true;
412                        break;
413                  case Nopreamble:
414                  case 'n':                                                                             // do not read preamble
415                        nopreludep = true;
416                        break;
417                  case Prototypes:
418                  case 'p':                                                                             // generate prototypes for preamble functions
419                        noprotop = true;
420                        break;
[3fe34ae]421                  case 'm':                                                                             // don't replace the main
422                        nomainp = true;
423                        break;
[0da3e2c]424                  case Parse:
425                  case 'q':                                                                             // dump parse tree
426                        parsep = true;
427                        break;
428                  case Resolver:
429                  case 'r':                                                                             // print resolver steps
430                        resolvep = true;
431                        break;
432                  case Symbol:
433                  case 's':                                                                             // print symbol table events
434                        symtabp = true;
435                        break;
436                  case Tree:
437                  case 't':                                                                             // build in tree
438                        treep = true;
439                        break;
[626dbc10]440                  case TupleExpansion:
441                  case 'T':                                                                             // print after tuple expansion
442                        tuplep = true;
443                        break;
[0da3e2c]444                  case 'v':                                                                             // dump AST after decl validation pass
445                        validp = true;
446                        break;
447                  case 'y':
448                        errorp = true;
449                        break;
450                  case 'z':
451                        codegenp = true;
452                        break;
453                  case 'D':                                                                             // ignore -Dxxx
454                        break;
455                  case 'F':                                                                             // source file-name without suffix
456                        filename = optarg;
457                        break;
458                  case '?':
[3b8e52c]459                        assertf( false, "Unknown option: '%c'\n", (char)optopt );
[0da3e2c]460                  default:
461                        abort();
462                } // switch
463        } // while
464} // parse_cmdline
465
[8b7ee09]466static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
[0da3e2c]467        extern int yyparse( void );
[cbaee0d]468        extern FILE * yyin;
[0da3e2c]469        extern int yylineno;
470
[8b7ee09]471        ::linkage = linkage;                                                            // set globals
[0da3e2c]472        yyin = input;
473        yylineno = 1;
474        typedefTable.enterScope();
475        int parseStatus = yyparse();
[81419b5]476
477        fclose( input );
[0da3e2c]478        if ( shouldExit || parseStatus != 0 ) {
479                exit( parseStatus );
[81419b5]480        } // if
[0da3e2c]481} // parse
[81419b5]482
[1ab4ce2]483static bool notPrelude( Declaration * decl ) {
484        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
[0da3e2c]485} // notPrelude
[1ab4ce2]486
[e6955b1]487static void dump( list< Declaration * > & translationUnit, ostream & out ) {
488        list< Declaration * > decls;
[926af74]489
[1ab4ce2]490        if ( noprotop ) {
[e6955b1]491                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
[1ab4ce2]492        } else {
493                decls = translationUnit;
[926af74]494        } // if
[1ab4ce2]495
[f77f12e2]496        printAll( decls, out );
[7f5566b]497        deleteAll( translationUnit );
[0da3e2c]498} // dump
[1ab4ce2]499
[51b7345]500// Local Variables: //
[b87a5ed]501// tab-width: 4 //
502// mode: c++ //
503// compile-command: "make install" //
[51b7345]504// End:  //
Note: See TracBrowser for help on using the repository browser.