source: src/SymTab/Validate.cc @ 48ed81c

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

Rename EliminateTypedef? to ReplaceTypedef? and add TypedefDecls? for implicit typedefs

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