source: src/AST/SymbolTable.cpp @ fa2c005

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

Finish Adt POC

  • Property mode set to 100644
File size: 28.9 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 AdtDecl * SymbolTable::lookupAdt( const std::string &id ) const {
221        ++*stats().lookup_calls;
222        if ( ! adtTable ) return nullptr;
223        auto it = adtTable->find( id );
224        return it == adtTable->end() ? nullptr : it->second.decl;
225}
226
227const EnumDecl * SymbolTable::lookupEnum( const std::string &id ) const {
228        ++*stats().lookup_calls;
229        if ( ! enumTable ) return nullptr;
230        ++*stats().map_lookups;
231        auto it = enumTable->find( id );
232        return it == enumTable->end() ? nullptr : it->second.decl;
233}
234
235const UnionDecl * SymbolTable::lookupUnion( const std::string &id ) const {
236        ++*stats().lookup_calls;
237        if ( ! unionTable ) return nullptr;
238        ++*stats().map_lookups;
239        auto it = unionTable->find( id );
240        return it == unionTable->end() ? nullptr : it->second.decl;
241}
242
243const TraitDecl * SymbolTable::lookupTrait( const std::string &id ) const {
244        ++*stats().lookup_calls;
245        if ( ! traitTable ) return nullptr;
246        ++*stats().map_lookups;
247        auto it = traitTable->find( id );
248        return it == traitTable->end() ? nullptr : it->second.decl;
249}
250
251const NamedTypeDecl * SymbolTable::globalLookupType( const std::string &id ) const {
252        return atScope( 0 )->lookupType( id );
253}
254
255const StructDecl * SymbolTable::globalLookupStruct( const std::string &id ) const {
256        return atScope( 0 )->lookupStruct( id );
257}
258
259const UnionDecl * SymbolTable::globalLookupUnion( const std::string &id ) const {
260        return atScope( 0 )->lookupUnion( id );
261}
262
263const EnumDecl * SymbolTable::globalLookupEnum( const std::string &id ) const {
264        return atScope( 0 )->lookupEnum( id );
265}
266
267void SymbolTable::addId( const DeclWithType * decl, const Expr * baseExpr ) {
268        // default handling of conflicts is to raise an error
269        addIdCommon( decl, OnConflict::error(), baseExpr, decl->isDeleted ? decl : nullptr );
270}
271
272void SymbolTable::addDeletedId( const DeclWithType * decl, const Decl * deleter ) {
273        // default handling of conflicts is to raise an error
274        addIdCommon( decl, OnConflict::error(), nullptr, deleter );
275}
276
277namespace {
278        /// true if redeclaration conflict between two types
279        bool addedTypeConflicts( const NamedTypeDecl * existing, const NamedTypeDecl * added ) {
280                if ( existing->base == nullptr ) {
281                        return false;
282                } else if ( added->base == nullptr ) {
283                        return true;
284                } else {
285                        // typedef redeclarations are errors only if types are different
286                        if ( ! ResolvExpr::typesCompatible( existing->base, added->base, SymbolTable{} ) ) {
287                                SemanticError( added->location, "redeclaration of " + added->name );
288                        }
289                }
290                // does not need to be added to the table if both existing and added have a base that are
291                // the same
292                return true;
293        }
294
295        /// true if redeclaration conflict between two aggregate declarations
296        bool addedDeclConflicts( const AggregateDecl * existing, const AggregateDecl * added ) {
297                if ( ! existing->body ) {
298                        return false;
299                } else if ( added->body ) {
300                        SemanticError( added, "redeclaration of " );
301                }
302                return true;
303        }
304}
305
306void SymbolTable::addType( const NamedTypeDecl * decl ) {
307        ++*stats().add_calls;
308        const std::string &id = decl->name;
309
310        if ( ! typeTable ) {
311                typeTable = TypeTable::new_ptr();
312        } else {
313                ++*stats().map_lookups;
314                auto existing = typeTable->find( id );
315                if ( existing != typeTable->end()
316                        && existing->second.scope == scope
317                        && addedTypeConflicts( existing->second.decl, decl ) ) return;
318        }
319
320        lazyInitScope();
321        ++*stats().map_mutations;
322        typeTable = typeTable->set( id, scoped<NamedTypeDecl>{ decl, scope } );
323}
324
325void SymbolTable::addStruct( const std::string &id ) {
326        addStruct( new StructDecl( CodeLocation(), id ) );
327}
328
329void SymbolTable::addStruct( const StructDecl * decl ) {
330        ++*stats().add_calls;
331        const std::string &id = decl->name;
332
333        if ( ! structTable ) {
334                structTable = StructTable::new_ptr();
335        } else {
336                ++*stats().map_lookups;
337                auto existing = structTable->find( id );
338                if ( existing != structTable->end()
339                        && existing->second.scope == scope
340                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
341        }
342
343        lazyInitScope();
344        ++*stats().map_mutations;
345        structTable = structTable->set( id, scoped<StructDecl>{ decl, scope } );
346}
347
348void SymbolTable::addAdt( const std::string &id ) {
349        addAdt( new AdtDecl( CodeLocation(), id ) );
350}
351
352void SymbolTable::addAdt( const AdtDecl *decl ) {
353        ++*stats().add_calls;
354        const std::string &id = decl->name;
355
356        if ( ! adtTable ) {
357                adtTable = AdtTable::new_ptr();
358        } else {
359                ++*stats().map_lookups;
360                auto existing = adtTable->find( id );
361                if ( existing != adtTable->end()
362                        && existing->second.scope == scope
363                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
364       
365        }
366
367        lazyInitScope();
368        ++*stats().map_mutations;
369        adtTable = adtTable->set( id, scoped<AdtDecl>{ decl, scope });
370}
371
372void SymbolTable::addEnum( const EnumDecl *decl ) {
373        ++*stats().add_calls;
374        const std::string &id = decl->name;
375
376        if ( ! enumTable ) {
377                enumTable = EnumTable::new_ptr();
378        } else {
379                ++*stats().map_lookups;
380                auto existing = enumTable->find( id );
381                if ( existing != enumTable->end()
382                        && existing->second.scope == scope
383                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
384        }
385
386        lazyInitScope();
387        ++*stats().map_mutations;
388        enumTable = enumTable->set( id, scoped<EnumDecl>{ decl, scope } );
389}
390
391
392void SymbolTable::addUnion( const std::string &id ) {
393        addUnion( new UnionDecl( CodeLocation(), id ) );
394}
395
396void SymbolTable::addUnion( const UnionDecl * decl ) {
397        ++*stats().add_calls;
398        const std::string &id = decl->name;
399
400        if ( ! unionTable ) {
401                unionTable = UnionTable::new_ptr();
402        } else {
403                ++*stats().map_lookups;
404                auto existing = unionTable->find( id );
405                if ( existing != unionTable->end()
406                        && existing->second.scope == scope
407                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
408        }
409
410        lazyInitScope();
411        ++*stats().map_mutations;
412        unionTable = unionTable->set( id, scoped<UnionDecl>{ decl, scope } );
413}
414
415void SymbolTable::addTrait( const TraitDecl * decl ) {
416        ++*stats().add_calls;
417        const std::string &id = decl->name;
418
419        if ( ! traitTable ) {
420                traitTable = TraitTable::new_ptr();
421        } else {
422                ++*stats().map_lookups;
423                auto existing = traitTable->find( id );
424                if ( existing != traitTable->end()
425                        && existing->second.scope == scope
426                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
427        }
428
429        lazyInitScope();
430        ++*stats().map_mutations;
431        traitTable = traitTable->set( id, scoped<TraitDecl>{ decl, scope } );
432}
433
434
435void SymbolTable::addWith( const std::vector< ptr<Expr> > & withExprs, const Decl * withStmt ) {
436        for ( const Expr * expr : withExprs ) {
437                if ( ! expr->result ) continue;
438                const Type * resTy = expr->result->stripReferences();
439                auto aggrType = dynamic_cast< const BaseInstType * >( resTy );
440                assertf( aggrType, "WithStmt expr has non-aggregate type: %s",
441                        toString( expr->result ).c_str() );
442                const AggregateDecl * aggr = aggrType->aggr();
443                assertf( aggr, "WithStmt has null aggregate from type: %s",
444                        toString( expr->result ).c_str() );
445
446                addMembers( aggr, expr, OnConflict::deleteWith( withStmt ) );
447        }
448}
449
450void SymbolTable::addIds( const std::vector< ptr<DeclWithType> > & decls ) {
451        for ( const DeclWithType * decl : decls ) { addId( decl ); }
452}
453
454void SymbolTable::addTypes( const std::vector< ptr<TypeDecl> > & tds ) {
455        for ( const TypeDecl * td : tds ) {
456                addType( td );
457                addIds( td->assertions );
458        }
459}
460
461
462void SymbolTable::addFunction( const FunctionDecl * func ) {
463        for (auto & td : func->type_params) {
464                addType(td);
465        }
466        for (auto & asst : func->assertions) {
467                addId(asst);
468        }
469        // addTypes( func->type->forall );
470        addIds( func->returns );
471        addIds( func->params );
472}
473
474
475void SymbolTable::lazyInitScope() {
476        // do nothing if already in represented scope
477        if ( repScope == scope ) return;
478
479        ++*stats().lazy_scopes;
480        // create rollback
481        prevScope = std::make_shared<SymbolTable>( *this );
482        // update repScope
483        repScope = scope;
484}
485
486const ast::SymbolTable * SymbolTable::atScope( unsigned long target ) const {
487        // by lazy construction, final symtab in list has repScope 0, cannot be > target
488        // otherwise, will find first scope representing the target
489        const SymbolTable * symtab = this;
490        while ( symtab->repScope > target ) {
491                symtab = symtab->prevScope.get();
492        }
493        return symtab;
494}
495
496namespace {
497        /// gets the base type of the first parameter; decl must be a ctor/dtor/assignment function
498        std::string getOtypeKey( const FunctionType * ftype, bool stripParams = true ) {
499                const auto & params = ftype->params;
500                assert( ! params.empty() );
501                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
502                const Type * base = ast::getPointerBase( params.front() );
503                assert( base );
504                if (stripParams) {
505                        if (dynamic_cast<const PointerType *>(base)) return Mangle::Encoding::pointer;
506                        return Mangle::mangle( base, Mangle::Type | Mangle::NoGenericParams );
507                }
508                else
509                        return Mangle::mangle( base ); 
510        }
511
512        /// gets the declaration for the function acting on a type specified by otype key,
513        /// nullptr if none such
514        const FunctionDecl * getFunctionForOtype(
515                        const DeclWithType * decl, const std::string & otypeKey ) {
516                auto func = dynamic_cast< const FunctionDecl * >( decl );
517                if ( ! func || otypeKey != getOtypeKey( func->type, false ) ) return nullptr;
518                return func;
519        }
520}
521
522bool SymbolTable::removeSpecialOverrides(
523                SymbolTable::IdData & data, SymbolTable::MangleTable::Ptr & mangleTable ) {
524        // if a type contains user defined ctor/dtor/assign, then special rules trigger, which
525        // determine the set of ctor/dtor/assign that can be used  by the requester. In particular,
526        // if the user defines a default ctor, then the generated default ctor is unavailable,
527        // likewise for copy ctor and dtor. If the user defines any ctor/dtor, then no generated
528        // field ctors are available. If the user defines any ctor then the generated default ctor
529        // is unavailable (intrinsic default ctor must be overridden exactly). If the user defines
530        // anything that looks like a copy constructor, then the generated copy constructor is
531        // unavailable, and likewise for the assignment operator.
532
533        // only relevant on function declarations
534        const FunctionDecl * function = data.id.as< FunctionDecl >();
535        if ( ! function ) return true;
536        // only need to perform this check for constructors, destructors, and assignment functions
537        if ( ! CodeGen::isCtorDtorAssign( data.id->name ) ) return true;
538
539        // set up information for this type
540        bool dataIsUserDefinedFunc = ! function->linkage.is_overrideable;
541        bool dataIsCopyFunc = InitTweak::isCopyFunction( function );
542        std::string dataOtypeKey = getOtypeKey( function->type, false ); // requires exact match to override autogen
543
544        if ( dataIsUserDefinedFunc && dataIsCopyFunc ) {
545                // this is a user-defined copy function
546                // if this is the first such, delete/remove non-user-defined overloads as needed
547                std::vector< std::string > removed;
548                std::vector< MangleTable::value_type > deleted;
549                bool alreadyUserDefinedFunc = false;
550
551                for ( const auto& entry : *mangleTable ) {
552                        // skip decls that aren't functions or are for the wrong type
553                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
554                        if ( ! decl ) continue;
555
556                        bool isCopyFunc = InitTweak::isCopyFunction( decl );
557                        if ( ! decl->linkage.is_overrideable ) {
558                                // matching user-defined function
559                                if ( isCopyFunc ) {
560                                        // mutation already performed, return early
561                                        return true;
562                                } else {
563                                        // note that non-copy deletions already performed
564                                        alreadyUserDefinedFunc = true;
565                                }
566                        } else {
567                                // non-user-defined function; mark for deletion/removal as appropriate
568                                if ( isCopyFunc ) {
569                                        removed.push_back( entry.first );
570                                } else if ( ! alreadyUserDefinedFunc ) {
571                                        deleted.push_back( entry );
572                                }
573                        }
574                }
575
576                // perform removals from mangle table, and deletions if necessary
577                for ( const auto& key : removed ) {
578                        ++*stats().map_mutations;
579                        mangleTable = mangleTable->erase( key );
580                }
581                if ( ! alreadyUserDefinedFunc ) for ( const auto& entry : deleted ) {
582                        ++*stats().map_mutations;
583                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
584                }
585        } else if ( dataIsUserDefinedFunc ) {
586                // this is a user-defined non-copy function
587                // if this is the first user-defined function, delete non-user-defined overloads
588                std::vector< MangleTable::value_type > deleted;
589
590                for ( const auto& entry : *mangleTable ) {
591                        // skip decls that aren't functions or are for the wrong type
592                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
593                        if ( ! decl ) continue;
594
595                        // exit early if already a matching user-defined function;
596                        // earlier function will have mutated table
597                        if ( ! decl->linkage.is_overrideable ) return true;
598
599                        // skip mutating intrinsic functions
600                        if ( decl->linkage == Linkage::Intrinsic ) continue;
601
602                        // user-defined non-copy functions do not override copy functions
603                        if ( InitTweak::isCopyFunction( decl ) ) continue;
604
605                        // this function to be deleted after mangleTable iteration is complete
606                        deleted.push_back( entry );
607                }
608
609                // mark deletions to update mangle table
610                // this needs to be a separate loop because of iterator invalidation
611                for ( const auto& entry : deleted ) {
612                        ++*stats().map_mutations;
613                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
614                }
615        } else if ( function->linkage != Linkage::Intrinsic ) {
616                // this is an overridable generated function
617                // if there already exists a matching user-defined function, delete this appropriately
618                for ( const auto& entry : *mangleTable ) {
619                        // skip decls that aren't functions or are for the wrong type
620                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
621                        if ( ! decl ) continue;
622
623                        // skip non-user-defined functions
624                        if ( decl->linkage.is_overrideable ) continue;
625
626                        if ( dataIsCopyFunc ) {
627                                // remove current function if exists a user-defined copy function
628                                // since the signatures for copy functions don't need to match exactly, using
629                                // a delete statement is the wrong approach
630                                if ( InitTweak::isCopyFunction( decl ) ) return false;
631                        } else {
632                                // mark current function deleted by first user-defined function found
633                                data.deleter = decl;
634                                return true;
635                        }
636                }
637        }
638
639        // nothing (more) to fix, return true
640        return true;
641}
642
643namespace {
644        /// true iff the declaration represents a function
645        bool isFunction( const DeclWithType * decl ) {
646                return GenPoly::getFunctionType( decl->get_type() );
647        }
648
649        bool isObject( const DeclWithType * decl ) { return ! isFunction( decl ); }
650
651        /// true if the declaration represents a definition instead of a forward decl
652        bool isDefinition( const DeclWithType * decl ) {
653                if ( auto func = dynamic_cast< const FunctionDecl * >( decl ) ) {
654                        // a function is a definition if it has a body
655                        return func->stmts;
656                } else {
657                        // an object is a definition if it is not marked extern
658                        return ! decl->storage.is_extern;
659                }
660        }
661}
662
663bool SymbolTable::addedIdConflicts(
664                const SymbolTable::IdData & existing, const DeclWithType * added,
665                SymbolTable::OnConflict handleConflicts, const Decl * deleter ) {
666        // if we're giving the same name mangling to things of different types then there is something
667        // wrong
668        assert( (isObject( added ) && isObject( existing.id ) )
669                || ( isFunction( added ) && isFunction( existing.id ) ) );
670
671        if ( existing.id->linkage.is_overrideable ) {
672                // new definition shadows the autogenerated one, even at the same scope
673                return false;
674        } else if ( existing.id->linkage.is_mangled
675                        || ResolvExpr::typesCompatible(
676                                added->get_type(), existing.id->get_type(), SymbolTable{} ) ) {
677
678                // it is a conflict if one declaration is deleted and the other is not
679                if ( deleter && ! existing.deleter ) {
680                        if ( handleConflicts.mode == OnConflict::Error ) {
681                                SemanticError( added, "deletion of defined identifier " );
682                        }
683                        return true;
684                } else if ( ! deleter && existing.deleter ) {
685                        if ( handleConflicts.mode == OnConflict::Error ) {
686                                SemanticError( added, "definition of deleted identifier " );
687                        }
688                        return true;
689                }
690
691                // it is a conflict if both declarations are definitions
692                if ( isDefinition( added ) && isDefinition( existing.id ) ) {
693                        if ( handleConflicts.mode == OnConflict::Error ) {
694                                SemanticError( added,
695                                        isFunction( added ) ?
696                                                "duplicate function definition for " :
697                                                "duplicate object definition for " );
698                        }
699                        return true;
700                }
701        } else {
702                if ( handleConflicts.mode == OnConflict::Error ) {
703                        SemanticError( added, "duplicate definition for " );
704                }
705                return true;
706        }
707
708        return true;
709}
710
711void SymbolTable::addIdCommon(
712                const DeclWithType * decl, SymbolTable::OnConflict handleConflicts,
713                const Expr * baseExpr, const Decl * deleter ) {
714        SpecialFunctionKind kind = getSpecialFunctionKind(decl->name);
715        if (kind == NUMBER_OF_KINDS) { // not a special decl
716                addIdToTable(decl, decl->name, idTable, handleConflicts, baseExpr, deleter);
717        }
718        else {
719                std::string key;
720                if (auto func = dynamic_cast<const FunctionDecl *>(decl)) {
721                        key = getOtypeKey(func->type);
722                }
723                else if (auto obj = dynamic_cast<const ObjectDecl *>(decl)) {
724                        key = getOtypeKey(obj->type.strict_as<PointerType>()->base.strict_as<FunctionType>());
725                }
726                else {
727                        assertf(false, "special decl with non-function type");
728                }
729                addIdToTable(decl, key, specialFunctionTable[kind], handleConflicts, baseExpr, deleter);
730        }
731}
732
733void SymbolTable::addIdToTable(
734                const DeclWithType * decl, const std::string & lookupKey,
735                IdTable::Ptr & table, SymbolTable::OnConflict handleConflicts,
736                const Expr * baseExpr, const Decl * deleter ) {
737        ++*stats().add_calls;
738        const std::string &name = decl->name;
739        if ( name == "" ) return;
740
741        std::string mangleName;
742        if ( decl->linkage.is_overrideable ) {
743                // mangle the name without including the appropriate suffix, so overridable routines
744                // are placed into the same "bucket" as their user defined versions.
745                mangleName = Mangle::mangle( decl, Mangle::Mode{ Mangle::NoOverrideable } );
746        } else {
747                mangleName = Mangle::mangle( decl );
748        }
749
750        // this ensures that no two declarations with the same unmangled name at the same scope
751        // both have C linkage
752        if ( decl->linkage.is_mangled ) {
753                // Check that a Cforall declaration doesn't override any C declaration
754                if ( hasCompatibleCDecl( name, mangleName ) ) {
755                        SemanticError( decl, "Cforall declaration hides C function " );
756                }
757        } else {
758                // NOTE: only correct if name mangling is completely isomorphic to C
759                // type-compatibility, which it may not be.
760                if ( hasIncompatibleCDecl( name, mangleName ) ) {
761                        SemanticError( decl, "conflicting overload of C function " );
762                }
763        }
764
765        // ensure tables exist and add identifier
766        MangleTable::Ptr mangleTable;
767        if ( ! table ) {
768                table = IdTable::new_ptr();
769                mangleTable = MangleTable::new_ptr();
770        } else {
771                ++*stats().map_lookups;
772                auto decls = table->find( lookupKey );
773                if ( decls == table->end() ) {
774                        mangleTable = MangleTable::new_ptr();
775                } else {
776                        mangleTable = decls->second;
777                        // skip in-scope repeat declarations of same identifier
778                        ++*stats().map_lookups;
779                        auto existing = mangleTable->find( mangleName );
780                        if ( existing != mangleTable->end()
781                                        && existing->second.scope == scope
782                                        && existing->second.id ) {
783                                if ( addedIdConflicts( existing->second, decl, handleConflicts, deleter ) ) {
784                                        if ( handleConflicts.mode == OnConflict::Delete ) {
785                                                // set delete expression for conflicting identifier
786                                                lazyInitScope();
787                                                *stats().map_mutations += 2;
788                                                table = table->set(
789                                                        lookupKey,
790                                                        mangleTable->set(
791                                                                mangleName,
792                                                                IdData{ existing->second, handleConflicts.deleter } ) );
793                                        }
794                                        return;
795                                }
796                        }
797                }
798        }
799
800        // add/overwrite with new identifier
801        lazyInitScope();
802        IdData data{ decl, baseExpr, deleter, scope };
803        // Ensure that auto-generated ctor/dtor/assignment are deleted if necessary
804        if (table != idTable) { // adding to special table
805                if ( ! removeSpecialOverrides( data, mangleTable ) ) return;
806        }
807        *stats().map_mutations += 2;
808        table = table->set( lookupKey, mangleTable->set( mangleName, std::move(data) ) );
809}
810
811void SymbolTable::addMembers(
812                const AggregateDecl * aggr, const Expr * expr, SymbolTable::OnConflict handleConflicts ) {
813        for ( const ptr<Decl> & decl : aggr->members ) {
814                auto dwt = decl.as<DeclWithType>();
815                if ( nullptr == dwt ) continue;
816                addIdCommon( dwt, handleConflicts, expr );
817                // Inline through unnamed struct/union members.
818                if ( "" != dwt->name ) continue;
819                const Type * t = dwt->get_type()->stripReferences();
820                if ( auto rty = dynamic_cast<const BaseInstType *>( t ) ) {
821                        if ( ! dynamic_cast<const StructInstType *>(rty)
822                                && ! dynamic_cast<const UnionInstType *>(rty) ) continue;
823                        ResolvExpr::Cost cost = ResolvExpr::Cost::zero;
824                        ast::ptr<ast::TypeSubstitution> tmp = expr->env;
825                        expr = mutate_field(expr, &Expr::env, nullptr);
826                        const Expr * base = ResolvExpr::referenceToRvalueConversion( expr, cost );
827                        base = mutate_field(base, &Expr::env, tmp);
828
829                        addMembers(
830                                rty->aggr(), new MemberExpr{ base->location, dwt, base }, handleConflicts );
831                }
832        }
833}
834
835bool SymbolTable::hasCompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
836        if ( ! idTable ) return false;
837
838        ++*stats().map_lookups;
839        auto decls = idTable->find( id );
840        if ( decls == idTable->end() ) return false;
841
842        for ( auto decl : *(decls->second) ) {
843                // skip other scopes (hidden by this decl)
844                if ( decl.second.scope != scope ) continue;
845                // check for C decl with compatible type (by mangleName)
846                if ( ! decl.second.id->linkage.is_mangled && decl.first == mangleName ) return true;
847        }
848
849        return false;
850}
851
852bool SymbolTable::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
853        if ( ! idTable ) return false;
854
855        ++*stats().map_lookups;
856        auto decls = idTable->find( id );
857        if ( decls == idTable->end() ) return false;
858
859        for ( auto decl : *(decls->second) ) {
860                // skip other scopes (hidden by this decl)
861                if ( decl.second.scope != scope ) continue;
862                // check for C decl with incompatible type (by manglename)
863                if ( ! decl.second.id->linkage.is_mangled && decl.first != mangleName ) return true;
864        }
865
866        return false;
867}
868
869}
870
871// Local Variables: //
872// tab-width: 4 //
873// mode: c++ //
874// compile-command: "make install" //
875// End: //
Note: See TracBrowser for help on using the repository browser.