source: src/main.cpp @ dc1c430

Last change on this file since dc1c430 was 793eb2f, checked in by Andrew Beach <ajbeach@…>, 2 weeks ago

One extra whitespace line removed. I do not believe that represented an important ordering point.

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