source: src/SymTab/Validate.cc @ d419d8e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since d419d8e was d419d8e, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Rename nested types when hoisting

  • Property mode set to 100644
File size: 43.8 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 : Mon Aug 28 13:47:23 2017
13// Update Count     : 359
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 <utility>                     // for pair
47
48#include "CodeGen/CodeGenerator.h"     // for genName
49#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
50#include "ControlStruct/Mutate.h"      // for ForExprMutator
51#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
52#include "Common/ScopedMap.h"          // for ScopedMap
53#include "Common/SemanticError.h"      // for SemanticError
54#include "Common/UniqueName.h"         // for UniqueName
55#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
56#include "Concurrency/Keywords.h"      // for applyKeywords
57#include "FixFunction.h"               // for FixFunction
58#include "Indexer.h"                   // for Indexer
59#include "InitTweak/GenInit.h"         // for fixReturnStatements
60#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
61#include "Parser/LinkageSpec.h"        // for C
62#include "ResolvExpr/typeops.h"        // for typesCompatible
63#include "SymTab/Autogen.h"            // for SizeType
64#include "SynTree/Attribute.h"         // for noAttributes, Attribute
65#include "SynTree/Constant.h"          // for Constant
66#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
67#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
68#include "SynTree/Initializer.h"       // for ListInit, Initializer
69#include "SynTree/Label.h"             // for operator==, Label
70#include "SynTree/Mutator.h"           // for Mutator
71#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
72#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
73#include "SynTree/Visitor.h"           // for Visitor
74
75class CompoundStmt;
76class ReturnStmt;
77class SwitchStmt;
78
79#define debugPrint( x ) if ( doDebug ) x
80
81namespace SymTab {
82        /// hoists declarations that are difficult to hoist while parsing
83        struct HoistTypeDecls final : public WithDeclsToAdd {
84                void previsit( SizeofExpr * );
85                void previsit( AlignofExpr * );
86                void previsit( UntypedOffsetofExpr * );
87                void handleType( Type * );
88        };
89
90        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
91                /// Flattens nested struct types
92                static void hoistStruct( std::list< Declaration * > &translationUnit );
93
94                void previsit( StructDecl * aggregateDecl );
95                void previsit( UnionDecl * aggregateDecl );
96                void previsit( StaticAssertDecl * assertDecl );
97                void previsit( StructInstType * type );
98                void previsit( UnionInstType * type );
99                void previsit( EnumInstType * type );
100
101          private:
102                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
103
104                AggregateDecl * parentAggr = nullptr;
105        };
106
107        /// Fix return types so that every function returns exactly one value
108        struct ReturnTypeFixer {
109                static void fix( std::list< Declaration * > &translationUnit );
110
111                void postvisit( FunctionDecl * functionDecl );
112                void postvisit( FunctionType * ftype );
113        };
114
115        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
116        struct EnumAndPointerDecay {
117                void previsit( EnumDecl *aggregateDecl );
118                void previsit( FunctionType *func );
119        };
120
121        /// Associates forward declarations of aggregates with their definitions
122        struct LinkReferenceToTypes final : public WithIndexer, public WithGuards {
123                LinkReferenceToTypes( const Indexer *indexer );
124                void postvisit( TypeInstType *typeInst );
125
126                void postvisit( EnumInstType *enumInst );
127                void postvisit( StructInstType *structInst );
128                void postvisit( UnionInstType *unionInst );
129                void postvisit( TraitInstType *traitInst );
130
131                void postvisit( EnumDecl *enumDecl );
132                void postvisit( StructDecl *structDecl );
133                void postvisit( UnionDecl *unionDecl );
134                void postvisit( TraitDecl * traitDecl );
135
136                void previsit( StructDecl *structDecl );
137                void previsit( UnionDecl *unionDecl );
138
139                void renameGenericParams( std::list< TypeDecl * > & params );
140
141          private:
142                const Indexer *local_indexer;
143
144                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
145                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
146                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
147                ForwardEnumsType forwardEnums;
148                ForwardStructsType forwardStructs;
149                ForwardUnionsType forwardUnions;
150                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
151                bool inGeneric = false;
152        };
153
154        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
155        struct ForallPointerDecay final {
156                void previsit( ObjectDecl * object );
157                void previsit( FunctionDecl * func );
158                void previsit( FunctionType * ftype );
159                void previsit( StructDecl * aggrDecl );
160                void previsit( UnionDecl * aggrDecl );
161        };
162
163        struct ReturnChecker : public WithGuards {
164                /// Checks that return statements return nothing if their return type is void
165                /// and return something if the return type is non-void.
166                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
167
168                void previsit( FunctionDecl * functionDecl );
169                void previsit( ReturnStmt * returnStmt );
170
171                typedef std::list< DeclarationWithType * > ReturnVals;
172                ReturnVals returnVals;
173        };
174
175        struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
176                EliminateTypedef() : scopeLevel( 0 ) {}
177                /// Replaces typedefs by forward declarations
178                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
179
180                Type * postmutate( TypeInstType * aggregateUseType );
181                Declaration * postmutate( TypedefDecl * typeDecl );
182                void premutate( TypeDecl * typeDecl );
183                void premutate( FunctionDecl * funcDecl );
184                void premutate( ObjectDecl * objDecl );
185                DeclarationWithType * postmutate( ObjectDecl * objDecl );
186
187                void premutate( CastExpr * castExpr );
188
189                void premutate( CompoundStmt * compoundStmt );
190                CompoundStmt * postmutate( CompoundStmt * compoundStmt );
191
192                void premutate( StructDecl * structDecl );
193                Declaration * postmutate( StructDecl * structDecl );
194                void premutate( UnionDecl * unionDecl );
195                Declaration * postmutate( UnionDecl * unionDecl );
196                void premutate( EnumDecl * enumDecl );
197                Declaration * postmutate( EnumDecl * enumDecl );
198                Declaration * postmutate( TraitDecl * contextDecl );
199
200                void premutate( FunctionType * ftype );
201
202          private:
203                template<typename AggDecl>
204                AggDecl *handleAggregate( AggDecl * aggDecl );
205
206                template<typename AggDecl>
207                void addImplicitTypedef( AggDecl * aggDecl );
208
209                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
210                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
211                typedef std::map< std::string, TypeDecl * > TypeDeclMap; // xxx - convert to ScopedMap
212                TypedefMap typedefNames;
213                TypeDeclMap typedeclNames;
214                int scopeLevel;
215                bool inFunctionType = false;
216        };
217
218        struct VerifyCtorDtorAssign {
219                /// ensure that constructors, destructors, and assignment have at least one
220                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
221                /// return values.
222                static void verify( std::list< Declaration * > &translationUnit );
223
224                void previsit( FunctionDecl *funcDecl );
225        };
226
227        /// ensure that generic types have the correct number of type arguments
228        struct ValidateGenericParameters {
229                void previsit( StructInstType * inst );
230                void previsit( UnionInstType * inst );
231        };
232
233        struct ArrayLength {
234                /// for array types without an explicit length, compute the length and store it so that it
235                /// is known to the rest of the phases. For example,
236                ///   int x[] = { 1, 2, 3 };
237                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
238                /// here x and y are known at compile-time to have length 3, so change this into
239                ///   int x[3] = { 1, 2, 3 };
240                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
241                static void computeLength( std::list< Declaration * > & translationUnit );
242
243                void previsit( ObjectDecl * objDecl );
244        };
245
246        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
247                Type::StorageClasses storageClasses;
248
249                void premutate( ObjectDecl *objectDecl );
250                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
251        };
252
253        struct LabelAddressFixer final : public WithGuards {
254                std::set< Label > labels;
255
256                void premutate( FunctionDecl * funcDecl );
257                Expression * postmutate( AddressExpr * addrExpr );
258        };
259
260        FunctionDecl * dereferenceOperator = nullptr;
261        struct FindSpecialDeclarations final {
262                void previsit( FunctionDecl * funcDecl );
263        };
264
265        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
266                PassVisitor<EnumAndPointerDecay> epc;
267                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
268                PassVisitor<ForallPointerDecay> fpd;
269                PassVisitor<CompoundLiteral> compoundliteral;
270                PassVisitor<ValidateGenericParameters> genericParams;
271                PassVisitor<FindSpecialDeclarations> finder;
272                PassVisitor<LabelAddressFixer> labelAddrFixer;
273                PassVisitor<HoistTypeDecls> hoistDecls;
274
275                acceptAll( translationUnit, hoistDecls );
276                EliminateTypedef::eliminateTypedef( translationUnit );
277                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
278                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
279                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
280                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
281                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
282                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
283                ReturnChecker::checkFunctionReturns( translationUnit );
284                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
285                Concurrency::applyKeywords( translationUnit );
286                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
287                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
288                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
289                Concurrency::implementMutexFuncs( translationUnit );
290                Concurrency::implementThreadStarter( translationUnit );
291                mutateAll( translationUnit, compoundliteral );
292                ArrayLength::computeLength( translationUnit );
293                acceptAll( translationUnit, finder ); // xxx - remove this pass soon
294                mutateAll( translationUnit, labelAddrFixer );
295        }
296
297        void validateType( Type *type, const Indexer *indexer ) {
298                PassVisitor<EnumAndPointerDecay> epc;
299                PassVisitor<LinkReferenceToTypes> lrt( indexer );
300                PassVisitor<ForallPointerDecay> fpd;
301                type->accept( epc );
302                type->accept( lrt );
303                type->accept( fpd );
304        }
305
306
307        void HoistTypeDecls::handleType( Type * type ) {
308                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
309                AggregateDecl * aggr = nullptr;
310                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
311                        aggr = inst->baseStruct;
312                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
313                        aggr = inst->baseUnion;
314                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
315                        aggr = inst->baseEnum;
316                }
317                if ( aggr && aggr->body ) {
318                        declsToAddBefore.push_front( aggr );
319                }
320        }
321
322        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
323                handleType( expr->type );
324        }
325
326        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
327                handleType( expr->type );
328        }
329
330        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
331                handleType( expr->type );
332        }
333
334
335        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
336                PassVisitor<HoistStruct> hoister;
337                acceptAll( translationUnit, hoister );
338        }
339
340        bool shouldHoist( Declaration *decl ) {
341                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
342        }
343
344        namespace {
345                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
346                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
347                        ss << "__" << aggr->name;
348                }
349
350                // mangle nested type names using entire parent chain
351                std::string qualifiedName( AggregateDecl * aggr ) {
352                        std::ostringstream ss;
353                        qualifiedName( aggr, ss );
354                        return ss.str();
355                }
356        }
357
358        template< typename AggDecl >
359        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
360                if ( parentAggr ) {
361                        aggregateDecl->parent = parentAggr;
362                        aggregateDecl->name = qualifiedName( aggregateDecl );
363                        // Add elements in stack order corresponding to nesting structure.
364                        declsToAddBefore.push_front( aggregateDecl );
365                } else {
366                        GuardValue( parentAggr );
367                        parentAggr = aggregateDecl;
368                } // if
369                // Always remove the hoisted aggregate from the inner structure.
370                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
371        }
372
373        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
374                if ( parentAggr ) {
375                        declsToAddBefore.push_back( assertDecl );
376                }
377        }
378
379        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
380                handleAggregate( aggregateDecl );
381        }
382
383        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
384                handleAggregate( aggregateDecl );
385        }
386
387        void HoistStruct::previsit( StructInstType * type ) {
388                // need to reset type name after expanding to qualified name
389                assert( type->baseStruct );
390                type->name = type->baseStruct->name;
391        }
392
393        void HoistStruct::previsit( UnionInstType * type ) {
394                assert( type->baseUnion );
395                type->name = type->baseUnion->name;
396        }
397
398        void HoistStruct::previsit( EnumInstType * type ) {
399                assert( type->baseEnum );
400                type->name = type->baseEnum->name;
401        }
402
403
404        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
405                // Set the type of each member of the enumeration to be EnumConstant
406                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
407                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
408                        assert( obj );
409                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
410                } // for
411        }
412
413        namespace {
414                template< typename DWTList >
415                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
416                        auto nvals = dwts.size();
417                        bool containsVoid = false;
418                        for ( auto & dwt : dwts ) {
419                                // fix each DWT and record whether a void was found
420                                containsVoid |= fixFunction( dwt );
421                        }
422
423                        // the only case in which "void" is valid is where it is the only one in the list
424                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
425                                SemanticError( func, "invalid type void in function type " );
426                        }
427
428                        // one void is the only thing in the list; remove it.
429                        if ( containsVoid ) {
430                                delete dwts.front();
431                                dwts.clear();
432                        }
433                }
434        }
435
436        void EnumAndPointerDecay::previsit( FunctionType *func ) {
437                // Fix up parameters and return types
438                fixFunctionList( func->parameters, func->isVarArgs, func );
439                fixFunctionList( func->returnVals, false, func );
440        }
441
442        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
443                if ( other_indexer ) {
444                        local_indexer = other_indexer;
445                } else {
446                        local_indexer = &indexer;
447                } // if
448        }
449
450        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
451                EnumDecl *st = local_indexer->lookupEnum( enumInst->name );
452                // it's not a semantic error if the enum is not found, just an implicit forward declaration
453                if ( st ) {
454                        enumInst->baseEnum = st;
455                } // if
456                if ( ! st || ! st->body ) {
457                        // use of forward declaration
458                        forwardEnums[ enumInst->name ].push_back( enumInst );
459                } // if
460        }
461
462        void checkGenericParameters( ReferenceToType * inst ) {
463                for ( Expression * param : inst->parameters ) {
464                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
465                                SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
466                        }
467                }
468        }
469
470        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
471                StructDecl *st = local_indexer->lookupStruct( structInst->name );
472                // it's not a semantic error if the struct is not found, just an implicit forward declaration
473                if ( st ) {
474                        structInst->baseStruct = st;
475                } // if
476                if ( ! st || ! st->body ) {
477                        // use of forward declaration
478                        forwardStructs[ structInst->name ].push_back( structInst );
479                } // if
480                checkGenericParameters( structInst );
481        }
482
483        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
484                UnionDecl *un = local_indexer->lookupUnion( unionInst->name );
485                // it's not a semantic error if the union is not found, just an implicit forward declaration
486                if ( un ) {
487                        unionInst->baseUnion = un;
488                } // if
489                if ( ! un || ! un->body ) {
490                        // use of forward declaration
491                        forwardUnions[ unionInst->name ].push_back( unionInst );
492                } // if
493                checkGenericParameters( unionInst );
494        }
495
496        template< typename Decl >
497        void normalizeAssertions( std::list< Decl * > & assertions ) {
498                // ensure no duplicate trait members after the clone
499                auto pred = [](Decl * d1, Decl * d2) {
500                        // only care if they're equal
501                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
502                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
503                        if ( dwt1 && dwt2 ) {
504                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
505                                        // std::cerr << "=========== equal:" << std::endl;
506                                        // std::cerr << "d1: " << d1 << std::endl;
507                                        // std::cerr << "d2: " << d2 << std::endl;
508                                        return false;
509                                }
510                        }
511                        return d1 < d2;
512                };
513                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
514                // if ( unique_members.size() != assertions.size() ) {
515                //      std::cerr << "============different" << std::endl;
516                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
517                // }
518
519                std::list< Decl * > order;
520                order.splice( order.end(), assertions );
521                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
522                        return unique_members.count( decl );
523                });
524        }
525
526        // expand assertions from trait instance, performing the appropriate type variable substitutions
527        template< typename Iterator >
528        void expandAssertions( TraitInstType * inst, Iterator out ) {
529                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
530                std::list< DeclarationWithType * > asserts;
531                for ( Declaration * decl : inst->baseTrait->members ) {
532                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
533                }
534                // substitute trait decl parameters for instance parameters
535                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
536        }
537
538        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
539                if ( traitDecl->name == "sized" ) {
540                        // "sized" is a special trait - flick the sized status on for the type variable
541                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
542                        TypeDecl * td = traitDecl->parameters.front();
543                        td->set_sized( true );
544                }
545
546                // move assertions from type parameters into the body of the trait
547                for ( TypeDecl * td : traitDecl->parameters ) {
548                        for ( DeclarationWithType * assert : td->assertions ) {
549                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
550                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
551                                } else {
552                                        traitDecl->members.push_back( assert->clone() );
553                                }
554                        }
555                        deleteAll( td->assertions );
556                        td->assertions.clear();
557                } // for
558        }
559
560        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
561                // handle other traits
562                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
563                if ( ! traitDecl ) {
564                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
565                } // if
566                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
567                        SemanticError( traitInst, "incorrect number of trait parameters: " );
568                } // if
569                traitInst->baseTrait = traitDecl;
570
571                // need to carry over the 'sized' status of each decl in the instance
572                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
573                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
574                        if ( ! expr ) {
575                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
576                        }
577                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
578                                TypeDecl * formalDecl = std::get<0>(p);
579                                TypeDecl * instDecl = inst->baseType;
580                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
581                        }
582                }
583                // normalizeAssertions( traitInst->members );
584        }
585
586        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
587                // visit enum members first so that the types of self-referencing members are updated properly
588                if ( enumDecl->body ) {
589                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
590                        if ( fwds != forwardEnums.end() ) {
591                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
592                                        (*inst)->baseEnum = enumDecl;
593                                } // for
594                                forwardEnums.erase( fwds );
595                        } // if
596                } // if
597        }
598
599        void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
600                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
601                //   forall(otype T)
602                //   struct Box {
603                //     T x;
604                //   };
605                //   forall(otype T)
606                //   void f(Box(T) b) {
607                //     ...
608                //   }
609                // The T in Box and the T in f are different, so internally the naming must reflect that.
610                GuardValue( inGeneric );
611                inGeneric = ! params.empty();
612                for ( TypeDecl * td : params ) {
613                        td->name = "__" + td->name + "_generic_";
614                }
615        }
616
617        void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
618                renameGenericParams( structDecl->parameters );
619        }
620
621        void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
622                renameGenericParams( unionDecl->parameters );
623        }
624
625        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
626                // visit struct members first so that the types of self-referencing members are updated properly
627                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
628                if ( structDecl->body ) {
629                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
630                        if ( fwds != forwardStructs.end() ) {
631                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
632                                        (*inst)->baseStruct = structDecl;
633                                } // for
634                                forwardStructs.erase( fwds );
635                        } // if
636                } // if
637        }
638
639        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
640                if ( unionDecl->body ) {
641                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
642                        if ( fwds != forwardUnions.end() ) {
643                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
644                                        (*inst)->baseUnion = unionDecl;
645                                } // for
646                                forwardUnions.erase( fwds );
647                        } // if
648                } // if
649        }
650
651        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
652                // ensure generic parameter instances are renamed like the base type
653                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
654                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
655                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
656                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
657                        } // if
658                } // if
659        }
660
661        /// Fix up assertions - flattens assertion lists, removing all trait instances
662        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
663                for ( TypeDecl * type : forall ) {
664                        std::list< DeclarationWithType * > asserts;
665                        asserts.splice( asserts.end(), type->assertions );
666                        // expand trait instances into their members
667                        for ( DeclarationWithType * assertion : asserts ) {
668                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
669                                        // expand trait instance into all of its members
670                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
671                                        delete traitInst;
672                                } else {
673                                        // pass other assertions through
674                                        type->assertions.push_back( assertion );
675                                } // if
676                        } // for
677                        // apply FixFunction to every assertion to check for invalid void type
678                        for ( DeclarationWithType *& assertion : type->assertions ) {
679                                bool isVoid = fixFunction( assertion );
680                                if ( isVoid ) {
681                                        SemanticError( node, "invalid type void in assertion of function " );
682                                } // if
683                        } // for
684                        // normalizeAssertions( type->assertions );
685                } // for
686        }
687
688        void ForallPointerDecay::previsit( ObjectDecl *object ) {
689                // ensure that operator names only apply to functions or function pointers
690                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
691                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
692                }
693                object->fixUniqueId();
694        }
695
696        void ForallPointerDecay::previsit( FunctionDecl *func ) {
697                func->fixUniqueId();
698        }
699
700        void ForallPointerDecay::previsit( FunctionType * ftype ) {
701                forallFixer( ftype->forall, ftype );
702        }
703
704        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
705                forallFixer( aggrDecl->parameters, aggrDecl );
706        }
707
708        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
709                forallFixer( aggrDecl->parameters, aggrDecl );
710        }
711
712        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
713                PassVisitor<ReturnChecker> checker;
714                acceptAll( translationUnit, checker );
715        }
716
717        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
718                GuardValue( returnVals );
719                returnVals = functionDecl->get_functionType()->get_returnVals();
720        }
721
722        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
723                // Previously this also checked for the existence of an expr paired with no return values on
724                // the  function return type. This is incorrect, since you can have an expression attached to
725                // a return statement in a void-returning function in C. The expression is treated as if it
726                // were cast to void.
727                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
728                        SemanticError( returnStmt, "Non-void function returns no values: " );
729                }
730        }
731
732
733        bool isTypedef( Declaration *decl ) {
734                return dynamic_cast< TypedefDecl * >( decl );
735        }
736
737        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
738                PassVisitor<EliminateTypedef> eliminator;
739                mutateAll( translationUnit, eliminator );
740                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
741                        // grab and remember declaration of size_t
742                        SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
743                } else {
744                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
745                        // eventually should have a warning for this case.
746                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
747                }
748                filter( translationUnit, isTypedef, true );
749        }
750
751        Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
752                // instances of typedef types will come here. If it is an instance
753                // of a typdef type, link the instance to its actual type.
754                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
755                if ( def != typedefNames.end() ) {
756                        Type *ret = def->second.first->base->clone();
757                        ret->get_qualifiers() |= typeInst->get_qualifiers();
758                        // attributes are not carried over from typedef to function parameters/return values
759                        if ( ! inFunctionType ) {
760                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
761                        } else {
762                                deleteAll( ret->attributes );
763                                ret->attributes.clear();
764                        }
765                        // place instance parameters on the typedef'd type
766                        if ( ! typeInst->parameters.empty() ) {
767                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
768                                if ( ! rtt ) {
769                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
770                                }
771                                rtt->parameters.clear();
772                                cloneAll( typeInst->parameters, rtt->parameters );
773                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
774                        } // if
775                        delete typeInst;
776                        return ret;
777                } else {
778                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
779                        assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() );
780                        typeInst->set_baseType( base->second );
781                } // if
782                return typeInst;
783        }
784
785        struct VarLenChecker : WithShortCircuiting {
786                void previsit( FunctionType * ) { visit_children = false; }
787                void previsit( ArrayType * at ) {
788                        isVarLen |= at->isVarLen;
789                }
790                bool isVarLen = false;
791        };
792
793        bool isVariableLength( Type * t ) {
794                PassVisitor<VarLenChecker> varLenChecker;
795                maybeAccept( t, varLenChecker );
796                return varLenChecker.pass.isVarLen;
797        }
798
799        Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
800                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
801                        // typedef to the same name from the same scope
802                        // must be from the same type
803
804                        Type * t1 = tyDecl->base;
805                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
806                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
807                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
808                        }
809                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
810                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
811                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
812                        // to fix this corner case likely outweighs the utility of allowing it.
813                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
814                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
815                        }
816                } else {
817                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
818                } // if
819
820                // When a typedef is a forward declaration:
821                //    typedef struct screen SCREEN;
822                // the declaration portion must be retained:
823                //    struct screen;
824                // because the expansion of the typedef is:
825                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
826                // hence the type-name "screen" must be defined.
827                // Note, qualifiers on the typedef are superfluous for the forward declaration.
828
829                Type *designatorType = tyDecl->base->stripDeclarator();
830                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
831                        return new StructDecl( aggDecl->name, DeclarationNode::Struct, noAttributes, tyDecl->linkage );
832                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
833                        return new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage );
834                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
835                        return new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage );
836                } else {
837                        return tyDecl->clone();
838                } // if
839        }
840
841        void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
842                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
843                if ( i != typedefNames.end() ) {
844                        typedefNames.erase( i ) ;
845                } // if
846
847                typedeclNames[ typeDecl->name ] = typeDecl;
848        }
849
850        void EliminateTypedef::premutate( FunctionDecl * ) {
851                GuardScope( typedefNames );
852        }
853
854        void EliminateTypedef::premutate( ObjectDecl * ) {
855                GuardScope( typedefNames );
856        }
857
858        DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
859                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
860                        // replace the current object declaration with a function declaration
861                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
862                        objDecl->attributes.clear();
863                        objDecl->set_type( nullptr );
864                        delete objDecl;
865                        return newDecl;
866                } // if
867                return objDecl;
868        }
869
870        void EliminateTypedef::premutate( CastExpr * ) {
871                GuardScope( typedefNames );
872        }
873
874        void EliminateTypedef::premutate( CompoundStmt * ) {
875                GuardScope( typedefNames );
876                scopeLevel += 1;
877                GuardAction( [this](){ scopeLevel -= 1; } );
878        }
879
880        CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
881                // remove and delete decl stmts
882                filter( compoundStmt->kids, [](Statement * stmt) {
883                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
884                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
885                                        return true;
886                                } // if
887                        } // if
888                        return false;
889                }, true);
890                return compoundStmt;
891        }
892
893        // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
894        // as well
895        template<typename AggDecl>
896        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
897                filter( aggDecl->members, isTypedef, true );
898                return aggDecl;
899        }
900
901        template<typename AggDecl>
902        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
903                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
904                        Type *type = nullptr;
905                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
906                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
907                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
908                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
909                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
910                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
911                        } // if
912                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
913                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
914                } // if
915        }
916
917        void EliminateTypedef::premutate( StructDecl * structDecl ) {
918                addImplicitTypedef( structDecl );
919        }
920
921
922        Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
923                return handleAggregate( structDecl );
924        }
925
926        void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
927                addImplicitTypedef( unionDecl );
928        }
929
930        Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
931                return handleAggregate( unionDecl );
932        }
933
934        void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
935                addImplicitTypedef( enumDecl );
936        }
937
938        Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
939                return handleAggregate( enumDecl );
940        }
941
942        Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
943                return handleAggregate( traitDecl );
944        }
945
946        void EliminateTypedef::premutate( FunctionType * ) {
947                GuardValue( inFunctionType );
948                inFunctionType = true;
949        }
950
951        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
952                PassVisitor<VerifyCtorDtorAssign> verifier;
953                acceptAll( translationUnit, verifier );
954        }
955
956        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
957                FunctionType * funcType = funcDecl->get_functionType();
958                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
959                std::list< DeclarationWithType * > &params = funcType->get_parameters();
960
961                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
962                        if ( params.size() == 0 ) {
963                                SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
964                        }
965                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
966                        if ( ! refType ) {
967                                SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
968                        }
969                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
970                                SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
971                        }
972                }
973        }
974
975        template< typename Aggr >
976        void validateGeneric( Aggr * inst ) {
977                std::list< TypeDecl * > * params = inst->get_baseParameters();
978                if ( params ) {
979                        std::list< Expression * > & args = inst->get_parameters();
980
981                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
982                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
983                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
984                        //   vector(int) v;
985                        // after insertion of default values becomes
986                        //   vector(int, heap_allocator(T))
987                        // and the substitution is built with T=int so that after substitution, the result is
988                        //   vector(int, heap_allocator(int))
989                        TypeSubstitution sub;
990                        auto paramIter = params->begin();
991                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
992                                if ( i < args.size() ) {
993                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
994                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
995                                } else if ( i == args.size() ) {
996                                        Type * defaultType = (*paramIter)->get_init();
997                                        if ( defaultType ) {
998                                                args.push_back( new TypeExpr( defaultType->clone() ) );
999                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
1000                                        }
1001                                }
1002                        }
1003
1004                        sub.apply( inst );
1005                        if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1006                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1007                }
1008        }
1009
1010        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1011                validateGeneric( inst );
1012        }
1013
1014        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1015                validateGeneric( inst );
1016        }
1017
1018        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
1019                storageClasses = objectDecl->get_storageClasses();
1020        }
1021
1022        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
1023                // transform [storage_class] ... (struct S){ 3, ... };
1024                // into [storage_class] struct S temp =  { 3, ... };
1025                static UniqueName indexName( "_compLit" );
1026
1027                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1028                compLitExpr->set_result( nullptr );
1029                compLitExpr->set_initializer( nullptr );
1030                delete compLitExpr;
1031                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1032                return new VariableExpr( tempvar );
1033        }
1034
1035        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1036                PassVisitor<ReturnTypeFixer> fixer;
1037                acceptAll( translationUnit, fixer );
1038        }
1039
1040        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1041                FunctionType * ftype = functionDecl->get_functionType();
1042                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1043                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1044                if ( retVals.size() == 1 ) {
1045                        // 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).
1046                        // ensure other return values have a name.
1047                        DeclarationWithType * ret = retVals.front();
1048                        if ( ret->get_name() == "" ) {
1049                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1050                        }
1051                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1052                }
1053        }
1054
1055        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1056                // xxx - need to handle named return values - this information needs to be saved somehow
1057                // so that resolution has access to the names.
1058                // Note that this pass needs to happen early so that other passes which look for tuple types
1059                // find them in all of the right places, including function return types.
1060                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1061                if ( retVals.size() > 1 ) {
1062                        // generate a single return parameter which is the tuple of all of the return values
1063                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1064                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1065                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
1066                        deleteAll( retVals );
1067                        retVals.clear();
1068                        retVals.push_back( newRet );
1069                }
1070        }
1071
1072        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1073                PassVisitor<ArrayLength> len;
1074                acceptAll( translationUnit, len );
1075        }
1076
1077        void ArrayLength::previsit( ObjectDecl * objDecl ) {
1078                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1079                        if ( at->get_dimension() ) return;
1080                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1081                                at->set_dimension( new ConstantExpr( Constant::from_ulong( init->initializers.size() ) ) );
1082                        }
1083                }
1084        }
1085
1086        struct LabelFinder {
1087                std::set< Label > & labels;
1088                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1089                void previsit( Statement * stmt ) {
1090                        for ( Label & l : stmt->labels ) {
1091                                labels.insert( l );
1092                        }
1093                }
1094        };
1095
1096        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1097                GuardValue( labels );
1098                PassVisitor<LabelFinder> finder( labels );
1099                funcDecl->accept( finder );
1100        }
1101
1102        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1103                // convert &&label into label address
1104                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1105                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1106                                if ( labels.count( nameExpr->name ) ) {
1107                                        Label name = nameExpr->name;
1108                                        delete addrExpr;
1109                                        return new LabelAddressExpr( name );
1110                                }
1111                        }
1112                }
1113                return addrExpr;
1114        }
1115
1116        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1117                if ( ! dereferenceOperator ) {
1118                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1119                                FunctionType * ftype = funcDecl->get_functionType();
1120                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1121                                        dereferenceOperator = funcDecl;
1122                                }
1123                        }
1124                }
1125        }
1126} // namespace SymTab
1127
1128// Local Variables: //
1129// tab-width: 4 //
1130// mode: c++ //
1131// compile-command: "make install" //
1132// End: //
Note: See TracBrowser for help on using the repository browser.