source: src/AST/SymbolTable.cpp@ 4d5c5b6a

Last change on this file since 4d5c5b6a was 64f3b9f, checked in by Michael Brooks <mlbrooks@…>, 9 months ago

Fix support for partial autogen.

Partial autogen means that some lifecycle functions are possible to generate, and needed, while others are impossible to generate, but unneeded. It is a valid situation that a user can implicitly request.

Previous handling of "impossible to generate" left the function in a zombie state, where it could show up as an alternative later. This zombie state is problematic handling caused by a compiler bug. Without the fix, the added test fails by creating zombie states.

This change is also a prerequsite for an upcoming change to avoid gcc warnings by not emitting autogen forward declarations.

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