source: src/SymTab/Mangler.cc @ ff5caaf

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since ff5caaf was ff5caaf, checked in by Aaron Moss <a3moss@…>, 5 years ago

Add environment-based-replacement mode to Mangler

  • Property mode set to 100644
File size: 17.2 KB
RevLine 
[0dd3a2f]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//
[8c49c0e]7// Mangler.cc --
[0dd3a2f]8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:40:29 2015
[201aeb9]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Sep 25 15:49:26 2017
13// Update Count     : 23
[0dd3a2f]14//
[30f9072]15#include "Mangler.h"
[0dd3a2f]16
[ff5caaf]17#include <algorithm>                     // for copy, transform
18#include <cassert>                       // for assert, assertf
19#include <functional>                    // for const_mem_fun_t, mem_fun
20#include <iterator>                      // for ostream_iterator, back_insert_ite...
21#include <list>                          // for _List_iterator, list, _List_const...
22#include <string>                        // for string, char_traits, operator<<
23
24#include "CodeGen/OperatorTable.h"       // for OperatorInfo, operatorLookup
[d7d9a60]25#include "Common/PassVisitor.h"
[ff5caaf]26#include "Common/SemanticError.h"        // for SemanticError
27#include "Common/utility.h"              // for toString
28#include "Parser/LinkageSpec.h"          // for Spec, isOverridable, AutoGen, Int...
29#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
30#include "SynTree/Declaration.h"         // for TypeDecl, DeclarationWithType
31#include "SynTree/Expression.h"          // for TypeExpr, Expression, operator<<
32#include "SynTree/Type.h"                // for Type, ReferenceToType, Type::Fora...
[51b7345]33
34namespace SymTab {
[d7d9a60]35        namespace Mangler {
36                namespace {
37                        /// Mangles names to a unique C identifier
[c0453ca3]38                        struct Mangler : public WithShortCircuiting, public WithVisitorRef<Mangler>, public WithGuards {
[d7d9a60]39                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams );
[ff5caaf]40                                Mangler( const ResolvExpr::TypeEnvironment& env );
[b8a52f5]41                                Mangler( const Mangler & ) = delete;
[d7d9a60]42
43                                void previsit( BaseSyntaxNode * ) { visit_children = false; }
44
45                                void postvisit( ObjectDecl * declaration );
46                                void postvisit( FunctionDecl * declaration );
47                                void postvisit( TypeDecl * declaration );
48
49                                void postvisit( VoidType * voidType );
50                                void postvisit( BasicType * basicType );
51                                void postvisit( PointerType * pointerType );
52                                void postvisit( ArrayType * arrayType );
53                                void postvisit( ReferenceType * refType );
54                                void postvisit( FunctionType * functionType );
55                                void postvisit( StructInstType * aggregateUseType );
56                                void postvisit( UnionInstType * aggregateUseType );
57                                void postvisit( EnumInstType * aggregateUseType );
58                                void postvisit( TypeInstType * aggregateUseType );
[f465f0e]59                                void postvisit( TraitInstType * inst );
[d7d9a60]60                                void postvisit( TupleType * tupleType );
61                                void postvisit( VarArgsType * varArgsType );
62                                void postvisit( ZeroType * zeroType );
63                                void postvisit( OneType * oneType );
[e73becf]64                                void postvisit( QualifiedType * qualType );
[d7d9a60]65
66                                std::string get_mangleName() { return mangleName.str(); }
67                          private:
68                                std::ostringstream mangleName;  ///< Mangled name being constructed
[ff5caaf]69                                typedef std::map< std::string, std::pair< std::string, int > > VarMapType;
[d7d9a60]70                                VarMapType varNums;             ///< Map of type variables to indices
[ff5caaf]71                                const ResolvExpr::TypeEnvironment* env;  ///< optional environment for substitutions
[d7d9a60]72                                int nextVarNum;                 ///< Next type variable index
73                                bool isTopLevel;                ///< Is the Mangler at the top level
74                                bool mangleOverridable;         ///< Specially mangle overridable built-in methods
75                                bool typeMode;                  ///< Produce a unique mangled name for a type
76                                bool mangleGenericParams;       ///< Include generic parameters in name mangling if true
[c0453ca3]77                                bool inFunctionType = false;    ///< Include type qualifiers if false.
[642bc83]78                                bool inQualifiedType = false;   ///< Add start/end delimiters around qualified type
[d7d9a60]79
[ff5caaf]80                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams, 
81                                        int nextVarNum, const ResolvExpr::TypeEnvironment* env, 
82                                        const VarMapType& varNums );
83
[d7d9a60]84                                void mangleDecl( DeclarationWithType *declaration );
85                                void mangleRef( ReferenceToType *refType, std::string prefix );
86
87                                void printQualifiers( Type *type );
88                        }; // Mangler
89                } // namespace
90
91                std::string mangle( BaseSyntaxNode * decl, bool mangleOverridable, bool typeMode, bool mangleGenericParams ) {
92                        PassVisitor<Mangler> mangler( mangleOverridable, typeMode, mangleGenericParams );
93                        maybeAccept( decl, mangler );
94                        return mangler.pass.get_mangleName();
[4aa0858]95                }
[d7d9a60]96
97                std::string mangleType( Type * ty ) {
98                        PassVisitor<Mangler> mangler( false, true, true );
99                        maybeAccept( ty, mangler );
100                        return mangler.pass.get_mangleName();
101                }
102
103                std::string mangleConcrete( Type * ty ) {
104                        PassVisitor<Mangler> mangler( false, false, false );
105                        maybeAccept( ty, mangler );
106                        return mangler.pass.get_mangleName();
[0dd3a2f]107                }
[d7d9a60]108
[ff5caaf]109                std::string mangleAssnKey( DeclarationWithType* decl, 
110                                const ResolvExpr::TypeEnvironment& env ) {
111                        PassVisitor<Mangler> mangler( env );
112                        maybeAccept( decl, mangler );
113                        return mangler.pass.get_mangleName();
114                }
115
[d7d9a60]116                namespace {
117                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams )
[ff5caaf]118                                : nextVarNum( 0 ), env(nullptr), isTopLevel( true ), 
119                                mangleOverridable( mangleOverridable ), typeMode( typeMode ), 
120                                mangleGenericParams( mangleGenericParams ) {}
121                       
122                        Mangler::Mangler( const ResolvExpr::TypeEnvironment& env )
123                                : nextVarNum( 0 ), env( &env ), isTopLevel( true ), mangleOverridable( false ),
124                                typeMode( false ), mangleGenericParams( true ) {}
125                       
126                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams, 
127                                int nextVarNum, const ResolvExpr::TypeEnvironment* env, 
128                                const VarMapType& varNums )
129                                : nextVarNum( nextVarNum ), varNums( varNums ), env( env ), isTopLevel( false ), 
130                                mangleOverridable( mangleOverridable ), typeMode( typeMode ), 
131                                mangleGenericParams( mangleGenericParams ) {}
[d7d9a60]132
133                        void Mangler::mangleDecl( DeclarationWithType * declaration ) {
134                                bool wasTopLevel = isTopLevel;
135                                if ( isTopLevel ) {
136                                        varNums.clear();
137                                        nextVarNum = 0;
138                                        isTopLevel = false;
139                                } // if
[642bc83]140                                mangleName << Encoding::manglePrefix;
[d7d9a60]141                                CodeGen::OperatorInfo opInfo;
142                                if ( operatorLookup( declaration->get_name(), opInfo ) ) {
[642bc83]143                                        mangleName << opInfo.outputName.size() << opInfo.outputName;
[d7d9a60]144                                } else {
[642bc83]145                                        mangleName << declaration->name.size() << declaration->name;
[d7d9a60]146                                } // if
147                                maybeAccept( declaration->get_type(), *visitor );
148                                if ( mangleOverridable && LinkageSpec::isOverridable( declaration->get_linkage() ) ) {
149                                        // want to be able to override autogenerated and intrinsic routines,
150                                        // so they need a different name mangling
151                                        if ( declaration->get_linkage() == LinkageSpec::AutoGen ) {
[642bc83]152                                                mangleName << Encoding::autogen;
[d7d9a60]153                                        } else if ( declaration->get_linkage() == LinkageSpec::Intrinsic ) {
[642bc83]154                                                mangleName << Encoding::intrinsic;
[d7d9a60]155                                        } else {
156                                                // if we add another kind of overridable function, this has to change
157                                                assert( false && "unknown overrideable linkage" );
158                                        } // if
159                                }
160                                isTopLevel = wasTopLevel;
161                        }
162
163                        void Mangler::postvisit( ObjectDecl * declaration ) {
164                                mangleDecl( declaration );
165                        }
166
167                        void Mangler::postvisit( FunctionDecl * declaration ) {
168                                mangleDecl( declaration );
169                        }
170
171                        void Mangler::postvisit( VoidType * voidType ) {
172                                printQualifiers( voidType );
[7804e2a]173                                mangleName << Encoding::void_t;
[d7d9a60]174                        }
175
176                        void Mangler::postvisit( BasicType * basicType ) {
177                                printQualifiers( basicType );
[0e73845]178                                assertf( basicType->get_kind() < BasicType::NUMBER_OF_BASIC_TYPES, "Unhandled basic type: %d", basicType->get_kind() );
[642bc83]179                                mangleName << Encoding::basicTypes[ basicType->get_kind() ];
[d7d9a60]180                        }
181
182                        void Mangler::postvisit( PointerType * pointerType ) {
183                                printQualifiers( pointerType );
[3f024c9]184                                // mangle void (*f)() and void f() to the same name to prevent overloading on functions and function pointers
[642bc83]185                                if ( ! dynamic_cast<FunctionType *>( pointerType->base ) ) mangleName << Encoding::pointer;
[1da22500]186                                maybeAccept( pointerType->base, *visitor );
[d7d9a60]187                        }
188
189                        void Mangler::postvisit( ArrayType * arrayType ) {
190                                // TODO: encode dimension
191                                printQualifiers( arrayType );
[642bc83]192                                mangleName << Encoding::array << "0";
[1da22500]193                                maybeAccept( arrayType->base, *visitor );
[d7d9a60]194                        }
195
196                        void Mangler::postvisit( ReferenceType * refType ) {
[c0453ca3]197                                // don't print prefix (e.g. 'R') for reference types so that references and non-references do not overload.
198                                // Further, do not print the qualifiers for a reference type (but do run printQualifers because of TypeDecls, etc.),
199                                // by pretending every reference type is a function parameter.
200                                GuardValue( inFunctionType );
201                                inFunctionType = true;
[d7d9a60]202                                printQualifiers( refType );
[1da22500]203                                maybeAccept( refType->base, *visitor );
[d7d9a60]204                        }
205
206                        namespace {
207                                inline std::list< Type* > getTypes( const std::list< DeclarationWithType* > decls ) {
208                                        std::list< Type* > ret;
209                                        std::transform( decls.begin(), decls.end(), std::back_inserter( ret ),
210                                                                        std::mem_fun( &DeclarationWithType::get_type ) );
211                                        return ret;
212                                }
213                        }
214
215                        void Mangler::postvisit( FunctionType * functionType ) {
216                                printQualifiers( functionType );
[642bc83]217                                mangleName << Encoding::function;
[c0453ca3]218                                // turn on inFunctionType so that printQualifiers does not print most qualifiers for function parameters,
219                                // since qualifiers on outermost parameter type do not differentiate function types, e.g.,
220                                // void (*)(const int) and void (*)(int) are the same type, but void (*)(const int *) and void (*)(int *) are different
221                                GuardValue( inFunctionType );
222                                inFunctionType = true;
[96812c0]223                                std::list< Type* > returnTypes = getTypes( functionType->returnVals );
[7804e2a]224                                if (returnTypes.empty()) mangleName << Encoding::void_t;
[d1e0979]225                                else acceptAll( returnTypes, *visitor );
[d7d9a60]226                                mangleName << "_";
[96812c0]227                                std::list< Type* > paramTypes = getTypes( functionType->parameters );
[d7d9a60]228                                acceptAll( paramTypes, *visitor );
[e35f30a]229                                mangleName << "_";
[d7d9a60]230                        }
231
232                        void Mangler::mangleRef( ReferenceToType * refType, std::string prefix ) {
233                                printQualifiers( refType );
234
[642bc83]235                                mangleName << prefix << refType->name.length() << refType->name;
[d7d9a60]236
237                                if ( mangleGenericParams ) {
[96812c0]238                                        std::list< Expression* >& params = refType->parameters;
[d7d9a60]239                                        if ( ! params.empty() ) {
240                                                mangleName << "_";
241                                                for ( std::list< Expression* >::const_iterator param = params.begin(); param != params.end(); ++param ) {
242                                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
[96812c0]243                                                        assertf(paramType, "Aggregate parameters should be type expressions: %s", toCString(*param));
244                                                        maybeAccept( paramType->type, *visitor );
[d7d9a60]245                                                }
246                                                mangleName << "_";
247                                        }
[e35f30a]248                                }
[d7d9a60]249                        }
250
251                        void Mangler::postvisit( StructInstType * aggregateUseType ) {
[7804e2a]252                                mangleRef( aggregateUseType, Encoding::struct_t );
[d7d9a60]253                        }
254
255                        void Mangler::postvisit( UnionInstType * aggregateUseType ) {
[7804e2a]256                                mangleRef( aggregateUseType, Encoding::union_t );
[d7d9a60]257                        }
258
259                        void Mangler::postvisit( EnumInstType * aggregateUseType ) {
[7804e2a]260                                mangleRef( aggregateUseType, Encoding::enum_t );
[d7d9a60]261                        }
262
263                        void Mangler::postvisit( TypeInstType * typeInst ) {
264                                VarMapType::iterator varNum = varNums.find( typeInst->get_name() );
265                                if ( varNum == varNums.end() ) {
[d8cb7df]266                                        mangleRef( typeInst, Encoding::type );
[d7d9a60]267                                } else {
268                                        printQualifiers( typeInst );
[0e761e40]269                                        // Note: Can't use name here, since type variable names do not actually disambiguate a function, e.g.
270                                        //   forall(dtype T) void f(T);
271                                        //   forall(dtype S) void f(S);
272                                        // are equivalent and should mangle the same way. This is accomplished by numbering the type variables when they
273                                        // are first found and prefixing with the appropriate encoding for the type class.
[0e73845]274                                        assertf( varNum->second.second < TypeDecl::NUMBER_OF_KINDS, "Unhandled type variable kind: %d", varNum->second.second );
[0e761e40]275                                        mangleName << Encoding::typeVariables[varNum->second.second] << varNum->second.first;
[d7d9a60]276                                } // if
277                        }
278
[f465f0e]279                        void Mangler::postvisit( TraitInstType * inst ) {
280                                printQualifiers( inst );
[642bc83]281                                mangleName << inst->name.size() << inst->name;
[f465f0e]282                        }
283
[d7d9a60]284                        void Mangler::postvisit( TupleType * tupleType ) {
285                                printQualifiers( tupleType );
[642bc83]286                                mangleName << Encoding::tuple << tupleType->types.size();
[d7d9a60]287                                acceptAll( tupleType->types, *visitor );
[8360977]288                        }
[d7d9a60]289
290                        void Mangler::postvisit( VarArgsType * varArgsType ) {
291                                printQualifiers( varArgsType );
[642bc83]292                                static const std::string vargs = "__builtin_va_list";
[d8cb7df]293                                mangleName << Encoding::type << vargs.size() << vargs;
[d7d9a60]294                        }
295
296                        void Mangler::postvisit( ZeroType * ) {
[642bc83]297                                mangleName << Encoding::zero;
[d7d9a60]298                        }
299
300                        void Mangler::postvisit( OneType * ) {
[642bc83]301                                mangleName << Encoding::one;
[d7d9a60]302                        }
303
[e73becf]304                        void Mangler::postvisit( QualifiedType * qualType ) {
[642bc83]305                                bool inqual = inQualifiedType;
306                                if (! inqual ) {
307                                        // N marks the start of a qualified type
308                                        inQualifiedType = true;
309                                        mangleName << Encoding::qualifiedTypeStart;
310                                }
[e73becf]311                                maybeAccept( qualType->parent, *visitor );
312                                maybeAccept( qualType->child, *visitor );
[642bc83]313                                if ( ! inqual ) {
314                                        // E marks the end of a qualified type
315                                        inQualifiedType = false;
316                                        mangleName << Encoding::qualifiedTypeEnd;
317                                }
[e73becf]318                        }
319
[d7d9a60]320                        void Mangler::postvisit( TypeDecl * decl ) {
[0e761e40]321                                // TODO: is there any case where mangling a TypeDecl makes sense? If so, this code needs to be
322                                // fixed to ensure that two TypeDecls mangle to the same name when they are the same type and vice versa.
323                                // Note: The current scheme may already work correctly for this case, I have not thought about this deeply
324                                // and the case has not yet come up in practice. Alternatively, if not then this code can be removed
325                                // aside from the assert false.
326                                assertf(false, "Mangler should not visit typedecl: %s", toCString(decl));
[0e73845]327                                assertf( decl->get_kind() < TypeDecl::NUMBER_OF_KINDS, "Unhandled type variable kind: %d", decl->get_kind() );
328                                mangleName << Encoding::typeVariables[ decl->get_kind() ] << ( decl->name.length() ) << decl->name;
[d7d9a60]329                        }
330
331                        __attribute__((unused)) void printVarMap( const std::map< std::string, std::pair< int, int > > &varMap, std::ostream &os ) {
332                                for ( std::map< std::string, std::pair< int, int > >::const_iterator i = varMap.begin(); i != varMap.end(); ++i ) {
333                                        os << i->first << "(" << i->second.first << "/" << i->second.second << ")" << std::endl;
[0dd3a2f]334                                } // for
[d7d9a60]335                        }
336
337                        void Mangler::printQualifiers( Type * type ) {
338                                // skip if not including qualifiers
339                                if ( typeMode ) return;
340                                if ( ! type->get_forall().empty() ) {
341                                        std::list< std::string > assertionNames;
[0e73845]342                                        int dcount = 0, fcount = 0, vcount = 0, acount = 0;
343                                        mangleName << Encoding::forall;
[d7d9a60]344                                        for ( Type::ForallList::iterator i = type->forall.begin(); i != type->forall.end(); ++i ) {
345                                                switch ( (*i)->get_kind() ) {
346                                                  case TypeDecl::Dtype:
347                                                        dcount++;
348                                                        break;
349                                                  case TypeDecl::Ftype:
350                                                        fcount++;
351                                                        break;
352                                                  case TypeDecl::Ttype:
353                                                        vcount++;
354                                                        break;
355                                                  default:
356                                                        assert( false );
357                                                } // switch
[ff5caaf]358                                                std::string varName;
359                                                // replace type with substitution name if environment is available and bound
360                                                if ( env ) {
361                                                        const EqvClass* varClass = env->lookup( (*i)->name );
362                                                        if ( varClass && varClass->type ) {
363                                                                PassVisitor<Mangler> sub_mangler(
364                                                                        mangleOverridable, typeMode, mangleGenericParams, nextVarNum, 
365                                                                        env, varNums );
366                                                                varClass->type->accept( sub_mangler );
367                                                                varName = std::string{"%"} + sub_mangler.pass.get_mangleName();
368                                                        }
369                                                }
370                                                // otherwise just give type numeric name
371                                                if ( varName.empty() ) {
372                                                        varName = std::to_string( nextVarNum++ );
373                                                }
374                                                varNums[ (*i)->name ] = std::make_pair( varName, (int)(*i)->get_kind() );
[d7d9a60]375                                                for ( std::list< DeclarationWithType* >::iterator assert = (*i)->assertions.begin(); assert != (*i)->assertions.end(); ++assert ) {
[ff5caaf]376                                                        PassVisitor<Mangler> sub_mangler( 
377                                                                mangleOverridable, typeMode, mangleGenericParams, nextVarNum, env, 
378                                                                varNums );
[d7d9a60]379                                                        (*assert)->accept( sub_mangler );
[ff5caaf]380                                                        assertionNames.push_back( sub_mangler.pass.get_mangleName() );
[0e73845]381                                                        acount++;
[d7d9a60]382                                                } // for
383                                        } // for
[0e73845]384                                        mangleName << dcount << "_" << fcount << "_" << vcount << "_" << acount << "_";
[d7d9a60]385                                        std::copy( assertionNames.begin(), assertionNames.end(), std::ostream_iterator< std::string >( mangleName, "" ) );
386                                        mangleName << "_";
387                                } // if
[c0453ca3]388                                if ( ! inFunctionType ) {
389                                        // these qualifiers do not distinguish the outermost type of a function parameter
390                                        if ( type->get_const() ) {
[642bc83]391                                                mangleName << Encoding::qualifiers.at(Type::Const);
[c0453ca3]392                                        } // if
393                                        if ( type->get_volatile() ) {
[642bc83]394                                                mangleName << Encoding::qualifiers.at(Type::Volatile);
[c0453ca3]395                                        } // if
396                                        // Removed due to restrict not affecting function compatibility in GCC
397                                        // if ( type->get_isRestrict() ) {
398                                        //      mangleName << "E";
399                                        // } // if
400                                        if ( type->get_atomic() ) {
[642bc83]401                                                mangleName << Encoding::qualifiers.at(Type::Atomic);
[c0453ca3]402                                        } // if
403                                }
[d7d9a60]404                                if ( type->get_mutex() ) {
[642bc83]405                                        mangleName << Encoding::qualifiers.at(Type::Mutex);
[d7d9a60]406                                } // if
407                                if ( type->get_lvalue() ) {
408                                        // mangle based on whether the type is lvalue, so that the resolver can differentiate lvalues and rvalues
[642bc83]409                                        mangleName << Encoding::qualifiers.at(Type::Lvalue);
[d7d9a60]410                                }
[c0453ca3]411
412                                if ( inFunctionType ) {
413                                        // turn off inFunctionType so that types can be differentiated for nested qualifiers
414                                        GuardValue( inFunctionType );
415                                        inFunctionType = false;
416                                }
[d7d9a60]417                        }
418                }       // namespace
419        } // namespace Mangler
[0dd3a2f]420} // namespace SymTab
421
422// Local Variables: //
423// tab-width: 4 //
424// mode: c++ //
425// compile-command: "make install" //
426// End: //
Note: See TracBrowser for help on using the repository browser.