Movatterモバイル変換


[0]ホーム

URL:


Next:, Up:Specifying Attributes of Types   [Contents][Index]


6.4.3.1 Common Type Attributes

The following type attributes are supported on most targets.

aligned
aligned (alignment)

Thealigned attribute specifies a minimum alignment (in bytes) forvariables of the specified type. When specified,alignment must bea power of 2. Specifying noalignment argument implies the maximumalignment for the target, which is often, but by no means always, 8 or 16bytes. For example, the declarations:

struct __attribute__ ((aligned (8))) S { short f[3]; };typedef int more_aligned_int __attribute__ ((aligned (8)));

force the compiler to ensure (as far as it can) that each variable whosetype isstruct S ormore_aligned_int is allocated andalignedat least on a 8-byte boundary. On a SPARC, having allvariables of typestruct S aligned to 8-byte boundaries allowsthe compiler to use theldd andstd (doubleword load andstore) instructions when copying one variable of typestruct S toanother, thus improving run-time efficiency.

Note that the alignment of any givenstruct orunion typeis required by the ISO C standard to be at least a perfect multiple ofthe lowest common multiple of the alignments of all of the members ofthestruct orunion in question. This means that youcaneffectively adjust the alignment of astruct oruniontype by attaching analigned attribute to any one of the membersof such a type, but the notation illustrated in the example above is amore obvious, intuitive, and readable way to request the compiler toadjust the alignment of an entirestruct orunion type.

As in the preceding example, you can explicitly specify the alignment(in bytes) that you wish the compiler to use for a givenstructorunion type. Alternatively, you can leave out the alignment factorand just ask the compiler to align a type to the maximumuseful alignment for the target machine you are compiling for. Forexample, you could write:

struct __attribute__ ((aligned)) S { short f[3]; };

Whenever you leave out the alignment factor in analignedattribute specification, the compiler automatically sets the alignmentfor the type to the largest alignment that is ever used for any datatype on the target machine you are compiling for. Doing this can oftenmake copy operations more efficient, because the compiler can usewhatever instructions copy the biggest chunks of memory when performingcopies to or from the variables that have types that you have alignedthis way.

In the example above, if the size of eachshort is 2 bytes, thenthe size of the entirestruct S type is 6 bytes. The smallestpower of two that is greater than or equal to that is 8, so thecompiler sets the alignment for the entirestruct S type to 8bytes.

Note that although you can ask the compiler to select a time-efficientalignment for a given type and then declare only individual stand-aloneobjects of that type, the compiler’s ability to select a time-efficientalignment is primarily useful only when you plan to create arrays ofvariables having the relevant (efficiently aligned) type. If youdeclare or use arrays of variables of an efficiently-aligned type, thenit is likely that your program also does pointer arithmetic (orsubscripting, which amounts to the same thing) on pointers to therelevant type, and the code that the compiler generates for thesepointer arithmetic operations is often more efficient forefficiently-aligned types than for other types.

Note that the effectiveness ofaligned attributes may be limitedby inherent limitations in your linker. On many systems, the linker isonly able to arrange for variables to be aligned up to a certain maximumalignment. (For some linkers, the maximum supported alignment maybe very very small.) If your linker is only able to align variablesup to a maximum of 8-byte alignment, then specifyingaligned (16)in an__attribute__ still only provides you with 8-bytealignment. See your linker documentation for further information.

When used on a struct, or struct member, thealigned attribute canonly increase the alignment; in order to decrease it, thepackedattribute must be specified as well. When used as part of a typedef, thealigned attribute can both increase and decrease alignment, andspecifying thepacked attribute generates a warning.

alloc_size (position)
alloc_size (position-1,position-2)

Thealloc_size type attribute may be applied to the definitionof a type of a function that returns a pointer and takes at least oneargument of an integer type. It indicates that the returned pointerpoints to an object whose size is given by the function argument atposition-1, or by the product of the arguments atposition-1andposition-2. Meaningful sizes are positive values less thanPTRDIFF_MAX. Other sizes are diagnosed when detected. GCC usesthis information to improve the results of__builtin_object_size.

For instance, the following declarations

typedef __attribute__ ((alloc_size (1, 2))) void*  calloc_type (size_t, size_t);typedef __attribute__ ((alloc_size (1))) void*  malloc_type (size_t);

