source: src/main.cc @ 9a32903

Last change on this file since 9a32903 was dacd2c19, checked in by Andrew Beach <ajbeach@…>, 6 months ago

Added Peter's fix to ensure syscall argument is initialized. I did check it against valgrind.

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