source: src/main.cpp@ 4d5c5b6a

Last change on this file since 4d5c5b6a was d3d54b3, checked in by Michael Brooks <mlbrooks@…>, 8 months ago

Eliminate warnings due to sizeof returning type inconsistent with %zu. Fix #269.

Test

nowarn/printf-sizeof

: Activate direct test of the bug.

Tests

alloc-ERROR
extension
array-collections/dimexpr-match-c-ERRS

: Accommodate incidental changes in error-message text or generated code.

  • Property mode set to 100644
File size: 28.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.cpp --
8//
9// Author : Peter Buhr and Rob Schluntz
10// Created On : Fri May 15 23:12:02 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sun Jun 23 16:38:09 2024
13// Update Count : 691
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 <cassert> // for assertf
20#include <cstdio> // for fopen, FILE, fclose, stdin
21#include <cstdlib> // for exit, free, abort, EXIT_F...
22#include <csignal> // for signal, SIGABRT, SIGSEGV
23#include <cstring> // for index
24#include <fstream> // for ofstream
25#include <iostream> // for operator<<, basic_ostream
26#include <iomanip>
27#include <iterator> // for back_inserter
28#include <list> // for list
29#include <string> // for char_traits, operator<<
30
31#include "AST/Pass.hpp" // for pass_visitor_stats
32#include "AST/Print.hpp" // for printAll
33#include "AST/TranslationUnit.hpp" // for TranslationUnit
34#include "AST/Util.hpp" // for checkInvariants
35#include "CompilationState.hpp"
36#include "../config.h" // for CFA_LIBDIR
37#include "CodeGen/FixMain.hpp" // for FixMain
38#include "CodeGen/FixNames.hpp" // for fixNames
39#include "CodeGen/Generate.hpp" // for generate
40#include "CodeGen/LinkOnce.hpp" // for translateLinkOnce
41#include "Common/CodeLocationTools.hpp" // for forceFillCodeLocations
42#include "Common/DeclStats.hpp" // for printDeclStats
43#include "Common/ResolvProtoDump.hpp" // for dumpAsResolverProto
44#include "Common/Stats.hpp" // for Stats
45#include "Common/Utility.hpp" // for deleteAll, filter, printAll
46#include "Concurrency/Actors.hpp" // for implementActors
47#include "Concurrency/Corun.hpp" // for implementCorun
48#include "Concurrency/Keywords.hpp" // for implementMutex, implement...
49#include "Concurrency/Waitfor.hpp" // for generateWaitfor
50#include "Concurrency/Waituntil.hpp" // for generateWaitUntil
51#include "ControlStruct/ExceptDecl.hpp" // for translateExcept
52#include "ControlStruct/ExceptTranslate.hpp"// for translateThrows, translat...
53#include "ControlStruct/FixLabels.hpp" // for fixLabels
54#include "ControlStruct/HoistControlDecls.hpp" // hoistControlDecls
55#include "ControlStruct/TranslateEnumRange.hpp" // translateEnumRange
56#include "GenPoly/Box.hpp" // for box
57#include "GenPoly/InstantiateGeneric.hpp" // for instantiateGeneric
58#include "GenPoly/Lvalue.hpp" // for convertLvalue
59#include "GenPoly/Specialize.hpp" // for convertSpecializations
60#include "InitTweak/FixInit.hpp" // for fix
61#include "InitTweak/GenInit.hpp" // for genInit
62#include "MakeLibCfa.hpp" // for makeLibCfa
63#include "Parser/RunParser.hpp" // for buildList, dumpParseTree,...
64#include "ResolvExpr/CandidatePrinter.hpp" // for printCandidates
65#include "ResolvExpr/EraseWith.hpp" // for eraseWith
66#include "ResolvExpr/Resolver.hpp" // for resolve
67#include "Tuples/Tuples.hpp" // for expandMemberTuples, expan...
68#include "Validate/Autogen.hpp" // for autogenerateRoutines
69#include "Validate/CheckAssertions.hpp" // for checkAssertions
70#include "Validate/CompoundLiteral.hpp" // for handleCompoundLiterals
71#include "Validate/EliminateTypedef.hpp" // for eliminateTypedef
72#include "Validate/EnumAndPointerDecay.hpp" // for decayEnumsAndPointers
73#include "Validate/FindSpecialDecls.hpp" // for findGlobalDecls
74#include "Validate/FixQualifiedTypes.hpp" // for fixQualifiedTypes
75#include "Validate/FixReturnTypes.hpp" // for fixReturnTypes
76#include "Validate/ForallPointerDecay.hpp" // for decayForallPointers
77#include "Validate/GenericParameter.hpp" // for fillGenericParameters, tr...
78#include "Validate/HoistStruct.hpp" // for hoistStruct
79#include "Validate/HoistTypeDecls.hpp" // for hoistTypeDecls
80#include "Validate/ImplementEnumFunc.hpp" // for implementEnumFunc
81#include "Validate/InitializerLength.hpp" // for setLengthFromInitializer
82#include "Validate/LabelAddressFixer.hpp" // for fixLabelAddresses
83#include "Validate/LinkInstanceTypes.hpp" // for linkInstanceTypes
84#include "Validate/ReplaceTypedef.hpp" // for replaceTypedef
85#include "Validate/ReturnCheck.hpp" // for checkReturnStatements
86#include "Validate/VerifyCtorDtorAssign.hpp" // for verifyCtorDtorAssign
87#include "Virtual/ExpandCasts.hpp" // for expandCasts
88#include "Virtual/VirtualDtor.hpp" // for implementVirtDtors
89
90using namespace std;
91
92static void NewPass( const char * const name ) {
93 Stats::Heap::newPass( name );
94 using namespace Stats::Counters;
95 {
96 static auto group = build<CounterGroup>( "Pass Visitor Template" );
97 auto pass = build<CounterGroup>( name, group );
98 ast::pass_visitor_stats.depth = 0;
99 ast::pass_visitor_stats.avg = build<AverageCounter<double>>( "Average Depth", pass );
100 ast::pass_visitor_stats.max = build<MaxCounter<double>>( "Max Depth", pass );
101 }
102}
103
104#define PASS( name, pass, unit, ... ) \
105 if ( errorp ) { cerr << name << endl; } \
106 NewPass(name); \
107 Stats::Time::StartBlock(name); \
108 pass(unit,##__VA_ARGS__); \
109 Stats::Time::StopBlock(); \
110 if ( invariant ) { \
111 ast::checkInvariants(unit); \
112 }
113
114#define DUMP( cond, unit ) \
115 if ( cond ) { \
116 dump( std::move( unit ) ); \
117 return EXIT_SUCCESS; \
118 }
119
120static bool waiting_for_gdb = false; // flag to set cfa-cpp to wait for gdb on start
121
122static string PreludeDirector = "";
123
124static void parse_cmdline( int argc, char * argv[] );
125static void dump( ast::TranslationUnit && transUnit, ostream & out = cout );
126
127static void backtrace( int start );
128static void initSignals();
129
130int main( int argc, char * argv[] ) {
131 FILE * input; // use FILE rather than istream because yyin is FILE
132 ostream * output = & cout;
133 ast::TranslationUnit transUnit;
134
135 initSignals();
136
137 // cout << "main" << endl;
138 // for ( int i = 0; i < argc; i += 1 ) {
139 // cout << '\t' << argv[i] << endl;
140 // } // for
141
142 parse_cmdline( argc, argv ); // process command-line arguments
143
144 if ( waiting_for_gdb ) {
145 cerr << "Waiting for gdb" << endl;
146 cerr << "run :" << endl;
147 cerr << " gdb attach " << getpid() << endl;
148 raise(SIGSTOP);
149 } // if
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 because %s\n", argv[ optind ], strerror( errno ) );
156 optind += 1;
157 } else { // no input file name
158 input = stdin;
159 } // if
160
161 Stats::Time::StartGlobal();
162 NewPass("Parse");
163 Stats::Time::StartBlock("Parse");
164
165 // read in the builtins, extras, and the prelude
166 if ( ! nopreludep ) { // include gcc builtins
167 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
168
169 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
170
171 // Read to gcc builtins, if not generating the cfa library
172 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cfa").c_str(), "r" );
173 assertf( gcc_builtins, "cannot open gcc-builtins.cfa\n" );
174 parse( gcc_builtins, ast::Linkage::Compiler );
175
176 // read the extra prelude in, if not generating the cfa library
177 FILE * extras = fopen( (PreludeDirector + "/extras.cfa").c_str(), "r" );
178 assertf( extras, "cannot open extras.cfa\n" );
179 parse( extras, ast::Linkage::BuiltinC );
180 if ( ! libcfap ) {
181 // read the prelude in, if not generating the cfa library
182 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
183 assertf( prelude, "cannot open prelude.cfa\n" );
184 parse( prelude, ast::Linkage::Intrinsic );
185
186 // Read to cfa builtins, if not generating the cfa library
187 FILE * builtins = fopen( (PreludeDirector + "/builtins.cfa").c_str(), "r" );
188 assertf( builtins, "cannot open builtins.cfa\n" );
189 parse( builtins, ast::Linkage::BuiltinCFA );
190 } // if
191 } // if
192
193 parse( input, libcfap ? ast::Linkage::Intrinsic : ast::Linkage::Cforall, yydebug );
194
195 transUnit = buildUnit();
196
197 DUMP( astp, transUnit );
198
199 Stats::Time::StopBlock();
200
201 ast::TranslationDeps::evolve( transUnit );
202
203 PASS( "Hoist Type Decls", Validate::hoistTypeDecls, transUnit );
204
205 PASS( "Translate Exception Declarations", ControlStruct::translateExcept, transUnit );
206 DUMP( exdeclp, transUnit );
207 PASS( "Verify Ctor, Dtor & Assign", Validate::verifyCtorDtorAssign, transUnit );
208 PASS( "Replace Typedefs", Validate::replaceTypedef, transUnit );
209 PASS( "Fix Return Types", Validate::fixReturnTypes, transUnit );
210 PASS( "Check Assertions", Validate::checkAssertions, transUnit );
211 PASS( "Enum and Pointer Decay", Validate::decayEnumsAndPointers, transUnit );
212
213 PASS( "Link Instance Types", Validate::linkInstanceTypes, transUnit );
214
215 PASS( "Forall Pointer Decay", Validate::decayForallPointers, transUnit );
216 PASS( "Fix Qualified Types", Validate::fixQualifiedTypes, transUnit );
217 PASS( "Eliminate Typedef", Validate::eliminateTypedef, transUnit );
218 PASS( "Hoist Struct", Validate::hoistStruct, transUnit );
219 PASS( "Validate Generic Parameters", Validate::fillGenericParameters, transUnit );
220 PASS( "Translate Enum Range Expression", ControlStruct::translateEnumRange, transUnit );
221 PASS( "Translate Dimensions", Validate::translateDimensionParameters, transUnit );
222 PASS( "Generate Enum Attributes Functions", Validate::implementEnumFunc, transUnit );
223 PASS( "Check Function Returns", Validate::checkReturnStatements, transUnit );
224 PASS( "Fix Return Statements", InitTweak::fixReturnStatements, transUnit );
225 PASS( "Implement Concurrent Keywords", Concurrency::implementKeywords, transUnit );
226 PASS( "Fix Unique Ids", Validate::fixUniqueIds, transUnit );
227 PASS( "Implement Corun", Concurrency::implementCorun, transUnit );
228 PASS( "Fix Label Address", Validate::fixLabelAddresses, transUnit );
229 PASS( "Fix Labels", ControlStruct::fixLabels, transUnit );
230 PASS( "Hoist Control Declarations", ControlStruct::hoistControlDecls, transUnit );
231
232 PASS( "Generate Autogen Routines", Validate::autogenerateRoutines, transUnit );
233
234 PASS( "Implement Actors", Concurrency::implementActors, transUnit );
235 PASS( "Implement Virtual Destructors", Virtual::implementVirtDtors, transUnit );
236 PASS( "Implement Mutex", Concurrency::implementMutex, transUnit );
237 PASS( "Implement Thread Start", Concurrency::implementThreadStarter, transUnit );
238 PASS( "Compound Literal", Validate::handleCompoundLiterals, transUnit );
239 PASS( "Set Length From Initializer", Validate::setLengthFromInitializer, transUnit );
240 PASS( "Find Global Decls", Validate::findGlobalDecls, transUnit );
241
242 if ( symtabp ) {
243 return EXIT_SUCCESS;
244 } // if
245
246 if ( expraltp ) {
247 ResolvExpr::printCandidates( transUnit );
248 return EXIT_SUCCESS;
249 } // if
250
251 DUMP( validp, transUnit );
252
253 PASS( "Translate Throws", ControlStruct::translateThrows, transUnit );
254 PASS( "Implement Waituntil", Concurrency::generateWaitUntil, transUnit );
255 PASS( "Fix Names", CodeGen::fixNames, transUnit );
256 PASS( "Gen Init", InitTweak::genInit, transUnit );
257 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples, transUnit );
258
259 if ( libcfap ) {
260 // Generate the bodies of cfa library functions.
261 LibCfa::makeLibCfa( transUnit );
262 } // if
263
264 if ( declstatsp ) {
265 printDeclStats( transUnit );
266 return EXIT_SUCCESS;
267 } // if
268
269 DUMP( bresolvep, transUnit );
270
271 if ( resolvprotop ) {
272 dumpAsResolverProto( transUnit );
273 return EXIT_SUCCESS;
274 } // if
275
276 PASS( "Resolve", ResolvExpr::resolve, transUnit );
277 DUMP( exprp, transUnit );
278 PASS( "Fix Init", InitTweak::fix, transUnit, buildingLibrary() ); // Here
279 PASS( "Erase With", ResolvExpr::eraseWith, transUnit );
280
281 // fix ObjectDecl - replaces ConstructorInit nodes
282 DUMP( ctorinitp, transUnit );
283
284 // Currently not working due to unresolved issues with UniqueExpr
285 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr, transUnit ); // 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
286
287 PASS( "Translate Tries", ControlStruct::translateTries, transUnit );
288 PASS( "Gen Waitfor", Concurrency::generateWaitFor, transUnit );
289 PASS( "Fix Main Linkage", CodeGen::fixMainLinkage, transUnit, !nomainp );
290
291 // Needs to happen before tuple types are expanded.
292 PASS( "Convert Specializations", GenPoly::convertSpecializations, transUnit );
293
294 PASS( "Expand Tuples", Tuples::expandTuples, transUnit );
295 DUMP( tuplep, transUnit );
296
297 // Must come after Translate Tries.
298 PASS( "Virtual Expand Casts", Virtual::expandCasts, transUnit );
299
300 PASS( "Instantiate Generics", GenPoly::instantiateGeneric, transUnit );
301 DUMP( genericsp, transUnit );
302
303 PASS( "Convert L-Value", GenPoly::convertLvalue, transUnit );
304 DUMP( bboxp, transUnit );
305 PASS( "Box", GenPoly::box, transUnit );
306 PASS( "Link-Once", CodeGen::translateLinkOnce, transUnit );
307
308 // Code has been lowered to C, now we can start generation.
309
310 DUMP( bcodegenp, transUnit );
311
312 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
313 output = new ofstream( argv[ optind ] );
314 } // if
315
316 PASS( "Code Gen", CodeGen::generate, transUnit, *output, !genproto, prettycodegenp, true, linemarks, false );
317 CodeGen::fixMainInvoke( transUnit, *output, (PreludeDirector + "/bootloader.c").c_str() );
318
319 if ( output != &cout ) {
320 delete output;
321 } // if
322 } catch ( SemanticErrorException & e ) {
323 if ( errorp ) {
324 cerr << "---AST at error:---" << endl;
325 dump( std::move( transUnit ), cerr );
326 cerr << endl << "---End of AST, begin error message:---\n" << endl;
327 } // if
328 e.print();
329 if ( output != &cout ) {
330 delete output;
331 } // if
332 return EXIT_FAILURE;
333 } catch ( std::bad_alloc & ) {
334 cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
335 backtrace( 1 );
336 abort();
337 } catch ( ... ) {
338 exception_ptr eptr = current_exception();
339 try {
340 if (eptr) {
341 rethrow_exception(eptr);
342 } else {
343 cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
344 } // if
345 } catch( const exception & e ) {
346 cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
347 } // try
348 return EXIT_FAILURE;
349 } // try
350
351 // This pseudo-pass is used to get more accurate heap statistics.
352 NewPass("Clean-up");
353 Stats::Time::StartBlock("Clean-Up");
354 transUnit.global = ast::TranslationGlobal();
355 transUnit.decls.clear();
356 Stats::Time::StopBlock();
357
358 Stats::print();
359 return EXIT_SUCCESS;
360} // main
361
362
363static const char optstring[] = ":c:ghilLmNnpdP:S:twW:D:";
364
365enum { PreludeDir = 128 };
366static struct option long_opts[] = {
367 { "colors", required_argument, nullptr, 'c' },
368 { "gdb", no_argument, nullptr, 'g' },
369 { "help", no_argument, nullptr, 'h' },
370 { "invariant", no_argument, nullptr, 'i' },
371 { "libcfa", no_argument, nullptr, 'l' },
372 { "linemarks", no_argument, nullptr, 'L' },
373 { "no-main", no_argument, nullptr, 'm' },
374 { "no-linemarks", no_argument, nullptr, 'N' },
375 { "no-prelude", no_argument, nullptr, 'n' },
376 { "prototypes", no_argument, nullptr, 'p' },
377 { "deterministic-out", no_argument, nullptr, 'd' },
378 { "print", required_argument, nullptr, 'P' },
379 { "prelude-dir", required_argument, nullptr, PreludeDir },
380 { "statistics", required_argument, nullptr, 'S' },
381 { "tree", no_argument, nullptr, 't' },
382 { "", no_argument, nullptr, 0 }, // -w
383 { "", no_argument, nullptr, 0 }, // -W
384 { "", no_argument, nullptr, 0 }, // -D
385 { nullptr, 0, nullptr, 0 }
386}; // long_opts
387
388static const char * description[] = {
389 "diagnostic color: never, always, auto", // -c
390 "wait for gdb to attach", // -g
391 "print translator help message", // -h
392 "invariant checking during AST passes", // -i
393 "generate libcfa.c", // -l
394 "generate line marks", // -L
395 "do not replace main", // -m
396 "do not generate line marks", // -N
397 "do not read prelude", // -n
398 "do not generate prelude prototypes => prelude not printed", // -p
399 "only print deterministic output", // -d
400 "print", // -P
401 "<directory> prelude directory for debug/nodebug", // no flag
402 "<option-list> enable profiling information: counters, heap, time, all, none", // -S
403 "building cfa standard lib", // -t
404 "", // -w
405 "", // -W
406 "", // -D
407}; // description
408
409static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
410
411static struct Printopts {
412 const char * name;
413 int & flag;
414 int val;
415 const char * descript;
416} printopts[] = {
417 { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
418 { "asterr", errorp, true, "print AST on error" },
419 { "declstats", declstatsp, true, "print code property statistics" },
420 { "parse", yydebug, true, "print yacc (parsing) debug information" },
421 { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
422 { "rproto", resolvprotop, true, "resolver-proto instance" },
423 { "rsteps", resolvep, true, "print resolver steps" },
424 // AST dumps
425 { "ast", astp, true, "print AST after parsing" },
426 { "excpdecl", exdeclp, true, "print AST after translating exception decls" },
427 { "symevt", symtabp, true, "print AST after symbol table events" },
428 { "expralt", expraltp, true, "print AST after expressions alternatives" },
429 { "valdecl", validp, true, "print AST after declaration validation pass" },
430 { "bresolver", bresolvep, true, "print AST before resolver step" },
431 { "expranly", exprp, true, "print AST after expression analysis" },
432 { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
433 { "tuple", tuplep, true, "print AST after tuple expansion" },
434 { "instgen", genericsp, true, "print AST after instantiate generics" },
435 { "bbox", bboxp, true, "print AST before box pass" },
436 { "bcodegen", bcodegenp, true, "print AST before code generation" }
437};
438enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
439
440static void usage( char * argv[] ) {
441 cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
442 int i = 0, j = 1; // j skips starting colon
443 for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
444 if ( long_opts[i].name[0] != '\0' ) { // hidden option, internal usage only
445 if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
446 cout << " -" << optstring[j] << ",";
447 } else { // no flag
448 j -= 1; // compensate
449 cout << " ";
450 } // if
451 cout << " --" << left << setw(12) << long_opts[i].name << " ";
452 if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
453 cout << "one of: " << endl;
454 for ( int i = 0; i < printoptsSize; i += 1 ) {
455 cout << setw(10) << " " << left << setw(10) << printopts[i].name << " " << printopts[i].descript << endl;
456 } // for
457 } else {
458 cout << description[i] << endl;
459 } // if
460 } // if
461 if ( optstring[j + 1] == ':' ) j += 1;
462 } // for
463 if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
464 exit( EXIT_FAILURE );
465} // usage
466
467static void parse_cmdline( int argc, char * argv[] ) {
468 opterr = 0; // (global) prevent getopt from printing error messages
469
470 bool Wsuppress = false, Werror = false;
471 int c;
472 while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
473 switch ( c ) {
474 case 'c': // diagnostic colors
475 if ( strcmp( optarg, "always" ) == 0 ) {
476 ErrorHelpers::colors = ErrorHelpers::Colors::Always;
477 } else if ( strcmp( optarg, "never" ) == 0 ) {
478 ErrorHelpers::colors = ErrorHelpers::Colors::Never;
479 } else if ( strcmp( optarg, "auto" ) == 0 ) {
480 ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
481 } // if
482 break;
483 case 'h': // help message
484 usage( argv ); // no return
485 break;
486 case 'i': // invariant checking
487 invariant = true;
488 break;
489 case 'l': // generate libcfa.c
490 libcfap = true;
491 break;
492 case 'L': // generate line marks
493 linemarks = true;
494 break;
495 case 'm': // do not replace main
496 nomainp = true;
497 break;
498 case 'N': // do not generate line marks
499 linemarks = false;
500 break;
501 case 'n': // do not read prelude
502 nopreludep = true;
503 break;
504 case 'p': // generate prototypes for prelude functions
505 genproto = true;
506 break;
507 case 'd': // don't print non-deterministic output
508 deterministic_output = true;
509 break;
510 case 'P': // print options
511 for ( int i = 0;; i += 1 ) {
512 if ( i == printoptsSize ) {
513 cout << "Unknown --print option " << optarg << endl;
514 goto Default;
515 } // if
516 if ( strcmp( optarg, printopts[i].name ) == 0 ) {
517 printopts[i].flag = printopts[i].val;
518 break;
519 } // if
520 } // for
521 break;
522 case PreludeDir: // prelude directory for debug/nodebug, hidden
523 PreludeDirector = optarg;
524 break;
525 case 'S': // enable profiling information, argument comma separated list of names
526 Stats::parse_params( optarg );
527 break;
528 case 't': // building cfa stdlib
529 treep = true;
530 break;
531 case 'g': // wait for gdb
532 waiting_for_gdb = true;
533 break;
534 case 'w': // suppress all warnings, hidden
535 Wsuppress = true;
536 break;
537 case 'W': // coordinate gcc -W with CFA, hidden
538 if ( strcmp( optarg, "all" ) == 0 ) {
539 SemanticWarning_EnableAll();
540 } else if ( strcmp( optarg, "error" ) == 0 ) {
541 Werror = true;
542 } else {
543 char * warning = optarg;
544 Severity s;
545 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
546 warning += 3;
547 s = Severity::Suppress;
548 } else {
549 s = Severity::Warn;
550 } // if
551 SemanticWarning_Set( warning, s );
552 } // if
553 break;
554 case 'D': // ignore -Dxxx, forwarded by cpp, hidden
555 break;
556 case '?': // unknown option
557 if ( optopt ) { // short option ?
558 cout << "Unknown option -" << (char)optopt << endl;
559 } else {
560 cout << "Unknown option " << argv[optind - 1] << endl;
561 } // if
562 goto Default;
563 case ':': // missing option
564 if ( optopt ) { // short option ?
565 cout << "Missing option for -" << (char)optopt << endl;
566 } else {
567 cout << "Missing option for " << argv[optind - 1] << endl;
568 } // if
569 goto Default;
570 Default:
571 default:
572 usage( argv ); // no return
573 } // switch
574 } // while
575
576 if ( Werror ) {
577 SemanticWarning_WarningAsError();
578 } // if
579 if ( Wsuppress ) {
580 SemanticWarning_SuppressAll();
581 } // if
582 // for ( const auto w : WarningFormats ) {
583 // cout << w.name << ' ' << (int)w.severity << endl;
584 // } // for
585} // parse_cmdline
586
587static bool notPrelude( ast::ptr<ast::Decl> & decl ) {
588 return !decl->linkage.is_builtin;
589}
590
591static void dump( ast::TranslationUnit && unit, std::ostream & out ) {
592 // May filter out all prelude declarations.
593 if ( genproto ) {
594 std::list<ast::ptr<ast::Decl>> decls;
595 std::copy_if( unit.decls.begin(), unit.decls.end(),
596 std::back_inserter( decls ), notPrelude );
597 decls.swap( unit.decls );
598 }
599
600 // May print as full dump or as code generation.
601 if ( codegenp ) {
602 CodeGen::generate( unit, out, !genproto, prettycodegenp, false, false, false );
603 } else {
604 ast::printAll( out, unit.decls );
605 }
606}
607
608static void backtrace( int start ) { // skip first N stack frames
609 enum { Frames = 50, }; // maximum number of stack frames
610 void * array[Frames];
611 size_t size = ::backtrace( array, Frames );
612 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
613
614 *index( messages[0], '(' ) = '\0'; // find executable name
615 cerr << "Stack back trace for: " << messages[0] << endl;
616
617 // skip last 2 stack frames after main
618 for ( unsigned int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
619 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
620
621 for ( char * p = messages[i]; *p; p += 1 ) { // find parantheses and +offset
622 if ( *p == '(' ) {
623 mangled_name = p;
624 } else if ( *p == '+' ) {
625 offset_begin = p;
626 } else if ( *p == ')' ) {
627 offset_end = p;
628 break;
629 } // if
630 } // for
631
632 // if line contains symbol, attempt to demangle
633 int frameNo = i - start;
634 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
635 *mangled_name++ = '\0'; // delimit strings
636 *offset_begin++ = '\0';
637 *offset_end++ = '\0';
638
639 int status;
640 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
641 // bug in __cxa_demangle for single-character lower-case non-mangled names
642 if ( status == 0 ) { // demangling successful ?
643 cerr << "(" << frameNo << ") " << messages[i] << " : "
644 << real_name << "+" << offset_begin << offset_end << endl;
645 } else { // otherwise, output mangled name
646 cerr << "(" << frameNo << ") " << messages[i] << " : "
647 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
648 } // if
649
650 free( real_name );
651 } else { // otherwise, print the whole line
652 cerr << "(" << frameNo << ") " << messages[i] << endl;
653 } // if
654 } // for
655
656 free( messages );
657} // backtrace
658
659#define SIGPARMS int sig __attribute__(( unused )), siginfo_t * sfp __attribute__(( unused )), ucontext_t * cxt __attribute__(( unused ))
660
661static void _Signal(struct sigaction & act, int sig, int flags ) {
662 sigemptyset( &act.sa_mask );
663 act.sa_flags = flags;
664
665 if ( sigaction( sig, &act, nullptr ) == -1 ) {
666 cerr << "*cfa-cpp compilation error* problem installing signal handler, error(" << errno << ") " << strerror( errno ) << endl;
667 _exit( EXIT_FAILURE );
668 } // if
669}
670
671static void Signal( int sig, void (* handler)(SIGPARMS), int flags ) {
672 struct sigaction act;
673 act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
674 _Signal(act, sig, flags);
675} // Signal
676
677static void Signal( int sig, void (* handler)(int), int flags ) {
678 struct sigaction act;
679 act.sa_handler = handler;
680 _Signal(act, sig, flags);
681} // Signal
682
683static void sigSegvBusHandler( SIGPARMS ) {
684 if ( sfp->si_addr == nullptr ) {
685 cerr << "Null pointer (nullptr) dereference." << endl;
686 } else {
687 cerr << (sig == SIGSEGV ? "Segment fault" : "Bus error") << " at memory location " << sfp->si_addr << "." << endl
688 << "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript." << endl;
689 } // if
690 backtrace( 2 ); // skip first 2 stack frames
691 abort(); // cause core dump for debugging
692} // sigSegvBusHandler
693
694static void sigFpeHandler( SIGPARMS ) {
695 const char * msg;
696
697 switch ( sfp->si_code ) {
698 case FPE_INTDIV: case FPE_FLTDIV: msg = "divide by zero"; break;
699 case FPE_FLTOVF: msg = "overflow"; break;
700 case FPE_FLTUND: msg = "underflow"; break;
701 case FPE_FLTRES: msg = "inexact result"; break;
702 case FPE_FLTINV: msg = "invalid operation"; break;
703 default: msg = "unknown";
704 } // choose
705 cerr << "Computation error " << msg << " at location " << sfp->si_addr << endl
706 << "Possible cause is constant-expression evaluation invalid." << endl;
707 backtrace( 2 ); // skip first 2 stack frames
708 abort(); // cause core dump for debugging
709} // sigFpeHandler
710
711static void sigAbortHandler( SIGPARMS ) {
712 backtrace( 6 ); // skip first 6 stack frames
713 Signal( SIGABRT, SIG_DFL, SA_SIGINFO ); // reset default signal handler
714 raise( SIGABRT ); // reraise SIGABRT
715} // sigAbortHandler
716
717static void initSignals() {
718 Signal( SIGSEGV, sigSegvBusHandler, SA_SIGINFO );
719 Signal( SIGBUS, sigSegvBusHandler, SA_SIGINFO );
720 Signal( SIGFPE, sigFpeHandler, SA_SIGINFO );
721 Signal( SIGABRT, sigAbortHandler, SA_SIGINFO );
722}
723
724// Local Variables: //
725// tab-width: 4 //
726// mode: c++ //
727// compile-command: "make install" //
728// End: //
Note: See TracBrowser for help on using the repository browser.