source: src/AST/SymbolTable.cpp @ 561354f

ADT
Last change on this file since 561354f was 561354f, checked in by JiadaL <j82liang@…>, 12 months ago

Save progress

  • Property mode set to 100644
File size: 28.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// SymbolTable.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed May 29 11:00:00 2019
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count     : 1
14//
15
16#include "SymbolTable.hpp"
17
18#include <cassert>
19
20#include "Decl.hpp"
21#include "Expr.hpp"
22#include "Inspect.hpp"
23#include "Type.hpp"
24#include "CodeGen/OperatorTable.h"         // for isCtorDtorAssign
25#include "Common/SemanticError.h"
26#include "Common/Stats/Counter.h"
27#include "GenPoly/GenPoly.h"
28#include "InitTweak/InitTweak.h"
29#include "ResolvExpr/Cost.h"
30#include "ResolvExpr/CandidateFinder.hpp"  // for referenceToRvalueConversion
31#include "ResolvExpr/Unify.h"
32#include "SymTab/Mangler.h"
33
34namespace ast {
35
36// Statistics block
37namespace {
38        static inline auto stats() {
39                using namespace Stats::Counters;
40                static auto group   = build<CounterGroup>("Indexers");
41                static struct {
42                        SimpleCounter * count;
43                        AverageCounter<double> * size;
44                        SimpleCounter * new_scopes;
45                        SimpleCounter * lazy_scopes;
46                        AverageCounter<double> * avg_scope_depth;
47                        MaxCounter<size_t> * max_scope_depth;
48                        SimpleCounter * add_calls;
49                        SimpleCounter * lookup_calls;
50                        SimpleCounter * map_lookups;
51                        SimpleCounter * map_mutations;
52                } ret = {
53                        .count   = build<SimpleCounter>("Count", group),
54                        .size    = build<AverageCounter<double>>("Average Size", group),
55                        .new_scopes = build<SimpleCounter>("Scopes", group),
56                        .lazy_scopes = build<SimpleCounter>("Lazy Scopes", group),
57                        .avg_scope_depth = build<AverageCounter<double>>("Average Scope", group),
58                        .max_scope_depth = build<MaxCounter<size_t>>("Max Scope", group),
59                        .add_calls = build<SimpleCounter>("Add Calls", group),
60                        .lookup_calls = build<SimpleCounter>("Lookup Calls", group),
61                        .map_lookups = build<SimpleCounter>("Map Lookups", group),
62                        .map_mutations = build<SimpleCounter>("Map Mutations", group)
63                };
64                return ret;
65        }
66}
67
68Expr * SymbolTable::IdData::combine( const CodeLocation & loc, ResolvExpr::Cost & cost ) const {
69        Expr * ret;
70        if ( baseExpr ) {
71                if (baseExpr->env) {
72                        Expr * base = deepCopy(baseExpr);
73                        const TypeSubstitution * subs = baseExpr->env;
74                        base->env = nullptr;
75                        ret = new MemberExpr{loc, id, referenceToRvalueConversion( base, cost )};
76                        ret->env = subs;
77                }
78                else {
79                        ret = new MemberExpr{ loc, id, referenceToRvalueConversion( baseExpr, cost ) };
80                }
81        }
82        else {
83                ret = new VariableExpr{ loc, id };
84        }
85        if ( deleter ) { ret = new DeletedExpr{ loc, ret, deleter }; }
86        return ret;
87}
88
89SymbolTable::SymbolTable()
90: idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable(),
91  prevScope(), scope( 0 ), repScope( 0 ) { ++*stats().count; }
92
93SymbolTable::~SymbolTable() { stats().size->push( idTable ? idTable->size() : 0 ); }
94
95void SymbolTable::enterScope() {
96        ++scope;
97
98        ++*stats().new_scopes;
99        stats().avg_scope_depth->push( scope );
100        stats().max_scope_depth->push( scope );
101}
102
103void SymbolTable::leaveScope() {
104        if ( repScope == scope ) {
105                Ptr prev = prevScope;           // make sure prevScope stays live
106                *this = std::move(*prevScope);  // replace with previous scope
107        }
108
109        --scope;
110}
111
112SymbolTable::SpecialFunctionKind SymbolTable::getSpecialFunctionKind(const std::string & name) {
113        if (name == "?{}") return CTOR;
114        if (name == "^?{}") return DTOR;
115        if (name == "?=?") return ASSIGN;
116        return NUMBER_OF_KINDS;
117}
118
119std::vector<SymbolTable::IdData> SymbolTable::lookupId( const std::string &id ) const {
120        static Stats::Counters::CounterGroup * name_lookup_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Name Lookup Stats");
121        static std::map<std::string, Stats::Counters::SimpleCounter *> lookups_by_name;
122        static std::map<std::string, Stats::Counters::SimpleCounter *> candidates_by_name;
123
124        SpecialFunctionKind kind = getSpecialFunctionKind(id);
125        if (kind != NUMBER_OF_KINDS) return specialLookupId(kind);
126
127        ++*stats().lookup_calls;
128        if ( ! idTable ) return {};
129
130        ++*stats().map_lookups;
131        auto decls = idTable->find( id );
132        if ( decls == idTable->end() ) return {};
133
134        std::vector<IdData> out;
135        for ( auto decl : *(decls->second) ) {
136                out.push_back( decl.second );
137        }
138
139        if (Stats::Counters::enabled) {
140                if (! lookups_by_name.count(id)) {
141                        // leaks some strings, but it is because Counters do not hold them
142                        auto lookupCounterName = new std::string(id + "%count");
143                        auto candidatesCounterName = new std::string(id + "%candidate");
144                        lookups_by_name.emplace(id, new Stats::Counters::SimpleCounter(lookupCounterName->c_str(), name_lookup_stats));
145                        candidates_by_name.emplace(id, new Stats::Counters::SimpleCounter(candidatesCounterName->c_str(), name_lookup_stats));
146                }
147                (*lookups_by_name[id]) ++;
148                *candidates_by_name[id] += out.size();
149        }
150
151        return out;
152}
153
154std::vector<SymbolTable::IdData> SymbolTable::specialLookupId( SymbolTable::SpecialFunctionKind kind, const std::string & otypeKey ) const {
155        static Stats::Counters::CounterGroup * special_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Special Lookups");
156        static Stats::Counters::SimpleCounter * stat_counts[3] = {
157                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - count", special_stats),
158                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - count", special_stats),
159                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - count", special_stats)
160        };
161
162        static Stats::Counters::SimpleCounter * stat_candidates[3] = {
163                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - candidates", special_stats),
164                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - candidates", special_stats),
165                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - candidates", special_stats)
166        };
167
168        static Stats::Counters::SimpleCounter * num_lookup_with_key
169                = Stats::Counters::build<Stats::Counters::SimpleCounter>("keyed lookups", special_stats);
170        static Stats::Counters::SimpleCounter * num_lookup_without_key
171                = Stats::Counters::build<Stats::Counters::SimpleCounter>("unkeyed lookups", special_stats);
172
173        assert (kind != NUMBER_OF_KINDS);
174        ++*stats().lookup_calls;
175        if ( ! specialFunctionTable[kind] ) return {};
176
177        std::vector<IdData> out;
178
179        if (otypeKey.empty()) { // returns everything
180                ++*num_lookup_without_key;
181                for (auto & table : *specialFunctionTable[kind]) {
182                        for (auto & decl : *table.second) {
183                                out.push_back(decl.second);
184                        }
185                }
186        }
187        else {
188                ++*num_lookup_with_key;
189                ++*stats().map_lookups;
190                auto decls = specialFunctionTable[kind]->find(otypeKey);
191                if (decls == specialFunctionTable[kind]->end()) return {};
192
193                for (auto decl : *(decls->second)) {
194                        out.push_back(decl.second);
195                }
196        }
197
198        ++*stat_counts[kind];
199        *stat_candidates[kind] += out.size();
200
201        return out;
202}
203
204const NamedTypeDecl * SymbolTable::lookupType( const std::string &id ) const {
205        ++*stats().lookup_calls;
206        if ( ! typeTable ) return nullptr;
207        ++*stats().map_lookups;
208        auto it = typeTable->find( id );
209        return it == typeTable->end() ? nullptr : it->second.decl;
210}
211
212const StructDecl * SymbolTable::lookupStruct( const std::string &id ) const {
213        ++*stats().lookup_calls;
214        if ( ! structTable ) return nullptr;
215        ++*stats().map_lookups;
216        auto it = structTable->find( id );
217        return it == structTable->end() ? nullptr : it->second.decl;
218}
219
220const EnumDecl * SymbolTable::lookupEnum( const std::string &id ) const {
221        ++*stats().lookup_calls;
222        if ( ! enumTable ) return nullptr;
223        ++*stats().map_lookups;
224        auto it = enumTable->find( id );
225        return it == enumTable->end() ? nullptr : it->second.decl;
226}
227
228const UnionDecl * SymbolTable::lookupUnion( const std::string &id ) const {
229        ++*stats().lookup_calls;
230        if ( ! unionTable ) return nullptr;
231        ++*stats().map_lookups;
232        auto it = unionTable->find( id );
233        return it == unionTable->end() ? nullptr : it->second.decl;
234}
235
236const TraitDecl * SymbolTable::lookupTrait( const std::string &id ) const {
237        ++*stats().lookup_calls;
238        if ( ! traitTable ) return nullptr;
239        ++*stats().map_lookups;
240        auto it = traitTable->find( id );
241        return it == traitTable->end() ? nullptr : it->second.decl;
242}
243
244const NamedTypeDecl * SymbolTable::globalLookupType( const std::string &id ) const {
245        return atScope( 0 )->lookupType( id );
246}
247
248const StructDecl * SymbolTable::globalLookupStruct( const std::string &id ) const {
249        return atScope( 0 )->lookupStruct( id );
250}
251
252const UnionDecl * SymbolTable::globalLookupUnion( const std::string &id ) const {
253        return atScope( 0 )->lookupUnion( id );
254}
255
256const EnumDecl * SymbolTable::globalLookupEnum( const std::string &id ) const {
257        return atScope( 0 )->lookupEnum( id );
258}
259
260void SymbolTable::addId( const DeclWithType * decl, const Expr * baseExpr ) {
261        // default handling of conflicts is to raise an error
262        addIdCommon( decl, OnConflict::error(), baseExpr, decl->isDeleted ? decl : nullptr );
263}
264
265void SymbolTable::addDeletedId( const DeclWithType * decl, const Decl * deleter ) {
266        // default handling of conflicts is to raise an error
267        addIdCommon( decl, OnConflict::error(), nullptr, deleter );
268}
269
270namespace {
271        /// true if redeclaration conflict between two types
272        bool addedTypeConflicts( const NamedTypeDecl * existing, const NamedTypeDecl * added ) {
273                if ( existing->base == nullptr ) {
274                        return false;
275                } else if ( added->base == nullptr ) {
276                        return true;
277                } else {
278                        // typedef redeclarations are errors only if types are different
279                        if ( ! ResolvExpr::typesCompatible( existing->base, added->base, SymbolTable{} ) ) {
280                                SemanticError( added->location, "redeclaration of " + added->name );
281                        }
282                }
283                // does not need to be added to the table if both existing and added have a base that are
284                // the same
285                return true;
286        }
287
288        /// true if redeclaration conflict between two aggregate declarations
289        bool addedDeclConflicts( const AggregateDecl * existing, const AggregateDecl * added ) {
290                if ( ! existing->body ) {
291                        return false;
292                } else if ( added->body ) {
293                        SemanticError( added, "redeclaration of " );
294                }
295                return true;
296        }
297}
298
299void SymbolTable::addType( const NamedTypeDecl * decl ) {
300        ++*stats().add_calls;
301        const std::string &id = decl->name;
302
303        if ( ! typeTable ) {
304                typeTable = TypeTable::new_ptr();
305        } else {
306                ++*stats().map_lookups;
307                auto existing = typeTable->find( id );
308                if ( existing != typeTable->end()
309                        && existing->second.scope == scope
310                        && addedTypeConflicts( existing->second.decl, decl ) ) return;
311        }
312
313        lazyInitScope();
314        ++*stats().map_mutations;
315        typeTable = typeTable->set( id, scoped<NamedTypeDecl>{ decl, scope } );
316}
317
318void SymbolTable::addStruct( const std::string &id ) {
319        addStruct( new StructDecl( CodeLocation(), id ) );
320}
321
322void SymbolTable::addStruct( const StructDecl * decl ) {
323        ++*stats().add_calls;
324        const std::string &id = decl->name;
325
326        if ( ! structTable ) {
327                structTable = StructTable::new_ptr();
328        } else {
329                ++*stats().map_lookups;
330                auto existing = structTable->find( id );
331                if ( existing != structTable->end()
332                        && existing->second.scope == scope
333                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
334        }
335
336        lazyInitScope();
337        ++*stats().map_mutations;
338        structTable = structTable->set( id, scoped<StructDecl>{ decl, scope } );
339}
340
341void SymbolTable::addEnum( const EnumDecl *decl ) {
342        ++*stats().add_calls;
343        const std::string &id = decl->name;
344
345        if ( ! enumTable ) {
346                enumTable = EnumTable::new_ptr();
347        } else {
348                ++*stats().map_lookups;
349                auto existing = enumTable->find( id );
350                if ( existing != enumTable->end()
351                        && existing->second.scope == scope
352                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
353        }
354
355        lazyInitScope();
356        ++*stats().map_mutations;
357        enumTable = enumTable->set( id, scoped<EnumDecl>{ decl, scope } );
358}
359
360void SymbolTable::addAdt( const AdtDecl *decl ) {
361        ++*stats().add_calls;
362        const std::string &id = decl->name;
363
364        if ( ! adtTable ) {
365                adtTable = AdtTable::new_ptr();
366        } else {
367                ++*stats().map_lookups;
368                auto existing = adtTable->find( id );
369                if ( existing != adtTable->end()
370                        && existing->second.scope == scope
371                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
372       
373        }
374
375        lazyInitScope();
376        ++*stats().map_mutations;
377        adtTable = adtTable->set( id, scoped<AdtDecl>{ decl, scope });
378}
379
380void SymbolTable::addUnion( const std::string &id ) {
381        addUnion( new UnionDecl( CodeLocation(), id ) );
382}
383
384void SymbolTable::addUnion( const UnionDecl * decl ) {
385        ++*stats().add_calls;
386        const std::string &id = decl->name;
387
388        if ( ! unionTable ) {
389                unionTable = UnionTable::new_ptr();
390        } else {
391                ++*stats().map_lookups;
392                auto existing = unionTable->find( id );
393                if ( existing != unionTable->end()
394                        && existing->second.scope == scope
395                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
396        }
397
398        lazyInitScope();
399        ++*stats().map_mutations;
400        unionTable = unionTable->set( id, scoped<UnionDecl>{ decl, scope } );
401}
402
403void SymbolTable::addTrait( const TraitDecl * decl ) {
404        ++*stats().add_calls;
405        const std::string &id = decl->name;
406
407        if ( ! traitTable ) {
408                traitTable = TraitTable::new_ptr();
409        } else {
410                ++*stats().map_lookups;
411                auto existing = traitTable->find( id );
412                if ( existing != traitTable->end()
413                        && existing->second.scope == scope
414                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
415        }
416
417        lazyInitScope();
418        ++*stats().map_mutations;
419        traitTable = traitTable->set( id, scoped<TraitDecl>{ decl, scope } );
420}
421
422
423void SymbolTable::addWith( const std::vector< ptr<Expr> > & withExprs, const Decl * withStmt ) {
424        for ( const Expr * expr : withExprs ) {
425                if ( ! expr->result ) continue;
426                const Type * resTy = expr->result->stripReferences();
427                auto aggrType = dynamic_cast< const BaseInstType * >( resTy );
428                assertf( aggrType, "WithStmt expr has non-aggregate type: %s",
429                        toString( expr->result ).c_str() );
430                const AggregateDecl * aggr = aggrType->aggr();
431                assertf( aggr, "WithStmt has null aggregate from type: %s",
432                        toString( expr->result ).c_str() );
433
434                addMembers( aggr, expr, OnConflict::deleteWith( withStmt ) );
435        }
436}
437
438void SymbolTable::addIds( const std::vector< ptr<DeclWithType> > & decls ) {
439        for ( const DeclWithType * decl : decls ) { addId( decl ); }
440}
441
442void SymbolTable::addTypes( const std::vector< ptr<TypeDecl> > & tds ) {
443        for ( const TypeDecl * td : tds ) {
444                addType( td );
445                addIds( td->assertions );
446        }
447}
448
449
450void SymbolTable::addFunction( const FunctionDecl * func ) {
451        for (auto & td : func->type_params) {
452                addType(td);
453        }
454        for (auto & asst : func->assertions) {
455                addId(asst);
456        }
457        // addTypes( func->type->forall );
458        addIds( func->returns );
459        addIds( func->params );
460}
461
462
463void SymbolTable::lazyInitScope() {
464        // do nothing if already in represented scope
465        if ( repScope == scope ) return;
466
467        ++*stats().lazy_scopes;
468        // create rollback
469        prevScope = std::make_shared<SymbolTable>( *this );
470        // update repScope
471        repScope = scope;
472}
473
474const ast::SymbolTable * SymbolTable::atScope( unsigned long target ) const {
475        // by lazy construction, final symtab in list has repScope 0, cannot be > target
476        // otherwise, will find first scope representing the target
477        const SymbolTable * symtab = this;
478        while ( symtab->repScope > target ) {
479                symtab = symtab->prevScope.get();
480        }
481        return symtab;
482}
483
484namespace {
485        /// gets the base type of the first parameter; decl must be a ctor/dtor/assignment function
486        std::string getOtypeKey( const FunctionType * ftype, bool stripParams = true ) {
487                const auto & params = ftype->params;
488                assert( ! params.empty() );
489                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
490                const Type * base = ast::getPointerBase( params.front() );
491                assert( base );
492                if (stripParams) {
493                        if (dynamic_cast<const PointerType *>(base)) return Mangle::Encoding::pointer;
494                        return Mangle::mangle( base, Mangle::Type | Mangle::NoGenericParams );
495                }
496                else
497                        return Mangle::mangle( base ); 
498        }
499
500        /// gets the declaration for the function acting on a type specified by otype key,
501        /// nullptr if none such
502        const FunctionDecl * getFunctionForOtype(
503                        const DeclWithType * decl, const std::string & otypeKey ) {
504                auto func = dynamic_cast< const FunctionDecl * >( decl );
505                if ( ! func || otypeKey != getOtypeKey( func->type, false ) ) return nullptr;
506                return func;
507        }
508}
509
510bool SymbolTable::removeSpecialOverrides(
511                SymbolTable::IdData & data, SymbolTable::MangleTable::Ptr & mangleTable ) {
512        // if a type contains user defined ctor/dtor/assign, then special rules trigger, which
513        // determine the set of ctor/dtor/assign that can be used  by the requester. In particular,
514        // if the user defines a default ctor, then the generated default ctor is unavailable,
515        // likewise for copy ctor and dtor. If the user defines any ctor/dtor, then no generated
516        // field ctors are available. If the user defines any ctor then the generated default ctor
517        // is unavailable (intrinsic default ctor must be overridden exactly). If the user defines
518        // anything that looks like a copy constructor, then the generated copy constructor is
519        // unavailable, and likewise for the assignment operator.
520
521        // only relevant on function declarations
522        const FunctionDecl * function = data.id.as< FunctionDecl >();
523        if ( ! function ) return true;
524        // only need to perform this check for constructors, destructors, and assignment functions
525        if ( ! CodeGen::isCtorDtorAssign( data.id->name ) ) return true;
526
527        // set up information for this type
528        bool dataIsUserDefinedFunc = ! function->linkage.is_overrideable;
529        bool dataIsCopyFunc = InitTweak::isCopyFunction( function );
530        std::string dataOtypeKey = getOtypeKey( function->type, false ); // requires exact match to override autogen
531
532        if ( dataIsUserDefinedFunc && dataIsCopyFunc ) {
533                // this is a user-defined copy function
534                // if this is the first such, delete/remove non-user-defined overloads as needed
535                std::vector< std::string > removed;
536                std::vector< MangleTable::value_type > deleted;
537                bool alreadyUserDefinedFunc = false;
538
539                for ( const auto& entry : *mangleTable ) {
540                        // skip decls that aren't functions or are for the wrong type
541                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
542                        if ( ! decl ) continue;
543
544                        bool isCopyFunc = InitTweak::isCopyFunction( decl );
545                        if ( ! decl->linkage.is_overrideable ) {
546                                // matching user-defined function
547                                if ( isCopyFunc ) {
548                                        // mutation already performed, return early
549                                        return true;
550                                } else {
551                                        // note that non-copy deletions already performed
552                                        alreadyUserDefinedFunc = true;
553                                }
554                        } else {
555                                // non-user-defined function; mark for deletion/removal as appropriate
556                                if ( isCopyFunc ) {
557                                        removed.push_back( entry.first );
558                                } else if ( ! alreadyUserDefinedFunc ) {
559                                        deleted.push_back( entry );
560                                }
561                        }
562                }
563
564                // perform removals from mangle table, and deletions if necessary
565                for ( const auto& key : removed ) {
566                        ++*stats().map_mutations;
567                        mangleTable = mangleTable->erase( key );
568                }
569                if ( ! alreadyUserDefinedFunc ) for ( const auto& entry : deleted ) {
570                        ++*stats().map_mutations;
571                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
572                }
573        } else if ( dataIsUserDefinedFunc ) {
574                // this is a user-defined non-copy function
575                // if this is the first user-defined function, delete non-user-defined overloads
576                std::vector< MangleTable::value_type > deleted;
577
578                for ( const auto& entry : *mangleTable ) {
579                        // skip decls that aren't functions or are for the wrong type
580                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
581                        if ( ! decl ) continue;
582
583                        // exit early if already a matching user-defined function;
584                        // earlier function will have mutated table
585                        if ( ! decl->linkage.is_overrideable ) return true;
586
587                        // skip mutating intrinsic functions
588                        if ( decl->linkage == Linkage::Intrinsic ) continue;
589
590                        // user-defined non-copy functions do not override copy functions
591                        if ( InitTweak::isCopyFunction( decl ) ) continue;
592
593                        // this function to be deleted after mangleTable iteration is complete
594                        deleted.push_back( entry );
595                }
596
597                // mark deletions to update mangle table
598                // this needs to be a separate loop because of iterator invalidation
599                for ( const auto& entry : deleted ) {
600                        ++*stats().map_mutations;
601                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
602                }
603        } else if ( function->linkage != Linkage::Intrinsic ) {
604                // this is an overridable generated function
605                // if there already exists a matching user-defined function, delete this appropriately
606                for ( const auto& entry : *mangleTable ) {
607                        // skip decls that aren't functions or are for the wrong type
608                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
609                        if ( ! decl ) continue;
610
611                        // skip non-user-defined functions
612                        if ( decl->linkage.is_overrideable ) continue;
613
614                        if ( dataIsCopyFunc ) {
615                                // remove current function if exists a user-defined copy function
616                                // since the signatures for copy functions don't need to match exactly, using
617                                // a delete statement is the wrong approach
618                                if ( InitTweak::isCopyFunction( decl ) ) return false;
619                        } else {
620                                // mark current function deleted by first user-defined function found
621                                data.deleter = decl;
622                                return true;
623                        }
624                }
625        }
626
627        // nothing (more) to fix, return true
628        return true;
629}
630
631namespace {
632        /// true iff the declaration represents a function
633        bool isFunction( const DeclWithType * decl ) {
634                return GenPoly::getFunctionType( decl->get_type() );
635        }
636
637        bool isObject( const DeclWithType * decl ) { return ! isFunction( decl ); }
638
639        /// true if the declaration represents a definition instead of a forward decl
640        bool isDefinition( const DeclWithType * decl ) {
641                if ( auto func = dynamic_cast< const FunctionDecl * >( decl ) ) {
642                        // a function is a definition if it has a body
643                        return func->stmts;
644                } else {
645                        // an object is a definition if it is not marked extern
646                        return ! decl->storage.is_extern;
647                }
648        }
649}
650
651bool SymbolTable::addedIdConflicts(
652                const SymbolTable::IdData & existing, const DeclWithType * added,
653                SymbolTable::OnConflict handleConflicts, const Decl * deleter ) {
654        // if we're giving the same name mangling to things of different types then there is something
655        // wrong
656        assert( (isObject( added ) && isObject( existing.id ) )
657                || ( isFunction( added ) && isFunction( existing.id ) ) );
658
659        if ( existing.id->linkage.is_overrideable ) {
660                // new definition shadows the autogenerated one, even at the same scope
661                return false;
662        } else if ( existing.id->linkage.is_mangled
663                        || ResolvExpr::typesCompatible(
664                                added->get_type(), existing.id->get_type(), SymbolTable{} ) ) {
665
666                // it is a conflict if one declaration is deleted and the other is not
667                if ( deleter && ! existing.deleter ) {
668                        if ( handleConflicts.mode == OnConflict::Error ) {
669                                SemanticError( added, "deletion of defined identifier " );
670                        }
671                        return true;
672                } else if ( ! deleter && existing.deleter ) {
673                        if ( handleConflicts.mode == OnConflict::Error ) {
674                                SemanticError( added, "definition of deleted identifier " );
675                        }
676                        return true;
677                }
678
679                // it is a conflict if both declarations are definitions
680                if ( isDefinition( added ) && isDefinition( existing.id ) ) {
681                        if ( handleConflicts.mode == OnConflict::Error ) {
682                                SemanticError( added,
683                                        isFunction( added ) ?
684                                                "duplicate function definition for " :
685                                                "duplicate object definition for " );
686                        }
687                        return true;
688                }
689        } else {
690                if ( handleConflicts.mode == OnConflict::Error ) {
691                        SemanticError( added, "duplicate definition for " );
692                }
693                return true;
694        }
695
696        return true;
697}
698
699void SymbolTable::addIdCommon(
700                const DeclWithType * decl, SymbolTable::OnConflict handleConflicts,
701                const Expr * baseExpr, const Decl * deleter ) {
702        SpecialFunctionKind kind = getSpecialFunctionKind(decl->name);
703        if (kind == NUMBER_OF_KINDS) { // not a special decl
704                addIdToTable(decl, decl->name, idTable, handleConflicts, baseExpr, deleter);
705        }
706        else {
707                std::string key;
708                if (auto func = dynamic_cast<const FunctionDecl *>(decl)) {
709                        key = getOtypeKey(func->type);
710                }
711                else if (auto obj = dynamic_cast<const ObjectDecl *>(decl)) {
712                        key = getOtypeKey(obj->type.strict_as<PointerType>()->base.strict_as<FunctionType>());
713                }
714                else {
715                        assertf(false, "special decl with non-function type");
716                }
717                addIdToTable(decl, key, specialFunctionTable[kind], handleConflicts, baseExpr, deleter);
718        }
719}
720
721void SymbolTable::addIdToTable(
722                const DeclWithType * decl, const std::string & lookupKey,
723                IdTable::Ptr & table, SymbolTable::OnConflict handleConflicts,
724                const Expr * baseExpr, const Decl * deleter ) {
725        ++*stats().add_calls;
726        const std::string &name = decl->name;
727        if ( name == "" ) return;
728
729        std::string mangleName;
730        if ( decl->linkage.is_overrideable ) {
731                // mangle the name without including the appropriate suffix, so overridable routines
732                // are placed into the same "bucket" as their user defined versions.
733                mangleName = Mangle::mangle( decl, Mangle::Mode{ Mangle::NoOverrideable } );
734        } else {
735                mangleName = Mangle::mangle( decl );
736        }
737
738        // this ensures that no two declarations with the same unmangled name at the same scope
739        // both have C linkage
740        if ( decl->linkage.is_mangled ) {
741                // Check that a Cforall declaration doesn't override any C declaration
742                if ( hasCompatibleCDecl( name, mangleName ) ) {
743                        SemanticError( decl, "Cforall declaration hides C function " );
744                }
745        } else {
746                // NOTE: only correct if name mangling is completely isomorphic to C
747                // type-compatibility, which it may not be.
748                if ( hasIncompatibleCDecl( name, mangleName ) ) {
749                        SemanticError( decl, "conflicting overload of C function " );
750                }
751        }
752
753        // ensure tables exist and add identifier
754        MangleTable::Ptr mangleTable;
755        if ( ! table ) {
756                table = IdTable::new_ptr();
757                mangleTable = MangleTable::new_ptr();
758        } else {
759                ++*stats().map_lookups;
760                auto decls = table->find( lookupKey );
761                if ( decls == table->end() ) {
762                        mangleTable = MangleTable::new_ptr();
763                } else {
764                        mangleTable = decls->second;
765                        // skip in-scope repeat declarations of same identifier
766                        ++*stats().map_lookups;
767                        auto existing = mangleTable->find( mangleName );
768                        if ( existing != mangleTable->end()
769                                        && existing->second.scope == scope
770                                        && existing->second.id ) {
771                                if ( addedIdConflicts( existing->second, decl, handleConflicts, deleter ) ) {
772                                        if ( handleConflicts.mode == OnConflict::Delete ) {
773                                                // set delete expression for conflicting identifier
774                                                lazyInitScope();
775                                                *stats().map_mutations += 2;
776                                                table = table->set(
777                                                        lookupKey,
778                                                        mangleTable->set(
779                                                                mangleName,
780                                                                IdData{ existing->second, handleConflicts.deleter } ) );
781                                        }
782                                        return;
783                                }
784                        }
785                }
786        }
787
788        // add/overwrite with new identifier
789        lazyInitScope();
790        IdData data{ decl, baseExpr, deleter, scope };
791        // Ensure that auto-generated ctor/dtor/assignment are deleted if necessary
792        if (table != idTable) { // adding to special table
793                if ( ! removeSpecialOverrides( data, mangleTable ) ) return;
794        }
795        *stats().map_mutations += 2;
796        table = table->set( lookupKey, mangleTable->set( mangleName, std::move(data) ) );
797}
798
799void SymbolTable::addMembers(
800                const AggregateDecl * aggr, const Expr * expr, SymbolTable::OnConflict handleConflicts ) {
801        for ( const ptr<Decl> & decl : aggr->members ) {
802                auto dwt = decl.as<DeclWithType>();
803                if ( nullptr == dwt ) continue;
804                addIdCommon( dwt, handleConflicts, expr );
805                // Inline through unnamed struct/union members.
806                if ( "" != dwt->name ) continue;
807                const Type * t = dwt->get_type()->stripReferences();
808                if ( auto rty = dynamic_cast<const BaseInstType *>( t ) ) {
809                        if ( ! dynamic_cast<const StructInstType *>(rty)
810                                && ! dynamic_cast<const UnionInstType *>(rty) ) continue;
811                        ResolvExpr::Cost cost = ResolvExpr::Cost::zero;
812                        ast::ptr<ast::TypeSubstitution> tmp = expr->env;
813                        expr = mutate_field(expr, &Expr::env, nullptr);
814                        const Expr * base = ResolvExpr::referenceToRvalueConversion( expr, cost );
815                        base = mutate_field(base, &Expr::env, tmp);
816
817                        addMembers(
818                                rty->aggr(), new MemberExpr{ base->location, dwt, base }, handleConflicts );
819                }
820        }
821}
822
823bool SymbolTable::hasCompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
824        if ( ! idTable ) return false;
825
826        ++*stats().map_lookups;
827        auto decls = idTable->find( id );
828        if ( decls == idTable->end() ) return false;
829
830        for ( auto decl : *(decls->second) ) {
831                // skip other scopes (hidden by this decl)
832                if ( decl.second.scope != scope ) continue;
833                // check for C decl with compatible type (by mangleName)
834                if ( ! decl.second.id->linkage.is_mangled && decl.first == mangleName ) return true;
835        }
836
837        return false;
838}
839
840bool SymbolTable::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
841        if ( ! idTable ) return false;
842
843        ++*stats().map_lookups;
844        auto decls = idTable->find( id );
845        if ( decls == idTable->end() ) return false;
846
847        for ( auto decl : *(decls->second) ) {
848                // skip other scopes (hidden by this decl)
849                if ( decl.second.scope != scope ) continue;
850                // check for C decl with incompatible type (by manglename)
851                if ( ! decl.second.id->linkage.is_mangled && decl.first != mangleName ) return true;
852        }
853
854        return false;
855}
856
857}
858
859// Local Variables: //
860// tab-width: 4 //
861// mode: c++ //
862// compile-command: "make install" //
863// End: //
Note: See TracBrowser for help on using the repository browser.