source: src/main.cc@ 7a7ab42

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 no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 7a7ab42 was 37fe352, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Added proper multi-lib handling, tests still do not work and arm support is broken

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