source: src/main.cc@ 4f97937

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 4f97937 was 4f97937, checked in by tdelisle <tdelisle@…>, 7 years ago

First draft at timing results, left is better printing and more data

  • Property mode set to 100644
File size: 20.6 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 : Sat Feb 16 09:14:04 2019
13// Update Count : 500
14//
15
16#include <cxxabi.h> // for __cxa_demangle
17#include <execinfo.h> // for backtrace, backtrace_symbols
18#include <getopt.h> // for no_argument, optind, geto...
19#include <signal.h> // for signal, SIGABRT, SIGSEGV
20#include <cassert> // for assertf
21#include <cstdio> // for fopen, FILE, fclose, stdin
22#include <cstdlib> // for exit, free, abort, EXIT_F...
23#include <cstring> // for index
24#include <fstream> // for ofstream
25#include <iostream> // for operator<<, basic_ostream
26#include <iterator> // for back_inserter
27#include <list> // for list
28#include <string> // for char_traits, operator<<
29
30#include "CompilationState.h"
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/ResolvProtoDump.h" // for dumpAsResolvProto
37#include "CodeTools/TrackLoc.h" // for fillLocations
38#include "Common/CompilerError.h" // for CompilerError
39#include "Common/Stats.h"
40#include "Common/PassVisitor.h"
41#include "Common/SemanticError.h" // for SemanticError
42#include "Common/UnimplementedError.h" // for UnimplementedError
43#include "Common/utility.h" // for deleteAll, filter, printAll
44#include "Concurrency/Waitfor.h" // for generateWaitfor
45#include "ControlStruct/ExceptTranslate.h" // for translateEHM
46#include "ControlStruct/Mutate.h" // for mutate
47#include "GenPoly/Box.h" // for box
48#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
49#include "GenPoly/Lvalue.h" // for convertLvalue
50#include "GenPoly/Specialize.h" // for convertSpecializations
51#include "InitTweak/FixInit.h" // for fix
52#include "InitTweak/GenInit.h" // for genInit
53#include "MakeLibCfa.h" // for makeLibCfa
54#include "Parser/LinkageSpec.h" // for Spec, Cforall, Intrinsic
55#include "Parser/ParseNode.h" // for DeclarationNode, buildList
56#include "Parser/TypedefTable.h" // for TypedefTable
57#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
58#include "ResolvExpr/Resolver.h" // for resolve
59#include "SymTab/Validate.h" // for validate
60#include "SynTree/Declaration.h" // for Declaration
61#include "SynTree/Visitor.h" // for acceptAll
62#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
63#include "Virtual/ExpandCasts.h" // for expandCasts
64
65using namespace std;
66
67
68void NewPass(const char * const name) {
69 Stats::Heap::newPass(name);
70 using namespace Stats::Counters;
71 static auto pass_visitor_group = build<CounterGroup>("Pass Visitor");
72 auto pass = build<CounterGroup>(name, pass_visitor_group);
73 pass_visitor_stats.depth = 0;
74 pass_visitor_stats.avg = build<AverageCounter<double>>("Average Depth", pass);
75 pass_visitor_stats.max = build<MaxCounter<double>>("Max Depth", pass);
76}
77
78#define PASS(name, pass) \
79 if ( errorp ) { cerr << name << endl; } \
80 NewPass(name); \
81 Stats::Time::StartBlock(name); \
82 pass; \
83 Stats::Time::StopBlock();
84
85LinkageSpec::Spec linkage = LinkageSpec::Cforall;
86TypedefTable typedefTable;
87DeclarationNode * parseTree = nullptr; // program parse tree
88
89std::string PreludeDirector = "";
90
91static void parse_cmdline( int argc, char *argv[], const char *& filename );
92static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
93static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
94
95static void backtrace( int start ) { // skip first N stack frames
96 enum { Frames = 50 };
97 void * array[Frames];
98 int size = ::backtrace( array, Frames );
99 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
100
101 *index( messages[0], '(' ) = '\0'; // find executable name
102 cerr << "Stack back trace for: " << messages[0] << endl;
103
104 // skip last 2 stack frames after main
105 for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
106 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
107 for ( char *p = messages[i]; *p; ++p ) { // find parantheses and +offset
108 if ( *p == '(' ) {
109 mangled_name = p;
110 } else if ( *p == '+' ) {
111 offset_begin = p;
112 } else if ( *p == ')' ) {
113 offset_end = p;
114 break;
115 } // if
116 } // for
117
118 // if line contains symbol, attempt to demangle
119 int frameNo = i - start;
120 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
121 *mangled_name++ = '\0'; // delimit strings
122 *offset_begin++ = '\0';
123 *offset_end++ = '\0';
124
125 int status;
126 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
127 // bug in __cxa_demangle for single-character lower-case non-mangled names
128 if ( status == 0 ) { // demangling successful ?
129 cerr << "(" << frameNo << ") " << messages[i] << " : "
130 << real_name << "+" << offset_begin << offset_end << endl;
131 } else { // otherwise, output mangled name
132 cerr << "(" << frameNo << ") " << messages[i] << " : "
133 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
134 } // if
135
136 free( real_name );
137 } else { // otherwise, print the whole line
138 cerr << "(" << frameNo << ") " << messages[i] << endl;
139 } // if
140 } // for
141
142 free( messages );
143} // backtrace
144
145void sigSegvBusHandler( int sig_num ) {
146 cerr << "*CFA runtime error* program cfa-cpp terminated with "
147 << (sig_num == SIGSEGV ? "segment fault" : "bus error")
148 << "." << endl;
149 backtrace( 2 ); // skip first 2 stack frames
150 //_exit( EXIT_FAILURE );
151 abort();
152} // sigSegvBusHandler
153
154void sigAbortHandler( __attribute__((unused)) int sig_num ) {
155 backtrace( 6 ); // skip first 6 stack frames
156 signal( SIGABRT, SIG_DFL); // reset default signal handler
157 raise( SIGABRT ); // reraise SIGABRT
158} // sigAbortHandler
159
160
161int main( int argc, char * argv[] ) {
162 FILE * input; // use FILE rather than istream because yyin is FILE
163 ostream * output = & cout;
164 const char * filename = nullptr;
165 list< Declaration * > translationUnit;
166
167 signal( SIGSEGV, sigSegvBusHandler );
168 signal( SIGBUS, sigSegvBusHandler );
169 signal( SIGABRT, sigAbortHandler );
170
171 // std::cout << "main" << std::endl;
172 // for ( int i = 0; i < argc; i += 1 ) {
173 // std::cout << '\t' << argv[i] << std::endl;
174 // } // for
175
176 parse_cmdline( argc, argv, filename ); // process command-line arguments
177 CodeGen::FixMain::setReplaceMain( !nomainp );
178
179 try {
180 // choose to read the program from a file or stdin
181 if ( optind < argc ) { // any commands after the flags ? => input file name
182 input = fopen( argv[ optind ], "r" );
183 assertf( input, "cannot open %s\n", argv[ optind ] );
184 // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
185 if ( filename == nullptr ) filename = argv[ optind ];
186 // prelude filename comes in differently
187 if ( libcfap ) filename = "prelude.cfa";
188 optind += 1;
189 } else { // no input file name
190 input = stdin;
191 // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
192 // a fake name along
193 if ( filename == nullptr ) filename = "stdin";
194 } // if
195
196 NewPass("Parse");
197
198 // read in the builtins, extras, and the prelude
199 if ( ! nopreludep ) { // include gcc builtins
200 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
201
202 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
203
204 // Read to gcc builtins, if not generating the cfa library
205 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
206 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
207 parse( gcc_builtins, LinkageSpec::Compiler );
208
209 // read the extra prelude in, if not generating the cfa library
210 FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
211 assertf( extras, "cannot open extras.cf\n" );
212 parse( extras, LinkageSpec::BuiltinC );
213
214 if ( ! libcfap ) {
215 // read the prelude in, if not generating the cfa library
216 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
217 assertf( prelude, "cannot open prelude.cfa\n" );
218 parse( prelude, LinkageSpec::Intrinsic );
219
220 // Read to cfa builtins, if not generating the cfa library
221 FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
222 assertf( builtins, "cannot open builtins.cf\n" );
223 parse( builtins, LinkageSpec::BuiltinCFA );
224 } // if
225 } // if
226
227 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
228
229 if ( parsep ) {
230 parseTree->printList( cout );
231 delete parseTree;
232 return 0;
233 } // if
234
235 buildList( parseTree, translationUnit );
236 delete parseTree;
237 parseTree = nullptr;
238
239 if ( astp ) {
240 dump( translationUnit );
241 return 0;
242 } // if
243
244 // Temporary: fill locations after parsing so that every node has a location, for early error messages.
245 // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
246 // works okay for now.
247 CodeTools::fillLocations( translationUnit );
248
249 // add the assignment statement after the initialization of a type parameter
250 PASS( "Validate", SymTab::validate( translationUnit, symtabp ) );
251 if ( symtabp ) {
252 deleteAll( translationUnit );
253 return 0;
254 } // if
255
256 if ( expraltp ) {
257 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
258 acceptAll( translationUnit, printer );
259 return 0;
260 } // if
261
262 if ( validp ) {
263 dump( translationUnit );
264 return 0;
265 } // if
266
267 PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
268 PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
269 PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
270 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
271 if ( libcfap ) {
272 // generate the bodies of cfa library functions
273 LibCfa::makeLibCfa( translationUnit );
274 } // if
275
276 if ( declstatsp ) {
277 CodeTools::printDeclStats( translationUnit );
278 deleteAll( translationUnit );
279 return 0;
280 }
281
282 if ( bresolvep ) {
283 dump( translationUnit );
284 return 0;
285 } // if
286
287 CodeTools::fillLocations( translationUnit );
288
289 if ( resolvprotop ) {
290 CodeTools::dumpAsResolvProto( translationUnit );
291 return 0;
292 }
293
294 PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
295 if ( exprp ) {
296 dump( translationUnit );
297 return 0;
298 } // if
299
300 // fix ObjectDecl - replaces ConstructorInit nodes
301 PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
302 if ( ctorinitp ) {
303 dump ( translationUnit );
304 return 0;
305 } // if
306
307 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( translationUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent 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
308
309 PASS( "Translate EHM" , ControlStruct::translateEHM( translationUnit ) );
310
311 PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
312
313 PASS( "Convert Specializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
314
315 PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
316
317 if ( tuplep ) {
318 dump( translationUnit );
319 return 0;
320 }
321
322 PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
323
324 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
325 if ( genericsp ) {
326 dump( translationUnit );
327 return 0;
328 }
329 PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
330
331
332 if ( bboxp ) {
333 dump( translationUnit );
334 return 0;
335 } // if
336 PASS( "Box", GenPoly::box( translationUnit ) );
337
338 if ( bcodegenp ) {
339 dump( translationUnit );
340 return 0;
341 }
342
343 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
344 output = new ofstream( argv[ optind ] );
345 } // if
346
347 CodeTools::fillLocations( translationUnit );
348 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );
349
350 CodeGen::FixMain::fix( *output, (PreludeDirector + "/bootloader.c").c_str() );
351 if ( output != &cout ) {
352 delete output;
353 } // if
354 } catch ( SemanticErrorException &e ) {
355 if ( errorp ) {
356 cerr << "---AST at error:---" << endl;
357 dump( translationUnit, cerr );
358 cerr << endl << "---End of AST, begin error message:---\n" << endl;
359 } // if
360 e.print();
361 if ( output != &cout ) {
362 delete output;
363 } // if
364 return 1;
365 } catch ( UnimplementedError &e ) {
366 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
367 if ( output != &cout ) {
368 delete output;
369 } // if
370 return 1;
371 } catch ( CompilerError &e ) {
372 cerr << "Compiler Error: " << e.get_what() << endl;
373 cerr << "(please report bugs to [REDACTED])" << endl;
374 if ( output != &cout ) {
375 delete output;
376 } // if
377 return 1;
378 } catch(...) {
379 std::exception_ptr eptr = std::current_exception();
380 try {
381 if (eptr) {
382 std::rethrow_exception(eptr);
383 }
384 else {
385 std::cerr << "Exception Uncaught and Unkown" << std::endl;
386 }
387 } catch(const std::exception& e) {
388 std::cerr << "Uncaught Exception \"" << e.what() << "\"\n";
389 }
390 return 1;
391 }// try
392
393 deleteAll( translationUnit );
394 Stats::print();
395
396 return 0;
397} // main
398
399void parse_cmdline( int argc, char * argv[], const char *& filename ) {
400 enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, PreludeDir, Prototypes, Resolver, ResolvProto, Stats, Symbol, Tree, TupleExpansion, Validate};
401
402 static struct option long_opts[] = {
403 { "ast", no_argument, 0, Ast },
404 { "before-box", no_argument, 0, Bbox },
405 { "before-resolver", no_argument, 0, Bresolver },
406 { "ctorinitfix", no_argument, 0, CtorInitFix },
407 { "decl-stats", no_argument, 0, DeclStats },
408 { "expr", no_argument, 0, Expr },
409 { "expralt", no_argument, 0, ExprAlt },
410 { "grammar", no_argument, 0, Grammar },
411 { "libcfa", no_argument, 0, LibCFA },
412 { "line-marks", no_argument, 0, Linemarks },
413 { "no-line-marks", no_argument, 0, Nolinemarks },
414 { "no-preamble", no_argument, 0, Nopreamble },
415 { "parse", no_argument, 0, Parse },
416 { "prelude-dir", required_argument, 0, PreludeDir },
417 { "no-prototypes", no_argument, 0, Prototypes },
418 { "resolver", no_argument, 0, Resolver },
419 { "resolv-proto", no_argument, 0, ResolvProto },
420 { "stats", required_argument, 0, Stats },
421 { "symbol", no_argument, 0, Symbol },
422 { "tree", no_argument, 0, Tree },
423 { "tuple-expansion", no_argument, 0, TupleExpansion },
424 { "validate", no_argument, 0, Validate },
425 { 0, 0, 0, 0 }
426 }; // long_opts
427 int long_index;
428
429 opterr = 0; // (global) prevent getopt from printing error messages
430
431 bool Wsuppress = false, Werror = false;
432 int c;
433 while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrRstTvwW:yzZD:F:", long_opts, &long_index )) != -1 ) {
434 switch ( c ) {
435 case Ast:
436 case 'a': // dump AST
437 astp = true;
438 break;
439 case Bresolver:
440 case 'b': // print before resolver steps
441 bresolvep = true;
442 break;
443 case 'B': // print before box steps
444 bboxp = true;
445 break;
446 case CtorInitFix:
447 case 'c': // print after constructors and destructors are replaced
448 ctorinitp = true;
449 break;
450 case 'C': // print before code generation
451 bcodegenp = true;
452 break;
453 case DeclStats:
454 case 'd':
455 declstatsp = true;
456 break;
457 case Expr:
458 case 'e': // dump AST after expression analysis
459 exprp = true;
460 break;
461 case ExprAlt:
462 case 'f': // print alternatives for expressions
463 expraltp = true;
464 break;
465 case Grammar:
466 case 'g': // bison debugging info (grammar rules)
467 yydebug = true;
468 break;
469 case 'G': // dump AST after instantiate generics
470 genericsp = true;
471 break;
472 case LibCFA:
473 case 'l': // generate libcfa.c
474 libcfap = true;
475 break;
476 case Linemarks:
477 case 'L': // print lines marks
478 linemarks = true;
479 break;
480 case Nopreamble:
481 case 'n': // do not read preamble
482 nopreludep = true;
483 break;
484 case Nolinemarks:
485 case 'N': // suppress line marks
486 linemarks = false;
487 break;
488 case Prototypes:
489 case 'p': // generate prototypes for preamble functions
490 noprotop = true;
491 break;
492 case PreludeDir:
493 PreludeDirector = optarg;
494 break;
495 case 'm': // don't replace the main
496 nomainp = true;
497 break;
498 case Parse:
499 case 'q': // dump parse tree
500 parsep = true;
501 break;
502 case Resolver:
503 case 'r': // print resolver steps
504 resolvep = true;
505 break;
506 case 'R': // dump resolv-proto instance
507 resolvprotop = true;
508 break;
509 case Stats:
510 Stats::parse_params(optarg);
511 break;
512 case Symbol:
513 case 's': // print symbol table events
514 symtabp = true;
515 break;
516 case Tree:
517 case 't': // build in tree
518 treep = true;
519 break;
520 case TupleExpansion:
521 case 'T': // print after tuple expansion
522 tuplep = true;
523 break;
524 case 'v': // dump AST after decl validation pass
525 validp = true;
526 break;
527 case 'w':
528 Wsuppress = true;
529 break;
530 case 'W':
531 if ( strcmp( optarg, "all" ) == 0 ) {
532 SemanticWarning_EnableAll();
533 } else if ( strcmp( optarg, "error" ) == 0 ) {
534 Werror = true;
535 } else {
536 char * warning = optarg;
537 Severity s;
538 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
539 warning += 3;
540 s = Severity::Suppress;
541 } else {
542 s = Severity::Warn;
543 } // if
544 SemanticWarning_Set( warning, s );
545 } // if
546 break;
547 case 'y': // dump AST on error
548 errorp = true;
549 break;
550 case 'z': // dump as codegen rather than AST
551 codegenp = true;
552 break;
553 case 'Z': // prettyprint during codegen (i.e. print unmangled names, etc.)
554 prettycodegenp = true;
555 break;
556 case 'D': // ignore -Dxxx
557 break;
558 case 'F': // source file-name without suffix
559 filename = optarg;
560 break;
561 case '?':
562 if ( optopt ) { // short option ?
563 assertf( false, "Unknown option: -%c\n", (char)optopt );
564 } else {
565 assertf( false, "Unknown option: %s\n", argv[optind - 1] );
566 } // if
567 #if defined(__GNUC__) && __GNUC__ >= 7
568 __attribute__((fallthrough));
569 #endif
570 default:
571 abort();
572 } // switch
573 } // while
574
575 if ( Werror ) {
576 SemanticWarning_WarningAsError();
577 } // if
578 if ( Wsuppress ) {
579 SemanticWarning_SuppressAll();
580 } // if
581 // for ( const auto w : WarningFormats ) {
582 // cout << w.name << ' ' << (int)w.severity << endl;
583 // } // for
584} // parse_cmdline
585
586static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
587 extern int yyparse( void );
588 extern FILE * yyin;
589 extern int yylineno;
590
591 ::linkage = linkage; // set globals
592 yyin = input;
593 yylineno = 1;
594 int parseStatus = yyparse();
595
596 fclose( input );
597 if ( shouldExit || parseStatus != 0 ) {
598 exit( parseStatus );
599 } // if
600} // parse
601
602static bool notPrelude( Declaration * decl ) {
603 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
604} // notPrelude
605
606static void dump( list< Declaration * > & translationUnit, ostream & out ) {
607 list< Declaration * > decls;
608
609 if ( noprotop ) {
610 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
611 } else {
612 decls = translationUnit;
613 } // if
614
615 // depending on commandline options, either generate code or dump the AST
616 if ( codegenp ) {
617 CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
618 } else {
619 printAll( decls, out );
620 }
621 deleteAll( translationUnit );
622} // dump
623
624// Local Variables: //
625// tab-width: 4 //
626// mode: c++ //
627// compile-command: "make install" //
628// End: //
Note: See TracBrowser for help on using the repository browser.