source: src/GenPoly/Box.cc@ a9a259c

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 with_gc
Last change on this file since a9a259c was a172972, checked in by Rob Schluntz <rschlunt@…>, 10 years ago

Merge branch 'master' into ctor

Conflicts:

src/ResolvExpr/Resolver.cc

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