source: src/main.cc @ 348006f

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 348006f was 64adb03, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Added first implementation of mutex keyword

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