source: src/AST/SymbolTable.cpp @ cd6a6ff

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since cd6a6ff was e5c3811, checked in by Fangren Yu <f37yu@…>, 3 years ago

create dedicated symbol tables for big 3 operators
note: arbitrary this param type is not supported; it is currently allowed although never used

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