source: src/main.cpp@ b24cbaf

Last change on this file since b24cbaf was 82a5ea2, checked in by Andrew Beach <ajbeach@…>, 13 months ago

Added checks for (and a test to check the checks) assertions we will not be able to adapt. Using an adapted version of Mike's error message.

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