specify thatcalloc_type is a type of a function that, likethe standard C functioncalloc, returns an object whose sizeis given by the product of arguments 1 and 2, and thatmalloc_type, like the standard C functionmalloc,returns an object whose size is given by argument 1 to the function.

btf_type_tag (argument)

Thebtf_type_tag attribute may be used to associate (to “tag”)particular types with arbitrary string annotations. These annotationsare recorded in debugging info by supported debug formats, currentlyDWARF (viaDW_AT_GNU_annotation andDW_TAG_GNU_annotationextensions) and BTF (viaBTF_KIND_TYPE_TAG records). Theseannotation strings are not interpreted by the compiler in any way, andhave no effect on code generation. If neither DWARF nor BTFinformation is generated, the attribute has no effect.

The argument is treated as a null-terminated sequence of zero or morenon-null bytes. Wide character strings are not supported.

The attribute may be supplied multiple times for a single type, inwhich case each distinct argument string will be recorded in aseparate DIE or BTF record, each associated to the type. For a singletype with multiplebtf_type_tag attributes, the order of theDW_TAG_GNU_annotation DIEs produced is not guaranteed tomaintain the order of attributes in the source code.

For example the following code:

int * __attribute__ ((btf_type_tag ("__user"))) foo;

when compiled with-gbtf results in an additionalBTF_KIND_TYPE_TAG BTF record to be emitted in the BTF info,associating the string ‘__user’ with the normalBTF_KIND_PTRrecord for the pointer-to-integer type used in the declaration.

Note that the BTF format currently only has a representation for typetags associated with pointer types. Type tags on non-pointer typesmay be silently skipped when generating BTF.

copy
copy (expression)

Thecopy attribute applies the set of attributes with whichthe type of theexpression has been declared to the declarationof the type to which the attribute is applied. The attribute isdesigned for libraries that define aliases that are expected tospecify the same set of attributes as the aliased symbols.Thecopy attribute can be used with types, variables, orfunctions. However, the kind of symbol to which the attribute isapplied (either varible or function) must match the kind of symbolto which the argument refers.Thecopy attribute copies only syntactic and semantic attributesbut not attributes that affect a symbol’s linkage or visibility such asalias,visibility, orweak. Thedeprecatedattribute is also not copied. SeeCommon Function Attributes.SeeCommon Variable Attributes.

For example, supposestruct A below is defined in some thirdparty library header to have the alignment requirementN andto force a warning whenever a variable of the type is not so aligneddue to attributepacked. Specifying thecopy attributeon the definition on the unrelatedstruct B has the effect ofcopying all relevant attributes from the type referenced by the pointerexpression tostruct B.

