source: src/main.cc@ 6d611fb

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum stuck-waitfor-destruct with_gc
Last change on this file since 6d611fb was 6d611fb, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Implemented heap stats backend

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