source: src/main.cc @ 30f9072

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 30f9072 was bf2438c, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Cleaned-up some headers using a tool called 'include-what-you-use'

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