This document was originally developed jointly by an informalindustry coalition consisting of (in alphabetical order) CodeSourcery,Compaq, EDG, HP, IBM, Intel, Red Hat, and SGI. Additional contributionswere provided by a variety of individuals. It is now developed as anopen-source project with contributions from a variety of individualsand companies. In this document, we specify the Application Binary Interface (ABI)for C++ programs: that is, the object code interfaces between differentuser-provided C++ program fragments and between those fragments andthe implementation-provided runtime and libraries. This includes thememory layout for C++ data objects, including both predefined anduser-defined data types, as well as internal compiler generatedobjects such as virtual tables. It also includes function callinginterfaces, exception handling interfaces, global naming, and variousobject code conventions. In general, this document is meant to serve as a generic specificationwhich can be used by C++ implementations on a variety of platforms.It does this by layering on top of a platform's base C ABI. However,it was originally written for the Itanium architecture, and some partsstill directly make Itanium-specific or 64-bit-specific assumptions.There is an ongoing project to restate the entire C++ ABI specificationin terms of portable C concepts that are defined in the C ABI. Inthe meantime, it is usually straightforward to recognize theseunportable assumptions and translate them appropriately, e.g. byreplacing a 64-bit pointer with a 32-bit pointer. This document is not an authoritative definition of the C++ ABI forany particular platform. Platform vendors retain the ultimate powerto define the C++ ABI for their platform. Platforms using this ABIfor C++ should declare that they do so, either unmodified or with acertain set of changes. While this ABI has generally stood up well, there are some parts of itthat are now seen as mistakes. This document includes severalrecommendations for platforms adopting this ABI with no need tointeroperate with existing C++ object code. These recommendationsappear as follows: Platforms adopting any of these recommendations should describe theexact changes they've made in their platform ABI documentation,as the set of recommendations in this document may change over time. The descriptions below make use of the following definitions: Note that the traversal may be preorder or postorder.Unless otherwise specified,preorder (derived classes before their bases) is intended. This definition, as applied to class types, is intended to be thecomplement of the definition in [class.temporary]p3 of types for whichan extra temporary is allowed when passing or returning a type. A typewhich is trivial for the purposes of the ABI will be passed and returnedaccording to the rules of the base C ABI, e.g. in registers; oftenthis has the effect of performing a trivial copy of the type. In general, a type is considered a POD for the purposes of layout ifit is a POD type (in the sense of ISO C++[basic.types]). However, atype is not considered to be a POD for the purpose of layout if it is: Being tied to the TC1 definition of POD does not prevent compilersfrom being fully compliant with later revisions. This ABI uses thedefinition of POD only to decide whether to allocate objects in thetail-padding of a base-class subobject. While the standards havebroadened the definition of POD over time, they have also forbiddenthe programmer from directly reading or writing the underlying bytesof a base-class subobject with, say,memcpy. Therefore,even in the most conservative interpretation, implementations mayfreely allocate objects in the tail padding of any class which wouldnot have been POD in C++98. This ABI is in compliance with that. Various representations specified by this ABI impose limitations onconforming user programs.These include, for the 64-bit Itanium ABI: This ABI specifies a number of type and function APIs supplementalto those required by the ISO C++ Standard.A header file named These APIs will be placed in a namespace In general,API objects defined as part of this ABI are assumed to be extern "C++".However, some (many?) are specified to be extern "C" if they: The objective of a full ABI is to allow arbitrary mixing of objectfiles produced by conforming implementations,by fully specifying thebinary interface of application programs.We do not fully achieve this objective. There are two principal reasons for this: Notwithstanding these problems,because this ABI does completely specify the data modeland certain library interfaces that inherently interact between objects(e.g. construction, destruction, and exceptions),it is our intent that interoperation of object files produced bydifferent compilers be possible in the following cases: Even these cases can fail if the compiler makes use ofimplementation-defined library interfaces to implement runtimefunctionality without explicit user reference,e.g. a software divide function.We can distinguish between: An implementation shall place its standard support library in a DSOnamed This ABI does not specify the treatment of export templates,as there are no working implementations to serve as models at this time.We hope to address this weakness in the future when implementationexperience is available. A number of other documents provide a basis on which this ABI is built,and are occasionally referenced herein: In what follows, we define the memory layout for C++ data objects.Specifically, for each type, we specify the following information aboutan object O of that type: For purposes internal to the specification,we also specify: The size and alignment of a type which is aPOD for thepurpose of layout is as specified by the base C ABI, with thefollowing provisos: Thedsize,nvsize, andnvalign of these types aredefined to be their ordinary size and alignment. These propertiesonly matter for non-empty class types that are used as base classes.We ignore tail padding for PODs because the standard before the resolutionofCWG issue 43 did not allow us to useit for anything else and because it sometimes permits faster copying of thetype. The basic ABI properties of data member pointer types are thoseof A data member pointer is represented as the data member's offset in bytesfrom the address point of an object of the base type, as a A null data member pointer is represented as an offset of Note that by Base-to-derived and derived-to-base conversions of a non-null data memberpointer can be performed by adding or subtracting (respectively) the staticoffset of the base within the derived class. The C++ standard does notpermit base-to-derived and derived-to-base conversions of member pointersto cross a Data member pointers that identify members of their class will alwaysstore non-negative offsets. Unfortunately, it is possible to applyconversions to a non-null data member pointer that will cause it tohold a negative offset. If this value is It is relatively difficult to demonstrate this defect in well-definedcode. It is possible to convert a member pointer to a derived classand then cast it back it to a different base class; if the second baseclass is stored after the first, the resulting offset will be negative.However, this cast has undefined behavior because the member is nolonger a member of a base or derived class of the member pointer's class.To demonstrate the defect, either an empty base class or an emptydata member must be involved. For example: Several different representions of member function pointers are in use.The standard representation relies on several assumptions about theplatform, such as that the low bit of a function pointer to a non-virtualmember function is always zero. For platforms where this is not reasonableto guarantee, an alternate representation must be used. One suchrepresentation, used on the 32-bit ARM architecture, is also described here. In all representations, the basic ABI properties of member functionpointer types are those of the following class, where A member function pointer for a non-virtual member function is representedwith In the standard representation, a member function pointer for a virtualfunction is represented with In both of these cases, In the standard representation, a null member function pointer isrepresented with The standard representation relies on some assumptions which aretrue for most platforms: However, there are exceptions. For example, on the 32-bit ARMarchitecture, the low bit of a function pointer determines whetherthe function begins in THUMB mode. Such platforms must use analternate representation. In the 32-bit ARM representation, the A member function pointer is null if Two member function pointers are equal if they are both null orif their corresponding values of Base-to-derived and derived-to-base conversions of a member functionpointer can be performed by adding or subtracting (respectively) thestatic offset of the base within the derived class to the stored A call is performed as follows: The benefit is that using the derived class virtual pointer as the baseclass virtual pointer will often save a load,and no adjustment to the It was thought that 2b would allow the compiler to avoidadjusting When B and C are declared, A is a primary base in each case, so althoughvcall offsets are allocated in the A-in-B and A-in-C vtables, no For each data component D (first the primary base of C, if any, thenthe non-primary, non-virtual direct base classes in declaration order,then the non-static data members and unnamed bit-fields in declarationorder), allocate as follows: There are two cases depending on If dsize(C) > 0, and the byte at offset dsize(C) - 1 is partially filled by a bit-field, and that bit-field is also a data member declared in C (but not in one of C's proper base classes), the next available bits are the unfilled bits at offset dsize(C) - 1. Otherwise, the next available bits are at offset dsize(C). Update align(C) to max (align(C), align(T)). Update align(C) to max (align(C), align(T')). In either case, update dsize(C) to include the last byte containing (part of) the bit-field, and update sizeof(C) to max(sizeof(C),dsize(C)). Start at offset dsize(C),incremented if necessary for alignmentto nvalign(D) for base classes orto align(D) for data members.Place D at this offset unless doing so would result in twocomponents (direct or indirect) of the same type having thesame offset.If such a component type conflict occurs,increment the candidate offset by nvalign(D)for base classes or by align(D) for data membersand try again,repeating until success occurs(which will occur no later than sizeof(C) rounded up to therequired alignment). If D is a base class, this step allocates only its non-virtualpart, i.e. excluding any direct or indirect virtual bases. If D is a base class, update sizeof(C) to max (sizeof(C),offset(D)+nvsize(D)).Otherwise, if D is a potentially-overlapping data member,update sizeof(C) to max (sizeof(C), offset(D)+max (nvsize(D), dsize(D))).Otherwise, if D is a data member,update sizeof(C) to max (sizeof(C), offset(D)+sizeof(D)). If D is a base class (not empty in this case),update dsize(C) to offset(D)+nvsize(D),and align(C) to max (align(C), nvalign(D)).If D is a potentially-overlapping data member,update dsize(C) to offset(D)+max (nvsize(D), dsize(D)),align(C) to max (align(C), align(D)).If D is any other data member,update dsize(C) to offset(D)+sizeof(D),align(C) to max (align(C), align(D)). Its allocation is similar to case (2) above,except that additional candidate offsets are considered beforestarting at dsize(C).First, attempt to place D at offset zero.If unsuccessful (due to a component type conflict),proceed with attempts at dsize(C) as for non-empty bases and members.As for that case, if there is a type conflict at dsize(C)(with alignment updated as necessary),increment the candidate offset by nvalign(D),and try again,repeating until success occurs. Once offset(D) has been chosen, update sizeof(C) to max (sizeof(C),offset(D)+sizeof(D)), and update align(C) to max (alignof(C),nvalign(D)) for a base class or max (alignof(C), align(D)) fora data member. Since D is empty, no update of dsize(C) is needed. After all such components have been allocated, set nvalign(C) = align(C) and nvsize(C) = sizeof(C). The values of nvalign(C) and nvsize(C) will not change during virtual base allocation. Note that nvsize(C) need not be a multiple of nvalign(C). Avirtual table (vtable) is a table of information usedto dispatch virtual functions,to access virtual base class subobjects,and to access information for runtime type identification (RTTI).Each class that has virtual member functions or virtual baseshas an associated set of virtual tables.There may be multiple virtual tables for a particular class,if it is used as a base class for other classes.However, the virtual table pointers within all the objects (instances)of a particular most-derived class point to the same set of virtual tables. A virtual table consists of a sequence of offsets, data pointers,and function pointers, as well as structures composed of such items.We will describe below the sequence of such items.Their offsets within the virtual table are determined by that allocationsequence and the natural ABI size and alignment,just as a data struct would be. In particular: In general, what we consider the address of a virtual table(i.e. the address contained in objects pointing to a virtual table)may not be the beginning of the virtual table.We call it theaddress point of the virtual table.The virtual table may therefore contain components at either positive ornegative offsets from its address point. This section describes the usage and relative order of variouscomponents that may appear in virtual tables.Precisely which components are present in various possible virtualtables is specified in the next section.If present, components are present in the order described,except for the exceptions specified. The form of a virtual function pointer is specified by theprocessor-specific C++ ABI for the implementation.In the specific case of 64-bit Itanium shared library builds,a virtual function pointer entry contains a pair of components(each 64 bits):the value of the target GP value and the actual function address.That is, rather than being a normal function pointer,which points to such a two-component descriptor,a virtual function pointer entry is the descriptor. The order of the virtual function pointers in a virtual table isthe order of declaration of the corresponding member functions in the class.If an implicitly-declared copy assignment operator, move assignment operator,or destructor is virtual, it is treated as if it were declared at the end ofthe class, in that order.(Implicitly-declared assignment operators may be virtual ifa base class declares a virtual assignment operatortaking a reference to a derived class type.) An entry is added for every virtual function in a class,including deleted functions, unless: An override requires a return-type adjustment ifthe return types are different andhave potentially incompatible representations.C++ permits an override to differ in return type from the overridden functiononly if both types are pointer-to-class or reference-to-class types andthe class typeB in the overridden function isan unambiguous base class of the class typeD in the override.For the purposes of vtable layout,these types are considered to have potentially incompatible representations if: When a derived class and its primary base share a virtual table,the virtual function entries introduced by the derived class followthose for the primary base,so that the layout of the primary base's embedded virtual tableis the same as that of its standalone virtual table.In particular, if the derived class overrides a base class virtualfunction with a different (covariant) return type,the entry for the derived class comes after the primary base'sembedded virtual table in declaration order,and is the entry used for calls from the derived class without adjustment.The entry in the embedded primary virtual table points to a routinethat adjusts the result pointer before returning. The entries for virtual destructors are actually pairs of entries.The first destructor,called the complete object destructor,performs the destruction without calling delete() on the object.The second destructor,called the deleting destructor,calls delete() after destroying the object.Both destroy any virtual bases;a separate, non-virtual function,called the base object destructor,performs destruction of the object butnot its virtual base subobjects, and does not call delete(). Following the primary virtual table of a derived class aresecondary virtual tables for each of its proper base classes,except any primary base(s) with which it shares its primary virtual table.These are copies of the virtual tables for the respective base classes(copies in the sense that they have the same layout,though the fields may have different values).We call the collection consisting of a primary virtual table along with all ofits secondary virtual tables avirtual table group.The order in which they occur is the same as the order in which thebase class subobjects are considered for allocation in the derived object: This ABI does not make guarantees about the layout of other virtualtables in a virtual table group relative to a virtual table pointerin an object or a VTT. It guarantees only the layout of theglobal symbol for that virtual tablegroup. It does not guarantee that the virtual table pointers actuallyinstalled in an object or a VTT will point into that global symbol. In this section, we describe how to construct the virtual table for an class,given virtual tables for all of its proper base classes.To do so, we divide classes into several categories,based on their base class structure. Such a class has no associated virtual table,and an object of such a class contains no virtual pointer. The virtual table contains offset-to-top and RTTI fieldsfollowed by virtual function pointers (as specified above). The class has a virtual table for each proper base class that has avirtual table. The secondary virtual table for a base class B has thesame contents as the primary virtual table for B, except that: For a proper base class The primary virtual table for the derived class contains entries foreach of the functions in the primary base class virtual table,replaced by new overriding functions as appropriate. Following theseentries, there is an entry for each virtual function pointer for thederived class (as specified above). Structure: The class has a virtual table for each virtual base classthat has a virtual table.These are all secondary virtual tables,because there are no empty or nearly empty base classes to be primary,and they are constructed from copies of the base classfull object virtual tables according to the same rules as in Category 2,except that the virtual table for a virtual base A also includes a vcalloffset entry for each virtual function represented in A's primaryvirtual table and the secondary virtual tables from A's non-virtual bases. The vcall offsets in the secondary virtual table for a virtual base A areordered as described next.We describe the ordering from the entry closest to the virtual table addresspoint to that furthest.Since the vcall offsets precede the virtual table address point,this means that the memory address order is the reverse of thatdescribed. If the above listing of vcall offsets includes more than onefor a particular virtual function signature,only the first one (closest to the virtual table address point) is allocated.That is, an offset from primary base P (and its non-virtual bases)eliminates any from A or its other bases,an offset from A eliminates any from the non-primary bases,and an offset from a non-primary base B of A eliminates any from thebases of B. Note that there are no vcall offsets for virtual functions declared ina virtual base class V of A and never overridden within A or itsnon-virtual bases.Calls to such functions will use the vcall offset in V's virtual table. The class also has a virtual table that is not copied from the virtual baseclass virtual tables.This virtual table is the primary virtual table of the classand is addressed by the virtual table pointer at the top of the object,which is not sharedbecause there are no nearly empty virtual bases to be primary.It holds the virtual function pointer entries for the class.This includes all entries overridden from base classes,because there is no primary base class;such entries are known as replicated entriesbecause they are already in the secondary virtual tables of the class. The primary virtual table also has virtual base offset entriesto allow finding the virtual base subobjects.There is one virtual base offset entry for each virtual base class,direct or indirect.The entries are in the reverse of the inheritance graph order.That is, the entry for the leftmost virtualbase is closest to the address point of the virtual table. Structure: The rules for constructing virtual tables of the class are a combination ofthe rules from Categories 2 and 3,and can generally be determined inductively.The differences are mostly due to the fact that virtual base classescan now have (nearly empty) primary bases: T's virtual table contains a virtual base offset for S.U's virtual table contains virtual base offsets for S and T.V's virtual table contains virtual base offsets for S, U, and T(in reverse inheritance graph preorder),where the vbase offset for T is for the virtual base of U,not for the non-virtual direct base of V. Consider in addition: T is a primary base class for W.Therefore, its virtual base offset for S in its embedded T-in-W virtualtableis the only one present. In some situations,a special virtual table called a construction virtual table is used duringthe execution of proper base class constructors and destructors.These virtual tables are for specific cases of virtual inheritance. During the construction of a class object, the object assumes the typeof each of its proper base classes, as each base class subobject isconstructed. RTTI queries in the base class constructor will returnthe type of the base class, and virtual calls will resolve to memberfunctions of the base class rather than the complete class. RTTIqueries, dynamic casts and virtual calls of the object underconstruction statically converted to bases of the base underconstruction will dynamically resolve to the type of the base underconstruction.Normally, this behavior is accomplished by setting,in the base class constructor,the object's virtual table pointers to the addresses of thevirtual tables for the base class. However, if the base class has direct or indirect virtual bases, the virtual table pointers have to be set to the addresses of constructionvirtual tables.This is because the normal proper base class virtual tables may not hold the correct virtual base index values to access the virtual bases of the object under construction,and adjustment addressed by these virtual tables may holdthe wrong this parameter adjustment if the adjustment is to castfrom a virtual base to another part of the object. The problem isthat a complete object of a proper base class and a complete object of aderived class do not have virtual bases at the same offsets. A construction virtual table holds the virtual function addresses,offset-to-top,and RTTI information associated with the base class,and virtual base offsets and addresses of adjustor entry points with theirparameter adjustments associated with objects of the complete class. To ensure that the virtual table pointers are set to the appropriatevirtual tables during proper base class construction,a table of virtual table pointers, called the VTT, which holds the addresses of construction andnon-construction virtual tables is generated for the complete class. Theconstructor for the complete class passes to each proper base classconstructor a pointer to the appropriate place in the VTT where the proper base class constructor can find its set of virtual tables.Construction virtual tables are used in a similar way during theexecution of proper base class destructors. An array of virtual table addresses, called theVTT,is declared for each class type that hasindirect or direct virtual base classes.(Otherwise,each proper base class may be initializedusing its complete object virtual table group.) The elements of the VTT array for a class D are in this order: X is reachable along a virtual path from D if there exists a pathX, B1, B2, ..., BN, D in the inheritance graph such that at least oneof X, B1, B2, ..., or BN is a virtual base class. The order in which the virtual pointers appear in the VTT isinheritance graph preorder. Primary virtual bases require a secondary virtual pointer in the VTTbecause the derived class with which they will share a virtual pointeris determined by the most derived class in the hierarchy. Secondary virtual pointers may be required for base classes that donot require secondary VTTs. A virtual base with no virtual bases ofits own does not require a VTT, but does require a virtual pointerentry in the VTT. Each virtual table address in the VTT is the address to be assigned to therespective virtual pointer,i.e. the address past the end of the typeinfo pointer(the address of the first virtual function pointer, if there are any),not of the first vcall offset. Parts (1) and (3) of a primary (not secondary, i.e. nested) VTT,that is the primary and secondary virtual pointers,are used for the final initialization of an object's virtual pointersbefore the full-object initialization and later use,and must therefore point to the main virtual table group for the class.Those bases which do not have secondary virtual pointers in the VTThave their virtual pointers explicitly initialized to the main virtualtable group by the constructors(seeSubobject Construction and Destruction). The virtual pointers in the secondary VTTs and virtual VTTs are used forsubobject construction,and may always point to special construction virtual tables laid out asdescribed in the following subsections.However, it will sometimes be possible to use either the full-objectvirtual table for the base class,or its secondary virtual table for the full class being constructed.This ABI does not specify a choice,nor does it specify names for the construction virtual tables,so the constructors must use the VTT rather than assuming that aparticular construction virtual table exists. For example, suppose we have the following hierarchy: If A2 is a virtual base of V1,the VTT will contain more elements(exercise left to the astute reader). The construction virtual tables for a complete object are emitted in the same object file as the virtual table.So the virtual table structures for a complete object of class C include,in no particular order: The VTT array is referenced via its own mangled external name,and the construction virtual tables are accessed via the VTT array,so the latter do not have external names. The construction virtual table group for aproper base class subobject B (of derived class D)does not have the same entries in the sameorder as the main virtual table group for a complete object B,as described inVirtual Table Layout above.Some of the base class subobjects may not need construction virtual tables,which will therefore not be present in the construction virtual table group,even though the subobject virtual tables are present in the main virtualtable groupfor the complete object. Thevalues of some construction virtual table entries will differfrom the corresponding entries in either the main virtual tablegroup for B or the virtual table group for B-in-D,primarily because the virtual bases of B will be at different relativeoffsets in a D object than in a standalone B object,as follows: When a Let This operator must be looked up as if for a If a cookie is required, the allocation is adjusted as follows: A If a function-scope static variable or a static data member with vaguelinkage (i.e., a static data member of a class template) isdynamically initialized, then there is an associated guard variablewhich is used to guarantee that construction occurs only once. Theguard variable's name is mangledbased on the mangling of the guarded object name. Thus, forfunction-scope static variables, if multiple instances of the functionbody are emitted (e.g., due to inlining), each function uses the sameguard variable to ensure that the function-scope static is initializedonly once. Similarly, if a static data member is instantiated inmultiple object files, the initialization code in each object filewill use the same guard variable to ensure that the static data memberis initialized only once. The size of the guard variable is 64 bits.The first byte (i.e. the byte at the address of the full variable)shall contain the value 0 prior to initialization ofthe associated variable, and 1 after initialization is complete.Usage of the other bytes of the guard variable is implementation-defined. SeeSection 3.3.3for the API for references to this guard variable. The C++ programming language definition implies that information abouttypes be available at run time for three distinct purposes: It is intended that two type_info pointers point to equivalent typedescriptions if and only if the pointers are equal.An implementation must satisfy this constraint,e.g. by using symbol preemption, COMDAT sections, or other mechanisms. It is desirable to minimize the number of places where aparticular bit of RTTI is emitted.For dynamic class types,a similar problem occurs for virtual function tables,and hence the RTTI descriptor should be emittedwith the primary virtual table for that type.For other types, they must be emitted at the locationwhere their use is implied:the object file containing the typeid, throw or catch. Basic type information (e.g. for "int", "bool", etc.)will be kept in the run-time support library.Specifically, the run-time support libraryshould contain type_info objects for the typesX, X* and X const*,for every X in: void, std::nullptr_t,bool, wchar_t, char, unsigned char, signed char,short, unsigned short, int, unsigned int, long, unsigned long, long long,unsigned long long, float, double, long double, char8_t, char16_t, char32_t,and the IEEE 754r decimal and half-precision floating point types.Each of the type_info objects for X shall have type The typeid operator produces a reference to a std::type_info structurewith the following public interface (18.5.1): After linking and loading,only one std::type_info structure is accessible via the external namedefined by this ABI for any particular complete type symbol(seeVague Linkage).Therefore,except for direct or indirect pointers to incomplete types,the equality and inequality operators can bewritten as address comparisonswhen operating on those type_info objects:two type_info structures describe the same typeif and only if they are the same structure (at the same address).However, in the case of pointer types,directly or indirectly pointing to incomplete class types,a more complex comparison is required,described below with the RTTI layout of pointer types. The In a flat address space(such as that of the Itanium architecture),the This implies that the type information must keep a description of the public,unambiguous inheritance relationship of a type, as well as the constand volatile qualifications applied to types. We add one pointer to the The possible derived types are: This RTTI class mayalso be used for incomplete class types when referenced by a pointer RTTI,in which case it must be prevented from preemptingthe RTTI for the complete class type,for instance by emitting it as a static object (without external linkage). Two The All but the lower 8 bits of The low-order byte of Note that the resulting structure is variable-length,with the actual size depending on the number of trailing base classdescriptions. Note that the When the Two The null-terminated byte string returned by this routine isthemangled name of the type. Although dynamic_cast can work on pointers and references,from the point of view of representation we need only to worryabout polymorphic class types.Also, some kinds of dynamic_cast operations are handled at compile timeand do not need any RTTI.There are then three kinds of truly dynamic cast operations: The most common kind of dynamic_cast is base-to-derived in a singlyinherited hierarchy. Dynamic casts to "void cv*" are inserted inline at compile time.So are dynamic casts of null pointers and dynamic casts that are reallystatic. This leaves the following test to be implemented in the run-timelibrary for truly dynamic casts of the form "dynamic_cast<T>(v)":(see [expr.dynamic_cast] 5.2.7/8) The first check corresponds to a "base-to-derived cast" and the secondto a "cross cast".These tests are implemented by abi::__dynamic_cast: Since the RTTI related exception handling routines are "personality specific",no interfaces need to be specified in this document(beyond the layout of the RTTI data). This chapter describes how to define and call functions.It also specifies the APIs of a variety of runtime utility routinesrequired to be part of the support library of an ABI-conformingimplementation for use by compiled code.In addition, reference is made to the separate description ofexception handling in this ABI,which defines a large number of runtime utility routine APIs. In general, the calling conventions and rules for defining C++functions in this ABI follow those specified for functions ofthe corresponding type in the base C ABI. The corresponding typeis mostly determined by translating C++ constructs to theirobvious C analogues. This section specifies the behavior ofof features without analogues in C, as well as some exceptionsand extra rules required by C++-specific semantics. For the most part, non-static member functions, including constructorsand destructors, are defined as if they were ordinary functions exceptfor the addition of the implicit parameters to the prototype asdescribed in thesection on parameters. The rules formember functionpointers may require aligning the first instruction of ordinarynon-static member functions (i.e. not constructors or destructors)to a higher value than the platform would normally require. Non-static member functions, including constructors and destructors,take an implicit Base-subobject constructors and destructors for classes with virtualbases take an implicit If a parameter type is a class type that isnon-trivial for the purposes of calls, thecaller must allocate space for a temporary and pass that temporary byreference. Specifically: A C-style variadic argument of a type that is non-trivial for thepurposes of calls is passed the same way: the address of the temporaryis passed using the normal variadic mechanism, and An argument of class Reference parameters are handled by passing a pointer to the objectbound to the reference. Arguments of empty class types that are not non-trivial for the purposesof calls are passed no differently from ordinary classes. On Itanium, the NaT bit must be set on all registers that are associatedwith the argument. If the return type is a class type that isnon-trivial for the purposes of calls,the caller passes an address as an implicit parameter.The callee then constructs the return value into this address.If the return type has a non-trivial destructor, the caller is responsiblefor destroying the temporary when control is returned to itnormally.If an exception is thrown out of the callee after the return value isconstructed but before control returns to the caller, e.g. by athrowing destructor, it is the callee's responsibility to destroy thereturn value before propagating the exception to the caller. Thus,in general, the caller is responsible for destroying the return valueafter, and only after, the callee returns control to the caller normally. The address passed need not be of temporary memory; copy elision maycause it to point anywhere, including to global or heap-allocated memory. C ABIs usually provide treatment for "indirect" return values, e.g. whenreturning a large aggregate that cannot fit in registers. In some cases,this treatment may not be suitable for non-trivial C++ return values, suchas if the convention requires implicit copying or does not permit thereturn value to be constructed at an arbitrary address. If the treatmentexists and is suitable, it is used for non-trivial return values.Otherwise, the pointer is passed as if it were the first parameter inthe function prototype, preceding all other parameters, including the A return value of class A return value of reference type is returned as a pointer to the objectbound to the reference. A return value of an empty class type that is not non-trivial forthe purposes of calls will be returned as though it were thefollowing C type: On Itanium, the NaT bit must not be set for any register associated withthis return value. Constructors return Some platforms are known to modify this rule to specify that constructorsreturn a pointer to Destructors return Some platforms are known to modify this rule to specify that destructorsreturn a pointer to This section sketches the calling convention for virtual functions,based on the above virtual table layout.See also theABI examplesdocument for motivating examples and potential implementations. We explain, at a high level,what information must be present in the virtual table for a class Awhich declares a virtual function f in order that,given an pointer of type A*,the caller can call the virtual function f.This section does not specify exactly where that information is located(see above),nor does it specify how to convert a pointer to a classderived from A to an A*,if that is required. When this section uses the termfunction pointer it is understoodthat this term may refer either to a traditional function pointer(i.e., a pointer to a GP/address pair) or a GP/address pair itself.Which of these alternatives is actually usedis specified elsewhere in the ABI,but is independent of the description in this section. Throughout this section,we assume that A is the class for which we are creating a virtual table,B is the most derived class in the hierarchy,and C is the class that contains C::f,the unique final overrider for A::f.This section specifies the contents of the f entry in the A-in-B virtualtable.(If A is primary base in the hierarchy,then the A-in-B virtual table will be sharedwith the derived class virtual table --but the contents of the A portion of that virtual tablewill still be as specified here.) In all cases, thenon-adjusting entry point for a virtualfunction expects the `this' pointer to point to an instance of theclass in which the virtual function is defined.In other words, the non-adjusting entry point for C::f will expectthat its `this' pointer points to a C object. For each virtual function declared in a class C,we add an entry to its virtual table if one is not already there(i.e. if it is not overriding a function in its primary base).In particular, a declaration which overrides a function inherited froma secondary base gets a new slot in the primary virtual table.We do this to avoid useless adjustments when calling a virtualfunction through a pointer to the most derived class. The content of this entry for class A is a function pointer,as determined by one of the following cases.Recall that we are dealing with a hierarchy where B is most derived,A is a direct (or indirect) base of B defining f,and C contains the unique final overrider C::f of A::f. (In this case, we are creating either the primary virtual table for A,or the A-in-B secondary virtual table.) The virtual table contains a function pointer pointing to thenon-adjusting entry point for A::f. In this case, we are creating the A-in-B secondary virtual table. The virtual table contains a pointer to an entry point that performs theadjustment from an A* to a C*,and then transfers control to the non-adjusting entry point for C::f. There are some exceptions to this determination of function pointers: When a class is used as a virtual base,we add a vcall offset slot to the beginning of its virtual table for each ofthe virtual functions it provides,whether in its primary or secondary virtual tables.Derived classes which override these functions may use the slots todetermine the adjustment necessary. For each direct or indirect base A of C that is not a morally virtualbase of C,the compiler must emit, in the same object file as the code for C::f,anA-adjusting entry point for C::f.This entry point will expect that its For each direct or indirect virtual base V of C such that V declares f,the compiler must emit, in the same object file as the code for C::f,aV-adjusting entry point for C::f.This entry point will expect that its For each morally virtual base M of Csuch that M isnot a virtual base(and therefore must be a subobject of a virtual base V),and such that M declares f,the compiler must emit,in the same object file as the code for C::f,anM-adjusting entry point for C::f.This entry point will expect that its When calling a virtual function f,through a pointer of static type B*,the caller (Note that in general it will be optimal to select the class whichcontained the final overrider (i.e., C)as the class to which the B* should be converted.This class is always a satisfactory choice,since it is known to contain a definition of f.In addition, if the dynamic type of the object is B,then C::f will be the function ultimately selected by the call,which means that C's virtual table willcontain a pointer to the non-adjusting entry point,meaning that no additional adjustments to the However, there may be cases in which choosing a different basesubobject could be superior.For example, if there is an alternate base D which also declares f,and a pointer to the D subobject is already available,then it may be better to use the D subobject ratherthan converting the B* to a C*,in order to avoid the cost of the conversion.) Note that the ABI only specifies the multiple entry pointsfor a virtual function and its associated thunks;how those entry points are provided is unspecified.An existing compiler which uses thunks with a different means ofadjusting the virtual table pointerscan be made compliant with this ABI by only adding the vcall offsets --the thunks need not use them.A more efficient implementation would be to emit all of the thunksimmediately before the non-adjusting entry point to the function.Another might emit a new copy of the function for each entry point;this is a quality of implementation issue.See further discussion of implementation in theABI examples document. An implementation shall provide a standard entry point that a compilermay reference in virtual tables to indicate a pure virtual function.Its interface is: This routine will only be called if the user calls a non-overriddenpure virtual function, which has undefined behavior according to theC++ Standard.Therefore, this ABI does not specify its behavior,but it is expected that it will terminate the program,possibly with an error message. An implementation shall provide a standard entry point that a compilerwill reference in virtual tables to indicated a deleted virtualfunction. Its interface is: This routine shall not return and while this ABI does not otherwisespecify its behavior, it is expected that it will terminate the program,possibly with an error message. This section describes APIs to be used for the construction anddestruction of objects.This includes: The complete object constructors and destructors find the VTT,described in Section 2.6, Virtual Tables During Object Construction,via its mangled name. They pass the address of the subobject'ssub-VTT entry in the VTT as a second parameter when calling the baseobject constructors and destructors. The base object constructors anddestructors use the addresses passed to initialize the primary virtualpointer and virtual pointers that point to the classes which eitherhave virtual bases or override virtual functions with a virtual step(have vcall offsets needing adjustment). If a constructor calls constructors for base classsubobjects that do not need construction virtual tables,e.g. because they have no virtual bases,the construction virtual table parameter is not passed to the base classsubobject constructor,and the base class subobject constructors usetheir complete object virtual tables for initialization. If a class has a non-virtual destructor, and a deleting destructor isemitted for that class, the deleting destructor must correctlyhandle the case that the Suppose we have a subobject class D that needs a construction virtual table,derived from a base B that needs a construction virtual table as part of D,and possibly from others that do not need construction virtual tables.Then the sub-VTT and constructor code for D would look like the following: A test program for this can be found in theABI Examples document. A constructor inherited from a base class can be used to initialize a derivedclass object, if it is explicitly inherited by a An inheriting constructor describes the initialization that would be performedwhen a constructor inherited from a base class is selected to initialize aderived class, including the default-initialization of the other base classesand the non-static data members of the derived class. If the inheritingconstructor is a base subobject constructor and the inherited constructorconstructs a morally virtual base subobject, the inheriting constructor doesnot take any user-declared parameters; otherwise, it takes the same parametersas the inherited constructor. In all other respects, an inheriting constructorsbehaves the same as a constructor of the derived class. For example: Inheriting constructors are not permitted to make copies of their parameterswhen passing them to the inherited constructor. If it would not be possible totransparently forward all parameters from the inheriting constructor to theinherited constructor, an inheriting constructor cannot be used, and adifferent implementation technique (such as emitting the initialization inline)must be used instead. As described inSection 2.8, certain objects withstatic storage duration have associated guard variables used tosupport the requirement that they be initialized exactly once, thefirst time the scope declaring them is entered. An implementationthat does not anticipate supporting multi-threading may simply checkthe first byte (i.e., the byte with lowest address) of that guardvariable, initializing if and only if its value is zero, and thensetting it to a non-zero value. However, an implementation intending to supportautomatically thread-safe, one-time initialization(as opposed to requiring explicit user control for thread safety)may make use of the following API functions: Returns 1 if the initialization is not yet complete; 0 otherwise.This function is called before initialization takes place. If thisfunction returns 1, either A thread-safe implementation will probably guard access to the firstbyte of the Sets the first byte of the guard object to a non-zero value. Thisfunction is called after initialization is complete. A thread-safe implementation will release the mutex acquired by This function is called if the initialization terminates by throwingan exception. A thread-safe implementation will release the mutex acquired by The following is pseudo-code showing how these functions can be used: An implementation need not include the simple inline test of theinitialization flag in the guard variable around the above sequence.If it does so,the cost of this scheme,when run single-threaded with minimal versions of the above functions,will be two extra function calls,each of them accessing the guard variable,the first time the scope is entered. An implementation supporting thread-safety on multiprocessor systemsmust also guarantee that references to the initialized object do notoccur before the load of the initialization flag.On Itanium, this can be done by using a The intent of specifying an 8-byte structure for the guard variable,but only describing one byte of its contents,is to allow flexibility in the implementation of the API above.On systems with good small lock support,the second word might be used for a mutex lock.On others, it might identify (as a pointer or index)a more complex lock structure to use. An ABI-compliant system shall provide several runtime routines for usein array construction and destruction.They may be used by compilers, but their use is not required.The required APIs are: Equivalent to Given the number and size of elements for an array and thenon-negative size of prefix padding for a cookie, allocate space(using If The constructor may be Neither If the computed size of the allocated array object (including spacefor a cookie, if specified) would exceed the implementation-definedlimit, If the The only requirement of the C++ Standard with respect to file scopeobject construction order is that file scope objectsin a single object file are constructed in declaration order.However, building large programs sometimes requires careful attentionto construction ordering for objects in different object files,and a number of vendors have provided extra-lingual facilities tocontrol it.This ABI does not require an implementation to support this capability,but it specifies such a facility for those implementations that do. This facility only controls construction order within a singled linkedobject (executable or DSO).Construction order between linked objects is determined by theinitialization ordering specified in the base ABI. A user may specify the construction priority with the pragma: Initialization entries with the same priority from different files(or from other sources such as link command options)will be executed in an unspecified order. Initialization priority is represented in the object file by elementsof a target-specific section type, Each implementation supporting priority initialization shall providea runtime library function with prototype: The only required static linker processing is to concatenate the A more ambitious linker implementation could sort the The C++ Standard requires that destructors be called for global objectswhen a program exits in the opposite order of construction.Most implementations have handled this by calling the C library The API specified below is intended to providestandard-conforming treatment during normal program exit,which includes executing The runtime library shall maintain a list of termination functionswith the following information about each: The representation of this structure is implementation defined.All references are via the API described below. After constructing a global (or local static) object,that will require destruction on exit,a termination function isregistered as follows: The registration function is not called from within the constructor. When the user registers exit functions with When linking any DSO containing a call to Note that the above can be accomplished either by explicitly providingthe symbol and call in the linker, or by implicitly including arelocatable object in the link with the necessary definitions,using a .fini_array section for the FINI call.Also, note that these can be omitted for an object with no calls to When When the main program calls Note that the destructors must be called by Since Synopsis: Behavior:The return value is a pointer to a null-terminated array of characters, the demangled name.Ambiguities are possible between extern "C" object names and type manglings,e.g. "i" may be either an object named "i" or the built-in "int" type.Such ambiguous arguments are assumed to be type manglings. If the user has a set of external names to demangle, they should check that the names arein fact mangled (that is, begin with "_Z") before passing them to If there is an error in demangling, the return value is a null pointer.The user can examine *status to find out what kind of error occurred.Meaning of error indications: Memory management: SeeException Handling document,currently just the base psABI-level material,and theHPexception handling working paper,8 December 1999. This section specifies themangling, i.e. encoding,of external names (external in the sense of being visibleoutside the object file where they occur). The encoding isformalized as a derivation grammar along with the explanatorytext, in a modified BNF with the following conventions: See the separatetablesummarizing the encoding characters used as terminals.Also see additionalmangling examplesin the separate ABI examples document. In the various explanatory examples,we use Mangled names containing Entities with C linkage and global namespace variables are not mangled.Mangled names have the general structure: A ABI mangling is designed to ensure that entities receive thesame mangling if and only if they are the same entity accordingto the C++ standard's one-definition rule (ODR) and thevarious rules for declaration matching (such as[over.dcl] and[temp.over]. Those rules are quitecomplex, and they dictate the results of mangling, and so itshould not be surprising that the mangling rules are also complex.The ABI must be closely involved with the evolution of thoselanguage rules to ensure that they remain implementable withmangling. When the rules say that an ODR violation hasundefined behavior, that is often because it is impractical toensure that the entities involved will have different manglings.Similarly, when the rules forbid certain constructs from thesignature of a declaration, that is often because that constructwould create unreasonable problems for mangling. Mangling must sometimes be able to distinguish entities thatare not equivalent under the ODR and declaration-matchingrules. This is true even if the entities would not bedistinguishable by C++ code because, say, every name lookupwhich included both of them would be ambiguous. For example,different translation units might declare similar but noteqivalent function templates in the same namespace: The C++ standard grants implementations broad flexibility toignore certain kinds of differences. For example, the rulesin[temp.over.link] forfunctionally-equivalent function templates could be used toshorten manglings in certain cases where instantiation-dependenceprovably has no effect. This ABI generally does not takeadvantage of that flexibility. It is sometimes necessary to mangle unresolved and uninstantiatedlanguage constructs such as types and expressions that appearwithin templates. This accounts for a lot of the complexity ofentity mangling in this ABI. In many places, the mangling grammar formally allows a singleconstruct to be mangled in one of several different ways.Usually there is one production which allows a fully-resolvedvalue or entity reference, and there is another production thatallows an expression or unresolved entity reference. As anexample, this can be clearly seen in the mangling forarray types, which givesone mangling for a constant bound and another for an expression. There are two reasons for this. First, manglings using thefully-resolved case are often significantly more compact.More importantly, though, the language often treat dependentand non-dependent constructs differently. For example,[temp.over.link] gives rules forwhen two expressions that involve template parameters areconsidered equivalent, and those rules are reflected inthis ABI's expression mangling rules. Conversely, expressionsthat don't involve template parameters but are used inconstant-evaluated contexts (such an array length) areconsidered to be equivalent if and only if they resolveto the same value. Mangling a non-dependent expression usingits expression structure could incorrectly produce differentmanglings for different expressions that resolve to the samevalue, and it could incorrectly produce the same mangling forexpressions that resolve to different values but happen to bespelled the same. It is therefore important to use the right production giventhe dependence of the construct in question. The standarddefines several different kinds of dependence, such asvalue dependence andtype dependence. Ingeneral, the rule that should be used in mangling isinstantiationdependence: if a construct in instantiation-dependent,it should use the general production, and otherwise itshould use the narrow production. The grammar below willstate clearly when certain productions are only forinstantiation-dependent cases. For the purposes of mangling, the name of an anonymous union isconsidered to be the name of the first named data member found by apre-order, depth-first, declaration-order walk of the data members ofthe anonymous union. If there is no such data member (i.e., if all ofthe data members in the union are unnamed), then there is no way for aprogram to refer to the anonymous union, and there is therefore noneed to mangle its name. All of these examples: In general, the mangling of an entity's name depends on where it isdeclared. Entities declared at global scope, or in namespace The manglings of template specializations and non-template entitiesclosely overlap, but they can generally be disambiguated by whetherthe name is followed by the A <nested-name> recursivelybreaks down the enclosing scope until the global scope is reached. A<prefix> refers to a scope;confusingly, a <template-prefix>actually refers to a template name (without template arguments). Class and namespace members are always mangled with a<nested-name>, even if they aretemplate specializations and there is an existing substitution for thetemplate (and therefore the name could in principle be mangled as ifit were a <unscoped-template-name>). When a <nested-name> refersto a non-static class member function, the CV-qualifiers andref-qualifiers of the function are prefixed to the compound name.This prefix is required even when the member function is aspecialization of a substituted template and therefore thosequalifiers could be inferred from the substitution target. <identifier> is a pseudo-terminal representing the characters in the unqualified identifier for the entity in the source code. This ABI does not yet specify a mangling for identifiers containing characters outside of Note that <source-name> in the productions for <unqualified-name>may be either a function or data object name when derived from <name>,or a class or enum name when derived from <type>. The GNU Note that for member functions of a class template that are not membertemplates, the type in question is that of the instantiation, so tags thatappear only in the template do not affect mangling: If no arguments are specified for the attribute on an inline namespace, thenamespace has its own name as a tag. Tags on an inline namespace are notrepresented in the mangled name of the namespace, but they are subject to theabove tag propagation. For example: <number> is a pseudo-terminal representing a decimal integer,with a leading 'n' for negative integers.It is used in <source-name> to provide the bytelength of the following identifier.<number>s appearing in mangled names never have leading zeroes,except for the value zero, represented as '0'. A <seq-id> is a sequence number in base 36, using digits and upper case letters. Generally, wherever <seq-id> appears, the first element is encoded by the absence of a number, and the remainder of the sequence is encoded starting at 0. As with <number>, a <seq-id> has a leading zero only if that is the only digit. For example,substitutions are mangled as Operators appear as function names,and in nontype template argument expressions.Unlike Cfront,unary and binary operators using the same symbol have different encodings.Most operators are encoded using exactly two letters,the first of which is lowercase. Vendors who define builtin extended operators (e.g. Associated with a virtual table are several entities with mangledexternal names: the virtual table itself, the VTT for construction,the typeinfo structure, and the name it references.Each has a <special-name> encoding that is a simple two-character code,prefixed to the type encoding for the class to which it applies. Virtual function override thunks come in two forms.Those overriding from a non-virtual base,with fixed Virtual function override thunks with covariant returns are twice as complex. Just as normal virtual function override thunks must adjust thethispointer before calling the base function,those with covariant returns must adjust the return pointer after theyreturn from the base function.So the mangling must also encode a fixed offset to a non-virtual base,and possibly an offset to a vbase offset in the vtable to get to thevirtual base containing the result subobject.We achieve this by encoding two <call-offset> components,either of which may be either virtual or non-virtual. Constructors and destructors are simply special cases of<unqualified-name>,where the final <unqualified-name> of a nested nameis replaced by one of the following: The <base classtype> in an inheritingconstructor mangling identifies the base class in which the inheritedconstructor was originally declared. Some of the symbols for constructor and destructor variants areoptional. Initialization of certain objects with static storage durationrequires aguard variable to prevent multipleinitialization. The mangled name of a guard variable is the name ofthe guarded variable prefixed with The initializers of objects with static storage duration may introducetemporaries whose lifetime is extended to have static storageduration; this may also apply recursively to the initializers ofthose temporaries. If an initializer is visible to multipletranslation units, those translation units must agree on the addressesof the temporaries. Therefore the temporaries must be given aconsistent name andvague linkage. The mangledname of a temporary is the name of the non-temporary object in whoseinitializer they appear, prefixed with For example, consider the following code: Types are encoded according to their compound structure: the tree oftype constructors, such as Simple forms of type structure, such as reference and pointer types, areencoded with a single-character prefix. More complex forms of typestructure, such as qualifiers and function types, require individualdiscussion below. Vendors who define extended type qualifiers (e.g. In cases where multiple order-insensitive qualifiers are present,they should be ordered (beginning closest to the base type) 'K', 'V', 'r',and 'U' (farthest from the base type), with the 'U' qualifiers inalphabetical order by the vendor name (with alphabetically earlier namescloser to the base type). For example, For purposes of substitution, given a qualified type, the base typeis substitutible and the type with all the K, V, and r qualifiers plusany vendor extended types in the same order-insensitive set is substitutible;however, types with only a subset of those qualifiers are not.That is, given a type For example, Builtin types are represented by single-letter codes: Vendors who define builtin extended types shall encode themas a 'u' prefix followed by the name in <length,I> form,followed by any arguments to the extended type. Function types are composed from their parameter types and possibly theresult type.Except at the outer level type of an <encoding>,or in the <encoding> of an otherwise delimited external name in a<template-param> or <local-name> function encoding,these types are delimited by an "F..E" pair.For purposes of substitution(seeCompression below),delimited and undelimited function types are considered the same. Whether the mangling of a function type includes the return typedepends on the context and the nature of the function.The rules for deciding whether the return type is included are: Empty parameter lists,whether declared as The mangling of CV-qualifiers and ref-qualifiers on a function typediffers according to context. When mangling the name of a non-staticmember function, the CV-qualifiers and ref-qualifiers of that functionare encoded at the beginning ofthe When an exception-specification (i.e., A transaction-safe function type is encoded with a "Dx" before the "F". Thisaffects only type mangling; a transaction-safe function has the same manglingas a non-transaction-safe function. A "Y" prefix for the bare function type encodes extern "C" inimplementations which distinguish between function types with "C" and"C++" language linkage. This affects only type mangling, since extern"C" function objects have unmangled names. For the purposes of substitution, the CV-qualifiers and ref-qualifierof a function type are an indivisible part of the type; that is, whenmangling When a function parameter is a C++11 function parameter pack, its typeis mangled with The C++11 A class, union, or enum type is simply a name.It may be a simple <unqualified-name>,with or without a template argument list,or a more complex <nested-name>.Thus, it is encoded like a function name,except that no CV-qualifiers are present in a nested name specification. An exception, however, is that class Unnamed class, union, and enum types that aren't closure types, thathaven't acquired a "name for linkage purposes" (through a typedef), andthat aren't anonymous union types, followthe same rule when they are defined in class scopes,with the underlying <unqualified-name> an <unnamed-type-name> ofthe form (The mangling of such unnamed types defined in namespace scope isgenerally unspecified because they do not have to match acrosstranslation units. An implementation must only ensure that namingcollisions are avoided. The mangling of such unnamed types in localscopes is described inScope Encoding.The encoding of closure types is described in aClosure Types (Lambdas).) For example: Array types encode their array bound and element type. Note that"array" parameters to functions are encoded as pointer types.The array bound (but not the The second rule is used when the array bound is aninstantiation-dependentexpression. For example: Pointer-to-member types encode the class and member types: For example, A reference to a template parameter is mangled using the indexof the parameter, with a special mangling for the first parameter.The sequence of parameters is therefore For example: Note that a template parameter reference is asubstitution candidate.As a substitution, it is treated as distinct from the actualtemplate argument, including in recursive positions.For example, in the mangling of the following function templatespecialization, the first incidence of Typically, only references to function template parameters occurringwithin the dependent signature of the template are mangled this way.In other contexts, template instantiation replaces referencesto template parameters with the actual template arguments, and manglingshould mangle such references exactly as if they were that templateargument. For example: Function parameters referenced in other parameter types or inlate-specified return types are handled similarly to templateparameters, but involve a few more subtleties. Let L be the number of function prototype scopes from the innermost one(in which the parameter reference occurs) up to (and including) the onecontaining the declaration of the referenced parameter. If the parameterdeclaration clause of the innermost function prototype scope has beencompletely seen, it is not counted (in that case -- which is perhaps themost common -- L can be zero). For example: Template argument lists appear after the unqualified template name,and are bracketed by I/E. This is used in names for specializationsin particular, but also in types and scope identification. Templateargument packs are bracketed by J/E to distinguish them from otherarguments. Type arguments appear using their regular encoding.For example, the template class "A<char, float>" is encoded as "1AIcfE".A slightly more involved example isa dependent function parameter type "A<T2>::X"(T2 is the second template parameter)which is encoded as "N1AIT0_E1XE",where the "N...E" construct is used to describe a qualified name. Expressions must be mangled in several contexts. When mangling the name of a specialized template, non-typetemplate arguments are mangled as expressions. Theseexpressions are typically very simple, and they do notnecessarily reflect any argument expression that was usedin source. See the section on manglingtemplate arguments formore detail. More generally, when mangling the signature of a functiontemplate, anyinstantiation-dependentexpressions (e.g. in an array bound, In general, expression manglings reflect a prefix traversal of thesyntactic expression tree, with parentheses omitted. (Parenthesesmay be ignored because they are implicit in the prefix representationand typically do not affect semantics. However, when parenthesesare used to suppress argument-dependent lookup, the call expression mayneed to be mangled differently.) Unless explicitly stated otherwise, theexpression is mangled without constant folding or othersimplification. Each expression mangling begins with a code (typically two letters)indicating the kind of expression, which dictates the form ofthe rest of the mangling. For overloadable operators, this code isthe same as the For example, if If the operand of a A production for <expression> that directly specifies an operation code (e.g., for the The optional " If an implementation supports the full C99 designated initializer syntax (as an extension), a designator list comprising multiple designators results inmultiple nested <braced-expression>s. For example, In C++, a call expression where the callee operand is an unqualified nameuses argument-dependent lookup unless unqualified lookup finds certain kinds ofdeclarations; see C++11 [basic.lookup.argdep]p3. Because this rule does notapply when the name is parenthesized, it is sometimes necessary to distinguishparenthesized and unparenthesized calls in the mangling, despite the generalrule that parentheses can be ignored. This is encoded using the choice of Literal arguments, e.g. "A<42L>",are encoded with their type and value.Negative integer values are preceded with "n";for example, "A<-42L>" becomes "1AILln42EE".The bool value false is encoded as 0, true as 1. Floating-point literals are encoded using a fixed-length lowercasehexadecimal string corresponding to the internal representation,high-order bytes first. For example: "Lf bf800000 E" is -1.0f onplatforms conforming to IEEE 754. The encoding for a literal of an enumerated type is the encoding of thetype name followed by the encoding of the numeric value of the literalin its base integral type(which deals with values that don't have names declared in the type). String literals are encoded using their type, but not their value. For example, L"abc" and L"123" are both encoded as "LA4_KwE"("array [4] of const wchar_t"). The pointer literal expression A reference to an entity with external linkage is encoded with"L<mangled name>E".For example: The <encoding> of an extern "C" function is treated likeglobal-scope data,i.e. as its <source-name> without a type.For example: When encoding template signatures, a name appearing in the source codecannot always be resolved to a specific entity: In such cases the Entities declared in non-global scopes must include their scope intheir mangled name. For entities declared outside of functiondefinitions, this is dictated by the rules laid out for <name>. Entities declared within functiondefinitions usually do not require a well-defined mangling becauseonly one translation unit has access to the entity. However,different translation units must agree about the address of entitiesdeclared within inline functions, including template specializations.Therefore this ABI defines a mangling for even local entities. The mangling of a local entity is composed of three elements: themangling of the enclosing function, the mangling of the entityrelative to the function, and an optional discriminator within thefunction: The enclosing function is the closest function enclosing theentity. That is, when an entityE is declared within afunction that is itself local to another function, the<encoding> beginning themangling ofE will itself be a<local-name>,perhaps recursively. The name of a declared local entity is mangled with the rules for<name> as if the function were theglobal scope. That is, an entity declared directly within thefunction (e.g. a local type or It is possible to declare multiple entities with the same namewithin a function if they are declared in different scopes. In thiscase, a discriminator must be added to the<local-name>. Entities withthe same "top-level" name are numbered inlexical order withinthe function definition. A discriminator is added only for the secondand later occurrences of the same name, and so the<number> in the discriminatoris actuallyn-2 for thenth occurrence. "Top-level"here means the name declared directly in the local scope; e.g.,if there are three classes named For unnamed local types (excluding types with a name for linkagepurposes), the "name" is encoded as an<unnamed-type-name> ofthe form For example: The second production in <local-name>is used for string literals. The discriminator is used only if thereis more than one, for the second and subsequent ones. In this caseagain <number> isn-2 forthenth distinct string literal, inlexical order, appearing inthe function. Multiple references to the same string literal produceone string object with one name in the sequence.Note that thisassumes that the same string literal occurring twice in a givenfunction in fact represents a single entity, i.e. has a uniqueaddress. For entities in constructors and destructors, the mangling of thecomplete object constructor or destructor is used as the base functionname, i.e. the or version. This yields manglednames that are consistent across the versions. Example: A lambda expression introduces a unique class type calledclosure type. In some contexts, such closure types areunique to the translation unit: This ABI therefore does not specify anencoding for such cases (but an implementation must ensure that anyinternal encoding does not conflict with this ABI). For example: If the context is the body of a function (inline and/or template), theclosure type is encoded like any other local entity (seeScope Encoding above). For example: If the context is a default argument (of a member function parameter)appearing in a class definition, the closure class and its members are encoded as follows: If the context of a closure type is an initializer for a classmember (static or nonstatic), inline variable, or variable template,it is encoded in a qualified name with a In a generic lambda, uses of Lexical ordering is used for numbering local entities (named and unnamedlocal classes and enumerations, closure types, and static local variables)when there is no other way of distinguishing them. Except as described below,all local entities are to be numbered, even if subsequent optimization makessome of them unnecessary, or no mangled name is actually required forsome of them. The order of entities is the source order of a key token unique to theentity as if: In all cases, this is meant to imitate the numbering that wouldbe produced by a simple implementation which numbered entities as itprocessed the source and recursively expanded packs. Since discardedsubstatements ofif constexpr are still processed innon-template code, entities within them are still numbered. Entities may be lexically nested without being in differentcontexts for the purposes of mangling. For example, the lambdas in All entities from one expansion of a pack are considered to occurlexically before any entities from the next expansion of the same pack,but the ordering is otherwise based on the original token sequence.This is expected to match the numbering that would be established forthe corresponding non-template generated by substitution into the template.As a consequence of these rules, the entity instantiated for a particularsource construct can have a different mangling number in differentinstantiations of the same template. An entity appearing in the originalsource may also go entirely un-numbered if it appears in a discardedsub-statement of Note that the numbering of entities appearing within a To minimize the length of external names,we use two mechanisms,a substitution encoding to eliminate repetition of name components,and abbreviations for certain common names.Each non-terminal in the grammar above for which <substitution>appears on the right-hand side is both a source of future substitutionsand a candidate for being substituted.There are two exceptions that appear to be substitutioncandidates from the grammar, but are explicitly excluded: All substitutions are for entities that would appear in a symbol table.In particular,we make substitutions for prefixes of qualified names,but not for arbitrary components of them.Thus, the components ::n1::foo() and ::n2:foo() appearing in the samename would not result in substituting for the second "foo."Similarly, we do not substitute for expressions,though names appearing in them might be substituted.The reason for this is to facilitate implementations that use thesymbol table to keep track of components that might be substitutable. Note that the above exclusion of function and operator names fromconsideration for substitution doesnot exclude the fullfunction entity, i.e. its name plus its signature encoding. Logically, the substitutable components of a mangled name areconsidered left-to-right,components before the composite structure of which they are a part.If a component has been encountered before,it is substituted as described below.This decision is independent of whether its components have been substituted,so an implementation may optimize by considering large structuresfor substitution before their components.If a component has not been encountered before,its mangling is identified,and it is added to a dictionary of substitution candidates.No entity is added to the dictionary twice. The type of a non-static member function is considered to bedifferent, for the purposes of substitution, from the type of anamespace-scope or static member function whose type appears similar.The types of two non-static member functions are considered to bedifferent, for the purposes of substitution, if the functions aremembers of different classes. In other words, for the purposes ofsubstitution, the class of which the function is a member isconsidered part of the type of function. Substitutions are mangled using the usual rules for <seq-id>: Substitutable components are numbered left-to-right. A componentis earlier in the substitution dictionary than the structure of whichit is a part. All substitutable components are numbered, except thosethat have already been numbered for substitution. For example: Note that substitutable components are the represented symbolic constructs,not their associated mangling character strings.Thus, a substituted object matches its unsubstituted form,and a delimited <function-type> matches its <bare-function-type>. In addition,the following catalog of abbreviations of the form "Sx" are used: Note that the abbreviation St does not require N...E delimiters unlesseither followed by more than one additional composite name component,or preceded by CV-qualifiers or a ref-qualifier for a member function.For example: Many objects in C++ are not clearly part of a single object file,but are required by the ODR to have a single definition.This section identifies, for such objects,where (i.e. in which objects) they should be emitted,and what special treatment might be required if duplicates are possible. In many cases,we will deal with duplicates by putting possibly duplicated objectsin distinct ELF sections or groups of sections,and using the COMDAT feature of Note that nothing in this section should be construed to require COMDATusage for objects with internal linkage unless they may in fact bereferenced outside the translation unit where they appear,for instance due to inlining. It may sometimes be necessary or desirable to reference an out-of-linecopy of a function declared inline,i.e. to reference a global symbol naming the function.This may occur because the implementation cannot, or chooses not to,inline the function, or because it needs an address rather than a call.In such a case,the function is to be emitted in each object where its name is referenced.A COMDAT group is used to eliminate duplicates,with the mangled name of the function as the identifying symbol. Inline functions, whether or not declared as such,and whether they are inline or out-of-line copies,may reference static data or character string literals,that must be kept in common among all copiesby using the local symbol mangling defined above.These objects are named according to the rules for local names in the Scope Encoding section above,and the definition of each is emitted in a COMDAT group,identified by the symbol name described in the Scope Encoding section above.Each COMDAT group must be emitted in any object with referencesto the symbol for the object it contains, whether inline or out-of-line. Some objects with static storage duration have associated guard variablesused to ensure that they are initialized only once(see3.3.3).If the object is emitted using a COMDAT group,the guard variable must be too.It is suggested that it be emitted in the same COMDAT group as theassociated data object,but it may be emitted in its own COMDAT group,identified by its name.In either case, it must be weak. Virtual tables for dynamic classes are emitted as follows: All of the following must be emitted whenever tables are emitted: If the emission of the virtual tables is not unique (as definedabove), they are emitted with vague linkage in a single COMDATgroup, using the mangled name for the virtual table as the COMDATidentifier. On platforms that do not use COMDATs, the tables areemitted separately, and unreferenced tables can be omitted. The key function is the first non-pure virtual function that isnot inline at the point of class definition. Note that if the key function is not inline in the class definition,but its later definition is inline, it will be emitted in every objectcontaining the definition. The RTTI The RTTI The RTTI The RTTI The RTTI NTBS name object for a type is emitted in every objectthat references it, with vague linkage using the NTBS mangled nameas the COMDAT identifier. Vague linkage is required even for classeswhere the Constructors and destructors for a class, whether implicitly-definedor user-defined, are emitted under the same rules as other functions.That is, user-defined constructors or destructors, unless the functionis declared inline, or has internal linkage, are emitted wheredefined, with their complete, and base object variants. Fordestructors, in classes with a virtual destructor, the deletingvariant is emitted as well. A user-defined constructor or destructorwith non-inline, internal linkage is emitted where defined, with onlythe variants actually referenced. Implicitly-defined or inlineuser-defined constructors and destructors are emitted wherereferenced, each in its own COMDAT group identified by the constructoror destructor name. This ABI does not require the generation or use of allocating constructors orinheriting constructors, and does not require the generation or use of deletingdestructors for classes without a virtual destructor. However, if animplementation emits such functions, it must use the external names specifiedin this ABI. If such a function has external linkage, it must be emittedwherever referenced, in a COMDAT group whose name is the external name of thefunction. An instantiation of a class template requires: An instantiation of a function template or member function templateis emitted in any object where its symbol is referenced (non-inline),in a COMDAT group identified by the function name. As described in the Itanium psABI,Itanium implementations shall produce unwind table entries in a [160602] Describe [160907] Introduce layout restrictions on virtual table pointers stored in objects and VTTs. [151021] Support transaction-safe functions. [151019] Add mangling for unresolved names rooted in template template parameters. [150518] Allow arbitrary arguments (encoded as template arguments) in the mangling of vendor-specific type qualifiers. [150502] Clarify mangling of nested and local names and correct an ambiguity in prefix mangling. [150204] Fix alignment calculation for empty proper base classes. [150204] Add mangling for lifetime-extended temporaries. [150204] Add mangling for captured template parameter packs. [150204] Add mangling for braced initializer lists. [150204] Define behavior for variadic arguments of non-trivial type. [140427] Add mangling for dependent elaborated type specifiers. [130911] Add mangling for null template arguments. [130710] Add mangling for [130617] Fix an editorial error in the mangling of floating-point literals. [130606] Clarify rules for POD types in the face of the C++11 changes to the definition of POD. Minor restructuring for clarity in the mangling section. [130422] Add mangling for [130403] Add mangling for ref-qualifiers on function types. [121211] Add [120925] Add [110306] Update description of mangling for argument packs. [110306] Update description of mangling for argument packs. [110301] Change mangling for argument packs. [101124] Revise mangling specification to cover instantiation-dependent expressions. [100625] Add [100212] Permit mangling of additional expression forms as template arguments. [091124] Document passing for IEEE 754r decimal and half-precision floating point types. [091113] Document mangling for IEEE 754r decimal and half-precision floating point types. [091007] Document handling of lambdas. [090715] Document handling of deleted virtual functions. [090312] Remove type stub expressions. Add mangling for [090102] Remove mangling for N-argument functional casts. [081210] Add manglings for type stub expressions, call expressions, char*_t, and N-argument functional casts. Change argument pack mangling. [080707] Add manglings for IEEE 754r decimal and half-precision floating point types. [072507] Add mangling for variadic templates and decltype. [071207] Add mangling for rvalue references. [031006] Clarify that guard variables are used to guard static data members of class templates, as well as function-scope statics. [030806] Specify that function pointers in virtual tables are address/GP pairs on Itanium. [050504] Remove use of [050211] Reverse treatment of ambiguous arguments to __cxa_demangle (3.4). [041118] Clarify the layout of bit-fields. [041025] Indicate that the TC1 definition of POD is intended in the section defining a "POD for the purpose of layout". Clearly indicate that an array whose elements are not PODs for the purpose of layout is itself not a POD for the purpose of layout. [040923] Clarify behavior of [040219] Clarify substition of member function types. [031128] Fix alphabetization of company names. [031123] Add note about forward references to template parameters in member template conversion operators. [031102] Specify the behavior of [030905] Specify the behavior of [030609] Use [030518] Specify behavior of [030518] Define "POD for the purpose of layout." [030316] Add acknowledgements section. [030313] Correct broken links and incorrect formatting. [030103] Clarify definition of substantively different types. [021222] Document mangling for anonymous unions. [021204] Remove note about 32-bit RTTI variation. [021125] Clarify guard functions. [021110] Clarify definition of nearly empty class. [021110] Clarify ordering of string literals in mem-initializer-list. [021110] Remove unnecessary V-adjusting thunks. [021110] Clarify VTT contents. [021021] Specify place and manner of emission for deleting destructors. [021021] Clarify mangling of pointer-to-member functions. [021016] Clarify mangling of floating-point literals. [021014] Clarify use of [021011] Add mangling for unary plus. [021008] Make the names used for constructors and destructor entry points consistent throughout. [021008] Define manglings for typename types. [020916] Clarify ordering of functions in virtual function table. Correct mangling substitution example. [020906] Add ternary expression variant. Remove use of "low-order" to describe bytes in guard variables. [020827] Clarify definition of nearly empty class, dsize, nvsize, nvalign. [020827] Clarify handling of tail-padding. [020326] Clarify wording in [020220] Clarify pointer to member function mangling (5.1.5). [010407] Don't assume that virtual functions can be called through intermediate bases. Add notes about missed opportunities. The VTT parm isn't mangled, either. [010315] Many outstanding updates. Empty classes passed as ordinary classes (3.1.3). Secondary virtual pointers for subobjects reachable via a virtual path (text of 2.6.1, text and example in 2.6.2). Note about locating virtual bases statically during construction (2.6.1). Rename IA-64 to Itanium throughout. Add __cxa_vec_cleanup (3.3.4). [000817] Updates from 17 August meeting, email. [000807] Added base document section (1.5). Further RTTI field name cleanup (2.9.4). Update proposed one-time construction API (3.3.3). Update proposed object construction priority API (3.3.5). Removed <name> substitution (5.1.2). COMDAT not generally necessary for internal linkage (5.2). COMDAT for local static guard variables (5.2.2). [000727] Updates from 20 July meeting. Added section on controlling object construction order (3.3.5). [000707] Introduce consistent type_info field names (2.9.4). Removed vmi flags for publicly/non-publicly inherited bases (2.9.4). Collect all construction/destruction APIs in one section (3.3). Added one-time initialization API (3.3.3). Vector construction/destruction routines are extern "C" (3.3.4). Added routines for vector construction/destruction (3.3.4). Added copy construction runtime API (3.3.4). Make Alex's changes in mangling grammar (5.1). Add <special-name> cases for covariant override thunks (5.1.4). Allow expressions as array type dimensions (5.1.5). Discuss vague linkage for virtual function override thunks (5.2.6). [000621] Add scope section 1.4. Specify guard variables and vague linkage of static data (5.2.2) and instantiated templates (5.2.4). Clarify vcall offsets (2.5.3), VTT (2.6.2), mangling compression rules (5.1.7), and mangling examples. [000511] Specify 32-bit form of vmi_offset_flags. Add export template note. [000505] Updates from 4 May meeting. VTT is preorder, like everything else. Add issue C-3 destructor API. Added demangler API. Yet another try at the nested-name mangling grammar. Don't mangle builtin types (except vendor extended ones). Reverse mangling substitution order, and fix mangling substitution examples. Add vague linkage information for instantiated templates. Specify location of unwind tables. [000502] Fixed mangling of template parameters again. [000427] Reorganization and section numbering. Addednon-virtual function calling conventions. [000417] Updates from 17 April meeting. Clarify order of vcall offsets. More elaboration of construction virtual table. Specification of COMDAT RTTI name. Reorganization of pointer RTTI. Modify mangling grammar to clarify substitution in compound names. Clarify Vague Linkage section. [000407] Updates from 6 April meeting, email. More elaboration of construction vtable. Updates/issues in RTTI. Minor mangling changes. Added Vague Linkage section. [000327] Updates from 30 March meeting. Define base classes to include self, proper base classes. Modify local function mangling per JFW proposal. [000327] Updates from 23 March meeting. Adopt construction vtable Proposal B, and rewrite. Further work on mangling, especially substitution. [000320] Clarify class size limit. Editorial changes in vtable components description. Add alternate to construction vtable proposal. Clarification in array cookie specification. Removed COMMON proxy from class RTTI. Extensive changes to mangling writeup. [000314] Construction vtable modifications. RTTI modifications for incomplete class types. Mangling rework: grammar, new constructs, function return types. [000309] Add limits section. Specify NULL member pointer values. Combine vtable content and order sections; clarify ordering. Specify when distinct virtual function entries are needed for overriders. Define (and modify) vector constructor/destructor runtime APIs. Virtual base offsets are promoted from non-virtual bases. [000228] Add thunk definition. Revise inheritance graph order definition. Fix member function pointer description (no division by two). Move bit-field allocation description (much modified) to the non-virtual-base allocation description. Replace virtual function calling convention description. [000228] Add thunk definition. Revise inheritance graph order definition. Fix member function pointer description (no division by two). Move bit-field allocation description (much modified) to the non-virtual-base allocation description. Replace virtual function calling convention description. [000217] Add excess-size bit-field specification. Add namespace/header section. Touch up array new cookies. Remove construction vtable example to new file. Add mangling proposal. [000214] Complete array new cookie specification. Remove unnecessary RTTI flags. Correct repeated inheritance flag description. Move all type_info subclasses in namespace abi, not namespace std. Note requirements for an implementation to prevent users from emitting invalid vtables for RTTI classes. Include construction vtable proposal. [000203] Incorporate discussion of 3 Febrary. Remove __reference_type_info (issue A-22). Restructure struct RTTI and flags (issue A-23). Clarify __base_class_info layout. [000125] Incorporate discussion of 20 January, generally clarifications. Resolved A-19 (choice of a primary virtual base). Answered Nathan's questions about RTTI. Included RTTI "Deliberations" as rationale notes in the specification, or removed redundant ones. Added array operator new section. [000119] Clarify when virtual base offsets are required. Note that a vtable has offset-to-top and RTTI entries for classes with virtual bases even if there are no virtual functions. Resolve allocation of a virtual base class that is a primary base for another base (A-17). Resolve choice of a primary virtual base class that is a primary base for another base (A-19). Describe the (non-)effect of virtual bases on the alignment of the non-virtual part of a class as the base of another class (A-18). [991230] Integrate proposed resolution of A-16, A-17 in base class layout. Add outstanding questions list, and clean up questions in text. [991229] Clarify definition of nearly empty class, layout of virtual bases. font color=blue>[991203] Added description of vfunc calling convention from Jason. [991104] Noted pair of vtable entries for virtual destructors. [991019] Modified RTTI proposal for 14 October decisions. [991006] Added RTTI proposal. [990930] Updated to new vtable layout proposal. [990811] Described member pointer representations, virtual table layout. [990730] Selected first variant for empty base allocation; removed others. Acknowledgements
Chapter 1: Introduction
Recommendation for new platforms: consider forbidding the use of function templates on your platform so that the ABI can remove these expression-mangling rules.
1.1 Definitions
operator delete) for T.class A : public B, public C,A is walked first,then B and its subobjects,and then C and its subobjects.)p is a type-dependent identifier, the expressionsizeof(sizeof(p))is neither type-dependent, nor value-dependent, but it is instantiation-dependent (and couldturn out to be invalid if after substitution of template argumentsp turns out tohave an incomplete type).Similarly, a type expressed in source code isinstantiation-dependent if the sourceform includes aninstantiation-dependent expression. For example, the type formdouble[sizeof(sizeof(p))] (withp a type dependent identifier)is instantiation-dependent.
Such classes may be primary base classes even if virtual,sharing a virtual pointer with the derived class.
Where references to the ISO C++ are made in this paragraph, the TechnicalCorrigendum 1 version of the standard is intended.
There have been multiple published revisions to the ISO C++ standard,and each one has included a different definition of POD. To ensureinteroperation of code compiled according to different revisions ofthe standard, it is necessary to settle on a single definition for aplatform. A platform vendor may choose to follow a different revisionof the standard, but by default, the definition of POD under this ABIis the definition from the 2003 revision (TC1).this)or other parts of the environmentbefore transferring control to the target function,and possibly making further modifications after its return.A thunk may contain as little as an instruction to be executed prior tofalling through to an immediately following target function,or it may be a full function with its own stack frame that doesa full call to the target function. 1.2 Limits
1.3 Namespace and Header
cxxabi.h will be provided byimplementations that declares these APIs.The reference header file included with this ABI definitionshall be the authoritative definition of the APIs.__cxxabiv1.The header file will also declare a namespace aliasabifor__cxxabiv1.It is expected that users will use the alias,and the remainder of the ABI specification will use it as well.longjmp_unwind; or 1.4 Scope of This ABI
1.4.1 Runtime Libraries
libcxa.so on Itanium systems,or in auxiliary DSOs automatically loaded by it.It shall place implicit compiler supportin a library separate from the standard support library,with any external names chosen to avoid conflicts between vendors(e.g. by including a vendor identifier as part of the names).This allows a program to function properly if linked with thetarget's standard support library and the implicit compiler supportlibraries from any implementations used to build components. 1.4.2 Export Templates
1.5 Base Documents
Chapter 2: Data Layout
2.1 General
2.2 POD Data Types
_Bool,thenbool follows those rules. Otherwise, it has sizeand alignment 1.T & andT && are treatedexactly like the pointer typeT *. 2.3 Member Pointers
2.3.1 Data Member Pointers
ptrdiff_t.ptrdiff_t.-1.[dcl.init], "zero initialization" of a datamember pointer object stores a null pointer value into it. Under thisrepresentation, that value has a non-zero bit representation. On mostmodern platforms, data member pointers are the only type with thisproperty.virtual base relationship, and so a static offsetis always known.-1, the memberpointer will subsequently be treated as a null pointer. This isconsidered an irreparable defect in this ABI.Recommendation for new platforms: consider usinga different representation for data member pointers, such as left-shiftingthe offset by one and using a non-zero low bit to indicate a non-nullvalue. struct alignas(2) B1 {}; struct B2 : B1 {}; struct B3 : B1 {}; struct D : B2, B3 { char a, b; }; // The offset in D of the B3 base subobject is 2, but the // offset of the data member b is 1. auto mptr = static_cast<char B3::*>(&D::b); 2.3.2 Member Function Pointers
fnptr_tis the appropriate function-pointer type for a member function of this type: struct { fnptr_t ptr; ptrdiff_t adj; };ptr set to a pointer to the function, using the baseABI's representation of function pointers.ptr set to 1 plus the function'sv-table entry offset (in bytes), converted to a function pointer as if byreinterpret_cast<fnptr_t>(uintfnptr_t(1 + offset)),whereuintfnptr_t is an unsigned integer of the samesize asfnptr_t.adj stores the offset (in bytes)which must be added to thethis pointer before the call.ptr set to a null pointer. The valueofadj is unspecified for null member function pointers.this-adjustmentstored inadj is left-shifted by one, and the low bitofadj indicates whetherptr is a functionpointer (including null) or the offset of a v-table entry. A virtualmember function pointer setsptr to the v-table entryoffset as if byreinterpret_cast<fnptr_t>(uintfnptr_t(offset)).A null member function pointer setsptr to a nullfunction pointer and must ensure that the low bit ofadjis clear; the upper bits ofadj remain unspecified.ptr is equalto a null function pointer and (only when using the 32-bit ARMrepresentation) the low bit ofadj is clear.ptr andadjare equal. Note that the C++ standard does not require member pointersto the same virtual member function to compare equal; implementationsusing this ABI will do so, but only if the member pointers are builtusing the same v-table offset, which they may not be in the presenceof multiple inheritance or overrides with covariant return types.this-adjustment value. In the standard representation,this simply means adding it toadj; in the 32-bit ARMrepresentation, the addend must be left-shifted by one. Because theadjustment does not factor into whether a member function pointer isnull, this addition can be done unconditionally when performing aconversion.this address.this address and call the v-table entry at the stored offset. 2.4 Non-POD Class Types
For a class type C which is not aPOD for the purposeof layout, assume that all component types (i.e. proper baseclasses and non-static data member types) have been laid out, definingsize, data size, non-virtual size, alignment, and non-virtualalignment.(See the description of these terms inGeneral above.)Layout (of type C) is done using the following procedure. Initialization
Case (2b) above is now considered to be an error in the design. Theuse of the first indirect primary base class as the derived class'primary base does not save any space in the object, and will causesome duplication of virtual function pointers in the additional copyof the base classes virtual table.this pointer will be required forcalls to its virtual functions.this in some cases, but this was incorrect, asthevirtual function call algorithm requires thatthe function be looked up through a pointer to a class that definesthe function, not one that just inherits it. Removing thatrequirement would not be a good idea, as there would then no longer bea way to emit all thunks with the functions they jump to. Forinstance, consider this example:struct A { virtual void f(); };struct B : virtual public A { int i; };struct C : virtual public A { int j; };struct D : public B, public C {};this adjustment is required and no thunk is generated.However, inside D objects, A is no longer a primary base of C, so if weallowed calls toC::f() to use the copy of A's vtable in the Csubobject, we would need to adjustthis fromC*toB::A*, which would require a third-party thunk. Since werequire that a call toC::f() first convert toA*, C-in-D's copy of A's vtable is never referenced, so thisis not necessary. Allocation of Members Other Than Virtual Bases
T and whose declared width isn bits:sizeof(T) andn:sizeof(T)*8 >= n, the bit-field is allocated as required by the base C ABI, subject to the constraint that a bit-field is never placed in the tail padding of a base class of C.sizeof(T)*8< n, let T' be the largest integral POD type withsizeof(T')*8<= n. The bit-field is allocated starting at the next offset aligned appropriately for T', with length n bits. The firstsizeof(T)*8 bits are used to hold the value of the bit-field, followed byn - sizeof(T)*8 bits of padding. 2.5 Virtual Table Layout
2.5.1 General
ptrdiff_t unless otherwise stated. 2.5.2 Virtual Table Components and Order
this pointer to the virtual base,and then adds the value contained at the vcall offsetin the virtual base to itsthis pointerto get the address of the derived object where the function was overridden.These values may be positive or negative.These are first in the virtual table if present,ordered as specified in categories 3 and 4 ofSection 2.5.3 below.
However, in classes sharing a virtual table with a primary base class,the vcall and vbase offsets added by the derived class all come beforethe vcall and vbase offsets required by the base class,so that the latter may be laid out as required by the base classwithout regard to additions from the derived class(es).ptrdiff_t.It is always present.The offset provides a way to find the top of the object from any basesubobject with a virtual table pointer.This is necessary for dynamic_cast<void*> in particular.
In a complete object virtual table,and therefore in all of its primary base virtual tables,the value of this offset will be zero.For the secondary virtual tables of other non-virtual bases,and of many virtual bases,it will be negative.Only in some construction virtual tables will some virtual base virtualtables havepositive offsets, due to a different ordering of the virtual bases inthe full object than in the subobject's standalone layout. 2.5.3 Virtual Table Construction
Category 0: Trivial
Structure: Category 1: Leaf
Structure: Category 2: Non-Virtual Bases Only
Structure:Base,and a derived classDerived for which we are constructingthis set of virtual tables,we shall refer to the virtual table forBase asBase-in-Derived.The virtual pointer of each base subobject of an object of thederived class will point to the corresponding base virtual table in this set.
The primary virtual table can be viewed as two virtual tables accessedfrom a shared virtual table pointer.
A benefit of replicated virtual function entries (i.e., entries thatappear both in the primary virtual table and in a secondary virtualtable) is that they reduce the number of this pointer adjustmentsduring virtual calls. Without replication, there would be more caseswhere the this pointer would have to be adjusted to access a secondaryvirtual table prior to the call. These additional cases would beexactly those where the function is overridden in the derived class,implying an additional thunk adjustment back to the original pointer.Replication saves two 'this' adjustments for each virtual call to anoverridden function originally introduced by a non-primary proper baseclass. Category 3: Virtual Bases Only
Category 4: Complex
For an S-as-T virtual table,the vbase offset entries from the primary virtual table for Tare replaced with appropriate offsets given the completed hierarchy.
Consider the following inheritance hierarchy: struct S { virtual void f() }; struct T : virtual public S {}; struct U : virtual public T {}; struct V : public T, virtual public U {}; struct W : public T {};
The above-described virtual table group layout would allow allnon-virtual secondary base class virtual tables in a group to beaccessed from a virtual pointer for one of them,since the relative offsets would be fixed.(Since the primary virtual table could end up being embedded,as the primary base class virtual table,in another virtual table with additional virtual pointers separating itfrom its secondary virtual tables,this observation is not true of the primary virtual table.)However, since construction virtual table groups may be organizeddifferently (see below),an implementation may not depend on this relationship betweensecondary virtual tables.This tradeoff was made because the space savings resulting from notrequiring construction virtual tables to occur in complete groupswas considered more important than potential sharing of virtualpointers. 2.6 Virtual tables During Object Construction
2.6.1 General
When a complete object constructor is constructing a virtual base, itmust be wary of using the vbase offsets in the virtual table, sincethe possibly shared virtual pointer may point to a constructionvirtual table of an unrelated base class. For instance, in
the virtual pointers for T and V are in the same place. When V's constructor is about to construct U, that virtual pointer points toa virtual table for T, and therefore cannot be used to locate U. struct S {}; struct T: virtual S {}; struct U {}; struct V: virtual T, virtual U {}; 2.6.2 VTT Order
This construction is applied recursively.
There are virtual pointers for direct and indirect base classes.Although primary non-virtual bases do not get secondary virtualpointers, they do not otherwise affect the ordering.
The virtual VTT addresses come last because they are only passedto the virtual base class constructors for the complete object.
It is required that the VTT for a complete class D be identical instructure to the sub-VTT for the same class D as a base of anotherclass E derived from it,so that the constructors for D can depend on that structure.Therefore, the various components of its VTT are present based on therules given, even if they point to theD complete object virtual table or its secondary virtual tables.That is, secondary VTTs are present for all bases with virtual bases(including the virtual bases themselves,which have their secondary VTTs in the virtual VTT section),and secondary virtual pointers are present for all bases with eithervirtual bases or virtual function declarations overridden along avirtual path.The only exception is that a primary non-virtual base class does notrequire a secondary virtual pointer.Then the VTT for D would appear in the following order,where indenting indicates the sub-VTT structure,and asterisks (*) indicate that construction virtual tables instead ofcomplete object virtual tables are required. class A1 { int i; }; class A2 { int i; virtual void f(); }; class V1 : public A1, public A2 { int i; };// A2 is primary base of V1, A1 is non-polymorphic class B1 { int i; }; class B2 { int i; }; class V2 : public B1, public B2, public virtual V1 { int i; };// V2 has no primary base, V1 is secondary base class V3 {virtual void g(); }; class C1 : public virtual V1 { int i; };// C1 has no primary base, V1 is secondary base class C2 : public virtual V3, public virtual V2 { int i; };// C2 has V3 primary (nearly-empty virtual) base, V2 is secondary base class X1 { int i; }; class C3 : public X1 { int i; }; class D : public C1, public C2, public C3 { int i; };// C1 is primary base, C2 is secondary base, C3 is non-polymorphic // 1. Primary virtual pointer: [0] D has virtual bases (complete object vptr) // 2. Secondary VTTs: [1] C1 * (has virtual base) [2] V1-in-C1 in D (secondary vptr) [3] C2 * (has virtual bases) [4] V3-in-C2 in D (primary vptr) [5] V2-in-C2 in D (secondary vptr) [6] V1-in-C2 in D (secondary vptr) // 3. Secondary virtual pointers: // (no C1-in-D -- primary base) [7] V1-in-D (V1 is virtual) [8] C2-in-D (preorder; has virtual bases) [9] V3-in-D (V3 is virtual) [10] V2-in-D (V2 is virtual) // (For complete object D VTT, these all can point to the // secondary vtables in the D vtable, the V3-in-D entry // will be the same as the C2-in-D entry, as that is the active // V3 virtual base in the complete object D. In the sub-VTT for // D in a class derived from D, some might be construction // virtual tables.) // 4. Virtual VTTs: // (V1 has no virtual bases). [11] V2 * (V2 has virtual bases) [12] V1-in-V2 in D * (secondary vptr, V1 is virtual) (A2 is primary base of V1) // (V3 has no virtual bases)
2.6.3 Construction Virtual Table Layout
2.6.4 Construction Virtual Table entries
2.7 Array Operator
new Cookiesnew expression is used to create a new array,a "cookie" must sometimes be added to the allocation. A cookie isa header on the array allocation, preceding the array elements,which stores the number of array elements that were allocated.T be the element type of the allocated array,looking through all levels of nested array.Whether a cookie is required is determined as follows:::operator new[](size_t, void*)).T has a non-trivial destructor, or elseT (as would be found for thedelete[] operator on an operand of typeT*), and that function takes asize_targument.delete[] without a:: prefix, even if thenew expression does include a:: prefix. This is necessary to ensure consistency betweennew anddelete, as it is not always ill-defined under the standard to mix the use of global and class-scoped allocation and deallocation functions. (For example, a class-specific deallocation function might delegate to the corresponding global deallocation function.)cookie_t be the type of a cookie. Under the standard ABI, this issize_t; however, some platforms use a variant ABI which stores additional information.count be the total number of objects of typeT that will be created (including any scaling necessary for nested arrays). This is the value that will be stored in the cookie. For example, given the expresssionnew T[len][7][5],count islen * 7 * 5.align bealignof(T). This is the alignment of the allocation. Note that this does not include the alignment ofcookie_t. The standard permits array allocation to request a larger allocation to accommodate cookies, but not a more-aligned allocation. Adding a cookie is also not permitted to change the choice of allocation or deallocation function, which it otherwise could in uncommon situations wherecookie_t has a new-extended alignment. As a result, the implementation may be required to load and store the cookie with less than its natural alignment.prefix_size bemax(sizeof(cookie_t), align).allocation_size beprefix_size + count * sizeof(T). This is the size value that will be passed to the allocation function.prefix_size from the start of the allocation. This pointer is the result of thenew expression.prefix_size - sizeof(cookie_t) from the start of the allocation. However, in some variant ABIs, padding is added after the cookie, which is stored at the start of the allocation. In either case, any padding bytes have indeterminate values.delete[] expression must also compensate for thepossible presence of an array cookie:T be the element type of the pointer, looking through nested array types as above.ptr be the pointer (of typeT*) to the first array element.::-prefixed, non-placementnew expression creating an array of typeT. Note that it is not possible to invoke the reserved placement deallocation function (::operator delete[](void*, void*)) with adelete[] expression, and so there is no need for an exception for this case.-sizeof(cookie_t) fromptr, and the original allocation is found at offset-prefix_size fromptr. In variant ABIs that pad after the cookie, the cookie will be at offset-prefix_size.T has a non-trivial destructor, the value ofcount stored in the cookie is the number of elements to destroy.size_t argument, it is passedallocation_size, computed as above given the value ofcount stored in the cookie. 2.8 Initialization Guard Variables
2.9 Run-Time Type Information (RTTI)
2.9.1 General
(c) only requires type information about dynamic class types,but (a) and (b) may apply to other types as well;for example, when a pointer to an int is thrown,it can be caught by a handler that catches "int const*".
Note that the full structure described by an RTTI descriptor mayinclude incomplete types not required by the Standard to be completed,although not in contexts where it would cause ambiguity.Therefore, any cross-references within the RTTI to types not known tobe complete must be weak symbol references. 2.9.2 Place of Emission
abi::__fundamental_type_info (or a type derived therefrom),whereas the objects corresponding to X* and X const* shall have typeabi::__pointer_type_info (or a type derived therefrom).(Note that various other type_info objects for class types may residein the run-time support library by virtue of the preceding rules,e.g. that ofstd::bad_alloc.) 2.9.3 The
typeid Operator namespace std { class type_info { public:virtual ~type_info();bool operator==(const type_info &) const;bool operator!=(const type_info &) const;bool before(const type_info &) const;const char* name() const; private:type_info (const type_info& rhs);type_info& operator= (const type_info& rhs); }; }name() member function returns the address of anNTBS, unique to the type, containingthemangled name of the type.Themangled name of the NTBS is alsodefined by the ABI to allow consistent reference to it, andtheVague Linkage section specifies how toproduce a unique copy.operator==,operator!=, andbefore()members are easily implemented in terms ofan address comparison of the name NTBS. 2.9.4 RTTI Layout
std::type_info class given below,and do not imply anything about the member functions of these classes.Virtual member functions of these classes may only be used within thetarget systems' respective runtime libraries.The data members must be laid out exactly as specified.std::type_info.This entry is located at the word preceding the locationpointed to by the virtual pointer (i.e., entry "-1").The entry is allocated in all virtual tables;for classes having virtual bases but no virtual functions,the entry is zero.std::type_info class in addition to the virtual tablepointer implied by its virtual destructor: class type_info { ... // Seesection 2.9.3private: const char *__type_name; };__type_name is a pointer to a NTBS representing the mangled name of the type.abi::__fundamental_type_infoabi::__array_type_infoabi::__function_type_infoabi::__enum_type_infoabi::__class_type_infoabi::__si_class_type_infoabi::__vmi_class_type_infoabi::__pbase_type_infoabi::__pointer_type_infoabi::__pointer_to_member_type_infoabi::__fundamental_type_info adds no data memberstostd::type_info;abi::__array_type_info andabi::__function_type_info do not add datamembers tostd::type_info(these types are only produced by the typeid operator;they decay in other contexts). abi::__enum_type_info does not add data members either.abi::__class_type_info is used for class types having no bases,and is also a base type for the other two class type representations. class __class_type_info : public std::type_info {}abi::__class_type_info objects can always be compared,for equality (i.e. of the types represented) or ordering,by comparison of their name NTBS addresses.In addition, complete class RTTI objectsmay also be compared for equalityby comparison of their type_info addresses.abi::__si_class_type_info is used.It adds toabi::__class_type_info a single member pointing to the type_info structure for the base type,declared "__class_type_info const *__base_type". class __si_class_type_info : public __class_type_info {public: const __class_type_info *__base_type; };__si_class_type_info constraints,abi::__vmi_class_type_info is used.It is derived fromabi::__class_type_info: class __vmi_class_type_info : public __class_type_info {public: unsigned int __flags; unsigned int __base_count; __base_class_type_info __base_info[1]; enum __flags_masks { __non_diamond_repeat_mask = 0x1, __diamond_shaped_mask = 0x2 }; };__flags is a word with flags describing details about the class structure, which may be referenced by using the__flags_masks enumeration.
These flags refer to both direct and indirect bases. The type of the__flags field is defined by each psABI, but must be at least 16 bits. For the 64-bit Itanium ABI, it will be unsigned int (32 bits).__base_count is a word with the number of direct proper base class descriptions that follow. The type of the__base_count field is defined by each psABI. For the 64-bit Itanium ABI, it will be unsigned int (32 bits).__base_info[] is an array of base class descriptions -- one for every direct proper base. Each description is of the type: struct abi::__base_class_type_info {public: const __class_type_info *__base_type; long __offset_flags; enum __offset_flags_masks { __virtual_mask = 0x1, __public_mask = 0x2, __offset_shift = 8 }; };__base_type member points to the RTTI for the base type.__offset_flags are a signed offset. For a non-virtual base, this is the offset in the object of the base subobject. For a virtual base, this is the offset in the virtual table of the virtual base offset for the virtual base referenced (negative).__offset_flags contains flags, as given by the masks from the enumeration__offset_flags_masks:abi::__pbase_type_info is a base for both pointer types andpointer-to-member types.It adds two data members: class __pbase_type_info : public std::type_info {public: unsigned int __flags; const std::type_info *__pointee; enum __masks { __const_mask = 0x1, __volatile_mask = 0x2, __restrict_mask = 0x4, __incomplete_mask = 0x8, __incomplete_class_mask = 0x10, __transaction_safe_mask = 0x20 __noexcept_mask = 0x40 }; };__flags is a flag word describing the cv-qualification and other attributes of the type pointed to (e.g., "int volatile*" should have the "volatile" bit set in that word). For pointer to function and pointer-to-member-function types,__flags is also used to indicate a "qualification" of sorts for the pointed-to (member) function type. That is the case for__transaction_safe_mask and__noexcept_mask where__pointee is a pointer to the "unqualified" version of the function type (e.g., one without the exception specification in the case of__noexcept_mask).__pointee is a pointer to thestd::type_info derivation for the unqualified type being pointed to.__flagsbits should not be foldedinto the pointer to allow future definition of additional flags.It contains the following bits,and may be referenced using the flags defined in the__masks enum:__pointee type has const qualifier__pointee type has volatile qualifier__pointee type has restrict qualifier__pointee type is incomplete__pointee is incomplete (in pointer to member)__pointee type is function type without the transaction-safe indication__pointee type is function type without the exception specificationabi::__pbase_type_info is for a director indirect pointer to an incomplete class type,the incomplete target type flag is set.When it is for a direct or indirect pointer to a member ofan incomplete class type,the incomplete class type flag is set.In addition, it and all of the intermediateabi::__pointer_type_info structs in the chaindown to theabi::__class_type_info for theincomplete class type must be prevented from resolving to thecorresponding type_info structs for the complete class type,possibly by making them local static objects.Finally, a dummy class RTTI is generated for the incomplete typethat will not resolve to the final complete class RTTI(because the latter need not exist),possibly by making it a local static object.abi::__pbase_type_info objects can always be comparedfor equality (i.e. of the types represented) or orderingby comparison of their name NTBS addresses.In addition,unless either or both have either of the incomplete flags set,equality can be tested by comparing the type_info addresses.abi::__pointer_type_info is derived fromabi::__pbase_type_info with no additional data members.abi::__pointer_to_member_type_info type adds one fieldtoabi::__pbase_type_info: class __pointer_to_member_type_info : public __pbase_type_info {public: const abi::__class_type_info *__context; };__context is a pointer to anabi::__class_type_info corresponding to the class type containing the member pointed to (e.g., the "A" in "int A::*")
Note that this ABI requires elsewhere that a virtual table be emitted for adynamic type in the object where the first non-inline virtual functionmember is defined, if any, or everywhere referenced if none.Therefore, an implementation should include at least onenon-inline virtual function member and define it in the library,to avoid having user code inadvertently preempt the virtual table.Since the Standard requires a virtual destructor,and it will rarely be called,it is a good candidate for this role. 2.9.5
std::type_info::name() 2.9.6 The
dynamic_cast Operator 2.9.7 The
dynamic_cast Algorithm extern "C" void* __dynamic_cast ( const void *sub, const abi::__class_type_info *src, const abi::__class_type_info *dst, std::ptrdiff_t src2dst_offset); /* sub: source address to be adjusted; nonnull, and since the * source object is polymorphic, *(void**)sub is a virtual pointer. * src: static type of the source object. * dst: destination type (the "T" in "dynamic_cast<T>(v)"). * src2dst_offset: a static hint about the location of the * source subobject with respect to the complete object; * special negative values are: * -1: no hint * -2: src is not a public base of dst * -3: src is a multiple public base type but never a * virtual base type * otherwise, the src type is a unique public nonvirtual * base type of dst at offset src2dst_offset from the * origin of dst. */
Rationale: 2.9.8 The Exception Handler Matching Algorithm
Chapter 3: Code Emission and APIs
3.1.1 Function Definitions
3.1.2 Parameters
3.1.2.1
this Parametersthis parameter of pointer type. It ispassed as if it were the first parameter in the function prototype,except as modified fornon-trivialreturn values.3.1.2.2
VTT ParametersVTTparameter of pointer type. It is passed as if it were the secondparameter in the function prototype, immediately following thethis parameter, except as modified fornon-trivial return values.3.1.2.3 Non-Trivial Parameters
va_arg inthe callee retrieves the address and treats it as a reference to thetemporary.3.1.2.4 Parameters of Special Class Type
std::decimal::decimal32,std::decimal::decimal64, orstd::decimal::decimal128 as defined in TR 24733is passed the same as the corresponding native decimalfloating-point scalar type.3.1.2.5 Reference Parameters
3.1.2.6 Empty Parameters
3.1.3 Return Values
3.1.3.1 Non-trivial Return Values
this andVTT parameters.3.1.3.2 Return Values of Special Class Type
std::decimal::decimal32,std::decimal::decimal64, orstd::decimal::decimal128 as defined in TR 24733 isreturned the same as the corresponding native decimal floating-pointscalar type.3.1.3.3 Reference Return Values
3.1.3.4 Empty Return Values
struct { char c; };3.1.3.5 Constructor Return Values
void results.this. This may permit more efficientcode generation in the caller.3.1.3.6 Destructor Return Values
void results.this. This may permit more efficientcode generation in the caller. This modified rule does not apply todeleting destructors. It also does not apply when making a virtual callto a complete-object destructor, so thatthis-adjustment thunksdo not need to adjust the return value after the call. 3.2.1 General
3.2.2 Virtual Table Components
3.2.3 Callee
this pointerpoints to an A*,and will convert it to a C*(which merely requires adding a constant offset)before transferring control to the non-adjusting entry point for C::f.this pointerpoints to the unique virtual V subobject of C.(Note that there may in general be multiple V subobjects of C,but that only one of them will be virtual.)This entry point must load the vcall offset corresponding to f locatedin the virtual table for V obtained via itsthis pointer,extract the vcall offset corresponding to f located in that virtual table,and add this offset to thethis pointer.(Note that, as specified in the data layout document,when V is used as a virtual base,its virtual table contains vcall offsets for every virtual functiondeclared in V or any of its bases.)Then,this entry point must transfer control to the non-adjusting entry point.this pointerpoints to an M*,and will convert it to a V* (a fixed offset),where V is the nearest virtual base to Malong the inheritance path from C to M.Then, it will convert the V* to a C* by using the vcall offsetstored in the V's virtual table. 3.2.4 Caller
this pointer.thispointer will be required. 3.2.5 Implementation
3.2.6 Pure Virtual Function API
extern "C" void __cxa_pure_virtual ();
3.2.7 Deleted Virtual Function API
extern "C" void __cxa_deleted_virtual ();
3.3 Construction and Destruction APIs
3.3.1 Subobject Construction and Destruction
this pointer isNULL. All other destructors, including deletingdestructors for classes with a virtual destructor, may assume that thethis pointer is notNULL. // Sub-VTT for D (embedded in VTT for its derived class X): static vtable *__VTT__1D [1+n+m] ={ D primary vtable, // The sub-VTT for B-in-D in X may have further structure: B-in-D sub-VTT (n elements), // The secondary virtual pointers for D's bases have elements // corresponding to those in the B-in-D sub-VTT, // and possibly others for virtual bases of D: D secondary virtual pointer for B and bases (m elements) }; D ( D *this, vtable **ctorvtbls ) {// (The following will be unwound, not a real loop):for ( each base A of D ) { // A "boring" base is one that does not need a ctorvtbl: if ( ! boring(A) ) { // Call subobject constructors with sub-VTT index // if the base needs it -- only B in our example: A ( (A*)this, ctorvtbls + sub-VTT-index(A) ); } else { // Otherwise, just invoke the complete-object constructor: A ( (A*)this ); }} // Initialize virtual pointer with primary ctorvtbls address// (first element): this->vptr = ctorvtbls+0;// primary virtual pointer// (The following will be unwound, not a real loop):for ( each subobject A of D ) { // Initialize virtual pointers of subobjects with ctorvtbls // addresses for the bases if ( ! boring(A) ) { ((A*)this)->vptr = ctorvtbls + 1+n + secondary-vptr-index(A); // where n is the number of elements in the sub-VTTs } else { // Otherwise, just use the complete-object vtable: ((A *)this)->vptr = &(A-in-D vtable); }} // Code for D constructor.... } 3.3.2 Construction by Inherited Constructor
usingdeclaration. Formally, such initialization is not performed by a derived classconstructor, and instead the initialization expression itself directlyinitializes each base class (recursively, if the constructor is inherited froman indirect base class) and each non-static data member. To reduce codeduplication, this ABI permits such initialization to be factored out into aninheriting constructor function.struct X { X(); };struct A { A(int); };struct B : A { using A::A; };struct C : virtual B { using B::B; X x; };struct D : C { using C::C; };C c(0);D d(0);// The initializations of c and d behave as if they call C::Ccomplete A(int)(0) and D::Dcomplete A(int)(0):D::Dcomplete A(int)(int n) : Bbase A(int)(n), Cbase A(int)() {}// _ZN1DCI11AEiC::Ccomplete A(int)(int n) : Bbase A(int)(n), x() {} // _ZN1CCI11AEiC::Cbase A(int)() : /*no init for vbase B*/ x() {} // _ZN1CCI21AEiB::Bbase A(int)(int n) : A(n) {} // _ZN1BCI21AEi 3.3.3 One-time Construction API
extern "C" int __cxa_guard_acquire ( __int64_t *guard_object );
__cxa_guard_release or__cxa_guard_abort must be called with the same argument.The first byte of theguard_object is not modified by this function.guard_object with a mutex. If this functionreturns 1, the mutex will have been acquired by the calling thread.extern "C" void __cxa_guard_release ( __int64_t *guard_object );
__cxa_guard_acquire after setting the first byte of theguard object.extern "C" void __cxa_guard_abort ( __int64_t *guard_object );
__cxa_guard_acquire.
if (obj_guard.first_byte == 0) { if ( __cxa_guard_acquire (&obj_guard) ) { try {... initialize the object ...; } catch (...) { __cxa_guard_abort (&obj_guard); throw; }... queue object destructor with __cxa_atexit() ...; __cxa_guard_release (&obj_guard); } }ld1.acq operation toload the flag. 3.3.4 Array Construction and Destruction API
extern "C" void * __cxa_vec_new ( size_t element_count, size_t element_size, size_t padding_size, void (*constructor) ( void *this ), void (*destructor) ( void *this ) );
__cxa_vec_new2(element_count, element_size, padding_size, constructor, destructor, &::operator new[], &::operator delete[])
extern "C" void * __cxa_vec_new2 ( size_t element_count, size_t element_size, size_t padding_size, void (*constructor) ( void *this ), void (*destructor) ( void *this ), void* (*alloc) ( size_t size ), void (*dealloc) ( void *obj ) );
alloc) for the array preceded by the specifiedpadding, initialize the cookie if the padding is non-zero, and callthe given constructor on each element. Return the address of thearray proper, after the padding.alloc throws an exception, rethrow the exception.Ifalloc returnsNULL, returnNULL. If theconstructor throws anexception, calldestructor for any already constructedelements, and rethrow the exception. If thedestructorthrows an exception, callstd::terminate.NULL, in which case it mustnot be called. If thepadding_size is zero, thedestructor may beNULL; in that case it mustnot be called.alloc nordealloc may beNULL.std::bad_array_new_length is thrown.extern "C" void * __cxa_vec_new3 ( size_t element_count, size_t element_size, size_t padding_size, void (*constructor) ( void *this ), void (*destructor) ( void *this ), void* (*alloc) ( size_t size ), void (*dealloc) ( void *obj, size_t size ) );
__cxa_vec_new2 except that the deallocationfunction takes both the object address and its size.extern "C" void __cxa_throw_bad_array_new_length (void);
std::bad_array_new_length.May be invoked by the compiler when the number of array elementsexpression of anew[] operation violates the requirementsof the C++ standard.extern "C" void __cxa_vec_ctor ( void *array_address, size_t element_count, size_t element_size, void (*constructor) ( void *this ), void (*destructor) ( void *this ) );
terminate().The constructor and/or destructor pointers may be NULL.If either is NULL, no action is taken when it would have been called.extern "C" void __cxa_vec_dtor ( void *array_address, size_t element_count, size_t element_size, void (*destructor) ( void *this ) );
terminate().The destructor pointer may be NULL,in which case this routine does nothing.extern "C" void __cxa_vec_cleanup ( void *array_address, size_t element_count, size_t element_size, void (*destructor) ( void *this ) );
terminate().The destructor pointer may be NULL,in which case this routine does nothing.extern "C" void __cxa_vec_delete ( void *array_address, size_t element_size, size_t padding_size, void (*destructor) ( void *this ) );
array_address isNULL, returnimmediately. Otherwise, given the (data) address of an array, thenon-negative size of prefix padding for the cookie, and the size ofits elements, call the given destructor on each element, using thecookie to determine the number of elements, and then delete the spaceby calling::operator delete[](void *).If the destructor throws an exception, rethrow after (a) destroyingthe remaining elements, and (b) deallocating the storage. If thedestructor throws a second exception, callterminate().If padding_size is 0, the destructor pointer must be NULL. If thedestructor pointer is NULL, no destructor call is to be made.
The intent of this function is to permit an implementation to callthis function when confronted with an expression of the formdelete[] p in the source code, provided that the defaultdeallocation function can be used. Therefore, the semanticsof this function are consistent with those required by the standard.The requirement that the deallocation function be called even if thedestructor throws an exception derives from the resolution to DR 353to the C++ standard, which was adopted in April, 2003.extern "C" void __cxa_vec_delete2 ( void *array_address, size_t element_size, size_t padding_size, void (*destructor) ( void *this ), void (*dealloc) ( void *obj ) );
__cxa_vec_delete,except that the given function is used for deallocationinstead of the default delete function.Ifdealloc throws an exception,the result is undefined.Thedealloc pointer may not be NULL.extern "C" void __cxa_vec_delete3 ( void *array_address, size_t element_size, size_t padding_size, void (*destructor) ( void *this ), void (*dealloc) ( void *obj, size_t size ) );
__cxa_vec_delete,except that the given function is used for deallocationinstead of the default delete function.The deallocation function takes both the object address and its size.Ifdealloc throws an exception,the result is undefined.Thedealloc pointer may not be NULL.extern "C" void __cxa_vec_cctor ( void *dest_array, void *src_array, size_t element_count, size_t element_size, void (*constructor) (void *destination, void *source), void (*destructor) (void *));
terminate().The constructor and or destructor pointers may be NULL.If either is NULL, no action is taken when it would have been called. 3.3.5 Controlling Object Construction Order
3.3.5.1 Motivation
3.3.5.2 Source Code API
The <priority> parameter specifies a 32-bit signed initializationpriority, with lower numbers meaning earlier initialization.The range of priorities [MIN_INT .. MIN_INT+1023] is reservedto the implementation.The pragma applies to all file scope variables in the file where itappears, from the point of appearance to the next priority pragma orthe end of the file.Objects defined before any priority pragmas have a default priority of zero,as do initialization actions specified by other means,e.g. #pragma priority ( <priority> )
DT_INIT_ARRAY entries.For consistency with the C++ Standard requirements on initialization order,behavior is undefined unless the priorities appearing in a single file,including any default zero priorities,are in non-decreasing numeric (non-increasing priority) order. 3.3.5.3 Object File Representation
SHT_IA_64_PRIORITY_INIT,with section ID0x79000000 on Itanium,and section name.priority_init,and attributes allowing writing but not execution.The elements are structs:The fieldtypedef struct { ElfXX_Wordpi_pri; ElfXX_Addrpi_addr;} ElfXX_Priority_Init;pi_addr is a function pointer,as defined by the base ABI(a pointer to a function descriptor on Itanium).The function takes a singleunsigned int priority parameter,which performs some initialization at prioritypi_pri.The priority value is obtained from the signed int in the source pragmaby subtracting MIN_INT, so the default priority is -MIN_INT.The section header fieldsh_entsize is 8 for ELF-32,or 16 for ELF-64.
An implementation may initialize as many (or as few) objects of thesame priority as it chooses in a single such initialization function,as long as the sequence of such initialization entries for a given filepreserves the source code order of objects to be initialized. 3.3.5.4 Runtime Library Support
It will be called with the address of a void __cxa_priority_init ( ElfXX_Priority_Init *pi, int cnt );
cnt-element(sub-)vector of the priority initialization entries,and must call each of them in order.It will be called with the GP of the initialization entries. 3.3.5.5 Linker Processing
SHT_IA_64_PRIORITY_INIT sections in link order,which, given equal section IDs, section names, and section attributesas specified above, is the default behavior specified by the genericABI for unknown section types.
Given minimum static linker processing,an implementation supporting priority initialization would need toinclude bracketing files in the link command that(1) label the ends of theSHT_IA_64_PRIORITY_INIT section,and (2) provide initial and finalDT_INIT_ARRAY entries.The initialDT_INIT_ARRAY entry would need to sort theSHT_IA_64_PRIORITY_INIT section and call__cxa_priority_init to run the constructors with negativepriority (in the source).The finalDT_INIT_ARRAY entry would need to call__cxa_priority_init to run the constructors withnon-negative priority.OtherDT_INIT_ARRAY entries would thus run at the properpoint in the priority sequence.SHT_IA_64_PRIORITY_INIT section at link time and fabricatethe code to call__cxa_priority_init at the beginning andend.At the extreme, it could even include otherDT_INIT_ARRAYentries in theSHT_IA_64_PRIORITY_INIT sequence at theappropriate places and emit exactly one call to__cxa_priority_init,with no other entries in theDT_INIT_ARRAY section. 3.3.6 DSO Object Destruction API
3.3.6.1 Motivation
atexit routine to register the destructors.This is problematic because the 1999 C Standard only requires that theimplementation support 32 registered functions,although most implementations support many more.More important,it does not deal at all with the ability in most implementations toremove DSOs from a running program image by callingdlclose prior to program termination.atexit-registered functionsin the correct sequence relative to constructor-registered destructors,and reasonable treatment during early DSO unload (e.g.dlclose). 3.3.6.2 Runtime Data Structure
3.3.6.3 Runtime API
extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );__cxa_atexit(f,p,d),is intended to cause the callf(p) when DSOd is unloaded,before all such termination calls registered before this one.It returns zero if registration is successful, nonzero on failure.atexit calls:atexit,they should be registered with NULL parameters and DSO handles, i.e. __cxa_atexit ( f, NULL, NULL );atexitimplementation so that C-only DSOs will nevertheless interact with C++programs in a C++-standard-conforming manner.No user interface to__cxa_atexit is supported,so the user is not able to register anatexit functionwith a parameter or a home DSO.__cxa_atexit,the linker should define a hidden symbol__dso_handle,with a value which is an address in one of the object's segments.(It does not matter what address,as long as they are different in different DSOs.)It should also include a call to the following function in the FINIlist (to be executed first):extern "C" void __cxa_finalize ( void *d );&__dso_handle.__cxa_atexit, but they can be safely included in all objects.__cxa_finalize(d) is called,it should walk the termination function list,calling each in turn ifd matches__dso_handle for the termination function entry.Ifd == NULL, it should call all of them.Multiple calls to__cxa_finalize shall not result incalling termination function entries multiple times;the implementation may either remove entries or mark them finished.exit,it must call any remaining__cxa_atexit-registered functions,either by calling__cxa_finalize(NULL),or by walking the registration list itself.__cxa_finalize()in the opposite of the order in which they were enqueued by__cxa_atexit.__cxa_atexit and__cxa_finalizemust both manipulate the same termination function list,they must be defined in the implementation's runtime library,rather than in the individual linked objects. 3.4 Demangler API
namespace abi { extern "C" char* __cxa_demangle (const char* mangled_name, char* buf, size_t* n, int* status);}mangled-nameis a pointer to a null-terminated array of characters.It may be either an external name, i.e. with a "_Z" prefix,or an internal NTBS mangling, e.g. of a type for type_info.buf may be null.If it is non-null, thenn must also be nonnull,andbuf is a pointer to an array, of at least*n characters,that was allocated using malloc.status points to an int that is used as an error indicator.It is permitted to be null,in which case the user just doesn't get any detailed error information.__cxa_demangle.buf is a null pointer,__cxa_demangle allocates a new buffer withmalloc. It stores the size of the buffer in*n, ifn is notNULL.buf is not a null pointer, it must have been allocated withmalloc. Ifbuf is not big enough to store the resulting demangled name,__cxa_demangle must either a) callfree to deallocatebuf and then allocate a new buffer withmalloc, or b) callrealloc to increase the size of the buffer. In either case, the new buffer size will be stored in*n. Chapter 4: Exception Handling
Chapter 5: Linkage and Object Files
5.1 External Names (a.k.a. Mangling)
5.1.1 General
<>.<functionname> is the same as<name>, but it means this derivation rule should be used only for the names of functions.# is a comment, to be ignored until the end of the line. Comments are often used to describe in what case an alternative should be used.[] are optional.() are groups for the purposes of* and+.* allows the preceding item to repeat 0 or more times.+ allows the preceding item to repeat 1 or more times.Ret? for an unknown function return type(i.e. that is not given by the mangling),orType? for an unknown data type.$ or. are reserved for private implementationuse. Names produced using such extensions are inherently non-portableand should be given internal linkage where possible. 5.1.2 General Structure
Thus, a name is mangled by prefixing "_Z" to an encoding of its name,and in the case of functions its type (to support overloading).At this top level,function types do not have the special delimiter characters requiredwhen nested (see below). Furthermore, in the case of instances (orexplicit specializations) of function templates and member functiontemplates (but not ordinary member functions of class templates), the
<bare-function-type> encoding is that of the typeexpressed in the template (i.e., one likely involving templateparameters).The type is omitted for variables and static data members.<mangled-name>containing a period represents a vendor-specific version or portionof the entity named by the<encoding>prior to the first period. There is no restriction on the charactersthat may be used in the suffix following the period.// a.cpp:template <int> void foo() {}template <> void foo<0>();// b.cpp:template <long> void foo() {}template <> void foo<0>();Dependent constructs in templates
Anonymous entities
are considered to have the nameunion { int i; int j; };union { union { int : 7 }; union { int i; }; };union { union { int j; } i; };i for the purposes ofmangling.Names
std, are mangled as unscoped names. Entities declaredwithin a function, including members of local classes, are mangledwith <local-name>. Entitiesdeclared in a namespace or class scope are mangled with<nested-name>. When the actualentity is not known statically, as can occur in a dependent functiontemplate signature, the name is mangled with<unresolved-name>.which starts a <template-args>production._A-Za-z0-9.ABI tags
abi_tag attribute can be applied to a variable,function, inline namespace, class, or enumeration. The<unqualified-name> for a taggedvariable, function, or type includes a representation of the tags on thatentity, in alphabetical order:
For example: struct [[gnu::abi_tag ("foo","bar")]] A { }; // mangles as 1AB3barB3fooIf a name that would use a built-in<substitution> has ABI tags, the tagsare appended to the substitution; the result is a substitutable component. namespace std { template <class T> struct char_traits { /* ... */ }; template <class T> struct allocator { /* ... */ }; template <class T, class R = char_traits<T>, class A = allocator<T>> struct [[gnu::abi_tag ("X")]] basic_string { /* ... */ }; using string = basic_string<char>; } void f(std::string, std::string) { } // mangles as _Z1fSsB1XS_If part of a declaration's type is not represented in the mangling, i.e. thetype of a variable or a return type that is not represented in the mangling ofa function, any ABI tags on that type (or components of a compound type) thatare not also present in a mangled part of the type are applied to the name ofthe declaration. Note that there is no similar tag propagation from members orbases to a class type, as that would be impossible for incomplete types. struct [[gnu::abi_tag ("foo")]] A { template <class T> static T f(); template <class T> static A g(); }; template <class T> struct B { static decltype(A::f<T>()) fa(decltype(A::f<T>())); static decltype(A::f<T>()) fv(); static decltype(A::g<T>()) ga(decltype(A::g<T>())); static decltype(A::g<T>()) gv(); }; int main() { // decltype(A::f<T>()) resolves to int B<int>::fa(0); // _ZN1BIiE2faEi B<int>::fv(); // _ZN1BIiE2fvEv // decltype(A::g<T>()) resolves to A, which has a tag B<int>::ga(A()); // _ZN1BIiE2gaE1AB3foo B<int>::gv(); // _ZN1BIiE2gvB3fooEv } inline namespace [[gnu::abi_tag]] Foo { struct A {}; A f() { } // mangles as _ZN3Foo1fEv } template <class T> struct B { }; typedef void (*fp)(B<A>); fp p; // mangles as _Z1pB3Foo A g(A) { } // mangles as _Z1gN3Foo1AENumbers
Sequence numbers
. The first substitutable entity is encoded asS_, i.e. with no number. The second is encoded asS0_, the third asS1_, the twelfth asSA_, the thirty-eighth asS10_, etc. 5.1.3 Operator Encodings
__imag)shall encode them as a 'v' prefix followed bythe operand count as a single decimal digit, andthe name in <length,ID> form.
For a user-defined conversion operator the result type (i.e., the typeto which the operator converts) is part of the mangled name of thefunction. If the conversion operator is a member template, the resulttype will appear before the template parameters. There may be forwardreferences in the result type to the template parameters. 5.1.4 Other Special Functions and Entities
5.1.4.1 Virtual Tables and RTTI
5.1.4.2 Virtual Override Thunks
this adjustments,use a "Th" prefix and encode the required adjustment offset,probably negative, indicated by a 'n' prefix,and the encoding of the target function.Those overriding from a virtual base must encode two offsetsafter a "Tv" prefix.The first is the constant adjustment to the nearest virtual base(of the full object),of which the defining object is a non-virtual base.It is coded like the non-virtual case,with a 'n' prefix if negative.The second offset identifies the vcall offset in the nearest virtual base,which will be used to finish adjustingthis to the full object.After these two offsets comes the encoding of the target function.The target function encodings of both thunks incorporate the function type;no additional type is encoded for the thunk itself. 5.1.4.3 Constructors and Destructors
5.1.4.4 Guard Variables
GV. 5.1.4.5 Lifetime-Extended Temporaries
GR and suffixedwith a sequence number mangled using the usual rules for aseq-id. Temporaries are numberedwith a pre-order, depth-first, left-to-right walk of the completeinitializer.struct A { const int (&x)[3]; };struct B { const A (&x)[2]; };template <typename T> B &&b = { { { { 1, 2, 3 } }, { { 4, 5, 6 } } } };B &temp = b<void>;_ZGR1bIvE_ is the 'B' object that 'temp' would refer to._ZGR1bIvE0_ is the array of 'A' object references._ZGR1bIvE1_ is the object containing the first array of ints, {1, 2, 3}._ZGR1bIvE2_ is the object containing the second array of ints, {4, 5, 6}. 5.1.4.6 Transaction-Safe FunctionEntry Points
A function declared transaction-safe or[[optimize_for_synchronized]] has two entry points: the normal functionmangling, used for calls from a non-transaction context, and another entrypoint used for calls during a transaction. The mangled name of the transaction entry point is the normal mangling prefixed with GTt.5.1.5 Type encodings
const and*,that uniquely determine the type. The mangling of function templatesignatures necessitates the ability to encode the compound structureof dependent types.5.1.5.1 Qualified types
_near and_far for pointers) shall encode them as a 'U' prefix, followedby the name in <length,ID> form, followed optionally by any argumentsto the qualifier. It is recommended that the encoded name be thepreferred name used in source code; known exceptions arelisted below.int* volatile const restrict _far has mangled type nameU4_farrVKPi.Vendors must therefore specify which of theirextended qualifiers are considered order-insensitive. This need notnecessarily be resolved on the basis of whether their language translatorsimpose an order in source code. They are encouraged to resolve questionablecases as being order-insensitive to maximize consistency in mangling.const volatile foo,the fully qualified type or foo may be substituted,but notvolatile foo norconst foo.
The restrict qualifier is part of the C99 standard,but is strictly an extension to C++ at this time.There is no standard specification of whether the restrict attributeis part of the type for overloading purposes.An implementation should include its encoding in the mangled nameif and only if it also treats it as a distinguishing attribute foroverloading purposes.This ABI does not specify that choice.Known exceptions to the extended qualifier rules
address_space(N) qualifier is mangledusing the nameAS. For historical reasons, ifthe argument expression is notinstantiation-dependent,its value is incorporated directly into the<source-name> of thequalifier; otherwise it is encoded as a qualifier argument.int __attribute__((address_space(3))) * isencoded asPU3AS3i, butint __attribute__((address_space(K))) *(in whichK is a reference to the firsttemplate parameter) is encoded asPU2ASIT_Ei.5.1.5.2 Builtin types
5.1.5.3 Function types
The exceptions mentioned in (1) and (2) above,for which the return type is never included, areoperator int.() or conventionally as(void),are encoded with a void parameter specifier (v).Therefore function types always encode at least one parameter type,and function manglings can always be distinguished from data manglingsby the presence of the type.Member functions do not encode the types ofimplicit parameters, eitherthis or the VTT parameter.<nested-name>as described above. Otherwise, they are encoded as part of thefunction type as described below.noexcept,noexcept(expression), orthrow(type(s))) is part ofthe function type, it is mangled according to<exception-spec> asdescribed below.A non-instantiation-dependent, potentially-throwing exception specification isnot mangled.void () const,void () is not asubstitution candidate.Dp <type>, i.e., its type is a packexpansion:5.1.5.4 C++11
decltypedecltype type is encoded witheitherDt orDT, depending on howthedecltype type was parsed. (See fartherbelow forthe encoding of expressions.)decltype is notinstantiation-dependentthen the resulting type is encoded directly. For example: int x; template<class T> auto f(T p)->decltype(x); // The return type in the mangling of the template signature // is encoded as "i". template<class T> auto f(T p)->decltype(p); // The return type in the mangling of the template signature // is encoded as "Dtfp_E". void g(int); template<class T> auto f(T p)->decltype(g(p)); // The return type in the mangling of the template signature // is encoded as "DTcl1gfp_E".
5.1.5.5 Class, union, and enum types
std::decimal::decimal32,std::decimal::decimal64, orstd::decimal::decimal128as defined in TR 24733 uses the same encoding as the corresponding nativedecimal-floating point scalar type.The number is omitted for the first unnamed type in the class; it isn-2 for the nth unnamed type (inlexical order)otherwise.struct S { static struct {} x; };typedef decltype(S::x) TX; // Type mangled as N1SUt_ETX S::x; // _ZN1S1xEvoid f(TX) {} // _Z1fN1SUt_E5.1.5.6 Array types
_ separator)is omitted for incomplete array types (e.g.int[])and C99 variable-length array types. template<int I> void foo (int (&)[I + 1]) { } // Mangled as _Z3fooILi2EEvRAplT_Li1E_i template void foo<2> (int (&)[3]);5.1.5.7 Pointer-to-member types
produces the mangled name " void f (void (A::*)() const &) {}_Z1fM1AKFvvRE".5.1.5.8 Template parameters
T_,T0_,T1_, and so on. template<class T> void f(T) {} // Mangled as "_Z1fIiEvT_" template void f(int);T* is notsubstituted despite being known (in this specialization) to bethe same type asint*, and the second incidenceis substituted with the substitution derived from the firstincidence, not that from the incidence ofint*. template<class T> void f(int*, T*, T*) {} // Mangled as "_Z1fIiEvPiPT_S2_" template void f(int*, int*, int*); template<class T> class A { template<class U> void f(T, U) {} }; // Mangled as "_ZN1AIiE1fIfEEviT_" template void A<int>::f(int, float);5.1.5.9 Function parameter references
template<class T> void f(T p, decltype(p)); // L = 1 template<class T> void g(T p, decltype(p) (*)()); // L = 1 template<class T> void h(T p, auto (*)()->decltype(p)); // L = 1 template<class T> void i(T p, auto (*)(T q)->decltype(q)); // L = 0 template<class T> void j(T p, auto (*)(decltype(p))->T); // L = 2 template<class T> void k(T p, int (*(*)(T p))[sizeof(p)]); // L = 1
Note that top-level cv-qualifiers specified on a parameter type do notaffect the function type directly (i.e.,int(*)(T) andint(*)(T const) are the same type), but in expressioncontexts (such as decltype arguments) they do matter and must thereforebe encoded in<function-param>, unless the parameteris used as an rvalue of a known non-class type (in the latter case thequalifier cannot affect the semantics of the expression). For example: template<typename T> void f(T const p, decltype(p)*); // The specialization f<int> has type void(int, int const*) // and is encoded as _Z1fIiEvT_PDtfL0pK_E
5.1.5.10 Template Arguments
5.1.6 Expressions
decltype,or template argument) must be mangled in order to properlydistinguish templates that are different under the ODR.See the section ondependentmangling. As a result, nearly the entire expressiongrammar of C++ is subject to mangling, with only a fewexceptions (like lambdas) that are explicitly disallowedin function signatures.<operator-name>.J is the third template parameter,"B<(J+1)/2>" becomes "1BI Xdv pl T1_ Li1E Li2E E E" (the blanksare present only to visualize the decomposition).sizeof oralignof operatoris notinstantiation-dependent,it is encoded as an integer literal reflecting the result of theoperator. If the result of the operator is implicitly converted toa known integer type, that type is used for the literal; otherwise,the type ofstd::size_t orstd::ptrdiff_t is used.For example: template<class T, int N> struct S1 {}; template<class T, T N> struct S2 {}; template<class T> void f(S1<T, sizeof(long double)>); // The sizeof(...) is not instantiation-dependent, and converted to int: // the result is encoded as "Li16E" for 16-byte long double types. template<class T> void f(S2<T, sizeof(long double)>); // The sizeof(...) is not instantiation-dependent, and converted to an // unknown type: the result is encoded as "Lm16E" for 16-byte long double // types and std::size_t a synonym for "unsigned long". template<class T> void f(S2<T, sizeof(T*)>); // The sizeof(...) is instantiation-dependent (even though its value may // be known if all pointers have the same size): It is encoded as "stPT_".-> operator)takes precedence over one that is expressed in terms of (unary/binary/ternary) <operator-name>.gs" prefix on some of the productions indicates that the correspondingsource construct (name, new-expression, or delete-expression) includes a global-scope qualifier (e.g.,::x).tl is used for direct-list-initializations, where the type name is directly followed by a braced-init-list; e.g.,MyArray{1,2,3} should be mangledtl7MyArrayLi1ELi2ELi3EE. If the braced-init-list is parenthesized, this is not a direct-list-initialization, and it should be mangled withcv and a nestedil; for example,MyArray({1,2,3}) should be mangledcv7MyArrayilLi1ELi2ELi3EE.X{.a.b[3] = 1} should be mangledtl1Xdi1adi1bdxLi3ELi1EE.cl orcp for the call expression. Thecp mangling is used only when the callee operand is a parenthesizedunresolved name and would have used ADL if it were not parenthesized. Inparticular,cl is still used when unqualified lookup finds adeclaration that would suppress the use of ADL, such as a class member.5.1.6.1 Literals
nullptr is encoded as"LDnE". In contrast, a template argument which happens to be a nullpointer (an extension made standard in C++11) is mangled as if it werea literal0 of the appropriate pointer type; for example,"LPi0E" or "LDn0E". This inconsistency is an unfortunate accident.5.1.6.2 References to declared entities
void foo(char); // mangled as _Z3fooc template<void (&)(char)> struct CB; // CB<foo> is mangled as "2CBIL_Z3foocEE"
extern "C" bool IsEmpty(char *); // (un)mangled as IsEmpty template<void (&)(char *)> struct CB; // CB<IsEmpty> is mangled as "2CBIL_Z7IsEmptyEE"
<encoding> production (via<expr-primary>) does not apply, and instead the<unresolved-name> encoding is used. For example:In the case of member selection operations, the template<class T> auto f(T p)->decltype(p->x); // The return type in the mangling of the template signature // is encoded as "Dtptfp_1xE". template<class T> auto f(T p)->decltype(T::X::y); // The return type in the mangling of the template signature // is encoded as "DtsrNT_1XE1yE" (note how <type> is a // <nested-name> for T::X in this case). template<class T> auto f(T p)->decltype(p->::A::B::x); // The return type in the mangling of the template signature // is encoded as "Dtptfp_gssr1A1BE1xE". template<class T> auto f(T p)->decltype(p->x)::Y; // The return type in the mangling of the template signature // is encoded as "NDtptfp_1xE1YE".
<unresolved-name> is used even if the indicated member is actually known. Similarly,an<unresolved-qualifier-level> may encode a knownclass type.That production is also used for references to nonstatic members with noassociated expression designating the enclosing object (a C++11 feature).For example:If the struct Q { int x; } q; template<class T> auto f(T p)->decltype(p.x + q.x); // The return type in the mangling of the template signature // is encoded as "DTpldtfp_1xdtL_Z1qE1xE". template<class T> auto f(T p)->decltype(p.x + Q::x); // The return type in the mangling of the template signature // is encoded as "DTpldtfp_1xsr1QE1xE". template<class T> struct X { static T x; }; struct B: X<int> {}; struct D: B {} d; template<class T> auto f(T p)->decltype(p+d.B::X<T>::x); // The return type in the mangling of the template signature // is encoded as "DTplfp_dtL_Z1dEsr1B1XIT_EE1xE". (The // "1B" part is a <unresolved-qualifier-level> encoding // a resolved type.)<unresolved-name> refers to an operator forwhich both unary and binary manglings are available, the manglingchosen is the mangling for the binary version.For example: template<class T> auto f(T p)->decltype(&T::operator-); // The return type in the mangling of the template signature // is encoded as "DTadsrT_onmiE".
5.1.7 Scope Encoding
static local variable) ismangled using an unscoped name, whereas a member of a local type willbe mangled with a <nested-name>.X in a given functiong, and only the third has a member functionf,the name ofX::f ing will still includethe discriminator (because3 - 2 == 1).where the number is is omitted for the first unnamed type in thefunction, andn-2 for thenth unnamed type(inlexical order) otherwise.inline void g(int) { { struct S {}; } { struct S {}; } { struct S {}; } struct S { // Fourth occurrence: _2 void f(int) { // _ZZ1giEN1S1fE_2i struct {} x1; struct {} x2; struct { // Third occurrence: 1_, i.e. // _ZZZ1giEN1S1fE_2iEUt1_ int fx() { // _ZZZ1giEN1S1fE_2iENUt1_2fxEv return 3; } } x3; x3.fx(); } } s; s.f(1);}See additional examples in theABI examples document.inline char const* g() { "str1"; // First string in g() struct B {}; struct S: B { S() // Complete object ctor: _ZZ1gvEN1SC1Ev : msg("str2") {} // First string in g()::S::S(): // _ZZZ1gvEN1SC1EvEs char const *msg; } s; "str3"; // Second string in g() static char const *str4a // _ZZ1gvE5str4a = "str4"; // Third string in g() (n-2 == 1): // _ZZ1gvEs_1 static char const *str4b // _ZZ1gvE5str4b = "str4"; // Still the third string (_ZZ1gvEs_1) return str4b;}5.1.8 Closure Types (Lambdas)
In the following contexts, however, the one-definition rule requiresclosure types in different translation units to "correspond":namespace N { int n = []{ return 1; }(); // Closure type internal to} // the translation unit.
In all these contexts, the encoding of the closure types builds on anunderlying <unqualified-name> that is an <unnamed-type-name> ofthe formwithThe number is omitted for the first closure type with a given<lambda-sig> in a given context; it is n-2 for the nth closuretype (inlexical order)with that same <lambda-sig> and context.template<typename F> int algo(F fn) { return fn(); }inline void g(int n) { int bef(int i = []{ return 1; }()); // Default arguments of block-extern function declarations // remain in the context of the encloding function body. // The closure type is encoded as Z1giEUlvE_. // The call operator of that type is _ZZ1giENKUlvE_clEv. algo([=]{return n+bef();}); // The captured entities do not participate in <lambda-sig> // and so this closure type has the same <lambda-sig> as // the previous one. It encoding is therefore Z1giEUlvE0_ // and the call operator is _ZZ1giENKUlvE0_clEv. The // instance of "algo" being called is then // _Z4algoIZ1giEUlvE0_EiT_.}The parameter number is omitted for the last parameter, 0 for the second-to-last parameter, 1 for the third-to-last parameter, etc. The<entityname> will of course contain a<closure-type-name>: Its numbering will be local to theparticular argument in which it appears -- other default arguments donot affect its encoding. For example:struct S { void f(int = []{return 1;}() // Type: ZN1S1fEiiEd0_UlvE_ // Operator: _ZZN1S1fEiiEd0_NKUlvE_clEv + []{return 2;}(), // Type: ZN1S1fEiiEd0_UlvE0_ // Operator: _ZZN1S1fEiiEd0_NKUlvE0_clEv int = []{return 3;}()); // Type: ZN1S1fEiiEd_UlvE_ // Operator: _ZZN1S1fEiiEd_NKUlvE_clEv} s;<prefix> of the form:For example:template<typename T> struct S { static int x;};template<typename T> int S<T>::x = []{return 1;}();template int S<int>::x; // Type of lambda in intializer of S<int>::x: N1SIiE1xMUlvE_E // Corresponding operator(): _ZNK1SIiE1xMUlvE_clEvauto in the parameter listare mangled as the corresponding artificial template type parameter.This is never ambiguous with a lambda parameter whose type is anenclosing template type parameter, because lambdas are never mangledin a dependent context (they are forbidden from appearing in functionsignatures). A <template-param> in a <lambda-sig> can only ever refer to atemplate parameter of a generic lambda.5.1.9 Lexical ordering
[x = []{}]{} are both part of the enclosing context.The order of such entities is determined by the source order of a keytoken in the entity. In general, this token is the first tokenpast which the signature of the entity (as is necessary to mangle it)is known:enum-head-name (enum-key if unnamed) orclass-head-name (class-key if unnamed) in its first declaration.}).declarator (not its initializer).if constexpr or in a pack expansion of anempty pack. For example:void g(...);template<bool b, typename ...T> void f() { if constexpr(b) { []{}; } g(([]{}, []{ static T n; return &n; }())...);}// The first lambda is discarded and does not receive a number.// The variables passed to g are therefore mangled as// _ZZZ1fILb0EJiiEEvvENKUlvE0_clEvE1n and// _ZZZ1fILb0EJiiEEvvENKUlvE2_clEvE1n.template void f<false, int, int>();// The variable passed to g is mangled as// _ZZZ1fILb1EJiEEvvENKUlvE1_clEvE1n andtemplate void f<true, int>();// Both lambdas are numbered; returns _ZZZ1hvENKUlvE0_clEvE1n.inline int *h() { if constexpr(false) { []{}; } return []{ static int n; return &n; }();}mem-initializer-list reflects the order that theinitializers appear in the source, which may be different from theorder in which the initializers will be executed when the program runs.5.1.10 Compression
Therefore, in the following example:
the functiontypedef void T();struct S {};void f(T*, T (S::*)) {}f is mangled as_Z1fPFvvEM1SFvvE; the type of the member function pointedto by the second parameter is not considered the same as the type ofthe function pointed to by the first parameter. Both function typesare, however, entered the substitution table; subsequent references toeither variant of the function type will result in the use ofsubstitutions.since the substitutions generated for this name are: "_ZN1N1TIiiE2mfES0_IddE": Ret? N::T<int, int>::mf(N::T<double, double>)
"S_" == N (qualifier is less recent than qualified entity) "S0_" == N::T (template-id comes before template)(int is builtin, and isn't considered) "S1_" == N::T<int, int> "S2_" == N::T<double, double>
"_ZSt5state": ::std::state "_ZNSt3_In4wardE": ::std::_In::ward
5.2 Vague Linkage
SHT_GROUP sections in thegABI to remove duplicates.We will refer to this simply as using a COMDAT group,and specify the symbol to be used to identify duplicates in theSHT_GROUP section.COMDAT groups are a new gABI feature specified during the Itanium ABIdefinition, and may not be implemented everywhere immediately.See the separateABI examplesdocument for a discussion of alternatives pending COMDAT implementation. 5.2.1 Out-of-line Functions
5.2.2 Static Data
5.2.3 Virtual Tables
Note: previous versions of this ABI required virtual tables to always be emitted with vague linkage, even when emitted in a unique object. This is unnecessary and should not detectable in a valid program; however, it is also harmless, and implementations may opt to continue to do it for compatibility with programs that are not strictly valid.
Note: the requirement to emit all of the tables for a class in a single COMDAT does not currently serve any clear purpose beyond reducing the number of COMDATs. There is no known optimization that would result in e.g. a VTT that would only work correctly with the paired virtual table or vice-versa. Nonetheless, it is required by the ABI and is largely harmless.
constexprorconsteval functions are always declared as such ontheir first declarations and so are implicitlyinline,so they are never key functions.Recommendation for new platforms: when selecting the key function, ignore virtual function definitions that are inline outside of the class definition. Inline function definitions must be defined in every translation unit that ODR-use them, and virtual functions are considered to always be ODR-used. Therefore, in a valid program, every translation unit that sees a class definition must agree about which of its virtual functions are defined inline outside of the class. Some platforms are known to have already adopted this rule.
Recommendation for new platforms: when selecting the key function, also consider pure virtual destructors as candidates. Virtual destructors must be defined even if they are pure.
5.2.4
std::type_infostd::type_info structure for a complete dynamicclass type whose virtual tables are emitted in a unique object (seeabove) is emitted with non-vague linkagein the same object as its virtual tables.std::type_info structure for an incomplete classtype is emitted wherever referenced. It is implementation-definedwhat symbol name it uses, other than that it must not be the samesymbol name as any other entity, including the complete class type.It also implementation-defined whether they are emitted in a COMDATgroup or just with internal linkage.std::type_info structures for various basictypes as specified by theRun-Time Type Informationsection are provided by the runtime library.std::type_info structure for any other typeis emitted with vague linkage using the symbol name as the COMDATidentifier.std::type_info object has non-vague linkagein order to support interoperation with incomplete RTTI for incompletetypes.Recommendation for new platforms: the linkage rules for RTTI
std::type_info and name objects are known to cause both semantic and performance problems when dynamic linking is in use. This is an area where there is widespread divergence from this ABI, chiefly to avoid the need for cross-image symbol coalescing. Several different approaches for this are in use, with different underlying goals. For now, there is not a clear recommendation to make, other than that the current rule is not the best. 5.2.5 Constructors and Destructors
5.2.6 Instantiated Templates
5.3 Unwind Table Location
SHT_IA_64_UNWIND section,and unwind information descriptors in a section that will be linkedwith the associated code.Itanium linkers shall put the unwind table,the unwind information table,and the associated code in a single text segment,with aPT_IA_64_UNWIND program table entry identifying theunwind table location.Appendix R: Revision History
abi_tag mangling.operator "".decltype(auto).__cxa_throw_bad_array_new_length mangling.noexcept mangling.nullptr_t mangling.alignof, function parameters, and a different mangling for N-argument function casts.out0 for by-value return types on Itanium.__cxa_vec_delete.__cxa_vec_delete when thearray_address isNULL.__cxa_vec_new,__cxa_vec_new2, and__cxa_vec_new3 in the event that the allocation function returnsNULL.void* instead ofdso_handle.__cxa_vec_new2 and__cxa_vec_new3 when the deallocation function throws an exception.sr in mangling.__cxa_demangle memory management specification.
[8]ページ先頭