source: src/main.cc @ 3f8dd01

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 3f8dd01 was be9288a, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed errors made by the clean-up tool

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