source: src/GenPoly/Box.cc @ 0531b5d

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since 0531b5d was 0531b5d, checked in by Aaron Moss <a3moss@…>, 8 years ago

Fixed ScopedMap?'s const find, refactored InstantionMap? to use ScopedMap?

  • Property mode set to 100644
File size: 92.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// Box.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Feb  5 16:45:07 2016
13// Update Count     : 286
14//
15
16#include <algorithm>
17#include <iterator>
18#include <list>
19#include <map>
20#include <set>
21#include <stack>
22#include <string>
23#include <utility>
24#include <vector>
25#include <cassert>
26
27#include "Box.h"
28#include "DeclMutator.h"
29#include "PolyMutator.h"
30#include "FindFunction.h"
31#include "ScopedMap.h"
32#include "ScrubTyVars.h"
33
34#include "Parser/ParseNode.h"
35
36#include "SynTree/Constant.h"
37#include "SynTree/Declaration.h"
38#include "SynTree/Expression.h"
39#include "SynTree/Initializer.h"
40#include "SynTree/Mutator.h"
41#include "SynTree/Statement.h"
42#include "SynTree/Type.h"
43#include "SynTree/TypeSubstitution.h"
44
45#include "ResolvExpr/TypeEnvironment.h"
46#include "ResolvExpr/TypeMap.h"
47#include "ResolvExpr/typeops.h"
48
49#include "SymTab/Indexer.h"
50#include "SymTab/Mangler.h"
51
52#include "Common/SemanticError.h"
53#include "Common/UniqueName.h"
54#include "Common/utility.h"
55
56#include <ext/functional> // temporary
57
58namespace GenPoly {
59        namespace {
60                const std::list<Label> noLabels;
61
62                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
63
64                /// Abstracts type equality for a list of parameter types
65                struct TypeList {
66                        TypeList() : params() {}
67                        TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
68                        TypeList( std::list< Type* > &&_params ) : params( _params ) {}
69
70                        TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
71                        TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
72
73                        /// Extracts types from a list of TypeExpr*
74                        TypeList( const std::list< TypeExpr* >& _params ) : params() {
75                                for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
76                                        params.push_back( (*param)->get_type()->clone() );
77                                }
78                        }
79
80                        TypeList& operator= ( const TypeList &that ) {
81                                deleteAll( params );
82
83                                params.clear();
84                                cloneAll( that.params, params );
85
86                                return *this;
87                        }
88
89                        TypeList& operator= ( TypeList &&that ) {
90                                deleteAll( params );
91
92                                params = std::move( that.params );
93
94                                return *this;
95                        }
96
97                        ~TypeList() { deleteAll( params ); }
98
99                        bool operator== ( const TypeList& that ) const {
100                                if ( params.size() != that.params.size() ) return false;
101
102                                SymTab::Indexer dummy;
103                                for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
104                                        if ( ! ResolvExpr::typesCompatible( *it, *jt, dummy ) ) return false;
105                                }
106                                return true;
107                        }
108
109                        std::list< Type* > params;  ///< Instantiation parameters
110                };
111
112                /// Maps a key and a TypeList to the some value, accounting for scope
113                template< typename Key, typename Value >
114                class InstantiationMap {
115                        /// Wraps value for a specific (Key, TypeList) combination
116                        typedef std::pair< TypeList, Value* > Instantiation;
117                        /// List of TypeLists paired with their appropriate values
118                        typedef std::vector< Instantiation > ValueList;
119                        /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
120                        typedef ScopedMap< Key*, std::vector< Instantiation > > InnerMap;
121
122                        InnerMap instantiations;  ///< instantiations
123
124                public:
125                        /// Starts a new scope
126                        void beginScope() { instantiations.beginScope(); }
127
128                        /// Ends a scope
129                        void endScope() { instantiations.endScope(); }
130
131                        /// Gets the value for the (key, typeList) pair, returns NULL on none such.
132                        Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
133                                TypeList typeList( params );
134                               
135                                // scan scopes for matches to the key
136                                for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
137                                        for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
138                                                if ( inst->first == typeList ) return inst->second;
139                                        }
140                                }
141                                // no matching instantiations found
142                                return 0;
143                        }
144
145                        /// Adds a value for a (key, typeList) pair to the current scope
146                        void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
147                                instantiations[ key ].push_back( Instantiation( TypeList( params ), value ) );
148                        }
149                };
150
151                /// Adds layout-generation functions to polymorphic types
152                class LayoutFunctionBuilder : public DeclMutator {
153                        unsigned int functionNesting;  // current level of nested functions
154                public:
155                        LayoutFunctionBuilder() : functionNesting( 0 ) {}
156
157                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
158                        virtual Declaration *mutate( StructDecl *structDecl );
159                        virtual Declaration *mutate( UnionDecl *unionDecl );
160                };
161               
162                /// Replaces polymorphic return types with out-parameters, replaces calls to polymorphic functions with adapter calls as needed, and adds appropriate type variables to the function call
163                class Pass1 : public PolyMutator {
164                  public:
165                        Pass1();
166                        virtual Expression *mutate( ApplicationExpr *appExpr );
167                        virtual Expression *mutate( AddressExpr *addrExpr );
168                        virtual Expression *mutate( UntypedExpr *expr );
169                        virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
170                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
171                        virtual Expression *mutate( CommaExpr *commaExpr );
172                        virtual Expression *mutate( ConditionalExpr *condExpr );
173                        virtual Statement * mutate( ReturnStmt *returnStmt );
174                        virtual Type *mutate( PointerType *pointerType );
175                        virtual Type * mutate( FunctionType *functionType );
176
177                        virtual void doBeginScope();
178                        virtual void doEndScope();
179                  private:
180                        /// Makes a new temporary array holding the offsets of the fields of `type`, and returns a new variable expression referencing it
181                        Expression *makeOffsetArray( StructInstType *type );
182                        /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
183                        void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
184                        /// passes extra type parameters into a polymorphic function application
185                        void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
186                        /// wraps a function application with a new temporary for the out-parameter return value
187                        Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
188                        /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
189                        void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
190                        /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
191                        /// If `doClone` is set to false, will not clone interior types
192                        Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
193                        /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
194                        Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
195                        Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
196                        void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
197                        void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
198                        void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
199                        /// Stores assignment operators from assertion list in local map of assignment operations
200                        void findAssignOps( const std::list< TypeDecl *> &forall );
201                        void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
202                        FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
203                        /// Replaces intrinsic operator functions with their arithmetic desugaring
204                        Expression *handleIntrinsics( ApplicationExpr *appExpr );
205                        /// Inserts a new temporary variable into the current scope with an auto-generated name
206                        ObjectDecl *makeTemporary( Type *type );
207
208                        std::map< std::string, DeclarationWithType *> assignOps;
209                        ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps;
210                        ScopedMap< std::string, DeclarationWithType* > adapters;
211                        DeclarationWithType *retval;
212                        bool useRetval;
213                        UniqueName tempNamer;
214                };
215
216                /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
217                class Pass2 : public PolyMutator {
218                  public:
219                        template< typename DeclClass >
220                        DeclClass *handleDecl( DeclClass *decl, Type *type );
221                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
222                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
223                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
224                        virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
225                        virtual Type *mutate( PointerType *pointerType );
226                        virtual Type *mutate( FunctionType *funcType );
227                  private:
228                        void addAdapters( FunctionType *functionType );
229
230                        std::map< UniqueId, std::string > adapterName;
231                };
232
233                /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
234                class GenericInstantiator : public DeclMutator {
235                        /// Map of (generic type, parameter list) pairs to concrete type instantiations
236                        InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
237                        /// Namer for concrete types
238                        UniqueName typeNamer;
239
240                public:
241                        GenericInstantiator() : DeclMutator(), instantiations(), typeNamer("_conc_") {}
242
243                        virtual Type* mutate( StructInstType *inst );
244                        virtual Type* mutate( UnionInstType *inst );
245
246        //              virtual Expression* mutate( MemberExpr *memberExpr );
247
248                        virtual void doBeginScope();
249                        virtual void doEndScope();
250                private:
251                        /// Wrap instantiation lookup for structs
252                        StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
253                        /// Wrap instantiation lookup for unions
254                        UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
255                        /// Wrap instantiation insertion for structs
256                        void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
257                        /// Wrap instantiation insertion for unions
258                        void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
259                };
260
261                /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
262                /// also fixes offsetof expressions.
263                class MemberExprFixer : public PolyMutator {
264                  public:
265                        template< typename DeclClass >
266                        DeclClass *handleDecl( DeclClass *decl, Type *type );
267                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
268                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
269                        virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
270                        virtual TypeDecl *mutate( TypeDecl *objectDecl );
271                        virtual Statement *mutate( DeclStmt *declStmt );
272                        virtual Type *mutate( PointerType *pointerType );
273                        virtual Type *mutate( FunctionType *funcType );
274                        virtual Expression *mutate( MemberExpr *memberExpr );
275                        virtual Expression *mutate( OffsetofExpr *offsetofExpr );
276                };
277
278                /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, and sizeof expressions of polymorphic types with the proper variable
279                class Pass3 : public PolyMutator {
280                  public:
281                        template< typename DeclClass >
282                        DeclClass *handleDecl( DeclClass *decl, Type *type );
283                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
284                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
285                        virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
286                        virtual TypeDecl *mutate( TypeDecl *objectDecl );
287                        virtual Type *mutate( PointerType *pointerType );
288                        virtual Type *mutate( FunctionType *funcType );
289                  private:
290                };
291
292        } // anonymous namespace
293
294        /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
295        template< typename MutatorType >
296        inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
297                bool seenIntrinsic = false;
298                SemanticError errors;
299                for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
300                        try {
301                                if ( *i ) {
302                                        if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
303                                                seenIntrinsic = true;
304                                        } else if ( seenIntrinsic ) {
305                                                seenIntrinsic = false; // break on this line when debugging for end of prelude
306                                        }
307
308                                        *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
309                                        assert( *i );
310                                } // if
311                        } catch( SemanticError &e ) {
312                                errors.append( e );
313                        } // try
314                } // for
315                if ( ! errors.isEmpty() ) {
316                        throw errors;
317                } // if
318        }
319
320        void box( std::list< Declaration *>& translationUnit ) {
321                LayoutFunctionBuilder layoutBuilder;
322                Pass1 pass1;
323                Pass2 pass2;
324                GenericInstantiator instantiator;
325                MemberExprFixer memberFixer;
326                Pass3 pass3;
327               
328                layoutBuilder.mutateDeclarationList( translationUnit );
329                mutateTranslationUnit/*All*/( translationUnit, pass1 );
330                mutateTranslationUnit/*All*/( translationUnit, pass2 );
331                instantiator.mutateDeclarationList( translationUnit );
332                mutateTranslationUnit/*All*/( translationUnit, memberFixer );
333                mutateTranslationUnit/*All*/( translationUnit, pass3 );
334        }
335
336        ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
337
338        DeclarationWithType *LayoutFunctionBuilder::mutate( FunctionDecl *functionDecl ) {
339                functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
340                mutateAll( functionDecl->get_oldDecls(), *this );
341                ++functionNesting;
342                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
343                --functionNesting;
344                return functionDecl;
345        }
346       
347        /// Get a list of type declarations that will affect a layout function
348        std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
349                std::list< TypeDecl * > otypeDecls;
350
351                for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
352                        if ( (*decl)->get_kind() == TypeDecl::Any ) {
353                                otypeDecls.push_back( *decl );
354                        }
355                }
356               
357                return otypeDecls;
358        }
359
360        /// Adds parameters for otype layout to a function type
361        void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
362                BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
363               
364                for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
365                        TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
366                        layoutFnType->get_parameters().push_back( new ObjectDecl( sizeofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
367                        layoutFnType->get_parameters().push_back( new ObjectDecl( alignofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
368                }
369        }
370
371        /// Builds a layout function declaration
372        FunctionDecl *buildLayoutFunctionDecl( const std::string &typeName, unsigned int functionNesting, FunctionType *layoutFnType ) {
373                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
374                // because each unit generates copies of the default routines for each aggregate.
375                FunctionDecl *layoutDecl = new FunctionDecl(
376                        "__layoutof_" + typeName, functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, layoutFnType, new CompoundStmt( noLabels ), true, false );
377                layoutDecl->fixUniqueId();
378                return layoutDecl;
379        }
380
381        /// Makes a unary operation
382        Expression *makeOp( const std::string &name, Expression *arg ) {
383                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
384                expr->get_args().push_back( arg );
385                return expr;
386        }
387
388        /// Makes a binary operation
389        Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
390                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
391                expr->get_args().push_back( lhs );
392                expr->get_args().push_back( rhs );
393                return expr;
394        }
395
396        /// Returns the dereference of a local pointer variable
397        Expression *derefVar( ObjectDecl *var ) {
398                return makeOp( "*?", new VariableExpr( var ) );
399        }
400
401        /// makes an if-statement with a single-expression if-block and no then block
402        Statement *makeCond( Expression *cond, Expression *ifPart ) {
403                return new IfStmt( noLabels, cond, new ExprStmt( noLabels, ifPart ), 0 );
404        }
405
406        /// makes a statement that assigns rhs to lhs if lhs < rhs
407        Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
408                return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
409        }
410
411        /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
412        Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
413                // check that the lhs is zeroed out to the level of rhs
414                Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), "1" ) ) ) );
415                // if not aligned, increment to alignment
416                Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
417                return makeCond( ifCond, ifExpr );
418        }
419       
420        /// adds an expression to a compound statement
421        void addExpr( CompoundStmt *stmts, Expression *expr ) {
422                stmts->get_kids().push_back( new ExprStmt( noLabels, expr ) );
423        }
424
425        /// adds a statement to a compound statement
426        void addStmt( CompoundStmt *stmts, Statement *stmt ) {
427                stmts->get_kids().push_back( stmt );
428        }
429       
430        Declaration *LayoutFunctionBuilder::mutate( StructDecl *structDecl ) {
431                // do not generate layout function for "empty" tag structs
432                if ( structDecl->get_members().empty() ) return structDecl;
433
434                // get parameters that can change layout, exiting early if none
435                std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
436                if ( otypeParams.empty() ) return structDecl;
437
438                // build layout function signature
439                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
440                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
441                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
442               
443                ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
444                layoutFnType->get_parameters().push_back( sizeParam );
445                ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
446                layoutFnType->get_parameters().push_back( alignParam );
447                ObjectDecl *offsetParam = new ObjectDecl( "__offsetof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
448                layoutFnType->get_parameters().push_back( offsetParam );
449                addOtypeParams( layoutFnType, otypeParams );
450
451                // build function decl
452                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl->get_name(), functionNesting, layoutFnType );
453
454                // calculate struct layout in function body
455
456                // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size
457                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "0" ) ) ) );
458                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
459                unsigned long n_members = 0;
460                bool firstMember = true;
461                for ( std::list< Declaration* >::const_iterator member = structDecl->get_members().begin(); member != structDecl->get_members().end(); ++member ) {
462                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
463                        assert( dwt );
464                        Type *memberType = dwt->get_type();
465
466                        if ( firstMember ) {
467                                firstMember = false;
468                        } else {
469                                // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
470                                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
471                        }
472                       
473                        // place current size in the current offset index
474                        addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from( n_members ) ) ),
475                                                                              derefVar( sizeParam ) ) );
476                        ++n_members;
477
478                        // add member size to current size
479                        addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
480                       
481                        // take max of member alignment and global alignment
482                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
483                }
484                // make sure the type is end-padded to a multiple of its alignment
485                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
486
487                addDeclarationAfter( layoutDecl );
488                return structDecl;
489        }
490       
491        Declaration *LayoutFunctionBuilder::mutate( UnionDecl *unionDecl ) {
492                // do not generate layout function for "empty" tag unions
493                if ( unionDecl->get_members().empty() ) return unionDecl;
494               
495                // get parameters that can change layout, exiting early if none
496                std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
497                if ( otypeParams.empty() ) return unionDecl;
498
499                // build layout function signature
500                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
501                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
502                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
503               
504                ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
505                layoutFnType->get_parameters().push_back( sizeParam );
506                ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
507                layoutFnType->get_parameters().push_back( alignParam );
508                addOtypeParams( layoutFnType, otypeParams );
509
510                // build function decl
511                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl->get_name(), functionNesting, layoutFnType );
512
513                // calculate union layout in function body
514                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
515                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
516                for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
517                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
518                        assert( dwt );
519                        Type *memberType = dwt->get_type();
520                       
521                        // take max member size and global size
522                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
523                       
524                        // take max of member alignment and global alignment
525                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
526                }
527                // make sure the type is end-padded to a multiple of its alignment
528                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
529
530                addDeclarationAfter( layoutDecl );
531                return unionDecl;
532        }
533       
534        ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
535
536        namespace {
537                std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
538                        std::stringstream name;
539
540                        // NOTE: this function previously used isPolyObj, which failed to produce
541                        // the correct thing in some situations. It's not clear to me why this wasn't working.
542
543                        // if the return type or a parameter type involved polymorphic types, then the adapter will need
544                        // to take those polymorphic types as pointers. Therefore, there can be two different functions
545                        // with the same mangled name, so we need to further mangle the names.
546                        for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
547                                if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
548                                        name << "P";
549                                } else {
550                                        name << "M";
551                                }
552                        }
553                        name << "_";
554                        std::list< DeclarationWithType *> &paramList = function->get_parameters();
555                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
556                                if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
557                                        name << "P";
558                                } else {
559                                        name << "M";
560                                }
561                        } // for
562                        return name.str();
563                }
564
565                std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
566                        return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
567                }
568
569                std::string makeAdapterName( const std::string &mangleName ) {
570                        return "_adapter" + mangleName;
571                }
572
573                Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {}
574
575                /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
576                TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
577                        if ( decl->get_name() == "?=?" ) {
578                                if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
579                                        if ( funType->get_parameters().size() == 2 ) {
580                                                if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
581                                                        if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
582                                                                if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
583                                                                        if ( refType->get_name() == refType2->get_name() ) {
584                                                                                return refType;
585                                                                        } // if
586                                                                } // if
587                                                        } // if
588                                                } // if
589                                        } // if
590                                } // if
591                        } // if
592                        return 0;
593                }
594               
595                /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
596                /// Only picks assignments where neither parameter is cv-qualified
597                Type *isAssignment( DeclarationWithType *decl ) {
598                        if ( decl->get_name() == "?=?" ) {
599                                if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
600                                        if ( funType->get_parameters().size() == 2 ) {
601                                                Type::Qualifiers defaultQualifiers;
602                                                Type *paramType1 = funType->get_parameters().front()->get_type();
603                                                if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
604                                                Type *paramType2 = funType->get_parameters().back()->get_type();
605                                                if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
606                                               
607                                                if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
608                                                        Type *baseType1 = pointerType->get_base();
609                                                        if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
610                                                        SymTab::Indexer dummy;
611                                                        if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
612                                                                return baseType1;
613                                                        } // if
614                                                } // if
615                                        } // if
616                                } // if
617                        } // if
618                        return 0;
619                }
620
621                void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
622                        // what if a nested function uses an assignment operator?
623                        // assignOps.clear();
624                        for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
625                                for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
626                                        std::string typeName;
627                                        if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
628                                                assignOps[ typeInst->get_name() ] = *assert;
629                                        } // if
630                                } // for
631                        } // for
632                }
633
634                DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
635                        // if this is a polymorphic assignment function, put it in the map for this scope
636                        if ( Type *assignedType = isAssignment( functionDecl ) ) {
637                                if ( ! dynamic_cast< TypeInstType* >( assignedType ) ) {
638                                        scopedAssignOps.insert( assignedType, functionDecl );
639                                }
640                        }
641
642                        if ( functionDecl->get_statements() ) {         // empty routine body ?
643                                doBeginScope();
644                                TyVarMap oldtyVars = scopeTyVars;
645                                std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
646                                DeclarationWithType *oldRetval = retval;
647                                bool oldUseRetval = useRetval;
648
649                                // process polymorphic return value
650                                retval = 0;
651                                if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
652                                        retval = functionDecl->get_functionType()->get_returnVals().front();
653
654                                        // give names to unnamed return values
655                                        if ( retval->get_name() == "" ) {
656                                                retval->set_name( "_retparm" );
657                                                retval->set_linkage( LinkageSpec::C );
658                                        } // if
659                                } // if
660
661                                FunctionType *functionType = functionDecl->get_functionType();
662                                makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
663                                findAssignOps( functionDecl->get_functionType()->get_forall() );
664
665                                std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
666                                std::list< FunctionType *> functions;
667                                for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
668                                        for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
669                                                findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
670                                        } // for
671                                } // for
672                                for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
673                                        findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
674                                } // for
675
676                                for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
677                                        std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
678                                        if ( adapters.find( mangleName ) == adapters.end() ) {
679                                                std::string adapterName = makeAdapterName( mangleName );
680                                                adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
681                                        } // if
682                                } // for
683
684                                functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
685
686                                scopeTyVars = oldtyVars;
687                                assignOps = oldassignOps;
688                                // std::cerr << "end FunctionDecl: ";
689                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
690                                //      std::cerr << i->first << " ";
691                                // }
692                                // std::cerr << "\n";
693                                retval = oldRetval;
694                                useRetval = oldUseRetval;
695                                doEndScope();
696                        } // if
697                        return functionDecl;
698                }
699
700                TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
701                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
702                        return Mutator::mutate( typeDecl );
703                }
704
705                Expression *Pass1::mutate( CommaExpr *commaExpr ) {
706                        bool oldUseRetval = useRetval;
707                        useRetval = false;
708                        commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
709                        useRetval = oldUseRetval;
710                        commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
711                        return commaExpr;
712                }
713
714                Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
715                        bool oldUseRetval = useRetval;
716                        useRetval = false;
717                        condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
718                        useRetval = oldUseRetval;
719                        condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
720                        condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
721                        return condExpr;
722
723                }
724
725                Expression *Pass1::makeOffsetArray( StructInstType *ty ) {
726                        std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
727
728                        // make a new temporary array
729                        Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
730                        std::stringstream lenGen;
731                        lenGen << baseMembers.size();
732                        ConstantExpr *lenExpr = new ConstantExpr( Constant( offsetType->clone(), lenGen.str() ) );
733                        ObjectDecl *arrayTemp = makeTemporary( new ArrayType( Type::Qualifiers(), offsetType, lenExpr, false, false ) );
734
735                        // build initializer list for temporary
736                        std::list< Initializer* > inits;
737                        for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
738                                DeclarationWithType *memberDecl;
739                                if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
740                                        memberDecl = origMember->clone();
741                                } else {
742                                        memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
743                                }
744                                inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
745                        }
746                        arrayTemp->set_init( new ListInit( inits ) );
747
748                        // return variable pointing to temporary
749                        return new VariableExpr( arrayTemp );
750                }
751
752                void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
753                        Type *polyBase = hasPolyBase( parmType, exprTyVars );
754                        if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
755                                std::string sizeName = sizeofName( polyBase );
756                                if ( seenTypes.count( sizeName ) ) return;
757
758                                arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
759                                arg++;
760                                arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
761                                arg++;
762                                if ( dynamic_cast< StructInstType* >( polyBase ) ) {
763                                        if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
764                                                arg = appExpr->get_args().insert( arg, makeOffsetArray( argBaseStructType ) );
765                                                arg++;
766                                        } else {
767                                                throw SemanticError( "Cannot pass non-struct type for generic struct" );
768                                        }
769                                }
770
771                                seenTypes.insert( sizeName );
772                        }
773                }
774
775                void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
776                        // pass size/align for type variables
777                        for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
778                                ResolvExpr::EqvClass eqvClass;
779                                assert( env );
780                                if ( tyParm->second == TypeDecl::Any ) {
781                                        Type *concrete = env->lookup( tyParm->first );
782                                        if ( concrete ) {
783                                                arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
784                                                arg++;
785                                                arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
786                                                arg++;
787                                        } else {
788                                                throw SemanticError( "unbound type variable in application ", appExpr );
789                                        } // if
790                                } // if
791                        } // for
792
793                        // add size/align for generic types to parameter list
794                        if ( appExpr->get_function()->get_results().empty() ) return;
795                        FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
796                        assert( funcType );
797
798                        std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
799                        std::list< Expression* >::const_iterator fnArg = arg;
800                        std::set< std::string > seenTypes; //< names for generic types we've seen
801
802                        // a polymorphic return type may need to be added to the argument list
803                        if ( polyRetType ) {
804                                Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
805                                passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
806                        }
807                       
808                        // add type information args for presently unseen types in parameter list
809                        for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
810                                VariableExpr *fnArgBase = getBaseVar( *fnArg );
811                                if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
812                                passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
813                        }
814                }
815
816                ObjectDecl *Pass1::makeTemporary( Type *type ) {
817                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
818                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
819                        return newObj;
820                }
821
822                Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
823                        // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
824                        // if ( useRetval ) {
825                        //      assert( retval );
826                        //      arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
827                        //      arg++;
828                        // } else {
829
830                        // Create temporary to hold return value of polymorphic function and produce that temporary as a result
831                        // using a comma expression.  Possibly change comma expression into statement expression "{}" for multiple
832                        // return values.
833                        ObjectDecl *newObj = makeTemporary( retType->clone() );
834                        Expression *paramExpr = new VariableExpr( newObj );
835
836                        // If the type of the temporary is not polymorphic, box temporary by taking its address;
837                        // otherwise the temporary is already boxed and can be used directly.
838                        if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
839                                paramExpr = new AddressExpr( paramExpr );
840                        } // if
841                        arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
842                        arg++;
843                        // Build a comma expression to call the function and emulate a normal return.
844                        CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
845                        commaExpr->set_env( appExpr->get_env() );
846                        appExpr->set_env( 0 );
847                        return commaExpr;
848                        // } // if
849                        // return appExpr;
850                }
851
852                void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
853                        for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
854                                TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
855                                assert(paramType && "Aggregate parameters should be type expressions");
856                                paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
857                        }
858                }
859
860                Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
861                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
862                                Type *concrete = env->lookup( typeInst->get_name() );
863                                if ( concrete == 0 ) {
864                                        throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
865                                } // if
866                                return concrete;
867                        } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
868                                if ( doClone ) {
869                                        structType = structType->clone();
870                                }
871                                replaceParametersWithConcrete( appExpr, structType->get_parameters() );
872                                return structType;
873                        } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
874                                if ( doClone ) {
875                                        unionType = unionType->clone();
876                                }
877                                replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
878                                return unionType;
879                        }
880                        return type;
881                }
882
883                Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
884                        assert( env );
885                        Type *concrete = replaceWithConcrete( appExpr, polyType );
886                        // add out-parameter for return value   
887                        return addRetParam( appExpr, function, concrete, arg );
888                }
889
890                Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
891                        Expression *ret = appExpr;
892                        if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
893                                ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
894                        } // if
895                        std::string mangleName = mangleAdapterName( function, tyVars );
896                        std::string adapterName = makeAdapterName( mangleName );
897
898                        // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
899                        Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
900                        appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
901                        appExpr->set_function( new NameExpr( adapterName ) );
902
903                        return ret;
904                }
905
906                void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
907                        assert( ! arg->get_results().empty() );
908                        if ( isPolyType( param, exprTyVars ) ) {
909                                if ( isPolyType( arg->get_results().front() ) ) {
910                                        // if the argument's type is polymorphic, we don't need to box again!
911                                        return;
912                                } else if ( arg->get_results().front()->get_isLvalue() ) {
913                                        // VariableExpr and MemberExpr are lvalues
914                                        arg = new AddressExpr( arg );
915                                } else {
916                                        // use type computed in unification to declare boxed variables
917                                        Type * newType = param->clone();
918                                        if ( env ) env->apply( newType );
919                                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
920                                        newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
921                                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
922                                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
923                                        assign->get_args().push_back( new VariableExpr( newObj ) );
924                                        assign->get_args().push_back( arg );
925                                        stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
926                                        arg = new AddressExpr( new VariableExpr( newObj ) );
927                                } // if
928                        } // if
929                }
930
931                /// cast parameters to polymorphic functions so that types are replaced with
932                /// void * if they are type parameters in the formal type.
933                /// this gets rid of warnings from gcc.
934                void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
935                        Type * newType = formal->clone();
936                        if ( getFunctionType( newType ) ) {
937                                newType = ScrubTyVars::scrub( newType, tyVars );
938                                actual = new CastExpr( actual, newType );
939                        } // if
940                }
941
942                void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
943                        for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
944                                assert( arg != appExpr->get_args().end() );
945                                addCast( *arg, (*param)->get_type(), exprTyVars );
946                                boxParam( (*param)->get_type(), *arg, exprTyVars );
947                        } // for
948                }
949
950                void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
951                        std::list< Expression *>::iterator cur = arg;
952                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
953                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
954                                        InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
955                                        assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
956                                        Expression *newExpr = inferParam->second.expr->clone();
957                                        addCast( newExpr, (*assert)->get_type(), tyVars );
958                                        boxParam( (*assert)->get_type(), newExpr, tyVars );
959                                        appExpr->get_args().insert( cur, newExpr );
960                                } // for
961                        } // for
962                }
963
964                void makeRetParm( FunctionType *funcType ) {
965                        DeclarationWithType *retParm = funcType->get_returnVals().front();
966
967                        // make a new parameter that is a pointer to the type of the old return value
968                        retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
969                        funcType->get_parameters().push_front( retParm );
970
971                        // we don't need the return value any more
972                        funcType->get_returnVals().clear();
973                }
974
975                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
976                        // actually make the adapter type
977                        FunctionType *adapter = adaptee->clone();
978                        if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
979                                makeRetParm( adapter );
980                        } // if
981                        adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
982                        return adapter;
983                }
984
985                Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
986                        assert( param );
987                        assert( arg );
988                        if ( isPolyType( realParam->get_type(), tyVars ) ) {
989                                if ( ! isPolyType( arg->get_type() ) ) {
990                                        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
991                                        deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
992                                        deref->get_results().push_back( arg->get_type()->clone() );
993                                        return deref;
994                                } // if
995                        } // if
996                        return new VariableExpr( param );
997                }
998
999                void addAdapterParams( ApplicationExpr *adapteeApp, std::list< DeclarationWithType *>::iterator arg, std::list< DeclarationWithType *>::iterator param, std::list< DeclarationWithType *>::iterator paramEnd, std::list< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
1000                        UniqueName paramNamer( "_p" );
1001                        for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
1002                                if ( (*param)->get_name() == "" ) {
1003                                        (*param)->set_name( paramNamer.newName() );
1004                                        (*param)->set_linkage( LinkageSpec::C );
1005                                } // if
1006                                adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
1007                        } // for
1008                }
1009
1010
1011
1012                FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
1013                        FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
1014                        adapterType = ScrubTyVars::scrub( adapterType, tyVars );
1015                        DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
1016                        adapteeDecl->set_name( "_adaptee" );
1017                        ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
1018                        Statement *bodyStmt;
1019
1020                        std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
1021                        std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
1022                        std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
1023                        for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
1024                                assert( tyArg != realType->get_forall().end() );
1025                                std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
1026                                std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
1027                                std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
1028                                for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
1029                                        assert( assertArg != (*tyArg)->get_assertions().end() );
1030                                        adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
1031                                } // for
1032                        } // for
1033
1034                        std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
1035                        std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
1036                        std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
1037                        param++;                // skip adaptee parameter
1038                        if ( realType->get_returnVals().empty() ) {
1039                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1040                                bodyStmt = new ExprStmt( noLabels, adapteeApp );
1041                        } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
1042                                if ( (*param)->get_name() == "" ) {
1043                                        (*param)->set_name( "_ret" );
1044                                        (*param)->set_linkage( LinkageSpec::C );
1045                                } // if
1046                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
1047                                UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
1048                                deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
1049                                assign->get_args().push_back( deref );
1050                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1051                                assign->get_args().push_back( adapteeApp );
1052                                bodyStmt = new ExprStmt( noLabels, assign );
1053                        } else {
1054                                // adapter for a function that returns a monomorphic value
1055                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1056                                bodyStmt = new ReturnStmt( noLabels, adapteeApp );
1057                        } // if
1058                        CompoundStmt *adapterBody = new CompoundStmt( noLabels );
1059                        adapterBody->get_kids().push_back( bodyStmt );
1060                        std::string adapterName = makeAdapterName( mangleName );
1061                        return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
1062                }
1063
1064                void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
1065                        // collect a list of function types passed as parameters or implicit parameters (assertions)
1066                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1067                        std::list< FunctionType *> functions;
1068                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
1069                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
1070                                        findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
1071                                } // for
1072                        } // for
1073                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1074                                findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
1075                        } // for
1076
1077                        // parameter function types for which an appropriate adapter has been generated.  we cannot use the types
1078                        // after applying substitutions, since two different parameter types may be unified to the same type
1079                        std::set< std::string > adaptersDone;
1080
1081                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1082                                FunctionType *originalFunction = (*funType)->clone();
1083                                FunctionType *realFunction = (*funType)->clone();
1084                                std::string mangleName = SymTab::Mangler::mangle( realFunction );
1085
1086                                // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
1087                                // pre-substitution parameter function type.
1088                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1089                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1090
1091                                        // apply substitution to type variables to figure out what the adapter's type should look like
1092                                        assert( env );
1093                                        env->apply( realFunction );
1094                                        mangleName = SymTab::Mangler::mangle( realFunction );
1095                                        mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
1096
1097                                        typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
1098                                        AdapterIter adapter = adapters.find( mangleName );
1099                                        if ( adapter == adapters.end() ) {
1100                                                // adapter has not been created yet in the current scope, so define it
1101                                                FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
1102                                                std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
1103                                                adapter = answer.first;
1104                                                stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
1105                                        } // if
1106                                        assert( adapter != adapters.end() );
1107
1108                                        // add the appropriate adapter as a parameter
1109                                        appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
1110                                } // if
1111                        } // for
1112                } // passAdapters
1113
1114                Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
1115                        NameExpr *opExpr;
1116                        if ( isIncr ) {
1117                                opExpr = new NameExpr( "?+=?" );
1118                        } else {
1119                                opExpr = new NameExpr( "?-=?" );
1120                        } // if
1121                        UntypedExpr *addAssign = new UntypedExpr( opExpr );
1122                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1123                                addAssign->get_args().push_back( address->get_arg() );
1124                        } else {
1125                                addAssign->get_args().push_back( appExpr->get_args().front() );
1126                        } // if
1127                        addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
1128                        addAssign->get_results().front() = appExpr->get_results().front()->clone();
1129                        if ( appExpr->get_env() ) {
1130                                addAssign->set_env( appExpr->get_env() );
1131                                appExpr->set_env( 0 );
1132                        } // if
1133                        appExpr->get_args().clear();
1134                        delete appExpr;
1135                        return addAssign;
1136                }
1137
1138                Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
1139                        if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
1140                                if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
1141                                        if ( varExpr->get_var()->get_name() == "?[?]" ) {
1142                                                assert( ! appExpr->get_results().empty() );
1143                                                assert( appExpr->get_args().size() == 2 );
1144                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1145                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1146                                                assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1147                                                UntypedExpr *ret = 0;
1148                                                if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1149                                                        ret = new UntypedExpr( new NameExpr( "?+?" ) );
1150                                                } // if
1151                                                if ( baseType1 ) {
1152                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1153                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1154                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1155                                                        ret->get_args().push_back( appExpr->get_args().front() );
1156                                                        ret->get_args().push_back( multiply );
1157                                                } else if ( baseType2 ) {
1158                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1159                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1160                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1161                                                        ret->get_args().push_back( multiply );
1162                                                        ret->get_args().push_back( appExpr->get_args().back() );
1163                                                } // if
1164                                                if ( baseType1 || baseType2 ) {
1165                                                        ret->get_results().push_front( appExpr->get_results().front()->clone() );
1166                                                        if ( appExpr->get_env() ) {
1167                                                                ret->set_env( appExpr->get_env() );
1168                                                                appExpr->set_env( 0 );
1169                                                        } // if
1170                                                        appExpr->get_args().clear();
1171                                                        delete appExpr;
1172                                                        return ret;
1173                                                } // if
1174                                        } else if ( varExpr->get_var()->get_name() == "*?" ) {
1175                                                assert( ! appExpr->get_results().empty() );
1176                                                assert( ! appExpr->get_args().empty() );
1177                                                if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
1178                                                        Expression *ret = appExpr->get_args().front();
1179                                                        delete ret->get_results().front();
1180                                                        ret->get_results().front() = appExpr->get_results().front()->clone();
1181                                                        if ( appExpr->get_env() ) {
1182                                                                ret->set_env( appExpr->get_env() );
1183                                                                appExpr->set_env( 0 );
1184                                                        } // if
1185                                                        appExpr->get_args().clear();
1186                                                        delete appExpr;
1187                                                        return ret;
1188                                                } // if
1189                                        } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1190                                                assert( ! appExpr->get_results().empty() );
1191                                                assert( appExpr->get_args().size() == 1 );
1192                                                if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1193                                                        Type *tempType = appExpr->get_results().front()->clone();
1194                                                        if ( env ) {
1195                                                                env->apply( tempType );
1196                                                        } // if
1197                                                        ObjectDecl *newObj = makeTemporary( tempType );
1198                                                        VariableExpr *tempExpr = new VariableExpr( newObj );
1199                                                        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1200                                                        assignExpr->get_args().push_back( tempExpr->clone() );
1201                                                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1202                                                                assignExpr->get_args().push_back( address->get_arg()->clone() );
1203                                                        } else {
1204                                                                assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1205                                                        } // if
1206                                                        CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1207                                                        return new CommaExpr( firstComma, tempExpr );
1208                                                } // if
1209                                        } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1210                                                assert( ! appExpr->get_results().empty() );
1211                                                assert( appExpr->get_args().size() == 1 );
1212                                                if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1213                                                        return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1214                                                } // if
1215                                        } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1216                                                assert( ! appExpr->get_results().empty() );
1217                                                assert( appExpr->get_args().size() == 2 );
1218                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1219                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1220                                                if ( baseType1 && baseType2 ) {
1221                                                        UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1222                                                        divide->get_args().push_back( appExpr );
1223                                                        divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1224                                                        divide->get_results().push_front( appExpr->get_results().front()->clone() );
1225                                                        if ( appExpr->get_env() ) {
1226                                                                divide->set_env( appExpr->get_env() );
1227                                                                appExpr->set_env( 0 );
1228                                                        } // if
1229                                                        return divide;
1230                                                } else if ( baseType1 ) {
1231                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1232                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1233                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1234                                                        appExpr->get_args().back() = multiply;
1235                                                } else if ( baseType2 ) {
1236                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1237                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1238                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1239                                                        appExpr->get_args().front() = multiply;
1240                                                } // if
1241                                        } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1242                                                assert( ! appExpr->get_results().empty() );
1243                                                assert( appExpr->get_args().size() == 2 );
1244                                                Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
1245                                                if ( baseType ) {
1246                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1247                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1248                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
1249                                                        appExpr->get_args().back() = multiply;
1250                                                } // if
1251                                        } // if
1252                                        return appExpr;
1253                                } // if
1254                        } // if
1255                        return 0;
1256                }
1257
1258                Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
1259                        // std::cerr << "mutate appExpr: ";
1260                        // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1261                        //      std::cerr << i->first << " ";
1262                        // }
1263                        // std::cerr << "\n";
1264                        bool oldUseRetval = useRetval;
1265                        useRetval = false;
1266                        appExpr->get_function()->acceptMutator( *this );
1267                        mutateAll( appExpr->get_args(), *this );
1268                        useRetval = oldUseRetval;
1269
1270                        assert( ! appExpr->get_function()->get_results().empty() );
1271                        PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1272                        assert( pointer );
1273                        FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1274                        assert( function );
1275
1276                        if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1277                                return newExpr;
1278                        } // if
1279
1280                        Expression *ret = appExpr;
1281
1282                        std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1283                        std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1284
1285                        TyVarMap exprTyVars;
1286                        makeTyVarMap( function, exprTyVars );
1287                        ReferenceToType *polyRetType = isPolyRet( function );
1288
1289                        if ( polyRetType ) {
1290                                ret = addPolyRetParam( appExpr, function, polyRetType, arg );
1291                        } else if ( needsAdapter( function, scopeTyVars ) ) {
1292                                // std::cerr << "needs adapter: ";
1293                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1294                                //      std::cerr << i->first << " ";
1295                                // }
1296                                // std::cerr << "\n";
1297                                // change the application so it calls the adapter rather than the passed function
1298                                ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1299                        } // if
1300                        arg = appExpr->get_args().begin();
1301
1302                        passTypeVars( appExpr, polyRetType, arg, exprTyVars );
1303                        addInferredParams( appExpr, function, arg, exprTyVars );
1304
1305                        arg = paramBegin;
1306
1307                        boxParams( appExpr, function, arg, exprTyVars );
1308
1309                        passAdapters( appExpr, function, exprTyVars );
1310
1311                        return ret;
1312                }
1313
1314                Expression *Pass1::mutate( UntypedExpr *expr ) {
1315                        if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1316                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1317                                        if ( name->get_name() == "*?" ) {
1318                                                Expression *ret = expr->get_args().front();
1319                                                expr->get_args().clear();
1320                                                delete expr;
1321                                                return ret->acceptMutator( *this );
1322                                        } // if
1323                                } // if
1324                        } // if
1325                        return PolyMutator::mutate( expr );
1326                }
1327
1328                Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1329                        assert( ! addrExpr->get_arg()->get_results().empty() );
1330
1331                        bool needs = false;
1332                        if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1333                                if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1334                                        if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1335                                                if ( name->get_name() == "*?" ) {
1336                                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1337                                                                assert( ! appExpr->get_function()->get_results().empty() );
1338                                                                PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1339                                                                assert( pointer );
1340                                                                FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1341                                                                assert( function );
1342                                                                needs = needsAdapter( function, scopeTyVars );
1343                                                        } // if
1344                                                } // if
1345                                        } // if
1346                                } // if
1347                        } // if
1348                        addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1349                        if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
1350                                Expression *ret = addrExpr->get_arg();
1351                                delete ret->get_results().front();
1352                                ret->get_results().front() = addrExpr->get_results().front()->clone();
1353                                addrExpr->set_arg( 0 );
1354                                delete addrExpr;
1355                                return ret;
1356                        } else {
1357                                return addrExpr;
1358                        } // if
1359                }
1360
1361                /// Wraps a function declaration in a new pointer-to-function variable expression
1362                VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1363                        // line below cloned from FixFunction.cc
1364                        ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1365                                                                  new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1366                        functionObj->set_mangleName( functionDecl->get_mangleName() );
1367                        return new VariableExpr( functionObj );
1368                }
1369               
1370                Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1371                        if ( retval && returnStmt->get_expr() ) {
1372                                assert( ! returnStmt->get_expr()->get_results().empty() );
1373                                // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1374                                // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1375                                // by this point, a cast expr on a polymorphic return value is redundant
1376                                while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1377                                        returnStmt->set_expr( castExpr->get_arg() );
1378                                        returnStmt->get_expr()->set_env( castExpr->get_env() );
1379                                        castExpr->set_env( 0 );
1380                                        castExpr->set_arg( 0 );
1381                                        delete castExpr;
1382                                } //while
1383
1384                                // find assignment operator for (polymorphic) return type
1385                                ApplicationExpr *assignExpr = 0;
1386                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1387                                        // find assignment operator for type variable
1388                                        std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1389                                        if ( assignIter == assignOps.end() ) {
1390                                                throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1391                                        } // if
1392                                        assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1393                                } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1394                                        // find assignment operator for generic type
1395                                        DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1396                                        if ( ! functionDecl ) {
1397                                                throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1398                                        }
1399
1400                                        // wrap it up in an application expression
1401                                        assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1402                                        assignExpr->set_env( env->clone() );
1403
1404                                        // find each of its needed secondary assignment operators
1405                                        std::list< Expression* > &tyParams = refType->get_parameters();
1406                                        std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1407                                        std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1408                                        std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1409                                        for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1410                                                if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1411
1412                                                std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1413                                                assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1414                                                DeclarationWithType *actualDecl = asserts.front();
1415                                                TypeInstType *actualType = isTypeInstAssignment( actualDecl );
1416                                                assert( actualType && "First assertion of type with assertions should be assignment operator" );
1417                                                TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1418                                                assert( formalTypeExpr && "type parameters must be type expressions" );
1419                                                Type *formalType = formalTypeExpr->get_type();
1420                                                assignExpr->get_env()->add( actualType->get_name(), formalType );
1421                                               
1422                                                DeclarationWithType *assertAssign = 0;
1423                                                if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1424                                                        std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1425                                                        if ( assertAssignIt == assignOps.end() ) {
1426                                                                throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1427                                                        }
1428                                                        assertAssign = assertAssignIt->second;
1429                                                } else {
1430                                                        assertAssign = scopedAssignOps.find( formalType );
1431                                                        if ( ! assertAssign ) {
1432                                                                throw SemanticError( "No assignment operation found for ", formalType );
1433                                                        }
1434                                                }
1435                                               
1436
1437                                                assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1438                                                        = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1439                                        }
1440                                }
1441                                assert( assignExpr );
1442
1443                                // replace return statement with appropriate assignment to out parameter
1444                                Expression *retParm = new NameExpr( retval->get_name() );
1445                                retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1446                                assignExpr->get_args().push_back( retParm );
1447                                assignExpr->get_args().push_back( returnStmt->get_expr() );
1448                                stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1449                                // } else {
1450                                //      useRetval = true;
1451                                //      stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1452                                //      useRetval = false;
1453                                // } // if
1454                                returnStmt->set_expr( 0 );
1455                        } else {
1456                                returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1457                        } // if
1458                        return returnStmt;
1459                }
1460
1461                Type * Pass1::mutate( PointerType *pointerType ) {
1462                        TyVarMap oldtyVars = scopeTyVars;
1463                        makeTyVarMap( pointerType, scopeTyVars );
1464
1465                        Type *ret = Mutator::mutate( pointerType );
1466
1467                        scopeTyVars = oldtyVars;
1468                        return ret;
1469                }
1470
1471                Type * Pass1::mutate( FunctionType *functionType ) {
1472                        TyVarMap oldtyVars = scopeTyVars;
1473                        makeTyVarMap( functionType, scopeTyVars );
1474
1475                        Type *ret = Mutator::mutate( functionType );
1476
1477                        scopeTyVars = oldtyVars;
1478                        return ret;
1479                }
1480
1481                void Pass1::doBeginScope() {
1482                        adapters.beginScope();
1483                        scopedAssignOps.beginScope();
1484                }
1485
1486                void Pass1::doEndScope() {
1487                        adapters.endScope();
1488                        scopedAssignOps.endScope();
1489                }
1490
1491////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1492
1493                void Pass2::addAdapters( FunctionType *functionType ) {
1494                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1495                        std::list< FunctionType *> functions;
1496                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1497                                Type *orig = (*arg)->get_type();
1498                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1499                                (*arg)->set_type( orig );
1500                        }
1501                        std::set< std::string > adaptersDone;
1502                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1503                                std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1504                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1505                                        std::string adapterName = makeAdapterName( mangleName );
1506                                        paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1507                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1508                                }
1509                        }
1510//  deleteAll( functions );
1511                }
1512
1513                template< typename DeclClass >
1514                DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1515                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1516
1517                        return ret;
1518                }
1519
1520                DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1521                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1522                }
1523
1524                ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1525                        return handleDecl( objectDecl, objectDecl->get_type() );
1526                }
1527
1528                TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1529                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1530                        if ( typeDecl->get_base() ) {
1531                                return handleDecl( typeDecl, typeDecl->get_base() );
1532                        } else {
1533                                return Mutator::mutate( typeDecl );
1534                        }
1535                }
1536
1537                TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1538                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1539                }
1540
1541                Type * Pass2::mutate( PointerType *pointerType ) {
1542                        TyVarMap oldtyVars = scopeTyVars;
1543                        makeTyVarMap( pointerType, scopeTyVars );
1544
1545                        Type *ret = Mutator::mutate( pointerType );
1546
1547                        scopeTyVars = oldtyVars;
1548                        return ret;
1549                }
1550
1551                Type *Pass2::mutate( FunctionType *funcType ) {
1552                        TyVarMap oldtyVars = scopeTyVars;
1553                        makeTyVarMap( funcType, scopeTyVars );
1554
1555                        // move polymorphic return type to parameter list
1556                        if ( isPolyRet( funcType ) ) {
1557                                DeclarationWithType *ret = funcType->get_returnVals().front();
1558                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1559                                funcType->get_parameters().push_front( ret );
1560                                funcType->get_returnVals().pop_front();
1561                        }
1562
1563                        // add size/align and assertions for type parameters to parameter list
1564                        std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1565                        std::list< DeclarationWithType *> inferredParams;
1566                        ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1567                        ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1568                                           new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1569                        for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1570                                ObjectDecl *sizeParm, *alignParm;
1571                                // add all size and alignment parameters to parameter list
1572                                if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1573                                        TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1574
1575                                        sizeParm = newObj.clone();
1576                                        sizeParm->set_name( sizeofName( &parmType ) );
1577                                        last = funcType->get_parameters().insert( last, sizeParm );
1578                                        ++last;
1579
1580                                        alignParm = newObj.clone();
1581                                        alignParm->set_name( alignofName( &parmType ) );
1582                                        last = funcType->get_parameters().insert( last, alignParm );
1583                                        ++last;
1584                                }
1585                                // move all assertions into parameter list
1586                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1587//      *assert = (*assert)->acceptMutator( *this );
1588                                        inferredParams.push_back( *assert );
1589                                }
1590                                (*tyParm)->get_assertions().clear();
1591                        }
1592
1593                        // add size/align for generic parameter types to parameter list
1594                        std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1595                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1596                                Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1597                                if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1598                                        std::string sizeName = sizeofName( polyBase );
1599                                        if ( seenTypes.count( sizeName ) ) continue;
1600
1601                                        ObjectDecl *sizeParm, *alignParm, *offsetParm;
1602                                        sizeParm = newObj.clone();
1603                                        sizeParm->set_name( sizeName );
1604                                        last = funcType->get_parameters().insert( last, sizeParm );
1605                                        ++last;
1606
1607                                        alignParm = newObj.clone();
1608                                        alignParm->set_name( alignofName( polyBase ) );
1609                                        last = funcType->get_parameters().insert( last, alignParm );
1610                                        ++last;
1611
1612                                        if ( dynamic_cast< StructInstType* >( polyBase ) ) {
1613                                                offsetParm = newPtr.clone();
1614                                                offsetParm->set_name( offsetofName( polyBase ) );
1615                                                last = funcType->get_parameters().insert( last, offsetParm );
1616                                                ++last;
1617                                        }
1618
1619                                        seenTypes.insert( sizeName );
1620                                }
1621                        }
1622
1623                        // splice assertion parameters into parameter list
1624                        funcType->get_parameters().splice( last, inferredParams );
1625                        addAdapters( funcType );
1626                        mutateAll( funcType->get_returnVals(), *this );
1627                        mutateAll( funcType->get_parameters(), *this );
1628
1629                        scopeTyVars = oldtyVars;
1630                        return funcType;
1631                }
1632
1633//////////////////////////////////////// GenericInstantiator //////////////////////////////////////////////////
1634
1635                /// Makes substitutions of params into baseParams; returns true if all parameters substituted for a concrete type
1636                bool makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
1637                        bool allConcrete = true;  // will finish the substitution list even if they're not all concrete
1638
1639                        // substitute concrete types for given parameters, and incomplete types for placeholders
1640                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1641                        std::list< Expression* >::const_iterator param = params.begin();
1642                        for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
1643        //                      switch ( (*baseParam)->get_kind() ) {
1644        //                      case TypeDecl::Any: {   // any type is a valid substitution here; complete types can be used to instantiate generics
1645                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
1646                                        assert(paramType && "Aggregate parameters should be type expressions");
1647                                        out.push_back( paramType->clone() );
1648                                        // check that the substituted type isn't a type variable itself
1649                                        if ( dynamic_cast< TypeInstType* >( paramType->get_type() ) ) {
1650                                                allConcrete = false;
1651                                        }
1652        //                              break;
1653        //                      }
1654        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1655        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1656        //                              break;
1657        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1658        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1659        //                              break;
1660        //                      }
1661                        }
1662
1663                        // if any parameters left over, not done
1664                        if ( baseParam != baseParams.end() ) return false;
1665        //              // if not enough parameters given, substitute remaining incomplete types for placeholders
1666        //              for ( ; baseParam != baseParams.end(); ++baseParam ) {
1667        //                      switch ( (*baseParam)->get_kind() ) {
1668        //                      case TypeDecl::Any:    // no more substitutions here, fail early
1669        //                              return false;
1670        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1671        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1672        //                              break;
1673        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1674        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1675        //                              break;
1676        //                      }
1677        //              }
1678
1679                        return allConcrete;
1680                }
1681
1682                /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
1683                void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
1684                                                                std::list< Declaration* >& out ) {
1685                        // substitute types into new members
1686                        TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
1687                        for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
1688                                Declaration *newMember = (*member)->clone();
1689                                subs.apply(newMember);
1690                                out.push_back( newMember );
1691                        }
1692                }
1693
1694                Type* GenericInstantiator::mutate( StructInstType *inst ) {
1695                        // mutate subtypes
1696                        Type *mutated = Mutator::mutate( inst );
1697                        inst = dynamic_cast< StructInstType* >( mutated );
1698                        if ( ! inst ) return mutated;
1699
1700                        // exit early if no need for further mutation
1701                        if ( inst->get_parameters().empty() ) return inst;
1702                        assert( inst->get_baseParameters() && "Base struct has parameters" );
1703
1704                        // check if type can be concretely instantiated; put substitutions into typeSubs
1705                        std::list< TypeExpr* > typeSubs;
1706                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1707                                deleteAll( typeSubs );
1708                                return inst;
1709                        }
1710
1711                        // make concrete instantiation of generic type
1712                        StructDecl *concDecl = lookup( inst, typeSubs );
1713                        if ( ! concDecl ) {
1714                                // set concDecl to new type, insert type declaration into statements to add
1715                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
1716                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs,        concDecl->get_members() );
1717                                DeclMutator::addDeclaration( concDecl );
1718                                insert( inst, typeSubs, concDecl );
1719                        }
1720                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
1721                        newInst->set_baseStruct( concDecl );
1722
1723                        deleteAll( typeSubs );
1724                        delete inst;
1725                        return newInst;
1726                }
1727
1728                Type* GenericInstantiator::mutate( UnionInstType *inst ) {
1729                        // mutate subtypes
1730                        Type *mutated = Mutator::mutate( inst );
1731                        inst = dynamic_cast< UnionInstType* >( mutated );
1732                        if ( ! inst ) return mutated;
1733
1734                        // exit early if no need for further mutation
1735                        if ( inst->get_parameters().empty() ) return inst;
1736                        assert( inst->get_baseParameters() && "Base union has parameters" );
1737
1738                        // check if type can be concretely instantiated; put substitutions into typeSubs
1739                        std::list< TypeExpr* > typeSubs;
1740                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1741                                deleteAll( typeSubs );
1742                                return inst;
1743                        }
1744
1745                        // make concrete instantiation of generic type
1746                        UnionDecl *concDecl = lookup( inst, typeSubs );
1747                        if ( ! concDecl ) {
1748                                // set concDecl to new type, insert type declaration into statements to add
1749                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
1750                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
1751                                DeclMutator::addDeclaration( concDecl );
1752                                insert( inst, typeSubs, concDecl );
1753                        }
1754                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
1755                        newInst->set_baseUnion( concDecl );
1756
1757                        deleteAll( typeSubs );
1758                        delete inst;
1759                        return newInst;
1760                }
1761
1762        //      /// Gets the base struct or union declaration for a member expression; NULL if not applicable
1763        //      AggregateDecl* getMemberBaseDecl( MemberExpr *memberExpr ) {
1764        //              // get variable for member aggregate
1765        //              VariableExpr *varExpr = dynamic_cast< VariableExpr* >( memberExpr->get_aggregate() );
1766        //              if ( ! varExpr ) return NULL;
1767        //
1768        //              // get object for variable
1769        //              ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1770        //              if ( ! objectDecl ) return NULL;
1771        //
1772        //              // get base declaration from object type
1773        //              Type *objectType = objectDecl->get_type();
1774        //              StructInstType *structType = dynamic_cast< StructInstType* >( objectType );
1775        //              if ( structType ) return structType->get_baseStruct();
1776        //              UnionInstType *unionType = dynamic_cast< UnionInstType* >( objectType );
1777        //              if ( unionType ) return unionType->get_baseUnion();
1778        //
1779        //              return NULL;
1780        //      }
1781        //
1782        //      /// Finds the declaration with the given name, returning decls.end() if none such
1783        //      std::list< Declaration* >::const_iterator findDeclNamed( const std::list< Declaration* > &decls, const std::string &name ) {
1784        //              for( std::list< Declaration* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
1785        //                      if ( (*decl)->get_name() == name ) return decl;
1786        //              }
1787        //              return decls.end();
1788        //      }
1789        //
1790        //      Expression* Instantiate::mutate( MemberExpr *memberExpr ) {
1791        //              // mutate, exiting early if no longer MemberExpr
1792        //              Expression *expr = Mutator::mutate( memberExpr );
1793        //              memberExpr = dynamic_cast< MemberExpr* >( expr );
1794        //              if ( ! memberExpr ) return expr;
1795        //
1796        //              // get declaration of member and base declaration of member, exiting early if not found
1797        //              AggregateDecl *memberBase = getMemberBaseDecl( memberExpr );
1798        //              if ( ! memberBase ) return memberExpr;
1799        //              DeclarationWithType *memberDecl = memberExpr->get_member();
1800        //              std::list< Declaration* >::const_iterator baseIt = findDeclNamed( memberBase->get_members(), memberDecl->get_name() );
1801        //              if ( baseIt == memberBase->get_members().end() ) return memberExpr;
1802        //              DeclarationWithType *baseDecl = dynamic_cast< DeclarationWithType* >( *baseIt );
1803        //              if ( ! baseDecl ) return memberExpr;
1804        //
1805        //              // check if stated type of the member is not the type of the member's declaration; if so, need a cast
1806        //              // this *SHOULD* be safe, I don't think anything but the void-replacements I put in for dtypes would make it past the typechecker
1807        //              SymTab::Indexer dummy;
1808        //              if ( ResolvExpr::typesCompatible( memberDecl->get_type(), baseDecl->get_type(), dummy ) ) return memberExpr;
1809        //              else return new CastExpr( memberExpr, memberDecl->get_type() );
1810        //      }
1811
1812                void GenericInstantiator::doBeginScope() {
1813                        DeclMutator::doBeginScope();
1814                        instantiations.beginScope();
1815                }
1816
1817                void GenericInstantiator::doEndScope() {
1818                        DeclMutator::doEndScope();
1819                        instantiations.endScope();
1820                }
1821
1822////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
1823
1824                template< typename DeclClass >
1825                DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
1826                        TyVarMap oldtyVars = scopeTyVars;
1827                        makeTyVarMap( type, scopeTyVars );
1828
1829                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1830
1831                        scopeTyVars = oldtyVars;
1832                        return ret;
1833                }
1834
1835                ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
1836                        return handleDecl( objectDecl, objectDecl->get_type() );
1837                }
1838
1839                DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
1840                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1841                }
1842
1843                TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
1844                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1845                }
1846
1847                TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
1848                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1849                        return Mutator::mutate( typeDecl );
1850                }
1851
1852                Type * MemberExprFixer::mutate( PointerType *pointerType ) {
1853                        TyVarMap oldtyVars = scopeTyVars;
1854                        makeTyVarMap( pointerType, scopeTyVars );
1855
1856                        Type *ret = Mutator::mutate( pointerType );
1857
1858                        scopeTyVars = oldtyVars;
1859                        return ret;
1860                }
1861
1862                Type * MemberExprFixer::mutate( FunctionType *functionType ) {
1863                        TyVarMap oldtyVars = scopeTyVars;
1864                        makeTyVarMap( functionType, scopeTyVars );
1865
1866                        Type *ret = Mutator::mutate( functionType );
1867
1868                        scopeTyVars = oldtyVars;
1869                        return ret;
1870                }
1871
1872                Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
1873                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1874                                if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
1875                                        // change initialization of a polymorphic value object
1876                                        // to allocate storage with alloca
1877                                        Type *declType = objectDecl->get_type();
1878                                        UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
1879                                        alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
1880
1881                                        delete objectDecl->get_init();
1882
1883                                        std::list<Expression*> designators;
1884                                        objectDecl->set_init( new SingleInit( alloc, designators ) );
1885                                }
1886                        }
1887                        return Mutator::mutate( declStmt );
1888                }
1889
1890                /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1891                long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1892                        long i = 0;
1893                        for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1894                                if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1895
1896                                if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1897                                        if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1898                                             || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1899                                        else continue;
1900                                } else return i;
1901                        }
1902                        return -1;
1903                }
1904
1905                /// Returns an index expression into the offset array for a type
1906                Expression *makeOffsetIndex( Type *objectType, long i ) {
1907                        std::stringstream offset_namer;
1908                        offset_namer << i;
1909                        ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1910                        UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1911                        fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
1912                        fieldOffset->get_args().push_back( fieldIndex );
1913                        return fieldOffset;
1914                }
1915
1916                /// Returns an expression dereferenced n times
1917                Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1918                        for ( int i = 1; i < n; ++i ) {
1919                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1920                                derefExpr->get_args().push_back( derefdVar );
1921                                derefdVar = derefExpr;
1922                        }
1923                        return derefdVar;
1924                }
1925               
1926                Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
1927                        // mutate, exiting early if no longer MemberExpr
1928                        Expression *expr = Mutator::mutate( memberExpr );
1929                        memberExpr = dynamic_cast< MemberExpr* >( expr );
1930                        if ( ! memberExpr ) return expr;
1931
1932                        // get declaration for base struct, exiting early if not found
1933                        int varDepth;
1934                        VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
1935                        if ( ! varExpr ) return memberExpr;
1936                        ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1937                        if ( ! objectDecl ) return memberExpr;
1938
1939                        // only mutate member expressions for polymorphic types
1940                        int tyDepth;
1941                        Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
1942                        if ( ! objectType ) return memberExpr;
1943
1944                        Expression *newMemberExpr = 0;
1945                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1946                                // look up offset index
1947                                long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1948                                if ( i == -1 ) return memberExpr;
1949
1950                                // replace member expression with pointer to base plus offset
1951                                UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1952                                fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1953                                fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1954                                newMemberExpr = fieldLoc;
1955                        } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1956                                // union members are all at offset zero, so build appropriately-dereferenced variable
1957                                newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
1958                        } else return memberExpr;
1959                        assert( newMemberExpr );
1960
1961                        Type *memberType = memberExpr->get_member()->get_type();
1962                        if ( ! isPolyType( memberType, scopeTyVars ) ) {
1963                                // Not all members of a polymorphic type are themselves of polymorphic type; in this case the member expression should be wrapped and dereferenced to form an lvalue
1964                                CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1965                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1966                                derefExpr->get_args().push_back( ptrCastExpr );
1967                                newMemberExpr = derefExpr;
1968                        }
1969
1970                        delete memberExpr;
1971                        return newMemberExpr;
1972                }
1973
1974                Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
1975                        // mutate, exiting early if no longer OffsetofExpr
1976                        Expression *expr = Mutator::mutate( offsetofExpr );
1977                        offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1978                        if ( ! offsetofExpr ) return expr;
1979
1980                        // only mutate expressions for polymorphic structs/unions
1981                        Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
1982                        if ( ! ty ) return offsetofExpr;
1983
1984                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1985                                // replace offsetof expression by index into offset array
1986                                long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1987                                if ( i == -1 ) return offsetofExpr;
1988
1989                                Expression *offsetInd = makeOffsetIndex( ty, i );
1990                                delete offsetofExpr;
1991                                return offsetInd;
1992                        } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
1993                                // all union members are at offset zero
1994                                delete offsetofExpr;
1995                                return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
1996                        } else return offsetofExpr;
1997                }
1998
1999////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
2000
2001                template< typename DeclClass >
2002                DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
2003                        TyVarMap oldtyVars = scopeTyVars;
2004                        makeTyVarMap( type, scopeTyVars );
2005
2006                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2007                        ScrubTyVars::scrub( decl, scopeTyVars );
2008
2009                        scopeTyVars = oldtyVars;
2010                        return ret;
2011                }
2012
2013                ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
2014                        return handleDecl( objectDecl, objectDecl->get_type() );
2015                }
2016
2017                DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
2018                        return handleDecl( functionDecl, functionDecl->get_functionType() );
2019                }
2020
2021                TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
2022                        return handleDecl( typedefDecl, typedefDecl->get_base() );
2023                }
2024
2025                TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
2026//   Initializer *init = 0;
2027//   std::list< Expression *> designators;
2028//   scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2029//   if ( typeDecl->get_base() ) {
2030//     init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
2031//   }
2032//   return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
2033
2034                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2035                        return Mutator::mutate( typeDecl );
2036                }
2037
2038                Type * Pass3::mutate( PointerType *pointerType ) {
2039                        TyVarMap oldtyVars = scopeTyVars;
2040                        makeTyVarMap( pointerType, scopeTyVars );
2041
2042                        Type *ret = Mutator::mutate( pointerType );
2043
2044                        scopeTyVars = oldtyVars;
2045                        return ret;
2046                }
2047
2048                Type * Pass3::mutate( FunctionType *functionType ) {
2049                        TyVarMap oldtyVars = scopeTyVars;
2050                        makeTyVarMap( functionType, scopeTyVars );
2051
2052                        Type *ret = Mutator::mutate( functionType );
2053
2054                        scopeTyVars = oldtyVars;
2055                        return ret;
2056                }
2057        } // anonymous namespace
2058} // namespace GenPoly
2059
2060// Local Variables: //
2061// tab-width: 4 //
2062// mode: c++ //
2063// compile-command: "make install" //
2064// End: //
Note: See TracBrowser for help on using the repository browser.