source: src/GenPoly/Box.cc@ 33e6a2cc

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 33e6a2cc was 4067aa8, checked in by Aaron Moss <a3moss@…>, 10 years ago

Fix non-polymorphic members of polymorphic types (general case of Thierry's pointer bug)

  • Property mode set to 100644
File size: 69.0 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 <set>
17#include <stack>
18#include <string>
19#include <iterator>
20#include <algorithm>
21#include <cassert>
22
23#include "Box.h"
24#include "InstantiateGeneric.h"
25#include "PolyMutator.h"
26#include "FindFunction.h"
27#include "ScrubTyVars.h"
28
29#include "Parser/ParseNode.h"
30
31#include "SynTree/Constant.h"
32#include "SynTree/Type.h"
33#include "SynTree/Expression.h"
34#include "SynTree/Initializer.h"
35#include "SynTree/Statement.h"
36#include "SynTree/Mutator.h"
37
38#include "ResolvExpr/TypeEnvironment.h"
39#include "ResolvExpr/TypeMap.h"
40#include "ResolvExpr/typeops.h"
41
42#include "SymTab/Mangler.h"
43
44#include "Common/SemanticError.h"
45#include "Common/UniqueName.h"
46#include "Common/utility.h"
47
48#include <ext/functional> // temporary
49
50namespace GenPoly {
51 namespace {
52 const std::list<Label> noLabels;
53
54 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
55
56 /// 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
57 class Pass1 : public PolyMutator {
58 public:
59 Pass1();
60 virtual Expression *mutate( ApplicationExpr *appExpr );
61 virtual Expression *mutate( AddressExpr *addrExpr );
62 virtual Expression *mutate( UntypedExpr *expr );
63 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
64 virtual TypeDecl *mutate( TypeDecl *typeDecl );
65 virtual Expression *mutate( CommaExpr *commaExpr );
66 virtual Expression *mutate( ConditionalExpr *condExpr );
67 virtual Statement * mutate( ReturnStmt *returnStmt );
68 virtual Type *mutate( PointerType *pointerType );
69 virtual Type * mutate( FunctionType *functionType );
70
71 virtual void doBeginScope();
72 virtual void doEndScope();
73 private:
74 /// Makes a new temporary array holding the offsets of the fields of `type`, and returns a new variable expression referencing it
75 Expression *makeOffsetArray( StructInstType *type );
76 /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
77 void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
78 /// passes extra type parameters into a polymorphic function application
79 void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
80 /// wraps a function application with a new temporary for the out-parameter return value
81 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
82 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
83 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
84 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
85 /// If `doClone` is set to false, will not clone interior types
86 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
87 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
88 Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
89 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
90 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
91 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
92 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
93 /// Stores assignment operators from assertion list in local map of assignment operations
94 void findAssignOps( const std::list< TypeDecl *> &forall );
95 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
96 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
97 /// Replaces intrinsic operator functions with their arithmetic desugaring
98 Expression *handleIntrinsics( ApplicationExpr *appExpr );
99 /// Inserts a new temporary variable into the current scope with an auto-generated name
100 ObjectDecl *makeTemporary( Type *type );
101
102 typedef std::map< std::string, DeclarationWithType *> AdapterMap;
103 std::map< std::string, DeclarationWithType *> assignOps;
104 ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps;
105 std::stack< AdapterMap > adapters;
106 DeclarationWithType *retval;
107 bool useRetval;
108 UniqueName tempNamer;
109 };
110
111 /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
112 class Pass2 : public PolyMutator {
113 public:
114 template< typename DeclClass >
115 DeclClass *handleDecl( DeclClass *decl, Type *type );
116 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
117 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
118 virtual TypeDecl *mutate( TypeDecl *typeDecl );
119 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
120 virtual Type *mutate( PointerType *pointerType );
121 virtual Type *mutate( FunctionType *funcType );
122 private:
123 void addAdapters( FunctionType *functionType );
124
125 std::map< UniqueId, std::string > adapterName;
126 };
127
128 /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
129 /// also fixes offsetof expressions.
130 class MemberExprFixer : public PolyMutator {
131 public:
132 template< typename DeclClass >
133 DeclClass *handleDecl( DeclClass *decl, Type *type );
134 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
135 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
136 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
137 virtual TypeDecl *mutate( TypeDecl *objectDecl );
138 virtual Statement *mutate( DeclStmt *declStmt );
139 virtual Type *mutate( PointerType *pointerType );
140 virtual Type *mutate( FunctionType *funcType );
141 virtual Expression *mutate( MemberExpr *memberExpr );
142 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
143 };
144
145 /// 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
146 class Pass3 : public PolyMutator {
147 public:
148 template< typename DeclClass >
149 DeclClass *handleDecl( DeclClass *decl, Type *type );
150 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
151 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
152 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
153 virtual TypeDecl *mutate( TypeDecl *objectDecl );
154 virtual Type *mutate( PointerType *pointerType );
155 virtual Type *mutate( FunctionType *funcType );
156 private:
157 };
158
159 } // anonymous namespace
160
161 void printAllNotBuiltin( const std::list< Declaration *>& translationUnit, std::ostream &os ) {
162 for ( std::list< Declaration *>::const_iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
163 if ( ! LinkageSpec::isBuiltin( (*i)->get_linkage() ) ) {
164 (*i)->print( os );
165 os << std::endl;
166 } // if
167 } // for
168 }
169
170 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
171 template< typename MutatorType >
172 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
173 bool seenIntrinsic = false;
174 SemanticError errors;
175 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
176 try {
177 if ( *i ) {
178 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
179 seenIntrinsic = true;
180 } else if ( seenIntrinsic ) {
181 seenIntrinsic = false; // break on this line when debugging for end of prelude
182 }
183
184 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
185 assert( *i );
186 } // if
187 } catch( SemanticError &e ) {
188 errors.append( e );
189 } // try
190 } // for
191 if ( ! errors.isEmpty() ) {
192 throw errors;
193 } // if
194 }
195
196 void box( std::list< Declaration *>& translationUnit ) {
197 Pass1 pass1;
198 Pass2 pass2;
199 MemberExprFixer memberFixer;
200 Pass3 pass3;
201 mutateTranslationUnit/*All*/( translationUnit, pass1 );
202 mutateTranslationUnit/*All*/( translationUnit, pass2 );
203 instantiateGeneric( translationUnit );
204 mutateTranslationUnit/*All*/( translationUnit, memberFixer );
205 mutateTranslationUnit/*All*/( translationUnit, pass3 );
206 }
207
208 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
209
210 namespace {
211 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
212 std::stringstream name;
213
214 // NOTE: this function previously used isPolyObj, which failed to produce
215 // the correct thing in some situations. It's not clear to me why this wasn't working.
216
217 // if the return type or a parameter type involved polymorphic types, then the adapter will need
218 // to take those polymorphic types as pointers. Therefore, there can be two different functions
219 // with the same mangled name, so we need to further mangle the names.
220 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
221 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
222 name << "P";
223 } else {
224 name << "M";
225 }
226 }
227 name << "_";
228 std::list< DeclarationWithType *> &paramList = function->get_parameters();
229 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
230 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
231 name << "P";
232 } else {
233 name << "M";
234 }
235 } // for
236 return name.str();
237 }
238
239 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
240 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
241 }
242
243 std::string makeAdapterName( const std::string &mangleName ) {
244 return "_adapter" + mangleName;
245 }
246
247 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {
248 adapters.push(AdapterMap());
249 }
250
251 /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
252 TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
253 if ( decl->get_name() == "?=?" ) {
254 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
255 if ( funType->get_parameters().size() == 2 ) {
256 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
257 if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
258 if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
259 if ( refType->get_name() == refType2->get_name() ) {
260 return refType;
261 } // if
262 } // if
263 } // if
264 } // if
265 } // if
266 } // if
267 } // if
268 return 0;
269 }
270
271 /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
272 /// Only picks assignments where neither parameter is cv-qualified
273 Type *isAssignment( DeclarationWithType *decl ) {
274 if ( decl->get_name() == "?=?" ) {
275 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
276 if ( funType->get_parameters().size() == 2 ) {
277 Type::Qualifiers defaultQualifiers;
278 Type *paramType1 = funType->get_parameters().front()->get_type();
279 if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
280 Type *paramType2 = funType->get_parameters().back()->get_type();
281 if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
282
283 if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
284 Type *baseType1 = pointerType->get_base();
285 if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
286 SymTab::Indexer dummy;
287 if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
288 return baseType1;
289 } // if
290 } // if
291 } // if
292 } // if
293 } // if
294 return 0;
295 }
296
297 void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
298 // what if a nested function uses an assignment operator?
299 // assignOps.clear();
300 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
301 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
302 std::string typeName;
303 if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
304 assignOps[ typeInst->get_name() ] = *assert;
305 } // if
306 } // for
307 } // for
308 }
309
310 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
311 // if this is a polymorphic assignment function, put it in the map for this scope
312 if ( Type *assignedType = isAssignment( functionDecl ) ) {
313 if ( ! dynamic_cast< TypeInstType* >( assignedType ) ) {
314 scopedAssignOps.insert( assignedType, functionDecl );
315 }
316 }
317
318 if ( functionDecl->get_statements() ) { // empty routine body ?
319 doBeginScope();
320 TyVarMap oldtyVars = scopeTyVars;
321 std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
322 DeclarationWithType *oldRetval = retval;
323 bool oldUseRetval = useRetval;
324
325 // process polymorphic return value
326 retval = 0;
327 if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
328 retval = functionDecl->get_functionType()->get_returnVals().front();
329
330 // give names to unnamed return values
331 if ( retval->get_name() == "" ) {
332 retval->set_name( "_retparm" );
333 retval->set_linkage( LinkageSpec::C );
334 } // if
335 } // if
336
337 FunctionType *functionType = functionDecl->get_functionType();
338 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
339 findAssignOps( functionDecl->get_functionType()->get_forall() );
340
341 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
342 std::list< FunctionType *> functions;
343 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
344 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
345 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
346 } // for
347 } // for
348 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
349 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
350 } // for
351
352 AdapterMap & adapters = Pass1::adapters.top();
353 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
354 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
355 if ( adapters.find( mangleName ) == adapters.end() ) {
356 std::string adapterName = makeAdapterName( mangleName );
357 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
358 } // if
359 } // for
360
361 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
362
363 scopeTyVars = oldtyVars;
364 assignOps = oldassignOps;
365 // std::cerr << "end FunctionDecl: ";
366 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
367 // std::cerr << i->first << " ";
368 // }
369 // std::cerr << "\n";
370 retval = oldRetval;
371 useRetval = oldUseRetval;
372 doEndScope();
373 } // if
374 return functionDecl;
375 }
376
377 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
378 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
379 return Mutator::mutate( typeDecl );
380 }
381
382 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
383 bool oldUseRetval = useRetval;
384 useRetval = false;
385 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
386 useRetval = oldUseRetval;
387 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
388 return commaExpr;
389 }
390
391 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
392 bool oldUseRetval = useRetval;
393 useRetval = false;
394 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
395 useRetval = oldUseRetval;
396 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
397 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
398 return condExpr;
399
400 }
401
402 Expression *Pass1::makeOffsetArray( StructInstType *ty ) {
403 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
404
405 // make a new temporary array
406 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
407 std::stringstream lenGen;
408 lenGen << baseMembers.size();
409 ConstantExpr *lenExpr = new ConstantExpr( Constant( offsetType->clone(), lenGen.str() ) );
410 ObjectDecl *arrayTemp = makeTemporary( new ArrayType( Type::Qualifiers(), offsetType, lenExpr, false, false ) );
411
412 // build initializer list for temporary
413 std::list< Initializer* > inits;
414 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
415 DeclarationWithType *memberDecl;
416 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
417 memberDecl = origMember->clone();
418 } else {
419 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
420 }
421 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
422 }
423 arrayTemp->set_init( new ListInit( inits ) );
424
425 // return variable pointing to temporary
426 return new VariableExpr( arrayTemp );
427 }
428
429 void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
430 Type *polyBase = hasPolyBase( parmType, exprTyVars );
431 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
432 std::string sizeName = sizeofName( polyBase );
433 if ( seenTypes.count( sizeName ) ) return;
434
435 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
436 arg++;
437 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
438 arg++;
439 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
440 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
441 arg = appExpr->get_args().insert( arg, makeOffsetArray( argBaseStructType ) );
442 arg++;
443 } else {
444 throw SemanticError( "Cannot pass non-struct type for generic struct" );
445 }
446 }
447
448 seenTypes.insert( sizeName );
449 }
450 }
451
452 void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
453 // pass size/align for type variables
454 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
455 ResolvExpr::EqvClass eqvClass;
456 assert( env );
457 if ( tyParm->second == TypeDecl::Any ) {
458 Type *concrete = env->lookup( tyParm->first );
459 if ( concrete ) {
460 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
461 arg++;
462 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
463 arg++;
464 } else {
465 throw SemanticError( "unbound type variable in application ", appExpr );
466 } // if
467 } // if
468 } // for
469
470 // add size/align for generic types to parameter list
471 if ( appExpr->get_function()->get_results().empty() ) return;
472 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
473 assert( funcType );
474
475 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
476 std::list< Expression* >::const_iterator fnArg = arg;
477 std::set< std::string > seenTypes; //< names for generic types we've seen
478
479 // a polymorphic return type may need to be added to the argument list
480 if ( polyRetType ) {
481 Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
482 passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
483 }
484
485 // add type information args for presently unseen types in parameter list
486 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
487 VariableExpr *fnArgBase = getBaseVar( *fnArg );
488 if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
489 passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
490 }
491 }
492
493 ObjectDecl *Pass1::makeTemporary( Type *type ) {
494 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
495 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
496 return newObj;
497 }
498
499 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
500 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
501 // if ( useRetval ) {
502 // assert( retval );
503 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
504 // arg++;
505 // } else {
506
507 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
508 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
509 // return values.
510 ObjectDecl *newObj = makeTemporary( retType->clone() );
511 Expression *paramExpr = new VariableExpr( newObj );
512
513 // If the type of the temporary is not polymorphic, box temporary by taking its address;
514 // otherwise the temporary is already boxed and can be used directly.
515 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
516 paramExpr = new AddressExpr( paramExpr );
517 } // if
518 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
519 arg++;
520 // Build a comma expression to call the function and emulate a normal return.
521 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
522 commaExpr->set_env( appExpr->get_env() );
523 appExpr->set_env( 0 );
524 return commaExpr;
525 // } // if
526 // return appExpr;
527 }
528
529 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
530 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
531 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
532 assert(paramType && "Aggregate parameters should be type expressions");
533 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
534 }
535 }
536
537 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
538 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
539 Type *concrete = env->lookup( typeInst->get_name() );
540 if ( concrete == 0 ) {
541 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
542 } // if
543 return concrete;
544 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
545 if ( doClone ) {
546 structType = structType->clone();
547 }
548 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
549 return structType;
550 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
551 if ( doClone ) {
552 unionType = unionType->clone();
553 }
554 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
555 return unionType;
556 }
557 return type;
558 }
559
560 Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
561 assert( env );
562 Type *concrete = replaceWithConcrete( appExpr, polyType );
563 // add out-parameter for return value
564 return addRetParam( appExpr, function, concrete, arg );
565 }
566
567 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
568 Expression *ret = appExpr;
569 if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
570 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
571 } // if
572 std::string mangleName = mangleAdapterName( function, tyVars );
573 std::string adapterName = makeAdapterName( mangleName );
574
575 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
576 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
577 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
578 appExpr->set_function( new NameExpr( adapterName ) );
579
580 return ret;
581 }
582
583 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
584 assert( ! arg->get_results().empty() );
585 if ( isPolyType( param, exprTyVars ) ) {
586 if ( isPolyType( arg->get_results().front() ) ) {
587 // if the argument's type is polymorphic, we don't need to box again!
588 return;
589 } else if ( arg->get_results().front()->get_isLvalue() ) {
590 // VariableExpr and MemberExpr are lvalues
591 arg = new AddressExpr( arg );
592 } else {
593 // use type computed in unification to declare boxed variables
594 Type * newType = param->clone();
595 if ( env ) env->apply( newType );
596 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
597 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
598 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
599 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
600 assign->get_args().push_back( new VariableExpr( newObj ) );
601 assign->get_args().push_back( arg );
602 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
603 arg = new AddressExpr( new VariableExpr( newObj ) );
604 } // if
605 } // if
606 }
607
608 /// cast parameters to polymorphic functions so that types are replaced with
609 /// void * if they are type parameters in the formal type.
610 /// this gets rid of warnings from gcc.
611 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
612 Type * newType = formal->clone();
613 if ( getFunctionType( newType ) ) {
614 newType = ScrubTyVars::scrub( newType, tyVars );
615 actual = new CastExpr( actual, newType );
616 } // if
617 }
618
619 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
620 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
621 assert( arg != appExpr->get_args().end() );
622 addCast( *arg, (*param)->get_type(), exprTyVars );
623 boxParam( (*param)->get_type(), *arg, exprTyVars );
624 } // for
625 }
626
627 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
628 std::list< Expression *>::iterator cur = arg;
629 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
630 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
631 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
632 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
633 Expression *newExpr = inferParam->second.expr->clone();
634 addCast( newExpr, (*assert)->get_type(), tyVars );
635 boxParam( (*assert)->get_type(), newExpr, tyVars );
636 appExpr->get_args().insert( cur, newExpr );
637 } // for
638 } // for
639 }
640
641 void makeRetParm( FunctionType *funcType ) {
642 DeclarationWithType *retParm = funcType->get_returnVals().front();
643
644 // make a new parameter that is a pointer to the type of the old return value
645 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
646 funcType->get_parameters().push_front( retParm );
647
648 // we don't need the return value any more
649 funcType->get_returnVals().clear();
650 }
651
652 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
653 // actually make the adapter type
654 FunctionType *adapter = adaptee->clone();
655 if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
656 makeRetParm( adapter );
657 } // if
658 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
659 return adapter;
660 }
661
662 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
663 assert( param );
664 assert( arg );
665 if ( isPolyType( realParam->get_type(), tyVars ) ) {
666 if ( ! isPolyType( arg->get_type() ) ) {
667 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
668 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
669 deref->get_results().push_back( arg->get_type()->clone() );
670 return deref;
671 } // if
672 } // if
673 return new VariableExpr( param );
674 }
675
676 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 ) {
677 UniqueName paramNamer( "_p" );
678 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
679 if ( (*param)->get_name() == "" ) {
680 (*param)->set_name( paramNamer.newName() );
681 (*param)->set_linkage( LinkageSpec::C );
682 } // if
683 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
684 } // for
685 }
686
687
688
689 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
690 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
691 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
692 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
693 adapteeDecl->set_name( "_adaptee" );
694 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
695 Statement *bodyStmt;
696
697 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
698 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
699 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
700 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
701 assert( tyArg != realType->get_forall().end() );
702 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
703 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
704 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
705 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
706 assert( assertArg != (*tyArg)->get_assertions().end() );
707 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
708 } // for
709 } // for
710
711 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
712 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
713 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
714 param++; // skip adaptee parameter
715 if ( realType->get_returnVals().empty() ) {
716 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
717 bodyStmt = new ExprStmt( noLabels, adapteeApp );
718 } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
719 if ( (*param)->get_name() == "" ) {
720 (*param)->set_name( "_ret" );
721 (*param)->set_linkage( LinkageSpec::C );
722 } // if
723 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
724 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
725 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
726 assign->get_args().push_back( deref );
727 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
728 assign->get_args().push_back( adapteeApp );
729 bodyStmt = new ExprStmt( noLabels, assign );
730 } else {
731 // adapter for a function that returns a monomorphic value
732 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
733 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
734 } // if
735 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
736 adapterBody->get_kids().push_back( bodyStmt );
737 std::string adapterName = makeAdapterName( mangleName );
738 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
739 }
740
741 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
742 // collect a list of function types passed as parameters or implicit parameters (assertions)
743 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
744 std::list< FunctionType *> functions;
745 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
746 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
747 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
748 } // for
749 } // for
750 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
751 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
752 } // for
753
754 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
755 // after applying substitutions, since two different parameter types may be unified to the same type
756 std::set< std::string > adaptersDone;
757
758 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
759 FunctionType *originalFunction = (*funType)->clone();
760 FunctionType *realFunction = (*funType)->clone();
761 std::string mangleName = SymTab::Mangler::mangle( realFunction );
762
763 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
764 // pre-substitution parameter function type.
765 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
766 adaptersDone.insert( adaptersDone.begin(), mangleName );
767
768 // apply substitution to type variables to figure out what the adapter's type should look like
769 assert( env );
770 env->apply( realFunction );
771 mangleName = SymTab::Mangler::mangle( realFunction );
772 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
773
774 AdapterMap & adapters = Pass1::adapters.top();
775 AdapterMap::iterator adapter = adapters.find( mangleName );
776 if ( adapter == adapters.end() ) {
777 // adapter has not been created yet in the current scope, so define it
778 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
779 adapter = adapters.insert( adapters.begin(), std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
780 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
781 } // if
782 assert( adapter != adapters.end() );
783
784 // add the appropriate adapter as a parameter
785 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
786 } // if
787 } // for
788 } // passAdapters
789
790 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
791 NameExpr *opExpr;
792 if ( isIncr ) {
793 opExpr = new NameExpr( "?+=?" );
794 } else {
795 opExpr = new NameExpr( "?-=?" );
796 } // if
797 UntypedExpr *addAssign = new UntypedExpr( opExpr );
798 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
799 addAssign->get_args().push_back( address->get_arg() );
800 } else {
801 addAssign->get_args().push_back( appExpr->get_args().front() );
802 } // if
803 addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
804 addAssign->get_results().front() = appExpr->get_results().front()->clone();
805 if ( appExpr->get_env() ) {
806 addAssign->set_env( appExpr->get_env() );
807 appExpr->set_env( 0 );
808 } // if
809 appExpr->get_args().clear();
810 delete appExpr;
811 return addAssign;
812 }
813
814 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
815 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
816 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
817 if ( varExpr->get_var()->get_name() == "?[?]" ) {
818 assert( ! appExpr->get_results().empty() );
819 assert( appExpr->get_args().size() == 2 );
820 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
821 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
822 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
823 UntypedExpr *ret = 0;
824 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
825 ret = new UntypedExpr( new NameExpr( "?+?" ) );
826 } // if
827 if ( baseType1 ) {
828 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
829 multiply->get_args().push_back( appExpr->get_args().back() );
830 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
831 ret->get_args().push_back( appExpr->get_args().front() );
832 ret->get_args().push_back( multiply );
833 } else if ( baseType2 ) {
834 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
835 multiply->get_args().push_back( appExpr->get_args().front() );
836 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
837 ret->get_args().push_back( multiply );
838 ret->get_args().push_back( appExpr->get_args().back() );
839 } // if
840 if ( baseType1 || baseType2 ) {
841 ret->get_results().push_front( appExpr->get_results().front()->clone() );
842 if ( appExpr->get_env() ) {
843 ret->set_env( appExpr->get_env() );
844 appExpr->set_env( 0 );
845 } // if
846 appExpr->get_args().clear();
847 delete appExpr;
848 return ret;
849 } // if
850 } else if ( varExpr->get_var()->get_name() == "*?" ) {
851 assert( ! appExpr->get_results().empty() );
852 assert( ! appExpr->get_args().empty() );
853 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
854 Expression *ret = appExpr->get_args().front();
855 delete ret->get_results().front();
856 ret->get_results().front() = appExpr->get_results().front()->clone();
857 if ( appExpr->get_env() ) {
858 ret->set_env( appExpr->get_env() );
859 appExpr->set_env( 0 );
860 } // if
861 appExpr->get_args().clear();
862 delete appExpr;
863 return ret;
864 } // if
865 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
866 assert( ! appExpr->get_results().empty() );
867 assert( appExpr->get_args().size() == 1 );
868 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
869 Type *tempType = appExpr->get_results().front()->clone();
870 if ( env ) {
871 env->apply( tempType );
872 } // if
873 ObjectDecl *newObj = makeTemporary( tempType );
874 VariableExpr *tempExpr = new VariableExpr( newObj );
875 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
876 assignExpr->get_args().push_back( tempExpr->clone() );
877 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
878 assignExpr->get_args().push_back( address->get_arg()->clone() );
879 } else {
880 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
881 } // if
882 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
883 return new CommaExpr( firstComma, tempExpr );
884 } // if
885 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
886 assert( ! appExpr->get_results().empty() );
887 assert( appExpr->get_args().size() == 1 );
888 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
889 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
890 } // if
891 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
892 assert( ! appExpr->get_results().empty() );
893 assert( appExpr->get_args().size() == 2 );
894 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
895 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
896 if ( baseType1 && baseType2 ) {
897 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
898 divide->get_args().push_back( appExpr );
899 divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
900 divide->get_results().push_front( appExpr->get_results().front()->clone() );
901 if ( appExpr->get_env() ) {
902 divide->set_env( appExpr->get_env() );
903 appExpr->set_env( 0 );
904 } // if
905 return divide;
906 } else if ( baseType1 ) {
907 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
908 multiply->get_args().push_back( appExpr->get_args().back() );
909 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
910 appExpr->get_args().back() = multiply;
911 } else if ( baseType2 ) {
912 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
913 multiply->get_args().push_back( appExpr->get_args().front() );
914 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
915 appExpr->get_args().front() = multiply;
916 } // if
917 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
918 assert( ! appExpr->get_results().empty() );
919 assert( appExpr->get_args().size() == 2 );
920 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
921 if ( baseType ) {
922 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
923 multiply->get_args().push_back( appExpr->get_args().back() );
924 multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
925 appExpr->get_args().back() = multiply;
926 } // if
927 } // if
928 return appExpr;
929 } // if
930 } // if
931 return 0;
932 }
933
934 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
935 // std::cerr << "mutate appExpr: ";
936 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
937 // std::cerr << i->first << " ";
938 // }
939 // std::cerr << "\n";
940 bool oldUseRetval = useRetval;
941 useRetval = false;
942 appExpr->get_function()->acceptMutator( *this );
943 mutateAll( appExpr->get_args(), *this );
944 useRetval = oldUseRetval;
945
946 assert( ! appExpr->get_function()->get_results().empty() );
947 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
948 assert( pointer );
949 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
950 assert( function );
951
952 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
953 return newExpr;
954 } // if
955
956 Expression *ret = appExpr;
957
958 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
959 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
960
961 TyVarMap exprTyVars;
962 makeTyVarMap( function, exprTyVars );
963 ReferenceToType *polyRetType = isPolyRet( function );
964
965 if ( polyRetType ) {
966 ret = addPolyRetParam( appExpr, function, polyRetType, arg );
967 } else if ( needsAdapter( function, scopeTyVars ) ) {
968 // std::cerr << "needs adapter: ";
969 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
970 // std::cerr << i->first << " ";
971 // }
972 // std::cerr << "\n";
973 // change the application so it calls the adapter rather than the passed function
974 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
975 } // if
976 arg = appExpr->get_args().begin();
977
978 passTypeVars( appExpr, polyRetType, arg, exprTyVars );
979 addInferredParams( appExpr, function, arg, exprTyVars );
980
981 arg = paramBegin;
982
983 boxParams( appExpr, function, arg, exprTyVars );
984
985 passAdapters( appExpr, function, exprTyVars );
986
987 return ret;
988 }
989
990 Expression *Pass1::mutate( UntypedExpr *expr ) {
991 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
992 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
993 if ( name->get_name() == "*?" ) {
994 Expression *ret = expr->get_args().front();
995 expr->get_args().clear();
996 delete expr;
997 return ret->acceptMutator( *this );
998 } // if
999 } // if
1000 } // if
1001 return PolyMutator::mutate( expr );
1002 }
1003
1004 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1005 assert( ! addrExpr->get_arg()->get_results().empty() );
1006
1007 bool needs = false;
1008 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1009 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1010 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1011 if ( name->get_name() == "*?" ) {
1012 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1013 assert( ! appExpr->get_function()->get_results().empty() );
1014 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1015 assert( pointer );
1016 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1017 assert( function );
1018 needs = needsAdapter( function, scopeTyVars );
1019 } // if
1020 } // if
1021 } // if
1022 } // if
1023 } // if
1024 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1025 if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
1026 Expression *ret = addrExpr->get_arg();
1027 delete ret->get_results().front();
1028 ret->get_results().front() = addrExpr->get_results().front()->clone();
1029 addrExpr->set_arg( 0 );
1030 delete addrExpr;
1031 return ret;
1032 } else {
1033 return addrExpr;
1034 } // if
1035 }
1036
1037 /// Wraps a function declaration in a new pointer-to-function variable expression
1038 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1039 // line below cloned from FixFunction.cc
1040 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1041 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1042 functionObj->set_mangleName( functionDecl->get_mangleName() );
1043 return new VariableExpr( functionObj );
1044 }
1045
1046 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1047 if ( retval && returnStmt->get_expr() ) {
1048 assert( ! returnStmt->get_expr()->get_results().empty() );
1049 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1050 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1051 // by this point, a cast expr on a polymorphic return value is redundant
1052 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1053 returnStmt->set_expr( castExpr->get_arg() );
1054 returnStmt->get_expr()->set_env( castExpr->get_env() );
1055 castExpr->set_env( 0 );
1056 castExpr->set_arg( 0 );
1057 delete castExpr;
1058 } //while
1059
1060 // find assignment operator for (polymorphic) return type
1061 ApplicationExpr *assignExpr = 0;
1062 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1063 // find assignment operator for type variable
1064 std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1065 if ( assignIter == assignOps.end() ) {
1066 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1067 } // if
1068 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1069 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1070 // find assignment operator for generic type
1071 DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1072 if ( ! functionDecl ) {
1073 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1074 }
1075
1076 // wrap it up in an application expression
1077 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1078 assignExpr->set_env( env->clone() );
1079
1080 // find each of its needed secondary assignment operators
1081 std::list< Expression* > &tyParams = refType->get_parameters();
1082 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1083 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1084 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1085 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1086 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1087
1088 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1089 assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1090 DeclarationWithType *actualDecl = asserts.front();
1091 TypeInstType *actualType = isTypeInstAssignment( actualDecl );
1092 assert( actualType && "First assertion of type with assertions should be assignment operator" );
1093 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1094 assert( formalTypeExpr && "type parameters must be type expressions" );
1095 Type *formalType = formalTypeExpr->get_type();
1096 assignExpr->get_env()->add( actualType->get_name(), formalType );
1097
1098 DeclarationWithType *assertAssign = 0;
1099 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1100 std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1101 if ( assertAssignIt == assignOps.end() ) {
1102 throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1103 }
1104 assertAssign = assertAssignIt->second;
1105 } else {
1106 assertAssign = scopedAssignOps.find( formalType );
1107 if ( ! assertAssign ) {
1108 throw SemanticError( "No assignment operation found for ", formalType );
1109 }
1110 }
1111
1112
1113 assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1114 = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1115 }
1116 }
1117 assert( assignExpr );
1118
1119 // replace return statement with appropriate assignment to out parameter
1120 Expression *retParm = new NameExpr( retval->get_name() );
1121 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1122 assignExpr->get_args().push_back( retParm );
1123 assignExpr->get_args().push_back( returnStmt->get_expr() );
1124 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1125 // } else {
1126 // useRetval = true;
1127 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1128 // useRetval = false;
1129 // } // if
1130 returnStmt->set_expr( 0 );
1131 } else {
1132 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1133 } // if
1134 return returnStmt;
1135 }
1136
1137 Type * Pass1::mutate( PointerType *pointerType ) {
1138 TyVarMap oldtyVars = scopeTyVars;
1139 makeTyVarMap( pointerType, scopeTyVars );
1140
1141 Type *ret = Mutator::mutate( pointerType );
1142
1143 scopeTyVars = oldtyVars;
1144 return ret;
1145 }
1146
1147 Type * Pass1::mutate( FunctionType *functionType ) {
1148 TyVarMap oldtyVars = scopeTyVars;
1149 makeTyVarMap( functionType, scopeTyVars );
1150
1151 Type *ret = Mutator::mutate( functionType );
1152
1153 scopeTyVars = oldtyVars;
1154 return ret;
1155 }
1156
1157 void Pass1::doBeginScope() {
1158 // push a copy of the current map
1159 adapters.push(adapters.top());
1160 scopedAssignOps.beginScope();
1161 }
1162
1163 void Pass1::doEndScope() {
1164 adapters.pop();
1165 scopedAssignOps.endScope();
1166 }
1167
1168////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1169
1170 void Pass2::addAdapters( FunctionType *functionType ) {
1171 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1172 std::list< FunctionType *> functions;
1173 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1174 Type *orig = (*arg)->get_type();
1175 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1176 (*arg)->set_type( orig );
1177 }
1178 std::set< std::string > adaptersDone;
1179 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1180 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1181 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1182 std::string adapterName = makeAdapterName( mangleName );
1183 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1184 adaptersDone.insert( adaptersDone.begin(), mangleName );
1185 }
1186 }
1187// deleteAll( functions );
1188 }
1189
1190 template< typename DeclClass >
1191 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1192 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1193
1194 return ret;
1195 }
1196
1197 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1198 return handleDecl( functionDecl, functionDecl->get_functionType() );
1199 }
1200
1201 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1202 return handleDecl( objectDecl, objectDecl->get_type() );
1203 }
1204
1205 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1206 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1207 if ( typeDecl->get_base() ) {
1208 return handleDecl( typeDecl, typeDecl->get_base() );
1209 } else {
1210 return Mutator::mutate( typeDecl );
1211 }
1212 }
1213
1214 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1215 return handleDecl( typedefDecl, typedefDecl->get_base() );
1216 }
1217
1218 Type * Pass2::mutate( PointerType *pointerType ) {
1219 TyVarMap oldtyVars = scopeTyVars;
1220 makeTyVarMap( pointerType, scopeTyVars );
1221
1222 Type *ret = Mutator::mutate( pointerType );
1223
1224 scopeTyVars = oldtyVars;
1225 return ret;
1226 }
1227
1228 Type *Pass2::mutate( FunctionType *funcType ) {
1229 TyVarMap oldtyVars = scopeTyVars;
1230 makeTyVarMap( funcType, scopeTyVars );
1231
1232 // move polymorphic return type to parameter list
1233 if ( isPolyRet( funcType ) ) {
1234 DeclarationWithType *ret = funcType->get_returnVals().front();
1235 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1236 funcType->get_parameters().push_front( ret );
1237 funcType->get_returnVals().pop_front();
1238 }
1239
1240 // add size/align and assertions for type parameters to parameter list
1241 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1242 std::list< DeclarationWithType *> inferredParams;
1243 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1244 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1245 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1246// ObjectDecl *newFunPtr = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 );
1247 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1248 ObjectDecl *sizeParm, *alignParm;
1249 // add all size and alignment parameters to parameter list
1250 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1251 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1252
1253 sizeParm = newObj.clone();
1254 sizeParm->set_name( sizeofName( &parmType ) );
1255 last = funcType->get_parameters().insert( last, sizeParm );
1256 ++last;
1257
1258 alignParm = newObj.clone();
1259 alignParm->set_name( alignofName( &parmType ) );
1260 last = funcType->get_parameters().insert( last, alignParm );
1261 ++last;
1262 }
1263 // move all assertions into parameter list
1264 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1265// *assert = (*assert)->acceptMutator( *this );
1266 inferredParams.push_back( *assert );
1267 }
1268 (*tyParm)->get_assertions().clear();
1269 }
1270
1271 // add size/align for generic parameter types to parameter list
1272 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1273 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1274 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1275 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1276 std::string sizeName = sizeofName( polyBase );
1277 if ( seenTypes.count( sizeName ) ) continue;
1278
1279 ObjectDecl *sizeParm, *alignParm, *offsetParm;
1280 sizeParm = newObj.clone();
1281 sizeParm->set_name( sizeName );
1282 last = funcType->get_parameters().insert( last, sizeParm );
1283 ++last;
1284
1285 alignParm = newObj.clone();
1286 alignParm->set_name( alignofName( polyBase ) );
1287 last = funcType->get_parameters().insert( last, alignParm );
1288 ++last;
1289
1290 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
1291 offsetParm = newPtr.clone();
1292 offsetParm->set_name( offsetofName( polyBase ) );
1293 last = funcType->get_parameters().insert( last, offsetParm );
1294 ++last;
1295 }
1296
1297 seenTypes.insert( sizeName );
1298 }
1299 }
1300
1301 // splice assertion parameters into parameter list
1302 funcType->get_parameters().splice( last, inferredParams );
1303 addAdapters( funcType );
1304 mutateAll( funcType->get_returnVals(), *this );
1305 mutateAll( funcType->get_parameters(), *this );
1306
1307 scopeTyVars = oldtyVars;
1308 return funcType;
1309 }
1310
1311////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
1312
1313 template< typename DeclClass >
1314 DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
1315 TyVarMap oldtyVars = scopeTyVars;
1316 makeTyVarMap( type, scopeTyVars );
1317
1318 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1319
1320 scopeTyVars = oldtyVars;
1321 return ret;
1322 }
1323
1324 ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
1325 return handleDecl( objectDecl, objectDecl->get_type() );
1326 }
1327
1328 DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
1329 return handleDecl( functionDecl, functionDecl->get_functionType() );
1330 }
1331
1332 TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
1333 return handleDecl( typedefDecl, typedefDecl->get_base() );
1334 }
1335
1336 TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
1337 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1338 return Mutator::mutate( typeDecl );
1339 }
1340
1341 Type * MemberExprFixer::mutate( PointerType *pointerType ) {
1342 TyVarMap oldtyVars = scopeTyVars;
1343 makeTyVarMap( pointerType, scopeTyVars );
1344
1345 Type *ret = Mutator::mutate( pointerType );
1346
1347 scopeTyVars = oldtyVars;
1348 return ret;
1349 }
1350
1351 Type * MemberExprFixer::mutate( FunctionType *functionType ) {
1352 TyVarMap oldtyVars = scopeTyVars;
1353 makeTyVarMap( functionType, scopeTyVars );
1354
1355 Type *ret = Mutator::mutate( functionType );
1356
1357 scopeTyVars = oldtyVars;
1358 return ret;
1359 }
1360
1361 Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
1362 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1363 if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
1364 // change initialization of a polymorphic value object
1365 // to allocate storage with alloca
1366 Type *declType = objectDecl->get_type();
1367 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
1368 alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
1369
1370 delete objectDecl->get_init();
1371
1372 std::list<Expression*> designators;
1373 objectDecl->set_init( new SingleInit( alloc, designators ) );
1374 }
1375 }
1376 return Mutator::mutate( declStmt );
1377 }
1378
1379 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1380 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1381 long i = 0;
1382 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1383 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1384
1385 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1386 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1387 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1388 else continue;
1389 } else return i;
1390 }
1391 return -1;
1392 }
1393
1394 /// Returns an index expression into the offset array for a type
1395 Expression *makeOffsetIndex( Type *objectType, long i ) {
1396 std::stringstream offset_namer;
1397 offset_namer << i;
1398 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1399 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1400 fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
1401 fieldOffset->get_args().push_back( fieldIndex );
1402 return fieldOffset;
1403 }
1404
1405 /// Returns an expression dereferenced n times
1406 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1407 for ( int i = 1; i < n; ++i ) {
1408 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1409 derefExpr->get_args().push_back( derefdVar );
1410 derefdVar = derefExpr;
1411 }
1412 return derefdVar;
1413 }
1414
1415 Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
1416 // mutate, exiting early if no longer MemberExpr
1417 Expression *expr = Mutator::mutate( memberExpr );
1418 memberExpr = dynamic_cast< MemberExpr* >( expr );
1419 if ( ! memberExpr ) return expr;
1420
1421 // get declaration for base struct, exiting early if not found
1422 int varDepth;
1423 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
1424 if ( ! varExpr ) return memberExpr;
1425 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1426 if ( ! objectDecl ) return memberExpr;
1427
1428 // only mutate member expressions for polymorphic types
1429 int tyDepth;
1430 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
1431 if ( ! objectType ) return memberExpr;
1432
1433 Expression *newMemberExpr = 0;
1434 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1435 // look up offset index
1436 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1437 if ( i == -1 ) return memberExpr;
1438
1439 // replace member expression with pointer to base plus offset
1440 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1441 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1442 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1443 newMemberExpr = fieldLoc;
1444 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1445 // union members are all at offset zero, so build appropriately-dereferenced variable
1446 newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
1447 } else return memberExpr;
1448 assert( newMemberExpr );
1449
1450 Type *memberType = memberExpr->get_member()->get_type();
1451 if ( ! isPolyType( memberType, scopeTyVars ) ) {
1452 // 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
1453 CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1454 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1455 derefExpr->get_args().push_back( ptrCastExpr );
1456 newMemberExpr = derefExpr;
1457 }
1458
1459 delete memberExpr;
1460 return newMemberExpr;
1461 }
1462
1463 Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
1464 // mutate, exiting early if no longer OffsetofExpr
1465 Expression *expr = Mutator::mutate( offsetofExpr );
1466 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1467 if ( ! offsetofExpr ) return expr;
1468
1469 // only mutate expressions for polymorphic structs/unions
1470 Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
1471 if ( ! ty ) return offsetofExpr;
1472
1473 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1474 // replace offsetof expression by index into offset array
1475 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1476 if ( i == -1 ) return offsetofExpr;
1477
1478 Expression *offsetInd = makeOffsetIndex( ty, i );
1479 delete offsetofExpr;
1480 return offsetInd;
1481 } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
1482 // all union members are at offset zero
1483 delete offsetofExpr;
1484 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
1485 } else return offsetofExpr;
1486 }
1487
1488////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1489
1490 template< typename DeclClass >
1491 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
1492 TyVarMap oldtyVars = scopeTyVars;
1493 makeTyVarMap( type, scopeTyVars );
1494
1495 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1496 ScrubTyVars::scrub( decl, scopeTyVars );
1497
1498 scopeTyVars = oldtyVars;
1499 return ret;
1500 }
1501
1502 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
1503 return handleDecl( objectDecl, objectDecl->get_type() );
1504 }
1505
1506 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
1507 return handleDecl( functionDecl, functionDecl->get_functionType() );
1508 }
1509
1510 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
1511 return handleDecl( typedefDecl, typedefDecl->get_base() );
1512 }
1513
1514 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
1515// Initializer *init = 0;
1516// std::list< Expression *> designators;
1517// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1518// if ( typeDecl->get_base() ) {
1519// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
1520// }
1521// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
1522
1523 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1524 return Mutator::mutate( typeDecl );
1525 }
1526
1527 Type * Pass3::mutate( PointerType *pointerType ) {
1528 TyVarMap oldtyVars = scopeTyVars;
1529 makeTyVarMap( pointerType, scopeTyVars );
1530
1531 Type *ret = Mutator::mutate( pointerType );
1532
1533 scopeTyVars = oldtyVars;
1534 return ret;
1535 }
1536
1537 Type * Pass3::mutate( FunctionType *functionType ) {
1538 TyVarMap oldtyVars = scopeTyVars;
1539 makeTyVarMap( functionType, scopeTyVars );
1540
1541 Type *ret = Mutator::mutate( functionType );
1542
1543 scopeTyVars = oldtyVars;
1544 return ret;
1545 }
1546 } // anonymous namespace
1547} // namespace GenPoly
1548
1549// Local Variables: //
1550// tab-width: 4 //
1551// mode: c++ //
1552// compile-command: "make install" //
1553// End: //
Note: See TracBrowser for help on using the repository browser.