struct __attribute__ ((aligned (N), warn_if_not_aligned (N)))A { /* */ };struct __attribute__ ((copy ( (struct A *)0)) B { /* */ };
deprecated
deprecated (msg)

Thedeprecated attribute results in a warning if the typeis used anywhere in the source file. This is useful when identifyingtypes that are expected to be removed in a future version of a program.If possible, the warning also includes the location of the declarationof the deprecated type, to enable users to easily find furtherinformation about why the type is deprecated, or what they should doinstead. Note that the warnings only occur for uses and then onlyif the type is being applied to an identifier that itself is not beingdeclared as deprecated.

typedef int T1 __attribute__ ((deprecated));T1 x;typedef T1 T2;T2 y;typedef T1 T3 __attribute__ ((deprecated));T3 z __attribute__ ((deprecated));

results in a warning on line 2 and 3 but not lines 4, 5, or 6. Nowarning is issued for line 4 because T2 is not explicitlydeprecated. Line 5 has no warning because T3 is explicitlydeprecated. Similarly for line 6. The optionalmsgargument, which must be a string, is printed in the warning ifpresent. Control characters in the string will be replaced withescape sequences, and if the-fmessage-length option is setto 0 (its default value) then any newline characters will be ignored.

Thedeprecated attribute can also be used for functions andvariables (seeDeclaring Attributes of Functions, seeSpecifying Attributes of Variables.)

The message attached to the attribute is affected by the setting ofthe-fmessage-length option.

designated_init

This attribute may only be applied to structure types. It indicatesthat any initialization of an object of this type must use designatedinitializers rather than positional initializers. The intent of thisattribute is to allow the programmer to indicate that a structure’slayout may change, and that therefore relying on positionalinitialization will result in future breakage.

GCC emits warnings based on this attribute by default; use-Wno-designated-init to suppress them.

flag_enum

This attribute may be applied to an enumerated type to indicate thatits enumerators are used in bitwise operations, so e.g.-Wswitchshould not warn about acase that corresponds to a bitwisecombination of enumerators.

hardbool
hardbool (false_value)
hardbool (false_value,true_value)

This attribute may only be applied to integral types in C, to introducehardened boolean types. It turns the integral type into a boolean-liketype with the same size and precision, that uses the specified values asrepresentations forfalse andtrue. Underneath, it isactually an enumerated type, but its observable behavior is like that of_Bool, except for the strict internal representations, verifiedby runtime checks.

Iftrue_value is omitted, the bitwise negation offalse_value is used. Iffalse_value is omitted, zero isused. The named representation values must be different when convertedto the original integral type. Narrower bitfields are rejected if therepresentations become indistinguishable.

Values of such types automatically decay to_Bool, at whichpoint, the selected representation values are mapped to thecorresponding_Bool values. When the represented value is notdetermined, at compile time, to be eitherfalse_value ortrue_value, runtime verification calls__builtin_trap if itis neither. This is what makes them hardened boolean types.

When converting scalar types to such hardened boolean types, implicitlyor explicitly, behavior corresponds to a conversion to_Bool,followed by a mapping fromfalse andtrue tofalse_value andtrue_value, respectively.

typedef char __attribute__ ((__hardbool__ (0x5a))) hbool;hbool first = 0;       /* False, stored as (char)0x5a.  */hbool second = !first; /* True, stored as ~(char)0x5a.  */static hbool zeroinit; /* False, stored as (char)0x5a.  */auto hbool uninit;     /* Undefined, may trap.  */

When zero-initializing a variable or field of hardened boolean type(presumably held in static storage) the implied zero initializer getsconverted to_Bool, and then to the hardened boolean type, sothat the initial value is the hardened representation forfalse.Using that value is well defined. This isnot the case whenvariables and fields of such types are uninitialized (presumably held inautomatic or dynamic storage): their values are indeterminate, and usingthem invokes undefined behavior. Using them may trap or not, dependingon the bits held in the storage (re)used for the variable, if any, andon optimizations the compiler may perform on the grounds that usinguninitialized values invokes undefined behavior.

Users of-ftrivial-auto-var-init should be aware that the bitpatterns used as initializers arenot converted tohardbool types, so using ahardbool variable that isimplicitly initialized by the-ftrivial-auto-var-init may trapif the representations values chosen forfalse andtrue donot match the initializer.

Since this is a language extension only available in C, interoperationwith other languages may pose difficulties. It should interoperate withAda Booleans defined with the same size and equivalent representationclauses, and with enumerations or other languages’ integral types thatcorrespond to C’s chosen integral type.

may_alias

Accesses through pointers to types with this attribute are not subjectto type-based alias analysis, but are instead assumed to be able to aliasany other type of objects.In the context of section 6.5 paragraph 7 of the C99 standard,an lvalue expressiondereferencing such a pointer is treated like having a character type.See-fstrict-aliasing for more information on aliasing issues.This extension exists to support some vector APIs, in which pointers toone vector type are permitted to alias pointers to a different vector type.

Note that an object of a type with this attribute does not have anyspecial semantics.

Example of use:

typedef short __attribute__ ((__may_alias__)) short_a;intmain (void){  int a = 0x12345678;  short_a *b = (short_a *) &a;  b[1] = 0;  if (a == 0x12345678)    abort();  exit(0);}

If you replacedshort_a withshort in the variabledeclaration, the above program would abort when compiled with-fstrict-aliasing, which is on by default at-O2 orabove.

mode (mode)

This attribute specifies the data type for the declaration—whichevertype corresponds to the modemode. This in effect lets yourequest an integer or floating-point type according to its width.

SeeMachine Modes inGNU Compiler Collection (GCC) Internals,for a list of the possible keywords formode.You may also specify a mode ofbyte or__byte__ toindicate the mode corresponding to a one-byte integer,word or__word__ for the mode of a one-word integer, andpointeror__pointer__ for the mode used to represent pointers.

objc_root_class(Objective-C and Objective-C++ only)

This attribute marks a class as being a root class, and thus allowsthe compiler to elide any warnings about a missing superclass and tomake additional checks for mandatory methods as needed.

packed

This attribute, attached to astruct,union, or C++classtype definition, specifies that each of its members (other than zero-widthbit-fields) is placed to minimize the memory required. This is equivalentto specifying thepacked attribute on each of the members.

When attached to anenum definition, thepacked attributeindicates that the smallest integral type should be used.Specifying the-fshort-enums flag on the command lineis equivalent to specifying thepackedattribute on allenum definitions.

In the following examplestruct my_packed_struct’s members arepacked closely together, but the internal layout of itss memberis not packed—to do that,struct my_unpacked_struct needs tobe packed too.

struct my_unpacked_struct {    char c;    int i; };struct __attribute__ ((__packed__)) my_packed_struct  {     char c;     int  i;     struct my_unpacked_struct s;  };

You may only specify thepacked attribute on the definitionof anenum,struct,union, orclass, not on atypedef that does not also define the enumerated type,structure, union, or class.

scalar_storage_order ("endianness")

When attached to aunion or astruct, this attribute setsthe storage order, aka endianness, of the scalar fields of the type, aswell as the array fields whose component is scalar. The supportedendiannesses arebig-endian andlittle-endian. The attributehas no effects on fields which are themselves aunion, astructor an array whose component is aunion or astruct, and it ispossible for these fields to have a different scalar storage order than theenclosing type.

Note that neither pointer nor vector fields are considered scalar fields inthis context, so the attribute has no effects on these fields.

This attribute is supported only for targets that use a uniform defaultscalar storage order (fortunately, most of them), i.e. targets that storethe scalars either all in big-endian or all in little-endian.

Additional restrictions are enforced for types with the reverse scalarstorage order with regard to the scalar storage order of the target:

  • Taking the address of a scalar field of aunion or astruct with reverse scalar storage order is not permitted and yieldsan error.
  • Taking the address of an array field, whose component is scalar, ofaunion or astruct with reverse scalar storage order ispermitted but yields a warning, unless-Wno-scalar-storage-orderis specified.
  • Taking the address of aunion or astruct with reversescalar storage order is permitted.

These restrictions exist because the storage order attribute is lost whenthe address of a scalar or the address of an array with scalar component istaken, so storing indirectly through this address generally does not work.The second case is nevertheless allowed to be able to perform a block copyfrom or to the array.

Moreover, the use of type punning or aliasing to toggle the storage orderis not supported; that is to say, if a given scalar object can be accessedthrough distinct types that assign a different storage order to it, then thebehavior is undefined.

strub

This attribute defines stack-scrubbing properties of functions andvariables, so that functions that access sensitive data can have theirstack frames zeroed-out upon returning or propagating exceptions. Thismay be enabled explicitly, by selecting certainstrub modes forspecific functions, or implicitly, by means ofstrub variables.

Being a type attribute, it attaches to types, even when specified infunction and variable declarations. When applied to function types, ittakes an optional string argument. When applied to apointer-to-function type, if the optional argument is given, it getspropagated to the function type.

/* A strub variable.  */int __attribute__ ((strub)) var;/* A strub variable that happens to be a pointer.  */__attribute__ ((strub)) int *strub_ptr_to_int;/* A pointer type that may point to a strub variable.  */typedef int __attribute__ ((strub)) *ptr_to_strub_int_type;/* A declaration of a strub function.  */extern int __attribute__ ((strub)) foo (void);/* A pointer to that strub function.  */int __attribute__ ((strub ("at-calls"))) (*ptr_to_strub_fn)(void) = foo;

A function associated withat-callsstrub mode(strub("at-calls"), or juststrub) undergoes interfacechanges. Its callers are adjusted to match the changes, and to scrub(overwrite with zeros) the stack space used by the called function afterit returns. The interface change makes the function type incompatiblewith an unadorned but otherwise equivalent type, soeverydeclaration and every type that may be used to call the function must beassociated with this strub mode.

A function associated withinternalstrub mode(strub("internal")) retains an unmodified, type-compatibleinterface, but it may be turned into a wrapper that calls the wrappedbody using a custom interface. The wrapper then scrubs the stack spaceused by the wrapped body. Though the wrapped body has its stack spacescrubbed, the wrapper does not, so arguments and return values mayremain unscrubbed even when such a function is called by anotherfunction that enablesstrub. This is why, when compiling with-fstrub=strict, astrub context is not allowed to callinternalstrub functions.

/* A declaration of an internal-strub function.  */extern int __attribute__ ((strub ("internal"))) bar (void);int __attribute__ ((strub))baz (void){  /* Ok, foo was declared above as an at-calls strub function.  */  foo ();  /* Not allowed in strict mode, otherwise allowed.  */  bar ();}

An automatically-allocated variable associated with thestrubattribute causes the (immediately) enclosing function to havestrub enabled.

A statically-allocated variable associated with thestrubattribute causes functions thatread it, through itsstrubdata type, to havestrub enabled. Reading data by dereferencinga pointer to astrub data type has the same effect. Note: Theattribute does not carry over from a composite type to the types of itscomponents, so the intended effect may not be obtained with non-scalartypes.

When selecting astrub-enabled mode for a function that is notexplicitly associated with one, because ofstrub variables ordata pointers, the function must satisfyinternal mode viabilityrequirements (see below), even whenat-calls mode is also viableand, being more efficient, ends up selected as an optimization.

/* zapme is implicitly strub-enabled because of strub variables.   Optimization may change its strub mode, but not the requirements.  */static intzapme (int i){  /* A local strub variable enables strub.  */  int __attribute__ ((strub)) lvar;  /* Reading strub data through a pointer-to-strub enables strub.  */  lvar = * (ptr_to_strub_int_type) &i;  /* Writing to a global strub variable does not enable strub.  */  var = lvar;  /* Reading from a global strub variable enables strub.  */  return var;}

Astrub context is the body (as opposed to the interface) of afunction that hasstrub enabled, be it explicitly, byat-calls orinternal mode, or implicitly, due tostrub variables or command-line options.

A function of a type associated with thedisabledstrubmode (strub("disabled") will not have its own stack spacescrubbed. Such functionscannot be called from withinstrub contexts.

In order to enable a function to be called from withinstrubcontexts without having its stack space scrubbed, associate it with thecallablestrub mode (strub("callable")).

When a function is not assigned astrub mode, explicitly orimplicitly, the mode defaults tocallable, except when compilingwith-fstrub=strict, that causesstrub mode to defaulttodisabled.

extern int __attribute__ ((strub ("callable"))) bac (void);extern int __attribute__ ((strub ("disabled"))) bad (void); /* Implicitly disabled with -fstrub=strict, otherwise callable.  */extern int bah (void);int __attribute__ ((strub))bal (void){  /* Not allowed, bad is not strub-callable.  */  bad ();  /* Ok, bac is strub-callable.  */  bac ();  /* Not allowed with -fstrub=strict, otherwise allowed.  */  bah ();}

Function types markedcallable anddisabled are notmutually compatible types, but the underlying interfaces are compatible,so it is safe to convert pointers between them, and to use such pointersor alternate declarations to call them. Interfaces are alsointerchangeable between them andinternal (but notat-calls!), but addinginternal to a pointer type will notcause the pointed-to function to perform stack scrubbing.

void __attribute__ ((strub))bap (void){  /* Assign a callable function to pointer-to-disabled.     Flagged as not quite compatible with -Wpedantic.  */  int __attribute__ ((strub ("disabled"))) (*d_p) (void) = bac;  /* Not allowed: calls disabled type in a strub context.  */  d_p ();  /* Assign a disabled function to pointer-to-callable.     Flagged as not quite compatible with -Wpedantic.  */  int __attribute__ ((strub ("callable"))) (*c_p) (void) = bad;  /* Ok, safe.  */  c_p ();  /* Assign an internal function to pointer-to-callable.     Flagged as not quite compatible with -Wpedantic.  */  c_p = bar;  /* Ok, safe.  */  c_p ();  /* Assign an at-calls function to pointer-to-callable.     Flaggged as incompatible.  */  c_p = bal;  /* The call through an interface-incompatible type will not use the     modified interface expected by the at-calls function, so it is     likely to misbehave at runtime.  */  c_p ();}

Strub contexts are never inlined into non-strub contexts.When aninternal-strub function is split up, the wrapper canoften be inlined, but the wrapped bodynever is. A functionmarked asalways_inline, even if explicitly assignedinternal strub mode, will not undergo wrapping, so its body getsinlined as required.

inline int __attribute__ ((strub ("at-calls")))inl_atc (void){  /* This body may get inlined into strub contexts.  */}inline int __attribute__ ((strub ("internal")))inl_int (void){  /* This body NEVER gets inlined, though its wrapper may.  */}inline int __attribute__ ((strub ("internal"), always_inline))inl_int_ali (void){  /* No internal wrapper, so this body ALWAYS gets inlined,     but it cannot be called from non-strub contexts.  */}void __attribute__ ((strub ("disabled")))bat (void){  /* Not allowed, cannot inline into a non-strub context.  */  inl_int_ali ();}

Some-fstrub=* command-line options enablestrub modesimplicitly where viable. Astrub mode is only viable for afunction if the function is eligible for that mode, and if otherconditions, detailed below, are satisfied. If it’s not eligible for amode, attempts to explicitly associate it with that mode are rejectedwith an error message. If it is eligible, that mode may be assignedexplicitly through this attribute, but implicit assignment throughcommand-line options may involve additional viability requirements.

A function is ineligible forat-callsstrub mode if adifferentstrub mode is explicitly requested, if attributenoipa is present, or if it calls__builtin_apply_args.At-callsstrub mode, if not requested through the functiontype, is only viable for an eligible function if the function is notvisible to other translation units, if it doesn’t have its addresstaken, and if it is never called with a function type overrider.

/* bar is eligible for at-calls strub mode,   but not viable for that mode because it is visible to other units.   It is eligible and viable for internal strub mode.  */void bav () {}/* setp is eligible for at-calls strub mode,   but not viable for that mode because its address is taken.   It is eligible and viable for internal strub mode.  */void setp (void) { static void (*p)(void); = setp; }

A function is ineligible forinternalstrub mode if adifferentstrub mode is explicitly requested, or if attributenoipa is present. For analways_inline function, meetingthese requirements is enough to make it eligible. Any function that hasattributenoclone, that uses such extensions as non-local labels,computed gotos, alternate variable argument passing interfaces,__builtin_next_arg, or__builtin_return_address, or thattakes too many (about 64Ki) arguments is ineligible, unless it isalways_inline. Forinternalstrub mode, alleligible functions are viable.

/* flop is not eligible, thus not viable, for at-calls strub mode.   Likewise for internal strub mode.  */__attribute__ ((noipa)) void flop (void) {}/* flip is eligible and viable for at-calls strub mode.   It would be ineligible for internal strub mode, because of noclone,   if it weren't for always_inline.  With always_inline, noclone is not   an obstacle, so it is also eligible and viable for internal strub mode.  */inline __attribute__ ((noclone, always_inline)) void flip (void) {}
transparent_union

This attribute, attached to aunion type definition, indicatesthat any function parameter having that union type causes calls to thatfunction to be treated in a special way.

First, the argument corresponding to a transparent union type can be ofany type in the union; no cast is required. Also, if the union containsa pointer type, the corresponding argument can be a null pointerconstant or a void pointer expression; and if the union contains a voidpointer type, the corresponding argument can be any pointer expression.If the union member type is a pointer, qualifiers likeconst onthe referenced type must be respected, just as with normal pointerconversions.

Second, the argument is passed to the function using the callingconventions of the first member of the transparent union, not the callingconventions of the union itself. All members of the union must have thesame machine representation; this is necessary for this argument passingto work properly.

Transparent unions are designed for library functions that have multipleinterfaces for compatibility reasons. For example, suppose thewait function must accept either a value of typeint * tocomply with POSIX, or a value of typeunion wait * to comply withthe 4.1BSD interface. Ifwait’s parameter werevoid *,wait would accept both kinds of arguments, but it would alsoaccept any other pointer type and this would make argument type checkingless useful. Instead,<sys/wait.h> might define the interfaceas follows:

typedef union __attribute__ ((__transparent_union__))  {    int *__ip;    union wait *__up;  } wait_status_ptr_t;pid_t wait (wait_status_ptr_t);

This interface allows eitherint * orunion wait *arguments to be passed, using theint * calling convention.The program can callwait with arguments of either type:

int w1 () { int w; return wait (&w); }int w2 () { union wait w; return wait (&w); }

With this interface,wait’s implementation might look like this:

pid_t wait (wait_status_ptr_t p){  return waitpid (-1, p.__ip, 0);}
unavailable
unavailable (msg)

Theunavailable attribute behaves in the same manner as thedeprecated one, but emits an error rather than a warning. It isused to indicate that a (perhaps previouslydeprecated) type isno longer usable.

Theunavailable attribute can also be used for functions andvariables (seeDeclaring Attributes of Functions, seeSpecifying Attributes of Variables.)

unused

When attached to a type (including aunion or astruct),this attribute means that variables of that type are meant to appearpossibly unused. GCC does not produce a warning for any variables ofthat type, even if the variable appears to do nothing. This is oftenthe case with lock or thread classes, which are usually defined and thennot referenced, but contain constructors and destructors that havenontrivial bookkeeping functions.

vector_size (bytes)

This attribute specifies the vector size for the type, measured in bytes.The type to which it applies is known as thebase type. Thebytesargument must be a positive power-of-two multiple of the base type size. Forexample, the following declarations:

typedef __attribute__ ((vector_size (32))) int int_vec32_t ;typedef __attribute__ ((vector_size (32))) int* int_vec32_ptr_t;typedef __attribute__ ((vector_size (32))) int int_vec32_arr3_t[3];

defineint_vec32_t to be a 32-byte vector type composed ofintsized units. Withint having a size of 4 bytes, the type definesa vector of eight units, four bytes each. The mode of variables of typeint_vec32_t isV8SI.int_vec32_ptr_t is then definedto be a pointer to such a vector type, andint_vec32_arr3_t to bean array of three such vectors. SeeUsing Vector Instructions through Built-in Functions, for details ofmanipulating objects of vector types.

This attribute is only applicable to integral and floating scalar types.In function declarations the attribute applies to the function returntype.

For example, the following:

__attribute__ ((vector_size (16))) float get_flt_vec16 (void);

declaresget_flt_vec16 to be a function returning a 16-byte vectorwith the base typefloat.

visibility

In C++, attribute visibility (seeDeclaring Attributes of Functions) can also beapplied to class, struct, union and enum types. Unlike other typeattributes, the attribute must appear between the initial keyword andthe name of the type; it cannot appear after the body of the type.

Note that the type visibility is applied to vague linkage entitiesassociated with the class (vtable, typeinfo node, etc.). Inparticular, if a class is thrown as an exception in one shared objectand caught in another, the class must have default visibility.Otherwise the two shared objects are unable to use the sametypeinfo node and exception handling will break.

warn_if_not_aligned (alignment)

This attribute specifies a threshold for the structure field, measuredin bytes. If the structure field is aligned below the threshold, awarning will be issued. For example, the declaration:

typedef unsigned long long __u64   __attribute__((aligned (4), warn_if_not_aligned (8)));struct foo{  int i1;  int i2;  __u64 x;};

causes the compiler to issue an warning onstruct foo, like‘warning: alignment 4 of 'struct foo' is less than 8’.It is used to definestruct foo in such a way thatstruct foo has the same layout and the structure fieldxhas the same alignment when__u64 is aligned at either 4 or8 bytes. Alignstruct foo to 8 bytes:

struct __attribute__ ((aligned (8))) foo{  int i1;  int i2;  __u64 x;};

silences the warning. The compiler also issues a warning, like‘warning: 'x' offset 12 in 'struct foo' isn't aligned to 8’,when the structure field has the misaligned offset:

struct __attribute__ ((aligned (8))) foo{  int i1;  int i2;  int i3;  __u64 x;};

This warning can be disabled by-Wno-if-not-aligned.

To specify multiple attributes, separate them by commas within thedouble parentheses: for example, ‘__attribute__ ((aligned (16),packed))’.


Next:ARC Type Attributes, Up:Specifying Attributes of Types   [Contents][Index]


[8]ページ先頭

©2009-2026 Movatter.jp