source: src/SymTab/Validate.cc@ f93d7fc

ADT ast-experimental enum forall-pointer-decay jacob/cs343-translation pthread-emulation qualifiedEnum
Last change on this file since f93d7fc was 943bfad, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Fixed several warnings for clang@head

  • Property mode set to 100644
File size: 78.2 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// Validate.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Dec 13 23:43:34 2019
13// Update Count : 363
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21// union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types. A function
26// taking no arguments has no argument types.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29// by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38// definition occurs later in the input.
39
40#include "Validate.h"
41
42#include <cassert> // for assertf, assert
43#include <cstddef> // for size_t
44#include <list> // for list
45#include <string> // for string
46#include <unordered_map> // for unordered_map
47#include <utility> // for pair
48
49#include "AST/Chain.hpp"
50#include "AST/Decl.hpp"
51#include "AST/Node.hpp"
52#include "AST/Pass.hpp"
53#include "AST/SymbolTable.hpp"
54#include "AST/Type.hpp"
55#include "AST/TypeSubstitution.hpp"
56#include "CodeGen/CodeGenerator.h" // for genName
57#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
58#include "ControlStruct/Mutate.h" // for ForExprMutator
59#include "Common/CodeLocation.h" // for CodeLocation
60#include "Common/Stats.h" // for Stats::Heap
61#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
62#include "Common/ScopedMap.h" // for ScopedMap
63#include "Common/SemanticError.h" // for SemanticError
64#include "Common/UniqueName.h" // for UniqueName
65#include "Common/utility.h" // for operator+, cloneAll, deleteAll
66#include "CompilationState.h" // skip some passes in new-ast build
67#include "Concurrency/Keywords.h" // for applyKeywords
68#include "FixFunction.h" // for FixFunction
69#include "Indexer.h" // for Indexer
70#include "InitTweak/GenInit.h" // for fixReturnStatements
71#include "InitTweak/InitTweak.h" // for isCtorDtorAssign
72#include "ResolvExpr/typeops.h" // for typesCompatible
73#include "ResolvExpr/Resolver.h" // for findSingleExpression
74#include "ResolvExpr/ResolveTypeof.h" // for resolveTypeof
75#include "SymTab/Autogen.h" // for SizeType
76#include "SynTree/LinkageSpec.h" // for C
77#include "SynTree/Attribute.h" // for noAttributes, Attribute
78#include "SynTree/Constant.h" // for Constant
79#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
80#include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio...
81#include "SynTree/Initializer.h" // for ListInit, Initializer
82#include "SynTree/Label.h" // for operator==, Label
83#include "SynTree/Mutator.h" // for Mutator
84#include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType
85#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
86#include "SynTree/Visitor.h" // for Visitor
87#include "Validate/HandleAttributes.h" // for handleAttributes
88#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
89
90class CompoundStmt;
91class ReturnStmt;
92class SwitchStmt;
93
94#define debugPrint( x ) if ( doDebug ) x
95
96namespace SymTab {
97 /// hoists declarations that are difficult to hoist while parsing
98 struct HoistTypeDecls final : public WithDeclsToAdd {
99 void previsit( SizeofExpr * );
100 void previsit( AlignofExpr * );
101 void previsit( UntypedOffsetofExpr * );
102 void previsit( CompoundLiteralExpr * );
103 void handleType( Type * );
104 };
105
106 struct FixQualifiedTypes final : public WithIndexer {
107 FixQualifiedTypes() : WithIndexer(false) {}
108 Type * postmutate( QualifiedType * );
109 };
110
111 struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
112 /// Flattens nested struct types
113 static void hoistStruct( std::list< Declaration * > &translationUnit );
114
115 void previsit( StructDecl * aggregateDecl );
116 void previsit( UnionDecl * aggregateDecl );
117 void previsit( StaticAssertDecl * assertDecl );
118 void previsit( StructInstType * type );
119 void previsit( UnionInstType * type );
120 void previsit( EnumInstType * type );
121
122 private:
123 template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
124
125 AggregateDecl * parentAggr = nullptr;
126 };
127
128 /// Fix return types so that every function returns exactly one value
129 struct ReturnTypeFixer {
130 static void fix( std::list< Declaration * > &translationUnit );
131
132 void postvisit( FunctionDecl * functionDecl );
133 void postvisit( FunctionType * ftype );
134 };
135
136 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
137 struct EnumAndPointerDecay_old {
138 void previsit( EnumDecl * aggregateDecl );
139 void previsit( FunctionType * func );
140 };
141
142 /// Associates forward declarations of aggregates with their definitions
143 struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
144 LinkReferenceToTypes_old( const Indexer * indexer );
145 void postvisit( TypeInstType * typeInst );
146
147 void postvisit( EnumInstType * enumInst );
148 void postvisit( StructInstType * structInst );
149 void postvisit( UnionInstType * unionInst );
150 void postvisit( TraitInstType * traitInst );
151 void previsit( QualifiedType * qualType );
152 void postvisit( QualifiedType * qualType );
153
154 void postvisit( EnumDecl * enumDecl );
155 void postvisit( StructDecl * structDecl );
156 void postvisit( UnionDecl * unionDecl );
157 void postvisit( TraitDecl * traitDecl );
158
159 void previsit( StructDecl * structDecl );
160 void previsit( UnionDecl * unionDecl );
161
162 void renameGenericParams( std::list< TypeDecl * > & params );
163
164 private:
165 const Indexer * local_indexer;
166
167 typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
168 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
169 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
170 ForwardEnumsType forwardEnums;
171 ForwardStructsType forwardStructs;
172 ForwardUnionsType forwardUnions;
173 /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
174 bool inGeneric = false;
175 };
176
177 /// Does early resolution on the expressions that give enumeration constants their values
178 struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
179 ResolveEnumInitializers( const Indexer * indexer );
180 void postvisit( EnumDecl * enumDecl );
181
182 private:
183 const Indexer * local_indexer;
184
185 };
186
187 /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
188 struct ForallPointerDecay_old final {
189 void previsit( ObjectDecl * object );
190 void previsit( FunctionDecl * func );
191 void previsit( FunctionType * ftype );
192 void previsit( StructDecl * aggrDecl );
193 void previsit( UnionDecl * aggrDecl );
194 };
195
196 struct ReturnChecker : public WithGuards {
197 /// Checks that return statements return nothing if their return type is void
198 /// and return something if the return type is non-void.
199 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
200
201 void previsit( FunctionDecl * functionDecl );
202 void previsit( ReturnStmt * returnStmt );
203
204 typedef std::list< DeclarationWithType * > ReturnVals;
205 ReturnVals returnVals;
206 };
207
208 struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
209 ReplaceTypedef() : scopeLevel( 0 ) {}
210 /// Replaces typedefs by forward declarations
211 static void replaceTypedef( std::list< Declaration * > &translationUnit );
212
213 void premutate( QualifiedType * );
214 Type * postmutate( QualifiedType * qualType );
215 Type * postmutate( TypeInstType * aggregateUseType );
216 Declaration * postmutate( TypedefDecl * typeDecl );
217 void premutate( TypeDecl * typeDecl );
218 void premutate( FunctionDecl * funcDecl );
219 void premutate( ObjectDecl * objDecl );
220 DeclarationWithType * postmutate( ObjectDecl * objDecl );
221
222 void premutate( CastExpr * castExpr );
223
224 void premutate( CompoundStmt * compoundStmt );
225
226 void premutate( StructDecl * structDecl );
227 void premutate( UnionDecl * unionDecl );
228 void premutate( EnumDecl * enumDecl );
229 void premutate( TraitDecl * );
230
231 void premutate( FunctionType * ftype );
232
233 private:
234 template<typename AggDecl>
235 void addImplicitTypedef( AggDecl * aggDecl );
236 template< typename AggDecl >
237 void handleAggregate( AggDecl * aggr );
238
239 typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
240 typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
241 typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
242 TypedefMap typedefNames;
243 TypeDeclMap typedeclNames;
244 int scopeLevel;
245 bool inFunctionType = false;
246 };
247
248 struct EliminateTypedef {
249 /// removes TypedefDecls from the AST
250 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
251
252 template<typename AggDecl>
253 void handleAggregate( AggDecl * aggregateDecl );
254
255 void previsit( StructDecl * aggregateDecl );
256 void previsit( UnionDecl * aggregateDecl );
257 void previsit( CompoundStmt * compoundStmt );
258 };
259
260 struct VerifyCtorDtorAssign {
261 /// ensure that constructors, destructors, and assignment have at least one
262 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
263 /// return values.
264 static void verify( std::list< Declaration * > &translationUnit );
265
266 void previsit( FunctionDecl * funcDecl );
267 };
268
269 /// ensure that generic types have the correct number of type arguments
270 struct ValidateGenericParameters {
271 void previsit( StructInstType * inst );
272 void previsit( UnionInstType * inst );
273 };
274
275 /// desugar declarations and uses of dimension paramaters like [N],
276 /// from type-system managed values, to tunnneling via ordinary types,
277 /// as char[-] in and sizeof(-) out
278 struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
279 static void translateDimensions( std::list< Declaration * > &translationUnit );
280 TranslateDimensionGenericParameters();
281
282 bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
283 bool visitingChildOfSUIT = false;
284 void changeState_ChildOfSUIT( bool newVal );
285 void premutate( StructInstType * sit );
286 void premutate( UnionInstType * uit );
287 void premutate( BaseSyntaxNode * node );
288
289 TypeDecl * postmutate( TypeDecl * td );
290 Expression * postmutate( DimensionExpr * de );
291 Expression * postmutate( Expression * e );
292 };
293
294 struct FixObjectType : public WithIndexer {
295 /// resolves typeof type in object, function, and type declarations
296 static void fix( std::list< Declaration * > & translationUnit );
297
298 void previsit( ObjectDecl * );
299 void previsit( FunctionDecl * );
300 void previsit( TypeDecl * );
301 };
302
303 struct InitializerLength {
304 /// for array types without an explicit length, compute the length and store it so that it
305 /// is known to the rest of the phases. For example,
306 /// int x[] = { 1, 2, 3 };
307 /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
308 /// here x and y are known at compile-time to have length 3, so change this into
309 /// int x[3] = { 1, 2, 3 };
310 /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
311 static void computeLength( std::list< Declaration * > & translationUnit );
312
313 void previsit( ObjectDecl * objDecl );
314 };
315
316 struct ArrayLength : public WithIndexer {
317 static void computeLength( std::list< Declaration * > & translationUnit );
318
319 void previsit( ArrayType * arrayType );
320 };
321
322 struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
323 Type::StorageClasses storageClasses;
324
325 void premutate( ObjectDecl * objectDecl );
326 Expression * postmutate( CompoundLiteralExpr * compLitExpr );
327 };
328
329 struct LabelAddressFixer final : public WithGuards {
330 std::set< Label > labels;
331
332 void premutate( FunctionDecl * funcDecl );
333 Expression * postmutate( AddressExpr * addrExpr );
334 };
335
336 void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
337 PassVisitor<EnumAndPointerDecay_old> epc;
338 PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
339 PassVisitor<ResolveEnumInitializers> rei( nullptr );
340 PassVisitor<ForallPointerDecay_old> fpd;
341 PassVisitor<CompoundLiteral> compoundliteral;
342 PassVisitor<ValidateGenericParameters> genericParams;
343 PassVisitor<LabelAddressFixer> labelAddrFixer;
344 PassVisitor<HoistTypeDecls> hoistDecls;
345 PassVisitor<FixQualifiedTypes> fixQual;
346
347 {
348 Stats::Heap::newPass("validate-A");
349 Stats::Time::BlockGuard guard("validate-A");
350 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
351 acceptAll( translationUnit, hoistDecls );
352 ReplaceTypedef::replaceTypedef( translationUnit );
353 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
354 acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling
355 }
356 {
357 Stats::Heap::newPass("validate-B");
358 Stats::Time::BlockGuard guard("validate-B");
359 acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
360 mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
361 HoistStruct::hoistStruct( translationUnit );
362 EliminateTypedef::eliminateTypedef( translationUnit );
363 }
364 {
365 Stats::Heap::newPass("validate-C");
366 Stats::Time::BlockGuard guard("validate-C");
367 Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
368 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
369 });
370 Stats::Time::TimeBlock("Translate Dimensions", [&]() {
371 TranslateDimensionGenericParameters::translateDimensions( translationUnit );
372 });
373 Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
374 acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
375 });
376 Stats::Time::TimeBlock("Check Function Returns", [&]() {
377 ReturnChecker::checkFunctionReturns( translationUnit );
378 });
379 Stats::Time::TimeBlock("Fix Return Statements", [&]() {
380 InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
381 });
382 }
383 {
384 Stats::Heap::newPass("validate-D");
385 Stats::Time::BlockGuard guard("validate-D");
386 Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
387 Concurrency::applyKeywords( translationUnit );
388 });
389 Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
390 acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
391 });
392 Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
393 ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines
394 });
395 Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
396 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
397 });
398 }
399 {
400 Stats::Heap::newPass("validate-E");
401 Stats::Time::BlockGuard guard("validate-E");
402 Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
403 Concurrency::implementMutexFuncs( translationUnit );
404 });
405 Stats::Time::TimeBlock("Implement Thread Start", [&]() {
406 Concurrency::implementThreadStarter( translationUnit );
407 });
408 Stats::Time::TimeBlock("Compound Literal", [&]() {
409 mutateAll( translationUnit, compoundliteral );
410 });
411 if (!useNewAST) {
412 Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
413 ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
414 });
415 }
416 }
417 {
418 Stats::Heap::newPass("validate-F");
419 Stats::Time::BlockGuard guard("validate-F");
420 if (!useNewAST) {
421 Stats::Time::TimeCall("Fix Object Type",
422 FixObjectType::fix, translationUnit);
423 }
424 Stats::Time::TimeCall("Initializer Length",
425 InitializerLength::computeLength, translationUnit);
426 if (!useNewAST) {
427 Stats::Time::TimeCall("Array Length",
428 ArrayLength::computeLength, translationUnit);
429 }
430 Stats::Time::TimeCall("Find Special Declarations",
431 Validate::findSpecialDecls, translationUnit);
432 Stats::Time::TimeCall("Fix Label Address",
433 mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
434 if (!useNewAST) {
435 Stats::Time::TimeCall("Handle Attributes",
436 Validate::handleAttributes, translationUnit);
437 }
438 }
439 }
440
441 void validateType( Type * type, const Indexer * indexer ) {
442 PassVisitor<EnumAndPointerDecay_old> epc;
443 PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
444 PassVisitor<ForallPointerDecay_old> fpd;
445 type->accept( epc );
446 type->accept( lrt );
447 type->accept( fpd );
448 }
449
450
451 void HoistTypeDecls::handleType( Type * type ) {
452 // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
453 AggregateDecl * aggr = nullptr;
454 if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
455 aggr = inst->baseStruct;
456 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
457 aggr = inst->baseUnion;
458 } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
459 aggr = inst->baseEnum;
460 }
461 if ( aggr && aggr->body ) {
462 declsToAddBefore.push_front( aggr );
463 }
464 }
465
466 void HoistTypeDecls::previsit( SizeofExpr * expr ) {
467 handleType( expr->type );
468 }
469
470 void HoistTypeDecls::previsit( AlignofExpr * expr ) {
471 handleType( expr->type );
472 }
473
474 void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
475 handleType( expr->type );
476 }
477
478 void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
479 handleType( expr->result );
480 }
481
482
483 Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
484 Type * parent = qualType->parent;
485 Type * child = qualType->child;
486 if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
487 // .T => lookup T at global scope
488 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
489 auto td = indexer.globalLookupType( inst->name );
490 if ( ! td ) {
491 SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
492 }
493 auto base = td->base;
494 assert( base );
495 Type * ret = base->clone();
496 ret->get_qualifiers() = qualType->get_qualifiers();
497 return ret;
498 } else {
499 // .T => T is not a type name
500 assertf( false, "unhandled global qualified child type: %s", toCString(child) );
501 }
502 } else {
503 // S.T => S must be an aggregate type, find the declaration for T in S.
504 AggregateDecl * aggr = nullptr;
505 if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
506 aggr = inst->baseStruct;
507 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
508 aggr = inst->baseUnion;
509 } else {
510 SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
511 }
512 assert( aggr ); // TODO: need to handle forward declarations
513 for ( Declaration * member : aggr->members ) {
514 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
515 // name on the right is a typedef
516 if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
517 if ( aggr->name == inst->name ) {
518 assert( aggr->base );
519 Type * ret = aggr->base->clone();
520 ret->get_qualifiers() = qualType->get_qualifiers();
521 TypeSubstitution sub = parent->genericSubstitution();
522 sub.apply(ret);
523 return ret;
524 }
525 }
526 } else {
527 // S.T - S is not an aggregate => error
528 assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
529 }
530 }
531 // failed to find a satisfying definition of type
532 SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
533 }
534
535 // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
536 }
537
538
539 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
540 PassVisitor<HoistStruct> hoister;
541 acceptAll( translationUnit, hoister );
542 }
543
544 bool shouldHoist( Declaration * decl ) {
545 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
546 }
547
548 namespace {
549 void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
550 if ( aggr->parent ) qualifiedName( aggr->parent, ss );
551 ss << "__" << aggr->name;
552 }
553
554 // mangle nested type names using entire parent chain
555 std::string qualifiedName( AggregateDecl * aggr ) {
556 std::ostringstream ss;
557 qualifiedName( aggr, ss );
558 return ss.str();
559 }
560 }
561
562 template< typename AggDecl >
563 void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
564 if ( parentAggr ) {
565 aggregateDecl->parent = parentAggr;
566 aggregateDecl->name = qualifiedName( aggregateDecl );
567 // Add elements in stack order corresponding to nesting structure.
568 declsToAddBefore.push_front( aggregateDecl );
569 } else {
570 GuardValue( parentAggr );
571 parentAggr = aggregateDecl;
572 } // if
573 // Always remove the hoisted aggregate from the inner structure.
574 GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
575 }
576
577 void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
578 if ( parentAggr ) {
579 declsToAddBefore.push_back( assertDecl );
580 }
581 }
582
583 void HoistStruct::previsit( StructDecl * aggregateDecl ) {
584 handleAggregate( aggregateDecl );
585 }
586
587 void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
588 handleAggregate( aggregateDecl );
589 }
590
591 void HoistStruct::previsit( StructInstType * type ) {
592 // need to reset type name after expanding to qualified name
593 assert( type->baseStruct );
594 type->name = type->baseStruct->name;
595 }
596
597 void HoistStruct::previsit( UnionInstType * type ) {
598 assert( type->baseUnion );
599 type->name = type->baseUnion->name;
600 }
601
602 void HoistStruct::previsit( EnumInstType * type ) {
603 assert( type->baseEnum );
604 type->name = type->baseEnum->name;
605 }
606
607
608 bool isTypedef( Declaration * decl ) {
609 return dynamic_cast< TypedefDecl * >( decl );
610 }
611
612 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
613 PassVisitor<EliminateTypedef> eliminator;
614 acceptAll( translationUnit, eliminator );
615 filter( translationUnit, isTypedef, true );
616 }
617
618 template< typename AggDecl >
619 void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
620 filter( aggregateDecl->members, isTypedef, true );
621 }
622
623 void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
624 handleAggregate( aggregateDecl );
625 }
626
627 void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
628 handleAggregate( aggregateDecl );
629 }
630
631 void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
632 // remove and delete decl stmts
633 filter( compoundStmt->kids, [](Statement * stmt) {
634 if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
635 if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
636 return true;
637 } // if
638 } // if
639 return false;
640 }, true);
641 }
642
643 void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
644 // Set the type of each member of the enumeration to be EnumConstant
645 for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
646 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
647 assert( obj );
648 obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
649 } // for
650 }
651
652 namespace {
653 template< typename DWTList >
654 void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
655 auto nvals = dwts.size();
656 bool containsVoid = false;
657 for ( auto & dwt : dwts ) {
658 // fix each DWT and record whether a void was found
659 containsVoid |= fixFunction( dwt );
660 }
661
662 // the only case in which "void" is valid is where it is the only one in the list
663 if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
664 SemanticError( func, "invalid type void in function type " );
665 }
666
667 // one void is the only thing in the list; remove it.
668 if ( containsVoid ) {
669 delete dwts.front();
670 dwts.clear();
671 }
672 }
673 }
674
675 void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
676 // Fix up parameters and return types
677 fixFunctionList( func->parameters, func->isVarArgs, func );
678 fixFunctionList( func->returnVals, false, func );
679 }
680
681 LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) : WithIndexer( false ) {
682 if ( other_indexer ) {
683 local_indexer = other_indexer;
684 } else {
685 local_indexer = &indexer;
686 } // if
687 }
688
689 void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
690 const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
691 // it's not a semantic error if the enum is not found, just an implicit forward declaration
692 if ( st ) {
693 enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
694 } // if
695 if ( ! st || ! st->body ) {
696 // use of forward declaration
697 forwardEnums[ enumInst->name ].push_back( enumInst );
698 } // if
699 }
700
701 void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
702 const StructDecl * st = local_indexer->lookupStruct( structInst->name );
703 // it's not a semantic error if the struct is not found, just an implicit forward declaration
704 if ( st ) {
705 structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
706 } // if
707 if ( ! st || ! st->body ) {
708 // use of forward declaration
709 forwardStructs[ structInst->name ].push_back( structInst );
710 } // if
711 }
712
713 void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
714 const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
715 // it's not a semantic error if the union is not found, just an implicit forward declaration
716 if ( un ) {
717 unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
718 } // if
719 if ( ! un || ! un->body ) {
720 // use of forward declaration
721 forwardUnions[ unionInst->name ].push_back( unionInst );
722 } // if
723 }
724
725 void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
726 visit_children = false;
727 }
728
729 void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
730 // linking only makes sense for the 'oldest ancestor' of the qualified type
731 qualType->parent->accept( * visitor );
732 }
733
734 template< typename Decl >
735 void normalizeAssertions( std::list< Decl * > & assertions ) {
736 // ensure no duplicate trait members after the clone
737 auto pred = [](Decl * d1, Decl * d2) {
738 // only care if they're equal
739 DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
740 DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
741 if ( dwt1 && dwt2 ) {
742 if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
743 // std::cerr << "=========== equal:" << std::endl;
744 // std::cerr << "d1: " << d1 << std::endl;
745 // std::cerr << "d2: " << d2 << std::endl;
746 return false;
747 }
748 }
749 return d1 < d2;
750 };
751 std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
752 // if ( unique_members.size() != assertions.size() ) {
753 // std::cerr << "============different" << std::endl;
754 // std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
755 // }
756
757 std::list< Decl * > order;
758 order.splice( order.end(), assertions );
759 std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
760 return unique_members.count( decl );
761 });
762 }
763
764 // expand assertions from trait instance, performing the appropriate type variable substitutions
765 template< typename Iterator >
766 void expandAssertions( TraitInstType * inst, Iterator out ) {
767 assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
768 std::list< DeclarationWithType * > asserts;
769 for ( Declaration * decl : inst->baseTrait->members ) {
770 asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
771 }
772 // substitute trait decl parameters for instance parameters
773 applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
774 }
775
776 void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
777 if ( traitDecl->name == "sized" ) {
778 // "sized" is a special trait - flick the sized status on for the type variable
779 assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
780 TypeDecl * td = traitDecl->parameters.front();
781 td->set_sized( true );
782 }
783
784 // move assertions from type parameters into the body of the trait
785 for ( TypeDecl * td : traitDecl->parameters ) {
786 for ( DeclarationWithType * assert : td->assertions ) {
787 if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
788 expandAssertions( inst, back_inserter( traitDecl->members ) );
789 } else {
790 traitDecl->members.push_back( assert->clone() );
791 }
792 }
793 deleteAll( td->assertions );
794 td->assertions.clear();
795 } // for
796 }
797
798 void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
799 // handle other traits
800 const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
801 if ( ! traitDecl ) {
802 SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
803 } // if
804 if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
805 SemanticError( traitInst, "incorrect number of trait parameters: " );
806 } // if
807 traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
808
809 // need to carry over the 'sized' status of each decl in the instance
810 for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
811 TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
812 if ( ! expr ) {
813 SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
814 }
815 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
816 TypeDecl * formalDecl = std::get<0>(p);
817 TypeDecl * instDecl = inst->baseType;
818 if ( formalDecl->get_sized() ) instDecl->set_sized( true );
819 }
820 }
821 // normalizeAssertions( traitInst->members );
822 }
823
824 void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
825 // visit enum members first so that the types of self-referencing members are updated properly
826 if ( enumDecl->body ) {
827 ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
828 if ( fwds != forwardEnums.end() ) {
829 for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
830 (* inst)->baseEnum = enumDecl;
831 } // for
832 forwardEnums.erase( fwds );
833 } // if
834 } // if
835 }
836
837 void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
838 // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
839 // forall(otype T)
840 // struct Box {
841 // T x;
842 // };
843 // forall(otype T)
844 // void f(Box(T) b) {
845 // ...
846 // }
847 // The T in Box and the T in f are different, so internally the naming must reflect that.
848 GuardValue( inGeneric );
849 inGeneric = ! params.empty();
850 for ( TypeDecl * td : params ) {
851 td->name = "__" + td->name + "_generic_";
852 }
853 }
854
855 void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
856 renameGenericParams( structDecl->parameters );
857 }
858
859 void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
860 renameGenericParams( unionDecl->parameters );
861 }
862
863 void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
864 // visit struct members first so that the types of self-referencing members are updated properly
865 // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
866 if ( structDecl->body ) {
867 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
868 if ( fwds != forwardStructs.end() ) {
869 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
870 (* inst)->baseStruct = structDecl;
871 } // for
872 forwardStructs.erase( fwds );
873 } // if
874 } // if
875 }
876
877 void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
878 if ( unionDecl->body ) {
879 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
880 if ( fwds != forwardUnions.end() ) {
881 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
882 (* inst)->baseUnion = unionDecl;
883 } // for
884 forwardUnions.erase( fwds );
885 } // if
886 } // if
887 }
888
889 void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
890 // ensure generic parameter instances are renamed like the base type
891 if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
892 if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
893 if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
894 typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
895 } // if
896 } // if
897 }
898
899 ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
900 if ( other_indexer ) {
901 local_indexer = other_indexer;
902 } else {
903 local_indexer = &indexer;
904 } // if
905 }
906
907 void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
908 if ( enumDecl->body ) {
909 for ( Declaration * member : enumDecl->members ) {
910 ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
911 if ( field->init ) {
912 // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
913 SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
914 ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
915 }
916 }
917 } // if
918 }
919
920 /// Fix up assertions - flattens assertion lists, removing all trait instances
921 void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
922 for ( TypeDecl * type : forall ) {
923 std::list< DeclarationWithType * > asserts;
924 asserts.splice( asserts.end(), type->assertions );
925 // expand trait instances into their members
926 for ( DeclarationWithType * assertion : asserts ) {
927 if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
928 // expand trait instance into all of its members
929 expandAssertions( traitInst, back_inserter( type->assertions ) );
930 delete traitInst;
931 } else {
932 // pass other assertions through
933 type->assertions.push_back( assertion );
934 } // if
935 } // for
936 // apply FixFunction to every assertion to check for invalid void type
937 for ( DeclarationWithType *& assertion : type->assertions ) {
938 bool isVoid = fixFunction( assertion );
939 if ( isVoid ) {
940 SemanticError( node, "invalid type void in assertion of function " );
941 } // if
942 } // for
943 // normalizeAssertions( type->assertions );
944 } // for
945 }
946
947 void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
948 // ensure that operator names only apply to functions or function pointers
949 if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
950 SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) );
951 }
952 object->fixUniqueId();
953 }
954
955 void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
956 func->fixUniqueId();
957 }
958
959 void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
960 forallFixer( ftype->forall, ftype );
961 }
962
963 void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
964 forallFixer( aggrDecl->parameters, aggrDecl );
965 }
966
967 void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
968 forallFixer( aggrDecl->parameters, aggrDecl );
969 }
970
971 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
972 PassVisitor<ReturnChecker> checker;
973 acceptAll( translationUnit, checker );
974 }
975
976 void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
977 GuardValue( returnVals );
978 returnVals = functionDecl->get_functionType()->get_returnVals();
979 }
980
981 void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
982 // Previously this also checked for the existence of an expr paired with no return values on
983 // the function return type. This is incorrect, since you can have an expression attached to
984 // a return statement in a void-returning function in C. The expression is treated as if it
985 // were cast to void.
986 if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
987 SemanticError( returnStmt, "Non-void function returns no values: " );
988 }
989 }
990
991
992 void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
993 PassVisitor<ReplaceTypedef> eliminator;
994 mutateAll( translationUnit, eliminator );
995 if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
996 // grab and remember declaration of size_t
997 Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
998 } else {
999 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
1000 // eventually should have a warning for this case.
1001 Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1002 }
1003 }
1004
1005 void ReplaceTypedef::premutate( QualifiedType * ) {
1006 visit_children = false;
1007 }
1008
1009 Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
1010 // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
1011 qualType->parent = qualType->parent->acceptMutator( * visitor );
1012 return qualType;
1013 }
1014
1015 static bool isNonParameterAttribute( Attribute * attr ) {
1016 static const std::vector<std::string> bad_names = {
1017 "aligned", "__aligned__",
1018 };
1019 for ( auto name : bad_names ) {
1020 if ( name == attr->name ) {
1021 return true;
1022 }
1023 }
1024 return false;
1025 }
1026
1027 Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
1028 // instances of typedef types will come here. If it is an instance
1029 // of a typdef type, link the instance to its actual type.
1030 TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
1031 if ( def != typedefNames.end() ) {
1032 Type * ret = def->second.first->base->clone();
1033 ret->location = typeInst->location;
1034 ret->get_qualifiers() |= typeInst->get_qualifiers();
1035 // GCC ignores certain attributes if they arrive by typedef, this mimics that.
1036 if ( inFunctionType ) {
1037 ret->attributes.remove_if( isNonParameterAttribute );
1038 }
1039 ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
1040 // place instance parameters on the typedef'd type
1041 if ( ! typeInst->parameters.empty() ) {
1042 ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
1043 if ( ! rtt ) {
1044 SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
1045 }
1046 rtt->parameters.clear();
1047 cloneAll( typeInst->parameters, rtt->parameters );
1048 mutateAll( rtt->parameters, * visitor ); // recursively fix typedefs on parameters
1049 } // if
1050 delete typeInst;
1051 return ret;
1052 } else {
1053 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
1054 if ( base == typedeclNames.end() ) {
1055 SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
1056 }
1057 typeInst->set_baseType( base->second );
1058 return typeInst;
1059 } // if
1060 assert( false );
1061 }
1062
1063 struct VarLenChecker : WithShortCircuiting {
1064 void previsit( FunctionType * ) { visit_children = false; }
1065 void previsit( ArrayType * at ) {
1066 isVarLen |= at->isVarLen;
1067 }
1068 bool isVarLen = false;
1069 };
1070
1071 bool isVariableLength( Type * t ) {
1072 PassVisitor<VarLenChecker> varLenChecker;
1073 maybeAccept( t, varLenChecker );
1074 return varLenChecker.pass.isVarLen;
1075 }
1076
1077 Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
1078 if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
1079 // typedef to the same name from the same scope
1080 // must be from the same type
1081
1082 Type * t1 = tyDecl->base;
1083 Type * t2 = typedefNames[ tyDecl->name ].first->base;
1084 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
1085 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1086 }
1087 // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
1088 // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
1089 // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
1090 // to fix this corner case likely outweighs the utility of allowing it.
1091 if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
1092 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1093 }
1094 } else {
1095 typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
1096 } // if
1097
1098 // When a typedef is a forward declaration:
1099 // typedef struct screen SCREEN;
1100 // the declaration portion must be retained:
1101 // struct screen;
1102 // because the expansion of the typedef is:
1103 // void rtn( SCREEN * p ) => void rtn( struct screen * p )
1104 // hence the type-name "screen" must be defined.
1105 // Note, qualifiers on the typedef are superfluous for the forward declaration.
1106
1107 Type * designatorType = tyDecl->base->stripDeclarator();
1108 if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
1109 declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
1110 } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
1111 declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
1112 } else if ( EnumInstType * enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
1113 declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
1114 } // if
1115 return tyDecl->clone();
1116 }
1117
1118 void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
1119 TypedefMap::iterator i = typedefNames.find( typeDecl->name );
1120 if ( i != typedefNames.end() ) {
1121 typedefNames.erase( i ) ;
1122 } // if
1123
1124 typedeclNames.insert( typeDecl->name, typeDecl );
1125 }
1126
1127 void ReplaceTypedef::premutate( FunctionDecl * ) {
1128 GuardScope( typedefNames );
1129 GuardScope( typedeclNames );
1130 }
1131
1132 void ReplaceTypedef::premutate( ObjectDecl * ) {
1133 GuardScope( typedefNames );
1134 GuardScope( typedeclNames );
1135 }
1136
1137 DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1138 if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1139 // replace the current object declaration with a function declaration
1140 FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1141 objDecl->attributes.clear();
1142 objDecl->set_type( nullptr );
1143 delete objDecl;
1144 return newDecl;
1145 } // if
1146 return objDecl;
1147 }
1148
1149 void ReplaceTypedef::premutate( CastExpr * ) {
1150 GuardScope( typedefNames );
1151 GuardScope( typedeclNames );
1152 }
1153
1154 void ReplaceTypedef::premutate( CompoundStmt * ) {
1155 GuardScope( typedefNames );
1156 GuardScope( typedeclNames );
1157 scopeLevel += 1;
1158 GuardAction( [this](){ scopeLevel -= 1; } );
1159 }
1160
1161 template<typename AggDecl>
1162 void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1163 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1164 Type * type = nullptr;
1165 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1166 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1167 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1168 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1169 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
1170 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1171 } // if
1172 TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1173 typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1174 // add the implicit typedef to the AST
1175 declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1176 } // if
1177 }
1178
1179 template< typename AggDecl >
1180 void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1181 SemanticErrorException errors;
1182
1183 ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1184 ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter );
1185 declsToAddBefore.clear();
1186 declsToAddAfter.clear();
1187
1188 GuardScope( typedefNames );
1189 GuardScope( typedeclNames );
1190 mutateAll( aggr->parameters, * visitor );
1191 mutateAll( aggr->attributes, * visitor );
1192
1193 // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1194 for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1195 if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1196
1197 try {
1198 * i = maybeMutate( * i, * visitor );
1199 } catch ( SemanticErrorException &e ) {
1200 errors.append( e );
1201 }
1202
1203 if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1204 }
1205
1206 if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1207 if ( !errors.isEmpty() ) { throw errors; }
1208 }
1209
1210 void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1211 visit_children = false;
1212 addImplicitTypedef( structDecl );
1213 handleAggregate( structDecl );
1214 }
1215
1216 void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1217 visit_children = false;
1218 addImplicitTypedef( unionDecl );
1219 handleAggregate( unionDecl );
1220 }
1221
1222 void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1223 addImplicitTypedef( enumDecl );
1224 }
1225
1226 void ReplaceTypedef::premutate( FunctionType * ) {
1227 GuardValue( inFunctionType );
1228 inFunctionType = true;
1229 }
1230
1231 void ReplaceTypedef::premutate( TraitDecl * ) {
1232 GuardScope( typedefNames );
1233 GuardScope( typedeclNames);
1234 }
1235
1236 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1237 PassVisitor<VerifyCtorDtorAssign> verifier;
1238 acceptAll( translationUnit, verifier );
1239 }
1240
1241 void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1242 FunctionType * funcType = funcDecl->get_functionType();
1243 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1244 std::list< DeclarationWithType * > &params = funcType->get_parameters();
1245
1246 if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1247 if ( params.size() == 0 ) {
1248 SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
1249 }
1250 ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1251 if ( ! refType ) {
1252 SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
1253 }
1254 if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1255 if(!returnVals.front()->get_type()->isVoid()) {
1256 SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
1257 }
1258 }
1259 }
1260 }
1261
1262 // Test for special name on a generic parameter. Special treatment for the
1263 // special name is a bootstrapping hack. In most cases, the worlds of T's
1264 // and of N's don't overlap (normal treamtemt). The foundations in
1265 // array.hfa use tagging for both types and dimensions. Tagging treats
1266 // its subject parameter even more opaquely than T&, which assumes it is
1267 // possible to have a pointer/reference to such an object. Tagging only
1268 // seeks to identify the type-system resident at compile time. Both N's
1269 // and T's can make tags. The tag definition uses the special name, which
1270 // is treated as "an N or a T." This feature is not inteded to be used
1271 // outside of the definition and immediate uses of a tag.
1272 static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1273 // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1274 int foundAt = name.find("__CFA_tysys_id_only");
1275 if (foundAt == 0) return true;
1276 if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1277 return false;
1278 }
1279
1280 template< typename Aggr >
1281 void validateGeneric( Aggr * inst ) {
1282 std::list< TypeDecl * > * params = inst->get_baseParameters();
1283 if ( params ) {
1284 std::list< Expression * > & args = inst->get_parameters();
1285
1286 // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1287 // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1288 // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1289 // vector(int) v;
1290 // after insertion of default values becomes
1291 // vector(int, heap_allocator(T))
1292 // and the substitution is built with T=int so that after substitution, the result is
1293 // vector(int, heap_allocator(int))
1294 TypeSubstitution sub;
1295 auto paramIter = params->begin();
1296 auto argIter = args.begin();
1297 for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1298 if ( argIter != args.end() ) {
1299 TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1300 if ( expr ) {
1301 sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1302 }
1303 } else {
1304 Type * defaultType = (* paramIter)->get_init();
1305 if ( defaultType ) {
1306 args.push_back( new TypeExpr( defaultType->clone() ) );
1307 sub.add( (* paramIter)->get_name(), defaultType->clone() );
1308 argIter = std::prev(args.end());
1309 } else {
1310 SemanticError( inst, "Too few type arguments in generic type " );
1311 }
1312 }
1313 assert( argIter != args.end() );
1314 bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1315 bool typeArgGiven;
1316 if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1317 // coerce a match when declaration is reserved name, which means "either"
1318 typeArgGiven = typeParamDeclared;
1319 } else {
1320 typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1321 }
1322 if ( ! typeParamDeclared && typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1323 if ( typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
1324 }
1325
1326 sub.apply( inst );
1327 if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1328 }
1329 }
1330
1331 void ValidateGenericParameters::previsit( StructInstType * inst ) {
1332 validateGeneric( inst );
1333 }
1334
1335 void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1336 validateGeneric( inst );
1337 }
1338
1339 void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1340 PassVisitor<TranslateDimensionGenericParameters> translator;
1341 mutateAll( translationUnit, translator );
1342 }
1343
1344 TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1345
1346 // Declaration of type variable: forall( [N] ) -> forall( N & | sized( N ) )
1347 TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1348 if ( td->kind == TypeDecl::Dimension ) {
1349 td->kind = TypeDecl::Dtype;
1350 if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1351 td->sized = true;
1352 }
1353 }
1354 return td;
1355 }
1356
1357 // Situational awareness:
1358 // array( float, [[currentExpr]] ) has visitingChildOfSUIT == true
1359 // array( float, [[currentExpr]] - 1 ) has visitingChildOfSUIT == false
1360 // size_t x = [[currentExpr]] has visitingChildOfSUIT == false
1361 void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1362 GuardValue( nextVisitedNodeIsChildOfSUIT );
1363 GuardValue( visitingChildOfSUIT );
1364 visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1365 nextVisitedNodeIsChildOfSUIT = newVal;
1366 }
1367 void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1368 (void) sit;
1369 changeState_ChildOfSUIT(true);
1370 }
1371 void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1372 (void) uit;
1373 changeState_ChildOfSUIT(true);
1374 }
1375 void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1376 (void) node;
1377 changeState_ChildOfSUIT(false);
1378 }
1379
1380 // Passing values as dimension arguments: array( float, 7 ) -> array( float, char[ 7 ] )
1381 // Consuming dimension parameters: size_t x = N - 1 ; -> size_t x = sizeof(N) - 1 ;
1382 // Intertwined reality: array( float, N ) -> array( float, N )
1383 // array( float, N - 1 ) -> array( float, char[ sizeof(N) - 1 ] )
1384 // Intertwined case 1 is not just an optimization.
1385 // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1386 // forall([N]) void f( array(float, N) & );
1387 // array(float, 7) a;
1388 // f(a);
1389
1390 Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1391 // Expression de is an occurrence of N in LHS of above examples.
1392 // Look up the name that de references.
1393 // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1394 // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1395 // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1396 // Thus, a potential struct's declaration is highest priority.
1397 // A struct's forall declarations are already renamed with _generic_ suffix. Try that name variant first.
1398
1399 std::string useName = "__" + de->name + "_generic_";
1400 TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1401
1402 if ( ! namedParamDecl ) {
1403 useName = de->name;
1404 namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1405 }
1406
1407 // Expect to find it always. A misspelled name would have been parsed as an identifier.
1408 assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1409
1410 delete de;
1411
1412 TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1413
1414 if ( visitingChildOfSUIT ) {
1415 // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1416 // But avoid ArrayType-Sizeof
1417 return new TypeExpr( refToDecl );
1418 } else {
1419 // the N occurrence is being used directly as a runtime value,
1420 // if we are in a type instantiation, then the N is within a bigger value computation
1421 return new SizeofExpr( refToDecl );
1422 }
1423 }
1424
1425 Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1426 if ( visitingChildOfSUIT ) {
1427 // e is an expression used as an argument to instantiate a type
1428 if (! dynamic_cast< TypeExpr * >( e ) ) {
1429 // e is a value expression
1430 // but not a DimensionExpr, which has a distinct postmutate
1431 Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1432 TypeExpr * result = new TypeExpr( typeExprContent );
1433 return result;
1434 }
1435 }
1436 return e;
1437 }
1438
1439 void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1440 storageClasses = objectDecl->get_storageClasses();
1441 }
1442
1443 Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1444 // transform [storage_class] ... (struct S){ 3, ... };
1445 // into [storage_class] struct S temp = { 3, ... };
1446 static UniqueName indexName( "_compLit" );
1447
1448 ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1449 compLitExpr->set_result( nullptr );
1450 compLitExpr->set_initializer( nullptr );
1451 delete compLitExpr;
1452 declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
1453 return new VariableExpr( tempvar );
1454 }
1455
1456 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1457 PassVisitor<ReturnTypeFixer> fixer;
1458 acceptAll( translationUnit, fixer );
1459 }
1460
1461 void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1462 FunctionType * ftype = functionDecl->get_functionType();
1463 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1464 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1465 if ( retVals.size() == 1 ) {
1466 // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
1467 // ensure other return values have a name.
1468 DeclarationWithType * ret = retVals.front();
1469 if ( ret->get_name() == "" ) {
1470 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1471 }
1472 ret->get_attributes().push_back( new Attribute( "unused" ) );
1473 }
1474 }
1475
1476 void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1477 // xxx - need to handle named return values - this information needs to be saved somehow
1478 // so that resolution has access to the names.
1479 // Note that this pass needs to happen early so that other passes which look for tuple types
1480 // find them in all of the right places, including function return types.
1481 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1482 if ( retVals.size() > 1 ) {
1483 // generate a single return parameter which is the tuple of all of the return values
1484 TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1485 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1486 ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1487 deleteAll( retVals );
1488 retVals.clear();
1489 retVals.push_back( newRet );
1490 }
1491 }
1492
1493 void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1494 PassVisitor<FixObjectType> fixer;
1495 acceptAll( translationUnit, fixer );
1496 }
1497
1498 void FixObjectType::previsit( ObjectDecl * objDecl ) {
1499 Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1500 objDecl->set_type( new_type );
1501 }
1502
1503 void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1504 Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1505 funcDecl->set_type( new_type );
1506 }
1507
1508 void FixObjectType::previsit( TypeDecl * typeDecl ) {
1509 if ( typeDecl->get_base() ) {
1510 Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1511 typeDecl->set_base( new_type );
1512 } // if
1513 }
1514
1515 void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1516 PassVisitor<InitializerLength> len;
1517 acceptAll( translationUnit, len );
1518 }
1519
1520 void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1521 PassVisitor<ArrayLength> len;
1522 acceptAll( translationUnit, len );
1523 }
1524
1525 void InitializerLength::previsit( ObjectDecl * objDecl ) {
1526 if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1527 if ( at->dimension ) return;
1528 if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1529 at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1530 }
1531 }
1532 }
1533
1534 void ArrayLength::previsit( ArrayType * type ) {
1535 if ( type->dimension ) {
1536 // need to resolve array dimensions early so that constructor code can correctly determine
1537 // if a type is a VLA (and hence whether its elements need to be constructed)
1538 ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1539
1540 // must re-evaluate whether a type is a VLA, now that more information is available
1541 // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1542 type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1543 }
1544 }
1545
1546 struct LabelFinder {
1547 std::set< Label > & labels;
1548 LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1549 void previsit( Statement * stmt ) {
1550 for ( Label & l : stmt->labels ) {
1551 labels.insert( l );
1552 }
1553 }
1554 };
1555
1556 void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1557 GuardValue( labels );
1558 PassVisitor<LabelFinder> finder( labels );
1559 funcDecl->accept( finder );
1560 }
1561
1562 Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1563 // convert &&label into label address
1564 if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1565 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1566 if ( labels.count( nameExpr->name ) ) {
1567 Label name = nameExpr->name;
1568 delete addrExpr;
1569 return new LabelAddressExpr( name );
1570 }
1571 }
1572 }
1573 return addrExpr;
1574 }
1575
1576namespace {
1577 /// Replaces enum types by int, and function/array types in function parameter and return
1578 /// lists by appropriate pointers
1579 /*
1580 struct EnumAndPointerDecay_new {
1581 const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) {
1582 // set the type of each member of the enumeration to be EnumConstant
1583 for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1584 // build new version of object with EnumConstant
1585 ast::ptr< ast::ObjectDecl > obj =
1586 enumDecl->members[i].strict_as< ast::ObjectDecl >();
1587 obj.get_and_mutate()->type =
1588 new ast::EnumInstType{ enumDecl->name, ast::CV::Const };
1589
1590 // set into decl
1591 ast::EnumDecl * mut = mutate( enumDecl );
1592 mut->members[i] = obj.get();
1593 enumDecl = mut;
1594 }
1595 return enumDecl;
1596 }
1597
1598 static const ast::FunctionType * fixFunctionList(
1599 const ast::FunctionType * func,
1600 std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field,
1601 ast::ArgumentFlag isVarArgs = ast::FixedArgs
1602 ) {
1603 const auto & dwts = func->* field;
1604 unsigned nvals = dwts.size();
1605 bool hasVoid = false;
1606 for ( unsigned i = 0; i < nvals; ++i ) {
1607 func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) );
1608 }
1609
1610 // the only case in which "void" is valid is where it is the only one in the list
1611 if ( hasVoid && ( nvals > 1 || isVarArgs ) ) {
1612 SemanticError(
1613 dwts.front()->location, func, "invalid type void in function type" );
1614 }
1615
1616 // one void is the only thing in the list, remove it
1617 if ( hasVoid ) {
1618 func = ast::mutate_field(
1619 func, field, std::vector< ast::ptr< ast::DeclWithType > >{} );
1620 }
1621
1622 return func;
1623 }
1624
1625 const ast::FunctionType * previsit( const ast::FunctionType * func ) {
1626 func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs );
1627 return fixFunctionList( func, &ast::FunctionType::returns );
1628 }
1629 };
1630
1631 /// expand assertions from a trait instance, performing appropriate type variable substitutions
1632 void expandAssertions(
1633 const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out
1634 ) {
1635 assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) );
1636
1637 // build list of trait members, substituting trait decl parameters for instance parameters
1638 ast::TypeSubstitution sub{
1639 inst->base->params.begin(), inst->base->params.end(), inst->params.begin() };
1640 // deliberately take ast::ptr by-value to ensure this does not mutate inst->base
1641 for ( ast::ptr< ast::Decl > decl : inst->base->members ) {
1642 auto member = decl.strict_as< ast::DeclWithType >();
1643 sub.apply( member );
1644 out.emplace_back( member );
1645 }
1646 }
1647
1648 /// Associates forward declarations of aggregates with their definitions
1649 class LinkReferenceToTypes_new final
1650 : public ast::WithSymbolTable, public ast::WithGuards, public
1651 ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting {
1652
1653 // these maps of uses of forward declarations of types need to have the actual type
1654 // declaration switched in * after * they have been traversed. To enable this in the
1655 // ast::Pass framework, any node that needs to be so mutated has mutate() called on it
1656 // before it is placed in the map, properly updating its parents in the usual traversal,
1657 // then can have the actual mutation applied later
1658 using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >;
1659 using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >;
1660 using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >;
1661
1662 const CodeLocation & location;
1663 const ast::SymbolTable * localSymtab;
1664
1665 ForwardEnumsType forwardEnums;
1666 ForwardStructsType forwardStructs;
1667 ForwardUnionsType forwardUnions;
1668
1669 /// true if currently in a generic type body, so that type parameter instances can be
1670 /// renamed appropriately
1671 bool inGeneric = false;
1672
1673 public:
1674 /// contstruct using running symbol table
1675 LinkReferenceToTypes_new( const CodeLocation & loc )
1676 : location( loc ), localSymtab( &symtab ) {}
1677
1678 /// construct using provided symbol table
1679 LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms )
1680 : location( loc ), localSymtab( &syms ) {}
1681
1682 const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
1683 // ensure generic parameter instances are renamed like the base type
1684 if ( inGeneric && typeInst->base ) {
1685 typeInst = ast::mutate_field(
1686 typeInst, &ast::TypeInstType::name, typeInst->base->name );
1687 }
1688
1689 if (
1690 auto typeDecl = dynamic_cast< const ast::TypeDecl * >(
1691 localSymtab->lookupType( typeInst->name ) )
1692 ) {
1693 typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind );
1694 }
1695
1696 return typeInst;
1697 }
1698
1699 const ast::Type * postvisit( const ast::EnumInstType * inst ) {
1700 const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name );
1701 // not a semantic error if the enum is not found, just an implicit forward declaration
1702 if ( decl ) {
1703 inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl );
1704 }
1705 if ( ! decl || ! decl->body ) {
1706 // forward declaration
1707 auto mut = mutate( inst );
1708 forwardEnums.emplace( inst->name, mut );
1709 inst = mut;
1710 }
1711 return inst;
1712 }
1713
1714 void checkGenericParameters( const ast::BaseInstType * inst ) {
1715 for ( const ast::Expr * param : inst->params ) {
1716 if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) {
1717 SemanticError(
1718 location, inst, "Expression parameters for generic types are currently "
1719 "unsupported: " );
1720 }
1721 }
1722 }
1723
1724 const ast::StructInstType * postvisit( const ast::StructInstType * inst ) {
1725 const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name );
1726 // not a semantic error if the struct is not found, just an implicit forward declaration
1727 if ( decl ) {
1728 inst = ast::mutate_field( inst, &ast::StructInstType::base, decl );
1729 }
1730 if ( ! decl || ! decl->body ) {
1731 // forward declaration
1732 auto mut = mutate( inst );
1733 forwardStructs.emplace( inst->name, mut );
1734 inst = mut;
1735 }
1736 checkGenericParameters( inst );
1737 return inst;
1738 }
1739
1740 const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) {
1741 const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name );
1742 // not a semantic error if the struct is not found, just an implicit forward declaration
1743 if ( decl ) {
1744 inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl );
1745 }
1746 if ( ! decl || ! decl->body ) {
1747 // forward declaration
1748 auto mut = mutate( inst );
1749 forwardUnions.emplace( inst->name, mut );
1750 inst = mut;
1751 }
1752 checkGenericParameters( inst );
1753 return inst;
1754 }
1755
1756 const ast::Type * postvisit( const ast::TraitInstType * traitInst ) {
1757 // handle other traits
1758 const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name );
1759 if ( ! traitDecl ) {
1760 SemanticError( location, "use of undeclared trait " + traitInst->name );
1761 }
1762 if ( traitDecl->params.size() != traitInst->params.size() ) {
1763 SemanticError( location, traitInst, "incorrect number of trait parameters: " );
1764 }
1765 traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl );
1766
1767 // need to carry over the "sized" status of each decl in the instance
1768 for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) {
1769 auto expr = traitInst->params[i].as< ast::TypeExpr >();
1770 if ( ! expr ) {
1771 SemanticError(
1772 traitInst->params[i].get(), "Expression parameters for trait instances "
1773 "are currently unsupported: " );
1774 }
1775
1776 if ( auto inst = expr->type.as< ast::TypeInstType >() ) {
1777 if ( traitDecl->params[i]->sized && ! inst->base->sized ) {
1778 // traitInst = ast::mutate_field_index(
1779 // traitInst, &ast::TraitInstType::params, i,
1780 // ...
1781 // );
1782 ast::TraitInstType * mut = ast::mutate( traitInst );
1783 ast::chain_mutate( mut->params[i] )
1784 ( &ast::TypeExpr::type )
1785 ( &ast::TypeInstType::base )->sized = true;
1786 traitInst = mut;
1787 }
1788 }
1789 }
1790
1791 return traitInst;
1792 }
1793
1794 void previsit( const ast::QualifiedType * ) { visit_children = false; }
1795
1796 const ast::Type * postvisit( const ast::QualifiedType * qualType ) {
1797 // linking only makes sense for the "oldest ancestor" of the qualified type
1798 return ast::mutate_field(
1799 qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) );
1800 }
1801
1802 const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) {
1803 // visit enum members first so that the types of self-referencing members are updated
1804 // properly
1805 if ( ! enumDecl->body ) return enumDecl;
1806
1807 // update forward declarations to point here
1808 auto fwds = forwardEnums.equal_range( enumDecl->name );
1809 if ( fwds.first != fwds.second ) {
1810 auto inst = fwds.first;
1811 do {
1812 // forward decl is stored * mutably * in map, can thus be updated
1813 inst->second->base = enumDecl;
1814 } while ( ++inst != fwds.second );
1815 forwardEnums.erase( fwds.first, fwds.second );
1816 }
1817
1818 // ensure that enumerator initializers are properly set
1819 for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1820 auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >();
1821 if ( field->init ) {
1822 // need to resolve enumerator initializers early so that other passes that
1823 // determine if an expression is constexpr have appropriate information
1824 auto init = field->init.strict_as< ast::SingleInit >();
1825
1826 enumDecl = ast::mutate_field_index(
1827 enumDecl, &ast::EnumDecl::members, i,
1828 ast::mutate_field( field, &ast::ObjectDecl::init,
1829 ast::mutate_field( init, &ast::SingleInit::value,
1830 ResolvExpr::findSingleExpression(
1831 init->value, new ast::BasicType{ ast::BasicType::SignedInt },
1832 symtab ) ) ) );
1833 }
1834 }
1835
1836 return enumDecl;
1837 }
1838
1839 /// rename generic type parameters uniquely so that they do not conflict with user defined
1840 /// function forall parameters, e.g. the T in Box and the T in f, below
1841 /// forall(otype T)
1842 /// struct Box {
1843 /// T x;
1844 /// };
1845 /// forall(otype T)
1846 /// void f(Box(T) b) {
1847 /// ...
1848 /// }
1849 template< typename AggrDecl >
1850 const AggrDecl * renameGenericParams( const AggrDecl * aggr ) {
1851 GuardValue( inGeneric );
1852 inGeneric = ! aggr->params.empty();
1853
1854 for ( unsigned i = 0; i < aggr->params.size(); ++i ) {
1855 const ast::TypeDecl * td = aggr->params[i];
1856
1857 aggr = ast::mutate_field_index(
1858 aggr, &AggrDecl::params, i,
1859 ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) );
1860 }
1861 return aggr;
1862 }
1863
1864 const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) {
1865 return renameGenericParams( structDecl );
1866 }
1867
1868 void postvisit( const ast::StructDecl * structDecl ) {
1869 // visit struct members first so that the types of self-referencing members are
1870 // updated properly
1871 if ( ! structDecl->body ) return;
1872
1873 // update forward declarations to point here
1874 auto fwds = forwardStructs.equal_range( structDecl->name );
1875 if ( fwds.first != fwds.second ) {
1876 auto inst = fwds.first;
1877 do {
1878 // forward decl is stored * mutably * in map, can thus be updated
1879 inst->second->base = structDecl;
1880 } while ( ++inst != fwds.second );
1881 forwardStructs.erase( fwds.first, fwds.second );
1882 }
1883 }
1884
1885 const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) {
1886 return renameGenericParams( unionDecl );
1887 }
1888
1889 void postvisit( const ast::UnionDecl * unionDecl ) {
1890 // visit union members first so that the types of self-referencing members are updated
1891 // properly
1892 if ( ! unionDecl->body ) return;
1893
1894 // update forward declarations to point here
1895 auto fwds = forwardUnions.equal_range( unionDecl->name );
1896 if ( fwds.first != fwds.second ) {
1897 auto inst = fwds.first;
1898 do {
1899 // forward decl is stored * mutably * in map, can thus be updated
1900 inst->second->base = unionDecl;
1901 } while ( ++inst != fwds.second );
1902 forwardUnions.erase( fwds.first, fwds.second );
1903 }
1904 }
1905
1906 const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) {
1907 // set the "sized" status for the special "sized" trait
1908 if ( traitDecl->name == "sized" ) {
1909 assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect "
1910 "number of parameters: %zd", traitDecl->params.size() );
1911
1912 traitDecl = ast::mutate_field_index(
1913 traitDecl, &ast::TraitDecl::params, 0,
1914 ast::mutate_field(
1915 traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) );
1916 }
1917
1918 // move assertions from type parameters into the body of the trait
1919 std::vector< ast::ptr< ast::DeclWithType > > added;
1920 for ( const ast::TypeDecl * td : traitDecl->params ) {
1921 for ( const ast::DeclWithType * assn : td->assertions ) {
1922 auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1923 if ( inst ) {
1924 expandAssertions( inst, added );
1925 } else {
1926 added.emplace_back( assn );
1927 }
1928 }
1929 }
1930 if ( ! added.empty() ) {
1931 auto mut = mutate( traitDecl );
1932 for ( const ast::DeclWithType * decl : added ) {
1933 mut->members.emplace_back( decl );
1934 }
1935 traitDecl = mut;
1936 }
1937
1938 return traitDecl;
1939 }
1940 };
1941
1942 /// Replaces array and function types in forall lists by appropriate pointer type and assigns
1943 /// each object and function declaration a unique ID
1944 class ForallPointerDecay_new {
1945 const CodeLocation & location;
1946 public:
1947 ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {}
1948
1949 const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) {
1950 // ensure that operator names only apply to functions or function pointers
1951 if (
1952 CodeGen::isOperator( obj->name )
1953 && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() )
1954 ) {
1955 SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not "
1956 "a function or function pointer." ) );
1957 }
1958
1959 // ensure object has unique ID
1960 if ( obj->uniqueId ) return obj;
1961 auto mut = mutate( obj );
1962 mut->fixUniqueId();
1963 return mut;
1964 }
1965
1966 const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) {
1967 // ensure function has unique ID
1968 if ( func->uniqueId ) return func;
1969 auto mut = mutate( func );
1970 mut->fixUniqueId();
1971 return mut;
1972 }
1973
1974 /// Fix up assertions -- flattens assertion lists, removing all trait instances
1975 template< typename node_t, typename parent_t >
1976 static const node_t * forallFixer(
1977 const CodeLocation & loc, const node_t * node,
1978 ast::FunctionType::ForallList parent_t::* forallField
1979 ) {
1980 for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) {
1981 const ast::TypeDecl * type = (node->* forallField)[i];
1982 if ( type->assertions.empty() ) continue;
1983
1984 std::vector< ast::ptr< ast::DeclWithType > > asserts;
1985 asserts.reserve( type->assertions.size() );
1986
1987 // expand trait instances into their members
1988 for ( const ast::DeclWithType * assn : type->assertions ) {
1989 auto traitInst =
1990 dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1991 if ( traitInst ) {
1992 // expand trait instance to all its members
1993 expandAssertions( traitInst, asserts );
1994 } else {
1995 // pass other assertions through
1996 asserts.emplace_back( assn );
1997 }
1998 }
1999
2000 // apply FixFunction to every assertion to check for invalid void type
2001 for ( ast::ptr< ast::DeclWithType > & assn : asserts ) {
2002 bool isVoid = false;
2003 assn = fixFunction( assn, isVoid );
2004 if ( isVoid ) {
2005 SemanticError( loc, node, "invalid type void in assertion of function " );
2006 }
2007 }
2008
2009 // place mutated assertion list in node
2010 auto mut = mutate( type );
2011 mut->assertions = move( asserts );
2012 node = ast::mutate_field_index( node, forallField, i, mut );
2013 }
2014 return node;
2015 }
2016
2017 const ast::FunctionType * previsit( const ast::FunctionType * ftype ) {
2018 return forallFixer( location, ftype, &ast::FunctionType::forall );
2019 }
2020
2021 const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) {
2022 return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params );
2023 }
2024
2025 const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) {
2026 return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params );
2027 }
2028 };
2029 */
2030} // anonymous namespace
2031
2032/*
2033const ast::Type * validateType(
2034 const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) {
2035 // ast::Pass< EnumAndPointerDecay_new > epc;
2036 ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab };
2037 ast::Pass< ForallPointerDecay_new > fpd{ loc };
2038
2039 return type->accept( lrt )->accept( fpd );
2040}
2041*/
2042
2043} // namespace SymTab
2044
2045// Local Variables: //
2046// tab-width: 4 //
2047// mode: c++ //
2048// compile-command: "make install" //
2049// End: //
Note: See TracBrowser for help on using the repository browser.