source: src/main.cc @ 6eb8948

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 6eb8948 was 6eb8948, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

make TupleAssignment? generate temporaries, add StmtExpr? for GCC statement expressions, expand tuple assignment expressions, collapse SolvedTupleExpr?, MassAssignExpr?, and MultipleAssignExpr? into TupleAssignExpr?

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