source: src/SymTab/Validate.cc @ afcb0a3

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

Ignore QualifiedType? children in LinkReferenceToTypes?

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