source: src/AST/SymbolTable.cpp @ 4962741

ADTast-experimentalpthread-emulation
Last change on this file since 4962741 was 9e23b446, checked in by Fangren Yu <f37yu@…>, 22 months ago

add specialize pass

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