source: src/GenPoly/Box.cc@ 3da470c

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay gc_noraii jacob/cs343-translation jenkins-sandbox memory new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new string with_gc
Last change on this file since 3da470c was 8a34677, checked in by Aaron Moss <a3moss@…>, 9 years ago

Move layout function generation into renamed MemberExprFixer pass

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