source: src/GenPoly/Box.cc @ 2f42718

no_list
Last change on this file since 2f42718 was 2f42718, checked in by tdelisle <tdelisle@…>, 5 years ago

Parameters and return value of functions are now vectors (and some related clean-up)

  • Property mode set to 100644
File size: 86.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// 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 : Wed Jun 21 15:49:59 2017
13// Update Count     : 346
14//
15
16#include <algorithm>                     // for mismatch
17#include <cassert>                       // for assert, strict_dynamic_cast
18#include <iostream>                      // for operator<<, stringstream
19#include <list>                          // for list, list<>::iterator, _Lis...
20#include <map>                           // for _Rb_tree_const_iterator, map
21#include <memory>                        // for auto_ptr
22#include <set>                           // for set
23#include <string>                        // for string, allocator, basic_string
24#include <utility>                       // for pair
25
26#include "Box.h"
27
28#include "CodeGen/OperatorTable.h"
29#include "Common/PassVisitor.h"          // for PassVisitor
30#include "Common/ScopedMap.h"            // for ScopedMap, ScopedMap<>::iter...
31#include "Common/SemanticError.h"        // for SemanticError
32#include "Common/UniqueName.h"           // for UniqueName
33#include "Common/utility.h"              // for toString
34#include "FindFunction.h"                // for findFunction, findAndReplace...
35#include "GenPoly/ErasableScopedMap.h"   // for ErasableScopedMap<>::const_i...
36#include "GenPoly/GenPoly.h"             // for TyVarMap, isPolyType, mangle...
37#include "InitTweak/InitTweak.h"         // for getFunctionName, isAssignment
38#include "Lvalue.h"                      // for generalizedLvalue
39#include "Parser/LinkageSpec.h"          // for C, Spec, Cforall, Intrinsic
40#include "ResolvExpr/TypeEnvironment.h"  // for EqvClass
41#include "ResolvExpr/typeops.h"          // for typesCompatible
42#include "ScopedSet.h"                   // for ScopedSet, ScopedSet<>::iter...
43#include "ScrubTyVars.h"                 // for ScrubTyVars
44#include "SymTab/Indexer.h"              // for Indexer
45#include "SymTab/Mangler.h"              // for Mangler
46#include "SynTree/Attribute.h"           // for Attribute
47#include "SynTree/Constant.h"            // for Constant
48#include "SynTree/Declaration.h"         // for DeclarationWithType, ObjectDecl
49#include "SynTree/Expression.h"          // for ApplicationExpr, UntypedExpr
50#include "SynTree/Initializer.h"         // for SingleInit, Initializer, Lis...
51#include "SynTree/Label.h"               // for Label
52#include "SynTree/Mutator.h"             // for maybeMutate, Mutator, mutateAll
53#include "SynTree/Statement.h"           // for ExprStmt, DeclStmt, ReturnStmt
54#include "SynTree/SynTree.h"             // for UniqueId
55#include "SynTree/Type.h"                // for Type, FunctionType, PointerType
56#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution, operator<<
57
58namespace GenPoly {
59        namespace {
60                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
61
62                class BoxPass {
63                protected:
64                        BoxPass() : scopeTyVars( TypeDecl::Data{} ) {}
65                        TyVarMap scopeTyVars;
66                };
67
68                /// Adds layout-generation functions to polymorphic types
69                class LayoutFunctionBuilder final : public WithDeclsToAdd, public WithVisitorRef<LayoutFunctionBuilder>, public WithShortCircuiting {
70                        unsigned int functionNesting = 0;  // current level of nested functions
71                public:
72                        void previsit( FunctionDecl *functionDecl );
73                        void previsit( StructDecl *structDecl );
74                        void previsit( UnionDecl *unionDecl );
75                };
76
77                /// 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
78                class Pass1 final : public BoxPass, public WithTypeSubstitution, public WithStmtsToAdd, public WithGuards, public WithVisitorRef<Pass1>, public WithShortCircuiting {
79                  public:
80                        Pass1();
81
82                        void premutate( FunctionDecl * functionDecl );
83                        void premutate( TypeDecl * typeDecl );
84                        void premutate( CommaExpr * commaExpr );
85                        Expression * postmutate( ApplicationExpr * appExpr );
86                        Expression * postmutate( UntypedExpr *expr );
87                        void premutate( AddressExpr * addrExpr );
88                        Expression * postmutate( AddressExpr * addrExpr );
89                        void premutate( ReturnStmt * returnStmt );
90                        void premutate( PointerType * pointerType );
91                        void premutate( FunctionType * functionType );
92
93                        void beginScope();
94                        void endScope();
95                  private:
96                        /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
97                        void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
98                        /// passes extra type parameters into a polymorphic function application
99                        void passTypeVars( ApplicationExpr *appExpr, Type *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
100                        /// wraps a function application with a new temporary for the out-parameter return value
101                        Expression *addRetParam( ApplicationExpr *appExpr, Type *retType, std::list< Expression *>::iterator &arg );
102                        /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
103                        void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
104                        /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
105                        /// If `doClone` is set to false, will not clone interior types
106                        Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
107                        /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
108                        Expression *addDynRetParam( ApplicationExpr *appExpr, Type *polyType, std::list< Expression *>::iterator &arg );
109                        Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
110                        void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
111                        void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
112                        void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
113                        /// Stores assignment operators from assertion list in local map of assignment operations
114                        void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
115                        FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
116                        /// Replaces intrinsic operator functions with their arithmetic desugaring
117                        Expression *handleIntrinsics( ApplicationExpr *appExpr );
118                        /// Inserts a new temporary variable into the current scope with an auto-generated name
119                        ObjectDecl *makeTemporary( Type *type );
120
121                        ScopedMap< std::string, DeclarationWithType* > adapters;     ///< Set of adapter functions in the current scope
122
123                        std::map< ApplicationExpr *, Expression * > retVals;
124
125                        DeclarationWithType *retval;
126                        UniqueName tempNamer;
127                };
128
129                /// * Moves polymorphic returns in function types to pointer-type parameters
130                /// * adds type size and assertion parameters to parameter lists
131                struct Pass2 final : public BoxPass, public WithGuards {
132                        void handleAggDecl();
133
134                        DeclarationWithType * postmutate( FunctionDecl *functionDecl );
135                        void premutate( StructDecl *structDecl );
136                        void premutate( UnionDecl *unionDecl );
137                        void premutate( TraitDecl *unionDecl );
138                        void premutate( TypeDecl *typeDecl );
139                        void premutate( PointerType *pointerType );
140                        void premutate( FunctionType *funcType );
141
142                  private:
143                        void addAdapters( FunctionType *functionType );
144
145                        std::map< UniqueId, std::string > adapterName;
146                };
147
148                /// Replaces member and size/align/offsetof expressions on polymorphic generic types with calculated expressions.
149                /// * Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference
150                /// * Calculates polymorphic offsetof expressions from offset array
151                /// * Inserts dynamic calculation of polymorphic type layouts where needed
152                class PolyGenericCalculator final : public BoxPass, public WithGuards, public WithVisitorRef<PolyGenericCalculator>, public WithStmtsToAdd, public WithDeclsToAdd, public WithTypeSubstitution {
153                public:
154                        PolyGenericCalculator();
155
156                        void premutate( ObjectDecl *objectDecl );
157                        void premutate( FunctionDecl *functionDecl );
158                        void premutate( TypedefDecl *objectDecl );
159                        void premutate( TypeDecl *objectDecl );
160                        Declaration * postmutate( TypeDecl *TraitDecl );
161                        void premutate( PointerType *pointerType );
162                        void premutate( FunctionType *funcType );
163                        void premutate( DeclStmt *declStmt );
164                        Expression *postmutate( MemberExpr *memberExpr );
165                        void premutate( AddressExpr *addrExpr );
166                        Expression *postmutate( AddressExpr *addrExpr );
167                        Expression *postmutate( SizeofExpr *sizeofExpr );
168                        Expression *postmutate( AlignofExpr *alignofExpr );
169                        Expression *postmutate( OffsetofExpr *offsetofExpr );
170                        Expression *postmutate( OffsetPackExpr *offsetPackExpr );
171                        void premutate( StructDecl * );
172                        void premutate( UnionDecl * );
173
174                        void beginScope();
175                        void endScope();
176
177                private:
178                        /// Makes a new variable in the current scope with the given name, type & optional initializer
179                        ObjectDecl *makeVar( const std::string &name, Type *type, Initializer *init = 0 );
180                        /// returns true if the type has a dynamic layout; such a layout will be stored in appropriately-named local variables when the function returns
181                        bool findGeneric( Type *ty );
182                        /// adds type parameters to the layout call; will generate the appropriate parameters if needed
183                        void addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams );
184                        /// change the type of generic aggregate members to char[]
185                        void mutateMembers( AggregateDecl * aggrDecl );
186                        /// returns the calculated sizeof expression for ty, or nullptr for use C sizeof()
187                        Expression* genSizeof( Type* ty );
188
189                        /// Enters a new scope for type-variables, adding the type variables from ty
190                        void beginTypeScope( Type *ty );
191                        /// Exits the type-variable scope
192                        void endTypeScope();
193                        /// Enters a new scope for knowLayouts and knownOffsets and queues exit calls
194                        void beginGenericScope();
195
196                        ScopedSet< std::string > knownLayouts;          ///< Set of generic type layouts known in the current scope, indexed by sizeofName
197                        ScopedSet< std::string > knownOffsets;          ///< Set of non-generic types for which the offset array exists in the current scope, indexed by offsetofName
198                        UniqueName bufNamer;                           ///< Namer for VLA buffers
199                        Expression * addrMember = nullptr;             ///< AddressExpr argument is MemberExpr?
200                };
201
202                /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, sizeof expressions of polymorphic types with the proper variable, and strips fields from generic struct declarations.
203                struct Pass3 final : public BoxPass, public WithGuards {
204                        template< typename DeclClass >
205                        void handleDecl( DeclClass * decl, Type * type );
206
207                        void premutate( ObjectDecl * objectDecl );
208                        void premutate( FunctionDecl * functionDecl );
209                        void premutate( TypedefDecl * typedefDecl );
210                        void premutate( StructDecl * structDecl );
211                        void premutate( UnionDecl * unionDecl );
212                        void premutate( TypeDecl * typeDecl );
213                        void premutate( PointerType * pointerType );
214                        void premutate( FunctionType * funcType );
215                };
216        } // anonymous namespace
217
218        /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
219        template< typename MutatorType >
220        inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
221                bool seenIntrinsic = false;
222                SemanticErrorException errors;
223                for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
224                        try {
225                                if ( *i ) {
226                                        if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
227                                                seenIntrinsic = true;
228                                        } else if ( seenIntrinsic ) {
229                                                seenIntrinsic = false; // break on this line when debugging for end of prelude
230                                        }
231
232                                        *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
233                                        assert( *i );
234                                } // if
235                        } catch( SemanticErrorException &e ) {
236                                errors.append( e );
237                        } // try
238                } // for
239                if ( ! errors.isEmpty() ) {
240                        throw errors;
241                } // if
242        }
243
244        void box( std::list< Declaration *>& translationUnit ) {
245                PassVisitor<LayoutFunctionBuilder> layoutBuilder;
246                PassVisitor<Pass1> pass1;
247                PassVisitor<Pass2> pass2;
248                PassVisitor<PolyGenericCalculator> polyCalculator;
249                PassVisitor<Pass3> pass3;
250
251                acceptAll( translationUnit, layoutBuilder );
252                mutateAll( translationUnit, pass1 );
253                mutateAll( translationUnit, pass2 );
254                mutateAll( translationUnit, polyCalculator );
255                mutateAll( translationUnit, pass3 );
256        }
257
258        ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
259
260        void LayoutFunctionBuilder::previsit( FunctionDecl *functionDecl ) {
261                visit_children = false;
262                maybeAccept( functionDecl->get_functionType(), *visitor );
263                ++functionNesting;
264                maybeAccept( functionDecl->get_statements(), *visitor );
265                --functionNesting;
266        }
267
268        /// Get a list of type declarations that will affect a layout function
269        std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
270                std::list< TypeDecl * > otypeDecls;
271
272                for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
273                        if ( (*decl)->isComplete() ) {
274                                otypeDecls.push_back( *decl );
275                        }
276                }
277
278                return otypeDecls;
279        }
280
281        /// Adds parameters for otype layout to a function type
282        void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
283                BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
284
285                for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
286                        TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
287                        std::string paramName = mangleType( &paramType );
288                        layoutFnType->parameters.push_back( new ObjectDecl( sizeofName( paramName ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
289                        layoutFnType->parameters.push_back( new ObjectDecl( alignofName( paramName ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
290                }
291        }
292
293        /// Builds a layout function declaration
294        FunctionDecl *buildLayoutFunctionDecl( AggregateDecl *typeDecl, unsigned int functionNesting, FunctionType *layoutFnType ) {
295                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
296                // because each unit generates copies of the default routines for each aggregate.
297                FunctionDecl *layoutDecl = new FunctionDecl( layoutofName( typeDecl ),
298                                                                                                         functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static ),
299                                                                                                         LinkageSpec::AutoGen, layoutFnType, new CompoundStmt(),
300                                                                                                         std::vector< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
301                layoutDecl->fixUniqueId();
302                return layoutDecl;
303        }
304
305        /// Makes a unary operation
306        Expression *makeOp( const std::string &name, Expression *arg ) {
307                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
308                expr->args.push_back( arg );
309                return expr;
310        }
311
312        /// Makes a binary operation
313        Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
314                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
315                expr->args.push_back( lhs );
316                expr->args.push_back( rhs );
317                return expr;
318        }
319
320        /// Returns the dereference of a local pointer variable
321        Expression *derefVar( ObjectDecl *var ) {
322                return UntypedExpr::createDeref( new VariableExpr( var ) );
323        }
324
325        /// makes an if-statement with a single-expression if-block and no then block
326        Statement *makeCond( Expression *cond, Expression *ifPart ) {
327                return new IfStmt( cond, new ExprStmt( ifPart ), 0 );
328        }
329
330        /// makes a statement that assigns rhs to lhs if lhs < rhs
331        Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
332                return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
333        }
334
335        /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
336        Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
337                // check that the lhs is zeroed out to the level of rhs
338                Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
339                // if not aligned, increment to alignment
340                Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
341                return makeCond( ifCond, ifExpr );
342        }
343
344        /// adds an expression to a compound statement
345        void addExpr( CompoundStmt *stmts, Expression *expr ) {
346                stmts->get_kids().push_back( new ExprStmt( expr ) );
347        }
348
349        /// adds a statement to a compound statement
350        void addStmt( CompoundStmt *stmts, Statement *stmt ) {
351                stmts->get_kids().push_back( stmt );
352        }
353
354        void LayoutFunctionBuilder::previsit( StructDecl *structDecl ) {
355                // do not generate layout function for "empty" tag structs
356                visit_children = false;
357                if ( structDecl->get_members().empty() ) return;
358
359                // get parameters that can change layout, exiting early if none
360                std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
361                if ( otypeParams.empty() ) return;
362
363                // build layout function signature
364                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
365                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
366                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
367
368                ObjectDecl *sizeParam = new ObjectDecl( sizeofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
369                layoutFnType->parameters.push_back( sizeParam );
370                ObjectDecl *alignParam = new ObjectDecl( alignofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
371                layoutFnType->parameters.push_back( alignParam );
372                ObjectDecl *offsetParam = new ObjectDecl( offsetofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
373                layoutFnType->parameters.push_back( offsetParam );
374                addOtypeParams( layoutFnType, otypeParams );
375
376                // build function decl
377                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl, functionNesting, layoutFnType );
378
379                // calculate struct layout in function body
380
381                // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size)
382                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant::from_ulong( 0 ) ) ) );
383                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
384                unsigned long n_members = 0;
385                bool firstMember = true;
386                for ( Declaration* member : structDecl->get_members() ) {
387                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( member );
388                        assert( dwt );
389                        Type *memberType = dwt->get_type();
390
391                        if ( firstMember ) {
392                                firstMember = false;
393                        } else {
394                                // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
395                                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
396                        }
397
398                        // place current size in the current offset index
399                        addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from_ulong( n_members ) ) ),
400                                                                              derefVar( sizeParam ) ) );
401                        ++n_members;
402
403                        // add member size to current size
404                        addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
405
406                        // take max of member alignment and global alignment
407                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
408                }
409                // make sure the type is end-padded to a multiple of its alignment
410                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
411
412                declsToAddAfter.push_back( layoutDecl );
413        }
414
415        void LayoutFunctionBuilder::previsit( UnionDecl *unionDecl ) {
416                // do not generate layout function for "empty" tag unions
417                visit_children = false;
418                if ( unionDecl->get_members().empty() ) return;
419
420                // get parameters that can change layout, exiting early if none
421                std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
422                if ( otypeParams.empty() ) return;
423
424                // build layout function signature
425                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
426                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
427                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
428
429                ObjectDecl *sizeParam = new ObjectDecl( sizeofName( unionDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
430                layoutFnType->parameters.push_back( sizeParam );
431                ObjectDecl *alignParam = new ObjectDecl( alignofName( unionDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
432                layoutFnType->parameters.push_back( alignParam );
433                addOtypeParams( layoutFnType, otypeParams );
434
435                // build function decl
436                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl, functionNesting, layoutFnType );
437
438                // calculate union layout in function body
439                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
440                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
441                for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
442                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
443                        assert( dwt );
444                        Type *memberType = dwt->get_type();
445
446                        // take max member size and global size
447                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
448
449                        // take max of member alignment and global alignment
450                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
451                }
452                // make sure the type is end-padded to a multiple of its alignment
453                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
454
455                declsToAddAfter.push_back( layoutDecl );
456        }
457
458        ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
459
460        namespace {
461                std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
462                        std::stringstream name;
463
464                        // NOTE: this function previously used isPolyObj, which failed to produce
465                        // the correct thing in some situations. It's not clear to me why this wasn't working.
466
467                        // if the return type or a parameter type involved polymorphic types, then the adapter will need
468                        // to take those polymorphic types as pointers. Therefore, there can be two different functions
469                        // with the same mangled name, so we need to further mangle the names.
470                        for ( auto retval : function->returnVals ) {
471                                if ( isPolyType( retval->get_type(), tyVars ) ) {
472                                        name << "P";
473                                } else {
474                                        name << "M";
475                                }
476                        }
477                        name << "_";
478                        auto & paramList = function->parameters;
479                        for ( auto arg : paramList ) {
480                                if ( isPolyType( arg->get_type(), tyVars ) ) {
481                                        name << "P";
482                                } else {
483                                        name << "M";
484                                }
485                        } // for
486                        return name.str();
487                }
488
489                std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
490                        return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
491                }
492
493                std::string makeAdapterName( const std::string &mangleName ) {
494                        return "_adapter" + mangleName;
495                }
496
497                Pass1::Pass1() : tempNamer( "_temp" ) {}
498
499                void Pass1::premutate( FunctionDecl *functionDecl ) {
500                        if ( functionDecl->get_statements() ) {         // empty routine body ?
501                                // std::cerr << "mutating function: " << functionDecl->get_mangleName() << std::endl;
502                                GuardScope( scopeTyVars );
503                                GuardValue( retval );
504
505                                // process polymorphic return value
506                                retval = nullptr;
507                                FunctionType *functionType = functionDecl->type;
508                                if ( isDynRet( functionType ) && functionDecl->linkage != LinkageSpec::C ) {
509                                        retval = functionType->returnVals.front();
510
511                                        // give names to unnamed return values
512                                        if ( retval->name == "" ) {
513                                                retval->name = "_retparm";
514                                                retval->linkage = LinkageSpec::C;
515                                        } // if
516                                } // if
517
518                                makeTyVarMap( functionType, scopeTyVars );
519
520                                auto & paramList = functionType->parameters;
521                                std::vector< FunctionType *> functions;
522                                for ( auto tyVar : functionType->forall ) {
523                                        for ( auto assert : tyVar->assertions ) {
524                                                findFunction( assert->get_type(), functions, scopeTyVars, needsAdapter );
525                                        } // for
526                                } // for
527                                for ( auto arg : paramList ) {
528                                        findFunction( arg->get_type(), functions, scopeTyVars, needsAdapter );
529                                } // for
530
531                                for ( auto funType : functions ) {
532                                        std::string mangleName = mangleAdapterName( funType, scopeTyVars );
533                                        if ( adapters.find( mangleName ) == adapters.end() ) {
534                                                std::string adapterName = makeAdapterName( mangleName );
535                                                adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, nullptr, new PointerType( Type::Qualifiers(), makeAdapterType( funType, scopeTyVars ) ), nullptr ) ) );
536                                        } // if
537                                } // for
538                                // std::cerr << "end function: " << functionDecl->get_mangleName() << std::endl;
539                        } // if
540                }
541
542                void Pass1::premutate( TypeDecl *typeDecl ) {
543                        addToTyVarMap( typeDecl, scopeTyVars );
544                }
545
546                void Pass1::premutate( CommaExpr *commaExpr ) {
547                        // Attempting to find application expressions that were mutated by the copy constructor passes
548                        // to use an explicit return variable, so that the variable can be reused as a parameter to the
549                        // call rather than creating a new temp variable. Previously this step was an optimization, but
550                        // with the introduction of tuples and UniqueExprs, it is necessary to ensure that they use the same variable.
551                        // Essentially, looking for pattern: (x=f(...), x)
552                        // To compound the issue, the right side can be *x, etc. because of lvalue-returning functions
553                        if ( UntypedExpr * assign = dynamic_cast< UntypedExpr * >( commaExpr->get_arg1() ) ) {
554                                if ( CodeGen::isAssignment( InitTweak::getFunctionName( assign ) ) ) {
555                                        assert( assign->get_args().size() == 2 );
556                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( assign->get_args().back() ) ) {
557                                                // first argument is assignable, so it must be an lvalue, so it should be legal to take its address.
558                                                retVals[appExpr] = assign->get_args().front();
559                                        }
560                                }
561                        }
562                }
563
564                void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
565                        Type *polyType = isPolyType( parmType, exprTyVars );
566                        if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
567                                std::string typeName = mangleType( polyType );
568                                if ( seenTypes.count( typeName ) ) return;
569
570                                arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
571                                arg++;
572                                arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
573                                arg++;
574                                if ( dynamic_cast< StructInstType* >( polyType ) ) {
575                                        if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
576                                                // zero-length arrays are forbidden by C, so don't pass offset for empty struct
577                                                if ( ! argBaseStructType->get_baseStruct()->get_members().empty() ) {
578                                                        arg = appExpr->get_args().insert( arg, new OffsetPackExpr( argBaseStructType->clone() ) );
579                                                        arg++;
580                                                }
581                                        } else {
582                                                SemanticError( argBaseType, "Cannot pass non-struct type for generic struct: " );
583                                        }
584                                }
585
586                                seenTypes.insert( typeName );
587                        }
588                }
589
590                void Pass1::passTypeVars( ApplicationExpr *appExpr, Type *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
591                        // pass size/align for type variables
592                        for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
593                                ResolvExpr::EqvClass eqvClass;
594                                assert( env );
595                                if ( tyParm->second.isComplete ) {
596                                        Type *concrete = env->lookup( tyParm->first );
597                                        if ( concrete ) {
598                                                arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
599                                                arg++;
600                                                arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
601                                                arg++;
602                                        } else {
603                                                // xxx - should this be an assertion?
604                                                SemanticError( appExpr, toString( *env, "\nunbound type variable: ", tyParm->first, " in application " ) );
605                                        } // if
606                                } // if
607                        } // for
608
609                        // add size/align for generic types to parameter list
610                        if ( ! appExpr->get_function()->result ) return;
611                        FunctionType *funcType = getFunctionType( appExpr->get_function()->get_result() );
612                        assert( funcType );
613
614                        std::vector< DeclarationWithType* >::const_iterator fnParm = funcType->parameters.begin();
615                        std::list< Expression* >::const_iterator fnArg = arg;
616                        std::set< std::string > seenTypes; ///< names for generic types we've seen
617
618                        // a polymorphic return type may need to be added to the argument list
619                        if ( polyRetType ) {
620                                Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
621                                passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
622                                ++fnArg; // skip the return parameter in the argument list
623                        }
624
625                        // add type information args for presently unseen types in parameter list
626                        for ( ; fnParm != funcType->parameters.end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
627                                if ( ! (*fnArg)->get_result() ) continue;
628                                Type * argType = (*fnArg)->get_result();
629                                passArgTypeVars( appExpr, (*fnParm)->get_type(), argType, arg, exprTyVars, seenTypes );
630                        }
631                }
632
633                ObjectDecl *Pass1::makeTemporary( Type *type ) {
634                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, type, 0 );
635                        stmtsToAddBefore.push_back( new DeclStmt( newObj ) );
636                        return newObj;
637                }
638
639                Expression *Pass1::addRetParam( ApplicationExpr *appExpr, Type *retType, std::list< Expression *>::iterator &arg ) {
640                        // Create temporary to hold return value of polymorphic function and produce that temporary as a result
641                        // using a comma expression.
642                        assert( retType );
643
644                        Expression * paramExpr = nullptr;
645                        // try to use existing return value parameter if it exists, otherwise create a new temporary
646                        if ( retVals.count( appExpr ) ) {
647                                paramExpr = retVals[appExpr]->clone();
648                        } else {
649                                ObjectDecl *newObj = makeTemporary( retType->clone() );
650                                paramExpr = new VariableExpr( newObj );
651                        }
652                        Expression * retExpr = paramExpr->clone();
653
654                        // If the type of the temporary is not polymorphic, box temporary by taking its address;
655                        // otherwise the temporary is already boxed and can be used directly.
656                        if ( ! isPolyType( paramExpr->get_result(), scopeTyVars, env ) ) {
657                                paramExpr = new AddressExpr( paramExpr );
658                        } // if
659                        arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
660                        arg++;
661                        // Build a comma expression to call the function and emulate a normal return.
662                        CommaExpr *commaExpr = new CommaExpr( appExpr, retExpr );
663                        commaExpr->set_env( appExpr->get_env() );
664                        appExpr->set_env( 0 );
665                        return commaExpr;
666                }
667
668                void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
669                        for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
670                                TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
671                                assertf(paramType, "Aggregate parameters should be type expressions");
672                                paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
673                        }
674                }
675
676                Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
677                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
678                                Type *concrete = env->lookup( typeInst->get_name() );
679                                if ( concrete == 0 ) {
680                                        return typeInst;
681                                } // if
682                                return concrete;
683                        } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
684                                if ( doClone ) {
685                                        structType = structType->clone();
686                                }
687                                replaceParametersWithConcrete( appExpr, structType->get_parameters() );
688                                return structType;
689                        } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
690                                if ( doClone ) {
691                                        unionType = unionType->clone();
692                                }
693                                replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
694                                return unionType;
695                        }
696                        return type;
697                }
698
699                Expression *Pass1::addDynRetParam( ApplicationExpr *appExpr, Type *dynType, std::list< Expression *>::iterator &arg ) {
700                        assert( env );
701                        Type *concrete = replaceWithConcrete( appExpr, dynType );
702                        // add out-parameter for return value
703                        return addRetParam( appExpr, concrete, arg );
704                }
705
706                Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
707                        Expression *ret = appExpr;
708//                      if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
709                        if ( isDynRet( function, tyVars ) ) {
710                                ret = addRetParam( appExpr, function->returnVals.front()->get_type(), arg );
711                        } // if
712                        std::string mangleName = mangleAdapterName( function, tyVars );
713                        std::string adapterName = makeAdapterName( mangleName );
714
715                        // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
716                        Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
717                        appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
718                        appExpr->set_function( new NameExpr( adapterName ) ); // xxx - result is never set on NameExpr
719
720                        return ret;
721                }
722
723                void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
724                        assertf( arg->result, "arg does not have result: %s", toString( arg ).c_str() );
725                        if ( ! needsBoxing( param, arg->result, exprTyVars, env ) ) return;
726
727                        if ( arg->result->get_lvalue() ) {
728                                // argument expression may be CFA lvalue, but not C lvalue -- apply generalizedLvalue transformations.
729                                // if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( arg ) ) {
730                                //      if ( dynamic_cast<ArrayType *>( varExpr->var->get_type() ) ){
731                                //              // temporary hack - don't box arrays, because &arr is not the same as &arr[0]
732                                //              return;
733                                //      }
734                                // }
735                                arg =  generalizedLvalue( new AddressExpr( arg ) );
736                                if ( ! ResolvExpr::typesCompatible( param, arg->get_result(), SymTab::Indexer() ) ) {
737                                        // silence warnings by casting boxed parameters when the actual type does not match up with the formal type.
738                                        arg = new CastExpr( arg, param->clone() );
739                                }
740                        } else {
741                                // use type computed in unification to declare boxed variables
742                                Type * newType = param->clone();
743                                if ( env ) env->apply( newType );
744                                ObjectDecl *newObj = ObjectDecl::newObject( tempNamer.newName(), newType, nullptr );
745                                newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
746                                stmtsToAddBefore.push_back( new DeclStmt( newObj ) );
747                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) ); // TODO: why doesn't this just use initialization syntax?
748                                assign->get_args().push_back( new VariableExpr( newObj ) );
749                                assign->get_args().push_back( arg );
750                                stmtsToAddBefore.push_back( new ExprStmt( assign ) );
751                                arg = new AddressExpr( new VariableExpr( newObj ) );
752                        } // if
753                }
754
755                // find instances of polymorphic type parameters
756                struct PolyFinder {
757                        const TyVarMap * tyVars = nullptr;
758                        bool found = false;
759
760                        void previsit( TypeInstType * t ) {
761                                if ( isPolyType( t, *tyVars ) ) {
762                                        found = true;
763                                }
764                        }
765                };
766
767                // true if there is an instance of a polymorphic type parameter in t
768                bool hasPolymorphism( Type * t, const TyVarMap &tyVars ) {
769                        PassVisitor<PolyFinder> finder;
770                        finder.pass.tyVars = &tyVars;
771                        maybeAccept( t, finder );
772                        return finder.pass.found;
773                }
774
775                /// cast parameters to polymorphic functions so that types are replaced with
776                /// void * if they are type parameters in the formal type.
777                /// this gets rid of warnings from gcc.
778                void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
779                        // type contains polymorphism, but isn't exactly a polytype, in which case it
780                        // has some real actual type (e.g. unsigned int) and casting to void * is wrong
781                        if ( hasPolymorphism( formal, tyVars ) && ! isPolyType( formal, tyVars ) ) {
782                                Type * newType = formal->clone();
783                                newType = ScrubTyVars::scrub( newType, tyVars );
784                                actual = new CastExpr( actual, newType );
785                        } // if
786                }
787
788                void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator & arg, const TyVarMap &exprTyVars ) {
789                        for ( auto param : function->parameters ) {
790                                assertf( arg != appExpr->args.end(), "boxParams: missing argument for param %s to %s in %s", toString( param ).c_str(), toString( function ).c_str(), toString( appExpr ).c_str() );
791                                addCast( *arg, param->get_type(), exprTyVars );
792                                boxParam( param->get_type(), *arg, exprTyVars );
793                                ++arg;
794                        } // for
795                }
796
797                void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
798                        std::list< Expression *>::iterator cur = arg;
799                        for ( auto tyVar : functionType->forall ) {
800                                for ( auto assert : tyVar->assertions ) {
801                                        InferredParams::const_iterator inferParam = appExpr->inferParams.find( assert->get_uniqueId() );
802                                        assertf( inferParam != appExpr->inferParams.end(), "addInferredParams missing inferred parameter: %s in: %s", toString( assert ).c_str(), toString( appExpr ).c_str() );
803                                        Expression *newExpr = inferParam->second.expr->clone();
804                                        addCast( newExpr, assert->get_type(), tyVars );
805                                        boxParam( assert->get_type(), newExpr, tyVars );
806                                        appExpr->get_args().insert( cur, newExpr );
807                                } // for
808                        } // for
809                }
810
811                void makeRetParm( FunctionType *funcType ) {
812                        DeclarationWithType *retParm = funcType->returnVals.front();
813
814                        // make a new parameter that is a pointer to the type of the old return value
815                        retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
816                        funcType->parameters.insert( funcType->parameters.begin(), retParm );
817
818                        // we don't need the return value any more
819                        funcType->returnVals.clear();
820                }
821
822                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
823                        // actually make the adapter type
824                        FunctionType *adapter = adaptee->clone();
825                        if ( isDynRet( adapter, tyVars ) ) {
826                                makeRetParm( adapter );
827                        } // if
828                        adapter->parameters.insert( adapter->parameters.begin(), new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
829                        return adapter;
830                }
831
832                Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
833                        assert( param );
834                        assert( arg );
835                        if ( isPolyType( realParam->get_type(), tyVars ) ) {
836                                if ( ! isPolyType( arg->get_type() ) ) {
837                                        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
838                                        deref->args.push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
839                                        deref->result = arg->get_type()->clone();
840                                        deref->result->set_lvalue( true );
841                                        return deref;
842                                } // if
843                        } // if
844                        return new VariableExpr( param );
845                }
846
847                void addAdapterParams( ApplicationExpr *adapteeApp, std::vector< DeclarationWithType *>::iterator arg, std::vector< DeclarationWithType *>::iterator param, std::vector< DeclarationWithType *>::iterator paramEnd, std::vector< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
848                        UniqueName paramNamer( "_p" );
849                        for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
850                                if ( (*param)->get_name() == "" ) {
851                                        (*param)->set_name( paramNamer.newName() );
852                                        (*param)->set_linkage( LinkageSpec::C );
853                                } // if
854                                adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
855                        } // for
856                }
857
858                FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
859                        FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
860                        adapterType = ScrubTyVars::scrub( adapterType, tyVars );
861                        DeclarationWithType *adapteeDecl = adapterType->parameters.front();
862                        adapteeDecl->set_name( "_adaptee" );
863                        // do not carry over attributes to real type parameters/return values
864                        for ( DeclarationWithType * dwt : realType->parameters ) {
865                                deleteAll( dwt->get_type()->attributes );
866                                dwt->get_type()->attributes.clear();
867                        }
868                        for ( DeclarationWithType * dwt : realType->returnVals ) {
869                                deleteAll( dwt->get_type()->attributes );
870                                dwt->get_type()->attributes.clear();
871                        }
872                        ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
873                        Statement *bodyStmt;
874
875                        Type::ForallList::iterator tyArg = realType->get_forall().begin();
876                        Type::ForallList::iterator tyParam = adapterType->get_forall().begin();
877                        Type::ForallList::iterator realTyParam = adaptee->get_forall().begin();
878                        for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
879                                assert( tyArg != realType->get_forall().end() );
880                                std::vector< DeclarationWithType *>::iterator assertArg = (*tyArg)->assertions.begin();
881                                std::vector< DeclarationWithType *>::iterator assertParam = (*tyParam)->assertions.begin();
882                                std::vector< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->assertions.begin();
883                                for ( ; assertParam != (*tyParam)->assertions.end(); ++assertArg, ++assertParam, ++realAssertParam ) {
884                                        assert( assertArg != (*tyArg)->assertions.end() );
885                                        adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
886                                } // for
887                        } // for
888
889                        std::vector< DeclarationWithType *>::iterator arg = realType->parameters.begin();
890                        std::vector< DeclarationWithType *>::iterator param = adapterType->parameters.begin();
891                        std::vector< DeclarationWithType *>::iterator realParam = adaptee->parameters.begin();
892                        param++;                // skip adaptee parameter in the adapter type
893                        if ( realType->returnVals.empty() ) {
894                                // void return
895                                addAdapterParams( adapteeApp, arg, param, adapterType->parameters.end(), realParam, tyVars );
896                                bodyStmt = new ExprStmt( adapteeApp );
897                        } else if ( isDynType( adaptee->returnVals.front()->get_type(), tyVars ) ) {
898                                // return type T
899                                if ( (*param)->get_name() == "" ) {
900                                        (*param)->set_name( "_ret" );
901                                        (*param)->set_linkage( LinkageSpec::C );
902                                } // if
903                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
904                                UntypedExpr *deref = UntypedExpr::createDeref( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->returnVals.front()->get_type()->clone() ) ) );
905                                assign->get_args().push_back( deref );
906                                addAdapterParams( adapteeApp, arg, param, adapterType->parameters.end(), realParam, tyVars );
907                                assign->get_args().push_back( adapteeApp );
908                                bodyStmt = new ExprStmt( assign );
909                        } else {
910                                // adapter for a function that returns a monomorphic value
911                                addAdapterParams( adapteeApp, arg, param, adapterType->parameters.end(), realParam, tyVars );
912                                bodyStmt = new ReturnStmt( adapteeApp );
913                        } // if
914                        CompoundStmt *adapterBody = new CompoundStmt();
915                        adapterBody->get_kids().push_back( bodyStmt );
916                        std::string adapterName = makeAdapterName( mangleName );
917                        return new FunctionDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, adapterType, adapterBody );
918                }
919
920                void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
921                        // collect a list of function types passed as parameters or implicit parameters (assertions)
922                        auto & paramList = functionType->parameters;
923                        std::vector< FunctionType *> functions;
924                        for ( auto tyVar : functionType->forall ) {
925                                for ( auto assert : tyVar->assertions ) {
926                                        findFunction( assert->get_type(), functions, exprTyVars, needsAdapter );
927                                } // for
928                        } // for
929                        for ( auto arg : paramList ) {
930                                findFunction( arg->get_type(), functions, exprTyVars, needsAdapter );
931                        } // for
932
933                        // parameter function types for which an appropriate adapter has been generated.  we cannot use the types
934                        // after applying substitutions, since two different parameter types may be unified to the same type
935                        std::set< std::string > adaptersDone;
936
937                        for ( auto funType : functions ) {
938                                FunctionType * originalFunction = funType->clone();
939                                FunctionType * realFunction = funType->clone();
940                                std::string mangleName = SymTab::Mangler::mangle( realFunction );
941
942                                // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
943                                // pre-substitution parameter function type.
944                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
945                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
946
947                                        // apply substitution to type variables to figure out what the adapter's type should look like
948                                        assert( env );
949                                        env->apply( realFunction );
950                                        mangleName = SymTab::Mangler::mangle( realFunction );
951                                        mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
952
953                                        typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
954                                        AdapterIter adapter = adapters.find( mangleName );
955                                        if ( adapter == adapters.end() ) {
956                                                // adapter has not been created yet in the current scope, so define it
957                                                FunctionDecl *newAdapter = makeAdapter( funType, realFunction, mangleName, exprTyVars );
958                                                std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
959                                                adapter = answer.first;
960                                                stmtsToAddBefore.push_back( new DeclStmt( newAdapter ) );
961                                        } // if
962                                        assert( adapter != adapters.end() );
963
964                                        // add the appropriate adapter as a parameter
965                                        appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
966                                } // if
967                        } // for
968                } // passAdapters
969
970                Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
971                        NameExpr *opExpr;
972                        if ( isIncr ) {
973                                opExpr = new NameExpr( "?+=?" );
974                        } else {
975                                opExpr = new NameExpr( "?-=?" );
976                        } // if
977                        UntypedExpr *addAssign = new UntypedExpr( opExpr );
978                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
979                                addAssign->get_args().push_back( address->get_arg() );
980                        } else {
981                                addAssign->get_args().push_back( appExpr->get_args().front() );
982                        } // if
983                        addAssign->get_args().push_back( new NameExpr( sizeofName( mangleType( polyType ) ) ) );
984                        addAssign->set_result( appExpr->get_result()->clone() );
985                        if ( appExpr->get_env() ) {
986                                addAssign->set_env( appExpr->get_env() );
987                                appExpr->set_env( 0 );
988                        } // if
989                        appExpr->get_args().clear();
990                        delete appExpr;
991                        return addAssign;
992                }
993
994                Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
995                        if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->function ) ) {
996                                if ( varExpr->var->linkage == LinkageSpec::Intrinsic ) {
997                                        if ( varExpr->var->name == "?[?]" ) {
998                                                assert( appExpr->result );
999                                                assert( appExpr->get_args().size() == 2 );
1000                                                Type *baseType1 = isPolyPtr( appExpr->args.front()->result, scopeTyVars, env );
1001                                                Type *baseType2 = isPolyPtr( appExpr->args.back()->result, scopeTyVars, env );
1002                                                assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1003                                                UntypedExpr *ret = 0;
1004                                                if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1005                                                        ret = new UntypedExpr( new NameExpr( "?+?" ) );
1006                                                } // if
1007                                                if ( baseType1 ) {
1008                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1009                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1010                                                        multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1011                                                        ret->get_args().push_back( appExpr->get_args().front() );
1012                                                        ret->get_args().push_back( multiply );
1013                                                } else if ( baseType2 ) {
1014                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1015                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1016                                                        multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1017                                                        ret->get_args().push_back( multiply );
1018                                                        ret->get_args().push_back( appExpr->get_args().back() );
1019                                                } // if
1020                                                if ( baseType1 || baseType2 ) {
1021                                                        delete ret->get_result();
1022                                                        ret->set_result( appExpr->get_result()->clone() );
1023                                                        if ( appExpr->get_env() ) {
1024                                                                ret->set_env( appExpr->get_env() );
1025                                                                appExpr->set_env( 0 );
1026                                                        } // if
1027                                                        appExpr->get_args().clear();
1028                                                        delete appExpr;
1029                                                        return ret;
1030                                                } // if
1031                                        } else if ( varExpr->get_var()->get_name() == "*?" ) {
1032                                                assert( appExpr->result );
1033                                                assert( ! appExpr->get_args().empty() );
1034                                                if ( isPolyType( appExpr->get_result(), scopeTyVars, env ) ) {
1035                                                        // remove dereference from polymorphic types since they are boxed.
1036                                                        Expression *ret = appExpr->get_args().front();
1037                                                        // fix expr type to remove pointer
1038                                                        delete ret->get_result();
1039                                                        ret->set_result( appExpr->get_result()->clone() );
1040                                                        if ( appExpr->get_env() ) {
1041                                                                ret->set_env( appExpr->get_env() );
1042                                                                appExpr->set_env( 0 );
1043                                                        } // if
1044                                                        appExpr->get_args().clear();
1045                                                        delete appExpr;
1046                                                        return ret;
1047                                                } // if
1048                                        } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1049                                                assert( appExpr->result );
1050                                                assert( appExpr->get_args().size() == 1 );
1051                                                if ( Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env ) ) {
1052                                                        Type *tempType = appExpr->get_result()->clone();
1053                                                        if ( env ) {
1054                                                                env->apply( tempType );
1055                                                        } // if
1056                                                        ObjectDecl *newObj = makeTemporary( tempType );
1057                                                        VariableExpr *tempExpr = new VariableExpr( newObj );
1058                                                        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1059                                                        assignExpr->get_args().push_back( tempExpr->clone() );
1060                                                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1061                                                                assignExpr->get_args().push_back( address->get_arg()->clone() );
1062                                                        } else {
1063                                                                assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1064                                                        } // if
1065                                                        CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1066                                                        return new CommaExpr( firstComma, tempExpr );
1067                                                } // if
1068                                        } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1069                                                assert( appExpr->result );
1070                                                assert( appExpr->get_args().size() == 1 );
1071                                                if ( Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env ) ) {
1072                                                        return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1073                                                } // if
1074                                        } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1075                                                assert( appExpr->result );
1076                                                assert( appExpr->get_args().size() == 2 );
1077                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_result(), scopeTyVars, env );
1078                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_result(), scopeTyVars, env );
1079                                                if ( baseType1 && baseType2 ) {
1080                                                        UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1081                                                        divide->get_args().push_back( appExpr );
1082                                                        divide->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1083                                                        divide->set_result( appExpr->get_result()->clone() );
1084                                                        if ( appExpr->get_env() ) {
1085                                                                divide->set_env( appExpr->get_env() );
1086                                                                appExpr->set_env( 0 );
1087                                                        } // if
1088                                                        return divide;
1089                                                } else if ( baseType1 ) {
1090                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1091                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1092                                                        multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1093                                                        appExpr->get_args().back() = multiply;
1094                                                } else if ( baseType2 ) {
1095                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1096                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1097                                                        multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1098                                                        appExpr->get_args().front() = multiply;
1099                                                } // if
1100                                        } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1101                                                assert( appExpr->result );
1102                                                assert( appExpr->get_args().size() == 2 );
1103                                                Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env );
1104                                                if ( baseType ) {
1105                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1106                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1107                                                        multiply->get_args().push_back( new SizeofExpr( baseType->clone() ) );
1108                                                        appExpr->get_args().back() = multiply;
1109                                                } // if
1110                                        } // if
1111                                        return appExpr;
1112                                } // if
1113                        } // if
1114                        return 0;
1115                }
1116
1117                Expression *Pass1::postmutate( ApplicationExpr *appExpr ) {
1118                        // std::cerr << "mutate appExpr: " << InitTweak::getFunctionName( appExpr ) << std::endl;
1119                        // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1120                        //      std::cerr << i->first << " ";
1121                        // }
1122                        // std::cerr << "\n";
1123
1124                        assert( appExpr->function->result );
1125                        FunctionType * function = getFunctionType( appExpr->function->result );
1126                        assertf( function, "ApplicationExpr has non-function type: %s", toString( appExpr->function->result ).c_str() );
1127
1128                        if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1129                                return newExpr;
1130                        } // if
1131
1132                        Expression *ret = appExpr;
1133
1134                        std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1135                        std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1136
1137                        TyVarMap exprTyVars( TypeDecl::Data{} );
1138                        makeTyVarMap( function, exprTyVars ); // xxx - should this take into account the variables already bound in scopeTyVars (i.e. remove them from exprTyVars?)
1139                        ReferenceToType *dynRetType = isDynRet( function, exprTyVars );
1140
1141                        // std::cerr << function << std::endl;
1142                        // std::cerr << "scopeTyVars: ";
1143                        // printTyVarMap( std::cerr, scopeTyVars );
1144                        // std::cerr << "exprTyVars: ";
1145                        // printTyVarMap( std::cerr, exprTyVars );
1146                        // std::cerr << "env: " << *env << std::endl;
1147                        // std::cerr << needsAdapter( function, scopeTyVars ) << ! needsAdapter( function, exprTyVars) << std::endl;
1148
1149                        // NOTE: addDynRetParam needs to know the actual (generated) return type so it can make a temp variable, so pass the result type from the appExpr
1150                        // passTypeVars needs to know the program-text return type (i.e. the distinction between _conc_T30 and T3(int))
1151                        // concRetType may not be a good name in one or both of these places. A more appropriate name change is welcome.
1152                        if ( dynRetType ) {
1153                                // std::cerr << "dynRetType: " << dynRetType << std::endl;
1154                                Type *concRetType = appExpr->get_result()->isVoid() ? nullptr : appExpr->get_result();
1155                                ret = addDynRetParam( appExpr, concRetType, arg ); // xxx - used to use dynRetType instead of concRetType
1156                        } else if ( needsAdapter( function, scopeTyVars ) && ! needsAdapter( function, exprTyVars) ) { // xxx - exprTyVars is used above...?
1157                                // xxx - the ! needsAdapter check may be incorrect. It seems there is some situation where an adapter is applied where it shouldn't be, and this fixes it for some cases. More investigation is needed.
1158
1159                                // std::cerr << "needs adapter: ";
1160                                // printTyVarMap( std::cerr, scopeTyVars );
1161                                // std::cerr << *env << std::endl;
1162                                // change the application so it calls the adapter rather than the passed function
1163                                ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1164                        } // if
1165                        arg = appExpr->get_args().begin();
1166
1167                        Type *concRetType = replaceWithConcrete( appExpr, dynRetType );
1168                        passTypeVars( appExpr, concRetType, arg, exprTyVars ); // xxx - used to use dynRetType instead of concRetType; this changed so that the correct type paramaters are passed for return types (it should be the concrete type's parameters, not the formal type's)
1169                        addInferredParams( appExpr, function, arg, exprTyVars );
1170
1171                        arg = paramBegin;
1172
1173                        boxParams( appExpr, function, arg, exprTyVars );
1174                        passAdapters( appExpr, function, exprTyVars );
1175
1176                        return ret;
1177                }
1178
1179                Expression * Pass1::postmutate( UntypedExpr *expr ) {
1180                        if ( expr->result && isPolyType( expr->result, scopeTyVars, env ) ) {
1181                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->function ) ) {
1182                                        if ( name->name == "*?" ) {
1183                                                Expression *ret = expr->args.front();
1184                                                expr->args.clear();
1185                                                delete expr;
1186                                                return ret;
1187                                        } // if
1188                                } // if
1189                        } // if
1190                        return expr;
1191                }
1192
1193                void Pass1::premutate( AddressExpr * ) { visit_children = false; }
1194                Expression * Pass1::postmutate( AddressExpr * addrExpr ) {
1195                        assert( addrExpr->arg->result && ! addrExpr->arg->result->isVoid() );
1196
1197                        bool needs = false;
1198                        if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->arg ) ) {
1199                                if ( expr->result && isPolyType( expr->result, scopeTyVars, env ) ) {
1200                                        if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->function ) ) {
1201                                                if ( name->name == "*?" ) {
1202                                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->args.front() ) ) {
1203                                                                assert( appExpr->function->result );
1204                                                                FunctionType *function = getFunctionType( appExpr->function->result );
1205                                                                assert( function );
1206                                                                needs = needsAdapter( function, scopeTyVars );
1207                                                        } // if
1208                                                } // if
1209                                        } // if
1210                                } // if
1211                        } // if
1212                        // isPolyType check needs to happen before mutating addrExpr arg, so pull it forward
1213                        // out of the if condition.
1214                        addrExpr->arg = addrExpr->arg->acceptMutator( *visitor );
1215                        // ... but must happen after mutate, since argument might change (e.g. intrinsic *?, ?[?]) - re-evaluate above comment
1216                        bool polytype = isPolyType( addrExpr->arg->result, scopeTyVars, env );
1217                        if ( polytype || needs ) {
1218                                Expression *ret = addrExpr->arg;
1219                                delete ret->result;
1220                                ret->result = addrExpr->result->clone();
1221                                addrExpr->arg = nullptr;
1222                                delete addrExpr;
1223                                return ret;
1224                        } else {
1225                                return addrExpr;
1226                        } // if
1227                }
1228
1229                void Pass1::premutate( ReturnStmt *returnStmt ) {
1230                        if ( retval && returnStmt->expr ) {
1231                                assert( returnStmt->expr->result && ! returnStmt->expr->result->isVoid() );
1232                                delete returnStmt->expr;
1233                                returnStmt->expr = nullptr;
1234                        } // if
1235                }
1236
1237                void Pass1::premutate( PointerType *pointerType ) {
1238                        GuardScope( scopeTyVars );
1239                        makeTyVarMap( pointerType, scopeTyVars );
1240                }
1241
1242                void Pass1::premutate( FunctionType *functionType ) {
1243                        GuardScope( scopeTyVars );
1244                        makeTyVarMap( functionType, scopeTyVars );
1245                }
1246
1247                void Pass1::beginScope() {
1248                        adapters.beginScope();
1249                }
1250
1251                void Pass1::endScope() {
1252                        adapters.endScope();
1253                }
1254
1255////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1256
1257                void Pass2::addAdapters( FunctionType *functionType ) {
1258                        auto & paramList = functionType->parameters;
1259                        std::vector< FunctionType *> functions;
1260                        for ( auto arg : paramList ) {
1261                                Type *orig = arg->get_type();
1262                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1263                                arg->set_type( orig );
1264                        }
1265                        std::set< std::string > adaptersDone;
1266                        for ( auto funType : functions ) {
1267                                std::string mangleName = mangleAdapterName( funType, scopeTyVars );
1268                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1269                                        std::string adapterName = makeAdapterName( mangleName );
1270                                        // adapter may not be used in body, pass along with unused attribute.
1271                                        paramList.insert( paramList.begin(), new ObjectDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( funType, scopeTyVars ) ), 0, { new Attribute( "unused" ) } ) );
1272                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1273                                }
1274                        }
1275                }
1276
1277                DeclarationWithType * Pass2::postmutate( FunctionDecl *functionDecl ) {
1278                        FunctionType * ftype = functionDecl->type;
1279                        if ( ! ftype->returnVals.empty() && functionDecl->statements ) {
1280                                if ( ! isPrefix( functionDecl->name, "_thunk" ) && ! isPrefix( functionDecl->name, "_adapter" ) ) { // xxx - remove check for prefix once thunks properly use ctor/dtors
1281                                        assert( ftype->returnVals.size() == 1 );
1282                                        DeclarationWithType * retval = ftype->returnVals.front();
1283                                        if ( retval->name == "" ) {
1284                                                retval->name = "_retval";
1285                                        }
1286                                        functionDecl->statements->kids.push_front( new DeclStmt( retval ) );
1287                                        DeclarationWithType * newRet = retval->clone(); // for ownership purposes
1288                                        ftype->returnVals.front() = newRet;
1289                                }
1290                        }
1291                        // errors should have been caught by this point, remove initializers from parameters to allow correct codegen of default arguments
1292                        for ( Declaration * param : functionDecl->type->parameters ) {
1293                                if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( param ) ) {
1294                                        delete obj->init;
1295                                        obj->init = nullptr;
1296                                }
1297                        }
1298                        return functionDecl;
1299                }
1300
1301                void Pass2::premutate( StructDecl * ) {
1302                        // prevent tyVars from leaking into containing scope
1303                        GuardScope( scopeTyVars );
1304                }
1305
1306                void Pass2::premutate( UnionDecl * ) {
1307                        // prevent tyVars from leaking into containing scope
1308                        GuardScope( scopeTyVars );
1309                }
1310
1311                void Pass2::premutate( TraitDecl * ) {
1312                        // prevent tyVars from leaking into containing scope
1313                        GuardScope( scopeTyVars );
1314                }
1315
1316                void Pass2::premutate( TypeDecl *typeDecl ) {
1317                        addToTyVarMap( typeDecl, scopeTyVars );
1318                }
1319
1320                void Pass2::premutate( PointerType *pointerType ) {
1321                        GuardScope( scopeTyVars );
1322                        makeTyVarMap( pointerType, scopeTyVars );
1323                }
1324
1325                void Pass2::premutate( FunctionType *funcType ) {
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345                        GuardScope( scopeTyVars );
1346                        makeTyVarMap( funcType, scopeTyVars );
1347
1348                        // move polymorphic return type to parameter list
1349                        if ( isDynRet( funcType ) ) {
1350                                ObjectDecl *ret = strict_dynamic_cast< ObjectDecl* >( funcType->returnVals.front() );
1351                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1352                                funcType->parameters.insert( funcType->parameters.begin(), ret );
1353                                funcType->returnVals.erase(funcType->returnVals.begin());
1354                                ret->set_init( nullptr ); // xxx - memory leak?
1355                        }
1356
1357                        // create a list of parameters after adding new ones
1358                        std::vector<DeclarationWithType *> newParams;
1359                        std::vector<DeclarationWithType *> inferredParams;
1360
1361                        // reserve some memory for these vectors
1362                        // Number of elements needed should be somewhat linear with the number of parameters / forall
1363                        // "somewhat linear" == 2X
1364                        newParams.reserve(funcType->parameters.size() * 2 + funcType->forall.size() * 2);
1365                        inferredParams.reserve(funcType->forall.size() * 2);
1366
1367                        // size/align/offset parameters may not be used in body, pass along with unused attribute.
1368                        ObjectDecl newObj( "", Type::StorageClasses(), LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0,
1369                                           { new Attribute( "unused" ) } );
1370                        ObjectDecl newPtr( "", Type::StorageClasses(), LinkageSpec::C, 0,
1371                                           new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1372
1373                        // We do this several time, create a functor for it
1374                        auto pushObj = [&newObj, &newParams]( const std::string & name ) {
1375                                auto parm = newObj.clone();
1376                                parm->set_name( name );
1377                                newParams.push_back( parm );
1378                        };
1379
1380                        // add size/align and assertions for type parameters to parameter list
1381                        for ( auto tyParm : funcType->forall ) {
1382                                // add all size and alignment parameters to parameter list
1383                                if ( tyParm->isComplete() ) {
1384                                        TypeInstType parmType( Type::Qualifiers(), tyParm->get_name(), tyParm );
1385                                        std::string parmName = mangleType( &parmType );
1386                                        pushObj( sizeofName( parmName ) );
1387                                        pushObj( alignofName( parmName ) );
1388                                }
1389                                // move all assertions into parameter list
1390                                // move all assertions into parameter list
1391                                for ( auto assert : tyParm->assertions ) {
1392                                        // assertion parameters may not be used in body, pass along with unused attribute.
1393                                        assert->attributes.push_back( new Attribute( "unused" ) );
1394                                        inferredParams.push_back( assert );
1395                                }
1396                                tyParm->assertions.clear();
1397                        }
1398
1399                        // add size/align for generic parameter types to parameter list
1400                        std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1401                        for ( DeclarationWithType * fnParm : funcType->parameters )
1402                        {
1403                                Type *polyType = isPolyType( fnParm->get_type(), scopeTyVars );
1404                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) )
1405                                {
1406                                        std::string typeName = mangleType( polyType );
1407                                        if ( seenTypes.count( typeName ) ) continue;
1408
1409                                        pushObj( sizeofName ( typeName ) );
1410                                        pushObj( alignofName( typeName ) );
1411
1412                                        if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyType ) ) {
1413                                                // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1414                                                if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1415                                                        auto offset = newPtr.clone();
1416                                                        offset->set_name( offsetofName( typeName ) );
1417                                                        newParams.push_back( offset );
1418                                                }
1419                                        }
1420                                        seenTypes.insert( typeName );
1421                                }
1422                        }
1423
1424                        // splice assertion parameters into parameter list
1425                        std::copy( inferredParams      , std::back_inserter(newParams) );
1426                        std::copy( funcType->parameters, std::back_inserter(newParams) );
1427
1428                        funcType->parameters.swap(newParams);
1429
1430                        addAdapters( funcType );
1431                }
1432
1433////////////////////////////////////////// PolyGenericCalculator ////////////////////////////////////////////////////
1434
1435                PolyGenericCalculator::PolyGenericCalculator()
1436                        : knownLayouts(), knownOffsets(), bufNamer( "_buf" ) {}
1437
1438                void PolyGenericCalculator::beginTypeScope( Type *ty ) {
1439                        GuardScope( scopeTyVars );
1440                        makeTyVarMap( ty, scopeTyVars );
1441                }
1442
1443                void PolyGenericCalculator::beginGenericScope() {
1444                        GuardScope( *this );
1445                }
1446
1447                void PolyGenericCalculator::premutate( ObjectDecl *objectDecl ) {
1448                        beginTypeScope( objectDecl->get_type() );
1449                }
1450
1451                void PolyGenericCalculator::premutate( FunctionDecl *functionDecl ) {
1452                        beginGenericScope();
1453
1454                        beginTypeScope( functionDecl->get_functionType() );
1455                }
1456
1457                void PolyGenericCalculator::premutate( TypedefDecl *typedefDecl ) {
1458                        assert(false);
1459                        beginTypeScope( typedefDecl->get_base() );
1460                }
1461
1462                void PolyGenericCalculator::premutate( TypeDecl * typeDecl ) {
1463                        addToTyVarMap( typeDecl, scopeTyVars );
1464                }
1465
1466                Declaration * PolyGenericCalculator::postmutate( TypeDecl *typeDecl ) {
1467                        if ( Type * base = typeDecl->base ) {
1468                                // add size/align variables for opaque type declarations
1469                                TypeInstType inst( Type::Qualifiers(), typeDecl->name, typeDecl );
1470                                std::string typeName = mangleType( &inst );
1471                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1472
1473                                ObjectDecl * sizeDecl = ObjectDecl::newObject( sizeofName( typeName ), layoutType, new SingleInit( new SizeofExpr( base->clone() ) ) );
1474                                ObjectDecl * alignDecl = ObjectDecl::newObject( alignofName( typeName ), layoutType->clone(), new SingleInit( new AlignofExpr( base->clone() ) ) );
1475
1476                                // ensure that the initializing sizeof/alignof exprs are properly mutated
1477                                sizeDecl->acceptMutator( *visitor );
1478                                alignDecl->acceptMutator( *visitor );
1479
1480                                // can't use makeVar, because it inserts into stmtsToAdd and TypeDecls can occur at global scope
1481                                declsToAddAfter.push_back( alignDecl );
1482                                // replace with sizeDecl
1483                                return sizeDecl;
1484                        }
1485                        return typeDecl;
1486                }
1487
1488                void PolyGenericCalculator::premutate( PointerType *pointerType ) {
1489                        beginTypeScope( pointerType );
1490                }
1491
1492                void PolyGenericCalculator::premutate( FunctionType *funcType ) {
1493                        beginTypeScope( funcType );
1494
1495                        // make sure that any type information passed into the function is accounted for
1496                        for ( auto fnParm : funcType->parameters ) {
1497                                // condition here duplicates that in Pass2::mutate( FunctionType* )
1498                                Type *polyType = isPolyType( fnParm->get_type(), scopeTyVars );
1499                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1500                                        knownLayouts.insert( mangleType( polyType ) );
1501                                }
1502                        }
1503                }
1504
1505                /// converts polymorphic type T into a suitable monomorphic representation, currently: __attribute__((aligned(8)) char[size_T]
1506                Type * polyToMonoType( Type * declType ) {
1507                        Type * charType = new BasicType( Type::Qualifiers(), BasicType::Kind::Char);
1508                        Expression * size = new NameExpr( sizeofName( mangleType(declType) ) );
1509                        Attribute * aligned = new Attribute( "aligned", std::list<Expression*>{ new ConstantExpr( Constant::from_int(8) ) } );
1510                        return new ArrayType( Type::Qualifiers(), charType, size,
1511                                true, false, std::vector< Attribute * >{ aligned } );
1512                }
1513
1514                void PolyGenericCalculator::mutateMembers( AggregateDecl * aggrDecl ) {
1515                        std::set< std::string > genericParams;
1516                        for ( TypeDecl * td : aggrDecl->parameters ) {
1517                                genericParams.insert( td->name );
1518                        }
1519                        for ( Declaration * decl : aggrDecl->members ) {
1520                                if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( decl ) ) {
1521                                        Type * ty = replaceTypeInst( field->type, env );
1522                                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( ty ) ) {
1523                                                // do not try to monomorphize generic parameters
1524                                                if ( scopeTyVars.find( typeInst->get_name() ) != scopeTyVars.end() && ! genericParams.count( typeInst->name ) ) {
1525                                                        // polymorphic aggregate members should be converted into monomorphic members.
1526                                                        // Using char[size_T] here respects the expected sizing rules of an aggregate type.
1527                                                        Type * newType = polyToMonoType( field->type );
1528                                                        delete field->type;
1529                                                        field->type = newType;
1530                                                }
1531                                        }
1532                                }
1533                        }
1534                }
1535
1536                void PolyGenericCalculator::premutate( StructDecl * structDecl ) {
1537                        mutateMembers( structDecl );
1538                }
1539
1540                void PolyGenericCalculator::premutate( UnionDecl * unionDecl ) {
1541                        mutateMembers( unionDecl );
1542                }
1543
1544                void PolyGenericCalculator::premutate( DeclStmt *declStmt ) {
1545                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1546                                if ( findGeneric( objectDecl->get_type() ) ) {
1547                                        // change initialization of a polymorphic value object to allocate via a VLA
1548                                        // (alloca was previously used, but can't be safely used in loops)
1549                                        ObjectDecl *newBuf = ObjectDecl::newObject( bufNamer.newName(), polyToMonoType( objectDecl->type ), nullptr );
1550                                        stmtsToAddBefore.push_back( new DeclStmt( newBuf ) );
1551
1552                                        delete objectDecl->get_init();
1553                                        objectDecl->set_init( new SingleInit( new VariableExpr( newBuf ) ) );
1554                                }
1555                        }
1556                }
1557
1558                /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1559                long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1560                        long i = 0;
1561                        for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1562                                if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1563
1564                                if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1565                                        if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1566                                             || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1567                                        else continue;
1568                                } else return i;
1569                        }
1570                        return -1;
1571                }
1572
1573                /// Returns an index expression into the offset array for a type
1574                Expression *makeOffsetIndex( Type *objectType, long i ) {
1575                        ConstantExpr *fieldIndex = new ConstantExpr( Constant::from_ulong( i ) );
1576                        UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1577                        fieldOffset->get_args().push_back( new NameExpr( offsetofName( mangleType( objectType ) ) ) );
1578                        fieldOffset->get_args().push_back( fieldIndex );
1579                        return fieldOffset;
1580                }
1581
1582                Expression *PolyGenericCalculator::postmutate( MemberExpr *memberExpr ) {
1583                        // only mutate member expressions for polymorphic types
1584                        int tyDepth;
1585                        Type *objectType = hasPolyBase( memberExpr->aggregate->result, scopeTyVars, &tyDepth );
1586                        if ( ! objectType ) return memberExpr;
1587                        findGeneric( objectType ); // ensure layout for this type is available
1588
1589                        // replace member expression with dynamically-computed layout expression
1590                        Expression *newMemberExpr = nullptr;
1591                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1592                                // look up offset index
1593                                long i = findMember( memberExpr->member, structType->baseStruct->members );
1594                                if ( i == -1 ) return memberExpr;
1595
1596                                // replace member expression with pointer to base plus offset
1597                                UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1598                                Expression * aggr = memberExpr->aggregate->clone();
1599                                delete aggr->env; // xxx - there's a problem with keeping the env for some reason, so for now just get rid of it
1600                                aggr->env = nullptr;
1601                                fieldLoc->get_args().push_back( aggr );
1602                                fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1603                                fieldLoc->set_result( memberExpr->result->clone() );
1604                                newMemberExpr = fieldLoc;
1605                        } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1606                                // union members are all at offset zero, so just use the aggregate expr
1607                                Expression * aggr = memberExpr->aggregate->clone();
1608                                delete aggr->env; // xxx - there's a problem with keeping the env for some reason, so for now just get rid of it
1609                                aggr->env= nullptr;
1610                                newMemberExpr = aggr;
1611                                newMemberExpr->result = memberExpr->result->clone();
1612                        } else return memberExpr;
1613                        assert( newMemberExpr );
1614
1615                        // Must apply the generic substitution to the member type to handle cases where the member is a generic parameter substituted by a known concrete type, e.g.
1616                        //   forall(otype T) struct Box { T x; }
1617                        //   forall(otype T) f() {
1618                        //     Box(T *) b; b.x;
1619                        //   }
1620                        // TODO: memberExpr->result should be exactly memberExpr->member->get_type() after substitution, so it doesn't seem like it should be necessary to apply the substitution manually. For some reason this is not currently the case. This requires more investigation.
1621                        Type *memberType = memberExpr->member->get_type()->clone();
1622                        TypeSubstitution sub = objectType->genericSubstitution();
1623                        sub.apply( memberType );
1624                        if ( ! isPolyType( memberType, scopeTyVars ) ) {
1625                                // 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
1626                                CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1627                                UntypedExpr *derefExpr = UntypedExpr::createDeref( ptrCastExpr );
1628                                newMemberExpr = derefExpr;
1629                        }
1630
1631                        delete memberType;
1632                        delete memberExpr;
1633                        return newMemberExpr;
1634                }
1635
1636                void PolyGenericCalculator::premutate( AddressExpr * addrExpr ) {
1637                        GuardValue( addrMember );
1638                        // is the argument a MemberExpr before mutating?
1639                        addrMember = dynamic_cast< MemberExpr * >( addrExpr->arg );
1640                }
1641
1642                Expression * PolyGenericCalculator::postmutate( AddressExpr * addrExpr ) {
1643                        if ( addrMember && addrMember != addrExpr->arg ) {
1644                                // arg was a MemberExpr and has been mutated
1645                                if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( addrExpr->arg ) ) {
1646                                        if ( InitTweak::getFunctionName( untyped ) == "?+?" ) {
1647                                                // MemberExpr was converted to pointer+offset, and it is not valid C to take the address of an addition, so strip the address-of
1648                                                // TODO: should  addrExpr->arg->result be changed to addrExpr->result?
1649                                                Expression * ret = addrExpr->arg;
1650                                                addrExpr->arg = nullptr;
1651                                                std::swap( addrExpr->env, ret->env );
1652                                                delete addrExpr;
1653                                                return ret;
1654                                        }
1655                                }
1656                        }
1657                        return addrExpr;
1658                }
1659
1660                ObjectDecl *PolyGenericCalculator::makeVar( const std::string &name, Type *type, Initializer *init ) {
1661                        ObjectDecl *newObj = new ObjectDecl( name, Type::StorageClasses(), LinkageSpec::C, nullptr, type, init );
1662                        stmtsToAddBefore.push_back( new DeclStmt( newObj ) );
1663                        return newObj;
1664                }
1665
1666                void PolyGenericCalculator::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1667                        for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1668                                if ( findGeneric( *param ) ) {
1669                                        // push size/align vars for a generic parameter back
1670                                        std::string paramName = mangleType( *param );
1671                                        layoutCall->get_args().push_back( new NameExpr( sizeofName( paramName ) ) );
1672                                        layoutCall->get_args().push_back( new NameExpr( alignofName( paramName ) ) );
1673                                } else {
1674                                        layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1675                                        layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1676                                }
1677                        }
1678                }
1679
1680                /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
1681                bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
1682                        bool hasDynamicLayout = false;
1683
1684                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1685                        std::list< Expression* >::const_iterator typeParam = typeParams.begin();
1686                        for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
1687                                // skip non-otype parameters
1688                                if ( ! (*baseParam)->isComplete() ) continue;
1689                                TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
1690                                assert( typeExpr && "all otype parameters should be type expressions" );
1691
1692                                Type *type = typeExpr->get_type();
1693                                out.push_back( type );
1694                                if ( isPolyType( type ) ) hasDynamicLayout = true;
1695                        }
1696                        assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
1697
1698                        return hasDynamicLayout;
1699                }
1700
1701                bool PolyGenericCalculator::findGeneric( Type *ty ) {
1702                        ty = replaceTypeInst( ty, env );
1703
1704                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( ty ) ) {
1705                                if ( scopeTyVars.find( typeInst->get_name() ) != scopeTyVars.end() ) {
1706                                        // NOTE assumes here that getting put in the scopeTyVars included having the layout variables set
1707                                        return true;
1708                                }
1709                                return false;
1710                        } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
1711                                // check if this type already has a layout generated for it
1712                                std::string typeName = mangleType( ty );
1713                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1714
1715                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1716                                std::list< Type* > otypeParams;
1717                                if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
1718
1719                                // insert local variables for layout and generate call to layout function
1720                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1721                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1722
1723                                int n_members = structTy->get_baseStruct()->get_members().size();
1724                                if ( n_members == 0 ) {
1725                                        // all empty structs have the same layout - size 1, align 1
1726                                        makeVar( sizeofName( typeName ), layoutType, new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1727                                        makeVar( alignofName( typeName ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1728                                        // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
1729                                } else {
1730                                        ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1731                                        ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1732                                        ObjectDecl *offsetVar = makeVar( offsetofName( typeName ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from_int( n_members ) ), false, false ) );
1733
1734                                        // generate call to layout function
1735                                        UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( structTy->get_baseStruct() ) ) );
1736                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1737                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1738                                        layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
1739                                        addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1740
1741                                        stmtsToAddBefore.push_back( new ExprStmt( layoutCall ) );
1742                                }
1743
1744                                return true;
1745                        } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
1746                                // check if this type already has a layout generated for it
1747                                std::string typeName = mangleType( ty );
1748                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1749
1750                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1751                                std::list< Type* > otypeParams;
1752                                if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
1753
1754                                // insert local variables for layout and generate call to layout function
1755                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1756                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1757
1758                                ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1759                                ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1760
1761                                // generate call to layout function
1762                                UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( unionTy->get_baseUnion() ) ) );
1763                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1764                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1765                                addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1766
1767                                stmtsToAddBefore.push_back( new ExprStmt( layoutCall ) );
1768
1769                                return true;
1770                        }
1771
1772                        return false;
1773                }
1774
1775                Expression * PolyGenericCalculator::genSizeof( Type* ty ) {
1776                        if ( ArrayType * aty = dynamic_cast<ArrayType *>(ty) ) {
1777                                // generate calculated size for possibly generic array
1778                                Expression * sizeofBase = genSizeof( aty->get_base() );
1779                                if ( ! sizeofBase ) return nullptr;
1780                                Expression * dim = aty->get_dimension();
1781                                aty->set_dimension( nullptr );
1782                                return makeOp( "?*?", sizeofBase, dim );
1783                        } else if ( findGeneric( ty ) ) {
1784                                // generate calculated size for generic type
1785                                return new NameExpr( sizeofName( mangleType( ty ) ) );
1786                        } else return nullptr;
1787                }
1788
1789                Expression *PolyGenericCalculator::postmutate( SizeofExpr *sizeofExpr ) {
1790                        Type *ty = sizeofExpr->get_isType() ?
1791                                sizeofExpr->get_type() : sizeofExpr->get_expr()->get_result();
1792
1793                        Expression * gen = genSizeof( ty );
1794                        if ( gen ) {
1795                                delete sizeofExpr;
1796                                return gen;
1797                        } else return sizeofExpr;
1798                }
1799
1800                Expression *PolyGenericCalculator::postmutate( AlignofExpr *alignofExpr ) {
1801                        Type *ty = alignofExpr->get_isType() ? alignofExpr->get_type() : alignofExpr->get_expr()->get_result();
1802                        if ( findGeneric( ty ) ) {
1803                                Expression *ret = new NameExpr( alignofName( mangleType( ty ) ) );
1804                                delete alignofExpr;
1805                                return ret;
1806                        }
1807                        return alignofExpr;
1808                }
1809
1810                Expression *PolyGenericCalculator::postmutate( OffsetofExpr *offsetofExpr ) {
1811                        // only mutate expressions for polymorphic structs/unions
1812                        Type *ty = offsetofExpr->get_type();
1813                        if ( ! findGeneric( ty ) ) return offsetofExpr;
1814
1815                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1816                                // replace offsetof expression by index into offset array
1817                                long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1818                                if ( i == -1 ) return offsetofExpr;
1819
1820                                Expression *offsetInd = makeOffsetIndex( ty, i );
1821                                delete offsetofExpr;
1822                                return offsetInd;
1823                        } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
1824                                // all union members are at offset zero
1825                                delete offsetofExpr;
1826                                return new ConstantExpr( Constant::from_ulong( 0 ) );
1827                        } else return offsetofExpr;
1828                }
1829
1830                Expression *PolyGenericCalculator::postmutate( OffsetPackExpr *offsetPackExpr ) {
1831                        StructInstType *ty = offsetPackExpr->get_type();
1832
1833                        Expression *ret = 0;
1834                        if ( findGeneric( ty ) ) {
1835                                // pull offset back from generated type information
1836                                ret = new NameExpr( offsetofName( mangleType( ty ) ) );
1837                        } else {
1838                                std::string offsetName = offsetofName( mangleType( ty ) );
1839                                if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
1840                                        // use the already-generated offsets for this type
1841                                        ret = new NameExpr( offsetName );
1842                                } else {
1843                                        knownOffsets.insert( offsetName );
1844
1845                                        std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
1846                                        Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1847
1848                                        // build initializer list for offset array
1849                                        std::vector< Initializer * > inits;
1850                                        for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
1851                                                if ( DeclarationWithType *memberDecl = dynamic_cast< DeclarationWithType* >( *member ) ) {
1852                                                        inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
1853                                                } else {
1854                                                        assertf( false, "Requesting offset of Non-DWT member: %s", toString( *member ).c_str() );
1855                                                }
1856                                        }
1857
1858                                        // build the offset array and replace the pack with a reference to it
1859                                        ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from_ulong( baseMembers.size() ) ), false, false ),
1860                                                        new ListInit( inits ) );
1861                                        ret = new VariableExpr( offsetArray );
1862                                }
1863                        }
1864
1865                        delete offsetPackExpr;
1866                        return ret;
1867                }
1868
1869                void PolyGenericCalculator::beginScope() {
1870                        knownLayouts.beginScope();
1871                        knownOffsets.beginScope();
1872                }
1873
1874                void PolyGenericCalculator::endScope() {
1875                        knownLayouts.endScope();
1876                        knownOffsets.endScope();
1877                }
1878
1879////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1880
1881                template< typename DeclClass >
1882                void Pass3::handleDecl( DeclClass * decl, Type * type ) {
1883                        GuardScope( scopeTyVars );
1884                        makeTyVarMap( type, scopeTyVars );
1885                        ScrubTyVars::scrubAll( decl );
1886                }
1887
1888                void Pass3::premutate( ObjectDecl * objectDecl ) {
1889                        handleDecl( objectDecl, objectDecl->type );
1890                }
1891
1892                void Pass3::premutate( FunctionDecl * functionDecl ) {
1893                        handleDecl( functionDecl, functionDecl->type );
1894                }
1895
1896                void Pass3::premutate( TypedefDecl * typedefDecl ) {
1897                        handleDecl( typedefDecl, typedefDecl->base );
1898                }
1899
1900                /// Strips the members from a generic aggregate
1901                void stripGenericMembers(AggregateDecl * decl) {
1902                        if ( ! decl->parameters.empty() ) decl->members.clear();
1903                }
1904
1905                void Pass3::premutate( StructDecl * structDecl ) {
1906                        stripGenericMembers( structDecl );
1907                }
1908
1909                void Pass3::premutate( UnionDecl * unionDecl ) {
1910                        stripGenericMembers( unionDecl );
1911                }
1912
1913                void Pass3::premutate( TypeDecl * typeDecl ) {
1914                        addToTyVarMap( typeDecl, scopeTyVars );
1915                }
1916
1917                void Pass3::premutate( PointerType * pointerType ) {
1918                        GuardScope( scopeTyVars );
1919                        makeTyVarMap( pointerType, scopeTyVars );
1920                }
1921
1922                void Pass3::premutate( FunctionType * functionType ) {
1923                        GuardScope( scopeTyVars );
1924                        makeTyVarMap( functionType, scopeTyVars );
1925                }
1926        } // anonymous namespace
1927} // namespace GenPoly
1928
1929// Local Variables: //
1930// tab-width: 4 //
1931// mode: c++ //
1932// compile-command: "make install" //
1933// End: //
Note: See TracBrowser for help on using the repository browser.