source: src/main.cc@ 436c0de

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 resolv-new with_gc
Last change on this file since 436c0de was b3c36f4, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Added some attribute((unused)) where appropriate

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