source: src/SymTab/Validate.cc@ 4b4f95f

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 4b4f95f was 298fe57, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Translated 3/4 of validate_B. Link Reference To Types has been removed and will be translated after we know how much support we need for forall function pointers.

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