Use __attribute__((alloc_align()) on a function declaration to specify that the return value of the function (which must be a pointer type) is at ...
« Clangcommandlineargumentreference
::
Contents
::
DiagnosticflagsinClang »
AttributesinClang¶
Introduction
AMDGPUAttributes
amdgpu_flat_work_group_size
amdgpu_num_sgpr
amdgpu_num_vgpr
amdgpu_waves_per_eu
CallingConventions
aarch64_sve_pcs
aarch64_vector_pcs
fastcall
ms_abi
pcs
preserve_all
preserve_most
regcall
regparm
stdcall
thiscall
vectorcall
ConsumedAnnotationChecking
callable_when
consumable
param_typestate
return_typestate
set_typestate
test_typestate
CustomizingSwiftImport
swift_async
swift_async_error
swift_async_name
swift_attr
swift_bridge
swift_bridged
swift_error
swift_name
swift_newtype
swift_objc_members
swift_private
DeclarationAttributes
Owner
Pointer
__single_inhertiance,__multiple_inheritance,__virtual_inheritance
asm
deprecated
empty_bases
enum_extensibility
external_source_symbol
flag_enum
layout_version
lto_visibility_public
managed
novtable
ns_error_domain
objc_boxable
objc_direct
objc_direct_members
objc_non_runtime_protocol
objc_nonlazy_class
objc_runtime_name
objc_runtime_visible
objc_subclassing_restricted
preferred_name
randomize_layout,no_randomize_layout
randomize_layout,no_randomize_layout
selectany
transparent_union
trivial_abi
using_if_exists
weak
FieldAttributes
no_unique_address
FunctionAttributes
#pragmaompdeclaresimd
#pragmaompdeclaretarget
#pragmaompdeclarevariant
SV_GroupIndex
_Noreturn
abi_tag
acquire_capability,acquire_shared_capability
alloc_align
alloc_size
allocator
always_inline,__force_inline
artificial
assert_capability,assert_shared_capability
assume
assume_aligned
availability
btf_decl_tag
callback
carries_dependency
cf_consumed
cf_returns_not_retained
cf_returns_retained
cfi_canonical_jump_table
clang::builtin_alias,clang_builtin_alias
clang_arm_builtin_alias
cmse_nonsecure_entry
code_seg
convergent
cpu_dispatch
cpu_specific
diagnose_as_builtin
diagnose_if
disable_sanitizer_instrumentation
disable_tail_calls
enable_if
enforce_tcb
enforce_tcb_leaf
error,warning
exclude_from_explicit_instantiation
export_name
flatten
force_align_arg_pointer
format
gnu_inline
guard
ifunc
import_module
import_name
internal_linkage
interrupt(ARM)
interrupt(AVR)
interrupt(MIPS)
interrupt(RISCV)
kernel
lifetimebound
long_call,far
malloc
micromips
mig_server_routine
min_vector_width
minsize
no_builtin
no_caller_saved_registers
no_profile_instrument_function
no_sanitize
no_sanitize_address,no_address_safety_analysis
no_sanitize_memory
no_sanitize_thread
no_speculative_load_hardening
no_split_stack
no_stack_protector
noalias
nocf_check
nodiscard,warn_unused_result
noduplicate
noinline
nomicromips
noreturn,_Noreturn
not_tail_called
nothrow
ns_consumed
ns_consumes_self
ns_returns_autoreleased
ns_returns_not_retained
ns_returns_retained
numthreads
objc_method_family
objc_requires_super
optnone
os_consumed
os_consumes_this
os_returns_not_retained
os_returns_retained
os_returns_retained_on_non_zero
os_returns_retained_on_zero
overloadable
patchable_function_entry
preserve_access_index
reinitializes
release_capability,release_shared_capability
retain
shader
short_call,near
signal
speculative_load_hardening
sycl_kernel
target
target_clones
try_acquire_capability,try_acquire_shared_capability
used
xray_always_instrument,xray_never_instrument,xray_log_args
xray_always_instrument,xray_never_instrument,xray_log_args
zero_call_used_regs
HandleAttributes
acquire_handle
release_handle
use_handle
NullabilityAttributes
_Nonnull
_Null_unspecified
_Nullable
_Nullable_result
nonnull
returns_nonnull
OpenCLAddressSpaces
[[clang::opencl_global_device]],[[clang::opencl_global_host]]
[[clang::opencl_global_device]],[[clang::opencl_global_host]]
__constant,constant,[[clang::opencl_constant]]
__generic,generic,[[clang::opencl_generic]]
__global,global,[[clang::opencl_global]]
__local,local,[[clang::opencl_local]]
__private,private,[[clang::opencl_private]]
StatementAttributes
#pragmaclangloop
#pragmaunroll,#pragmanounroll
__read_only,__write_only,__read_write(read_only,write_only,read_write)
fallthrough
intel_reqd_sub_group_size
likelyandunlikely
likelyandunlikely
musttail
nomerge
opencl_unroll_hint
suppress
sycl_special_class
TypeAttributes
__ptr32
__ptr64
__sptr
__uptr
align_value
annotate_type
arm_sve_vector_bits
btf_type_tag
clang_arm_mve_strict_polymorphism
cmse_nonsecure_call
device_builtin_surface_type
device_builtin_texture_type
noderef
objc_class_stub
TypeSafetyChecking
argument_with_type_tag
pointer_with_type_tag
type_tag_for_datatype
Undocumented
Alignas,align,alignas,aligned
NSObject
__kindof
acquired_after
acquired_before
address_space
alias
amdgpu_kernel
analyzer_noreturn
annotate
assert_exclusive_lock
assert_shared_lock
blocks
capability,shared_capability
cdecl
cf_audited_transfer
cf_unknown_transfer
cleanup
cold
common
const
constant
constructor
consumable_auto_cast_state
consumable_set_state_on_read
destructor
device
exclusive_locks_required,requires_capability,requires_shared_capability,shared_locks_required
exclusive_trylock_function
ext_vector_type
format_arg
global
guarded_by
guarded_var
host
hot
ibaction
iboutlet
iboutletcollection
intel_ocl_bicc
interrupt
interrupt
interrupt
kernel
launch_bounds
lock_returned
lockable
locks_excluded
matrix_type
may_alias
mips16
mode
ms_struct
naked
neon_polyvector_type
neon_vector_type
no_instrument_function
no_thread_safety_analysis
nocommon
nomips16
noreturn
objc_arc_weak_reference_unavailable
objc_bridge
objc_bridge_mutable
objc_bridge_related
objc_designated_initializer
objc_exception
objc_gc
objc_independent_class
objc_ownership
objc_precise_lifetime
objc_protocol_requires_explicit_implementation
objc_requires_property_definitions
objc_returns_inner_pointer
objc_root_class
ownership_holds,ownership_returns,ownership_takes
packed
pascal
pt_guarded_by
pt_guarded_var
pure
reqd_work_group_size
returns_twice
scoped_lockable
sentinel
shared
shared_trylock_function
sysv_abi
type_visibility
unavailable
uuid
vec_type_hint
vecreturn
vector_size
visibility
warn_unused
weak_import
weakref
work_group_size_hint
VariableAttributes
always_destroy
called_once
dllexport
dllimport
init_priority
init_seg
leaf
loader_uninitialized
maybe_unused,unused
no_destroy
nodebug
noescape
nosvm
objc_externally_retained
pass_object_size,pass_dynamic_object_size
require_constant_initialization,constinit(C++20)
section,__declspec(allocate)
standalone_debug
swift_async_context
swift_context
swift_error_result
swift_indirect_result
swiftasynccall
swiftcall
thread
tls_model
uninitialized
Introduction¶
ThispageliststheattributescurrentlysupportedbyClang.
AMDGPUAttributes¶
amdgpu_flat_work_group_size¶
SupportedSyntaxes¶
amdgpu_flat_work_group_size
clang::amdgpu_flat_work_group_size
Yes
Theflatwork-groupsizeisthenumberofwork-itemsinthework-groupsize
specifiedwhenthekernelisdispatched.Itistheproductofthesizesofthe
x,y,andzdimensionofthework-group.
Clangsupportsthe
__attribute__((amdgpu_flat_work_group_size(,)))attributeforthe
AMDGPUtarget.Thisattributemaybeattachedtoakernelfunctiondefinition
andisanoptimizationhint.
parameterspecifiestheminimumflatwork-groupsize,and
parameterspecifiesthemaximumflatwork-groupsize(mustbegreaterthan
)towhichalldispatchesofthekernelwillconform.Passing0,0
as,impliesthedefaultbehavior(128,256).
Ifspecified,theAMDGPUtargetbackendmightbeabletoproducebettermachine
codeforbarriersandperformscratchpromotionbyestimatingavailablegroup
segmentsize.
Anerrorwillbegivenif:
Specifiedvaluesviolatesubtargetspecifications;
Specifiedvaluesarenotcompatiblewithvaluesprovidedthroughother
attributes.
amdgpu_num_sgpr¶
SupportedSyntaxes¶
amdgpu_num_sgpr
clang::amdgpu_num_sgpr
Yes
Clangsupportsthe__attribute__((amdgpu_num_sgpr()))and
__attribute__((amdgpu_num_vgpr()))attributesfortheAMDGPU
target.Theseattributesmaybeattachedtoakernelfunctiondefinitionandare
anoptimizationhint.
Iftheseattributesarespecified,thentheAMDGPUtargetbackendwillattempt
tolimitthenumberofSGPRsand/orVGPRsusedtothespecifiedvalue(s).The
numberofusedSGPRsand/orVGPRsmayfurtherberoundeduptosatisfythe
allocationrequirementsorconstraintsofthesubtarget.Passing0as
num_sgprand/ornum_vgprimpliesthedefaultbehavior(nolimits).
TheseattributescanbeusedtotesttheAMDGPUtargetbackend.Itis
recommendedthattheamdgpu_waves_per_euattributebeusedtocontrol
resourcessuchasSGPRsandVGPRssinceitisawareofthelimitsfordifferent
subtargets.
Anerrorwillbegivenif:
Specifiedvaluesviolatesubtargetspecifications;
Specifiedvaluesarenotcompatiblewithvaluesprovidedthroughother
attributes;
TheAMDGPUtargetbackendisunabletocreatemachinecodethatcanmeetthe
request.
amdgpu_num_vgpr¶
SupportedSyntaxes¶
amdgpu_num_vgpr
clang::amdgpu_num_vgpr
Yes
Clangsupportsthe__attribute__((amdgpu_num_sgpr()))and
__attribute__((amdgpu_num_vgpr()))attributesfortheAMDGPU
target.Theseattributesmaybeattachedtoakernelfunctiondefinitionandare
anoptimizationhint.
Iftheseattributesarespecified,thentheAMDGPUtargetbackendwillattempt
tolimitthenumberofSGPRsand/orVGPRsusedtothespecifiedvalue(s).The
numberofusedSGPRsand/orVGPRsmayfurtherberoundeduptosatisfythe
allocationrequirementsorconstraintsofthesubtarget.Passing0as
num_sgprand/ornum_vgprimpliesthedefaultbehavior(nolimits).
TheseattributescanbeusedtotesttheAMDGPUtargetbackend.Itis
recommendedthattheamdgpu_waves_per_euattributebeusedtocontrol
resourcessuchasSGPRsandVGPRssinceitisawareofthelimitsfordifferent
subtargets.
Anerrorwillbegivenif:
Specifiedvaluesviolatesubtargetspecifications;
Specifiedvaluesarenotcompatiblewithvaluesprovidedthroughother
attributes;
TheAMDGPUtargetbackendisunabletocreatemachinecodethatcanmeetthe
request.
amdgpu_waves_per_eu¶
SupportedSyntaxes¶
amdgpu_waves_per_eu
clang::amdgpu_waves_per_eu
Yes
Acomputeunit(CU)isresponsibleforexecutingthewavefrontsofawork-group.
Itiscomposedofoneormoreexecutionunits(EU),whichareresponsiblefor
executingthewavefronts.AnEUcanhaveenoughresourcestomaintainthestate
ofmorethanoneexecutingwavefront.ThisallowsanEUtohidelatencyby
switchingbetweenwavefrontsinasimilarwaytosymmetricmultithreadingona
CPU.InordertoallowthestateformultiplewavefrontstofitonanEU,the
resourcesusedbyasinglewavefronthavetobelimited.Forexample,thenumber
ofSGPRsandVGPRs.Limitingsuchresourcescanallowgreaterlatencyhiding,
butcanresultinhavingtospillsomeregisterstatetomemory.
Clangsupportsthe__attribute__((amdgpu_waves_per_eu([,])))
attributefortheAMDGPUtarget.Thisattributemaybeattachedtoakernel
functiondefinitionandisanoptimizationhint.
parameterspecifiestherequestedminimumnumberofwavesperEU,and
optionalparameterspecifiestherequestedmaximumnumberofwaves
perEU(mustbegreaterthanifspecified).Ifisomitted,
thenthereisnorestrictiononthemaximumnumberofwavesperEUotherthan
theonedictatedbythehardwareforwhichthekerneliscompiled.Passing
0,0as,impliesthedefaultbehavior(nolimits).
Ifspecified,thisattributeallowsanadvanceddevelopertotunethenumberof
wavefrontsthatarecapableoffittingwithintheresourcesofanEU.TheAMDGPU
targetbackendcanusethisinformationtolimitresources,suchasnumberof
SGPRs,numberofVGPRs,sizeofavailablegroupandprivatememorysegments,in
suchawaythatguaranteesthatatleastwavefrontsandatmost
wavefrontsareabletofitwithintheresourcesofanEU.Requesting
morewavefrontscanhidememorylatencybutlimitsavailableregisterswhich
canresultinspilling.Requestingfewerwavefrontscanhelpreducecache
thrashing,butcanreducememorylatencyhiding.
ThisattributecontrolsthemachinecodegeneratedbytheAMDGPUtargetbackend
toensureitiscapableofmeetingtherequestedvalues.However,whenthe
kernelisexecuted,theremaybeotherreasonsthatpreventmeetingtherequest,
forexample,theremaybewavefrontsfromotherkernelsexecutingontheEU.
Anerrorwillbegivenif:
Specifiedvaluesviolatesubtargetspecifications;
Specifiedvaluesarenotcompatiblewithvaluesprovidedthroughother
attributes;
TheAMDGPUtargetbackendisunabletocreatemachinecodethatcanmeetthe
request.
CallingConventions¶
Clangsupportsseveraldifferentcallingconventions,dependingonthetarget
platformandarchitecture.Thecallingconventionusedforafunctiondetermines
howparametersarepassed,howresultsarereturnedtothecaller,andother
low-leveldetailsofcallingafunction.
aarch64_sve_pcs¶
SupportedSyntaxes¶
aarch64_sve_pcs
clang::aarch64_sve_pcs
clang::aarch64_sve_pcs
OnAArch64targets,thisattributechangesthecallingconventionofa
functiontopreserveadditionalScalableVectorregistersandScalable
Predicateregistersrelativetothedefaultcallingconventionusedfor
AArch64.
Thismeansitismoreefficienttocallsuchfunctionsfromcodethatperforms
extensivescalablevectorandscalablepredicatecalculations,becausefewer
liveSVEregistersneedtobesaved.Thispropertymakesitwell-suitedforSVE
mathlibraryfunctions,whicharetypicallyleaffunctionsthatrequireasmall
numberofregisters.
However,usingthisattributealsomeansthatitismoreexpensivetocall
afunctionthatadherestothedefaultcallingconventionfromwithinsuch
afunction.Therefore,itisrecommendedthatthisattributeisonlyused
forleaffunctions.
Formoreinformation,seethedocumentationforaarch64_sve_pcsinthe
ARMCLanguageExtension(ACLE)documentation.
aarch64_vector_pcs¶
SupportedSyntaxes¶
aarch64_vector_pcs
clang::aarch64_vector_pcs
clang::aarch64_vector_pcs
OnAArch64targets,thisattributechangesthecallingconventionofa
functiontopreserveadditionalfloating-pointandAdvancedSIMDregisters
relativetothedefaultcallingconventionusedforAArch64.
Thismeansitismoreefficienttocallsuchfunctionsfromcodethatperforms
extensivefloating-pointandvectorcalculations,becausefewerliveSIMDandFP
registersneedtobesaved.Thispropertymakesitwell-suitedfore.g.
floating-pointorvectormathlibraryfunctions,whicharetypicallyleaf
functionsthatrequireasmallnumberofregisters.
However,usingthisattributealsomeansthatitismoreexpensivetocall
afunctionthatadherestothedefaultcallingconventionfromwithinsuch
afunction.Therefore,itisrecommendedthatthisattributeisonlyused
forleaffunctions.
Formoreinformation,seethedocumentationforaarch64_vector_pcson
theArmDeveloperwebsite.
fastcall¶
SupportedSyntaxes¶
fastcall
gnu::fastcall
gnu::fastcall
__fastcall_fastcall
On32-bitx86targets,thisattributechangesthecallingconventionofa
functiontouseECXandEDXasregisterparametersandclearparametersoffof
thestackonreturn.Thisconventiondoesnotsupportvariadiccallsor
unprototypedfunctionsinC,andhasnoeffectonx86_64targets.Thiscalling
conventionissupportedprimarilyforcompatibilitywithexistingcode.Users
seekingregisterparametersshouldusetheregparmattribute,whichdoes
notrequirecallee-cleanup.Seethedocumentationfor__fastcallonMSDN.
ms_abi¶
SupportedSyntaxes¶
ms_abi
gnu::ms_abi
gnu::ms_abi
Onnon-Windowsx86_64targets,thisattributechangesthecallingconventionof
afunctiontomatchthedefaultconventionusedonWindowsx86_64.This
attributehasnoeffectonWindowstargetsornon-x86_64targets.
pcs¶
SupportedSyntaxes¶
pcs
gnu::pcs
gnu::pcs
OnARMtargets,thisattributecanbeusedtoselectcallingconventions
similartostdcallonx86.Validparametervaluesare“aapcs”and
“aapcs-vfp”.
preserve_all¶
SupportedSyntaxes¶
preserve_all
clang::preserve_all
clang::preserve_all
OnX86-64andAArch64targets,thisattributechangesthecallingconventionof
afunction.Thepreserve_allcallingconventionattemptstomakethecode
inthecallerevenlessintrusivethanthepreserve_mostcallingconvention.
ThiscallingconventionalsobehavesidenticaltotheCcallingconvention
onhowargumentsandreturnvaluesarepassed,butitusesadifferentsetof
caller/callee-savedregisters.Thisremovestheburdenofsavingand
recoveringalargeregistersetbeforeandafterthecallinthecaller.If
theargumentsarepassedincallee-savedregisters,thentheywillbe
preservedbythecalleeacrossthecall.Thisdoesn’tapplyforvalues
returnedincallee-savedregisters.
OnX86-64thecalleepreservesallgeneralpurposeregisters,exceptfor
R11.R11canbeusedasascratchregister.Furthermoreitalsopreserves
allfloating-pointregisters(XMMs/YMMs).
Theideabehindthisconventionistosupportcallstoruntimefunctions
thatdon’tneedtocallouttoanyotherfunctions.
Thiscallingconvention,likethepreserve_mostcallingconvention,willbe
usedbyafutureversionoftheObjective-Cruntimeandshouldbeconsidered
experimentalatthistime.
preserve_most¶
SupportedSyntaxes¶
preserve_most
clang::preserve_most
clang::preserve_most
OnX86-64andAArch64targets,thisattributechangesthecallingconventionof
afunction.Thepreserve_mostcallingconventionattemptstomakethecode
inthecallerasunintrusiveaspossible.Thisconventionbehavesidentically
totheCcallingconventiononhowargumentsandreturnvaluesarepassed,
butitusesadifferentsetofcaller/callee-savedregisters.Thisalleviates
theburdenofsavingandrecoveringalargeregistersetbeforeandafterthe
callinthecaller.Iftheargumentsarepassedincallee-savedregisters,
thentheywillbepreservedbythecalleeacrossthecall.Thisdoesn’t
applyforvaluesreturnedincallee-savedregisters.
OnX86-64thecalleepreservesallgeneralpurposeregisters,exceptfor
R11.R11canbeusedasascratchregister.Floating-pointregisters
(XMMs/YMMs)arenotpreservedandneedtobesavedbythecaller.
Theideabehindthisconventionistosupportcallstoruntimefunctions
thathaveahotpathandacoldpath.Thehotpathisusuallyasmallpiece
ofcodethatdoesn’tusemanyregisters.Thecoldpathmightneedtocalloutto
anotherfunctionandthereforeonlyneedstopreservethecaller-saved
registers,whichhaven’talreadybeensavedbythecaller.The
preserve_mostcallingconventionisverysimilartothecoldcalling
conventionintermsofcaller/callee-savedregisters,buttheyareusedfor
differenttypesoffunctioncalls.coldccisforfunctioncallsthatare
rarelyexecuted,whereaspreserve_mostfunctioncallsareintendedtobe
onthehotpathanddefinitelyexecutedalot.Furthermorepreserve_most
doesn’tpreventtheinlinerfrominliningthefunctioncall.
ThiscallingconventionwillbeusedbyafutureversionoftheObjective-C
runtimeandshouldthereforestillbeconsideredexperimentalatthistime.
Althoughthisconventionwascreatedtooptimizecertainruntimecallsto
theObjective-Cruntime,itisnotlimitedtothisruntimeandmightbeused
byotherruntimesinthefuturetoo.Thecurrentimplementationonly
supportsX86-64andAArch64,buttheintentionistosupportmorearchitectures
inthefuture.
regcall¶
SupportedSyntaxes¶
regcall
gnu::regcall
gnu::regcall
__regcall
Onx86targets,thisattributechangesthecallingconventionto
__regcallconvention.Thisconventionaimstopassasmanyarguments
aspossibleinregisters.Italsotriestoutilizeregistersforthe
returnvaluewheneveritispossible.
regparm¶
SupportedSyntaxes¶
regparm
gnu::regparm
gnu::regparm
On32-bitx86targets,theregparmattributecausesthecompilertopass
thefirstthreeintegerparametersinEAX,EDX,andECXinsteadofonthe
stack.Thisattributehasnoeffectonvariadicfunctions,andallparameters
arepassedviathestackasnormal.
stdcall¶
SupportedSyntaxes¶
stdcall
gnu::stdcall
gnu::stdcall
__stdcall_stdcall
On32-bitx86targets,thisattributechangesthecallingconventionofa
functiontoclearparametersoffofthestackonreturn.Thisconventiondoes
notsupportvariadiccallsorunprototypedfunctionsinC,andhasnoeffecton
x86_64targets.ThiscallingconventionisusedwidelybytheWindowsAPIand
COMapplications.Seethedocumentationfor__stdcallonMSDN.
thiscall¶
SupportedSyntaxes¶
thiscall
gnu::thiscall
gnu::thiscall
__thiscall_thiscall
On32-bitx86targets,thisattributechangesthecallingconventionofa
functiontouseECXforthefirstparameter(typicallytheimplicitthis
parameterofC++methods)andclearparametersoffofthestackonreturn.This
conventiondoesnotsupportvariadiccallsorunprototypedfunctionsinC,and
hasnoeffectonx86_64targets.Seethedocumentationfor__thiscallon
MSDN.
vectorcall¶
SupportedSyntaxes¶
vectorcall
clang::vectorcall
clang::vectorcall
__vectorcall_vectorcall
On32-bitx86andx86_64targets,thisattributechangesthecalling
conventionofafunctiontopassvectorparametersinSSEregisters.
On32-bitx86targets,thiscallingconventionissimilarto__fastcall.
ThefirsttwointegerparametersarepassedinECXandEDX.Subsequentinteger
parametersarepassedinmemory,andcalleeclearsthestack.Onx86_64
targets,thecalleedoesnotclearthestack,andintegerparametersare
passedinRCX,RDX,R8,andR9asisdoneforthedefaultWindowsx64calling
convention.
Onboth32-bitx86andx86_64targets,vectorandfloatingpointargumentsare
passedinXMM0-XMM5.Homogeneousvectoraggregatesofuptofourelementsare
passedinsequentialSSEregistersifenoughareavailable.IfAVXisenabled,
256bitvectorsarepassedinYMM0-YMM5.Anyvectororaggregatetypethat
cannotbepassedinregistersforanyreasonispassedbyreference,which
allowsthecallertoaligntheparametermemory.
Seethedocumentationfor__vectorcallonMSDNformoredetails.
ConsumedAnnotationChecking¶
Clangsupportsadditionalattributesforcheckingbasicresourcemanagement
properties,specificallyforuniqueobjectsthathaveasingleowningreference.
Thefollowingattributesarecurrentlysupported,althoughtheimplementation
fortheseannotationsiscurrentlyindevelopmentandaresubjecttochange.
callable_when¶
SupportedSyntaxes¶
callable_when
clang::callable_when
Yes
Use__attribute__((callable_when(...)))toindicatewhatstatesamethod
maybecalledin.Validstatesareunconsumed,consumed,orunknown.Each
argumenttothisattributemustbeaquotedstring.E.g.:
__attribute__((callable_when("unconsumed","unknown")))
consumable¶
SupportedSyntaxes¶
consumable
clang::consumable
Yes
Eachclassthatusesanyofthetypestateannotationsmustfirstbemarked
usingtheconsumableattribute.Failuretodosowillresultinawarning.
Thisattributeacceptsasingleparameterthatmustbeoneofthefollowing:
unknown,consumed,orunconsumed.
param_typestate¶
SupportedSyntaxes¶
param_typestate
clang::param_typestate
Yes
Thisattributespecifiesexpectationsaboutfunctionparameters.Callstoan
functionwithannotatedparameterswillissueawarningifthecorresponding
argumentisn’tintheexpectedstate.Theattributeisalsousedtosetthe
initialstateoftheparameterwhenanalyzingthefunction’sbody.
return_typestate¶
SupportedSyntaxes¶
return_typestate
clang::return_typestate
Yes
Thereturn_typestateattributecanbeappliedtofunctionsorparameters.
Whenappliedtoafunctiontheattributespecifiesthestateofthereturned
value.Thefunction’sbodyischeckedtoensurethatitalwaysreturnsavalue
inthespecifiedstate.Onthecallerside,valuesreturnedbytheannotated
functionareinitializedtothegivenstate.
Whenappliedtoafunctionparameteritmodifiesthestateofanargumentafter
acalltothefunctionreturns.Thefunction’sbodyischeckedtoensurethat
theparameterisintheexpectedstatebeforereturning.
set_typestate¶
SupportedSyntaxes¶
set_typestate
clang::set_typestate
Yes
Annotatemethodsthattransitionanobjectintoanewstatewith
__attribute__((set_typestate(new_state))).Thenewstatemustbe
unconsumed,consumed,orunknown.
test_typestate¶
SupportedSyntaxes¶
test_typestate
clang::test_typestate
Yes
Use__attribute__((test_typestate(tested_state)))toindicatethatamethod
returnstrueiftheobjectisinthespecifiedstate..
CustomizingSwiftImport¶
ClangsupportsadditionalattributesforcustomizinghowAPIsareimportedinto
Swift.
swift_async¶
SupportedSyntaxes¶
swift_async
clang::swift_async
clang::swift_async
Yes
Theswift_asyncattributespecifiesifandhowaparticularfunctionor
Objective-Cmethodisimportedintoaswiftasyncmethod.Forinstance:
@interfaceMyClass:NSObject
-(void)notActuallyAsync:(int)p1withCompletionHandler:(void(^)())handler
__attribute__((swift_async(none)));
-(void)actuallyAsync:(int)p1callThisAsync:(void(^)())fun
__attribute__((swift_async(swift_private,1)));
@end
Here,notActuallyAsync:withCompletionHandlerwouldhavebeenimportedas
async(becauseit’slastparameter’sselectorpieceis
withCompletionHandler)ifnotfortheswift_async(none)attribute.
Conversely,actuallyAsync:callThisAsyncwouldn’thavebeenimportedas
asyncifnotfortheswift_asyncattributebecauseitdoesn’tmatchthe
namingconvention.
Whenusingswift_asynctoenableimporting,thefirstargumenttothe
attributeiseitherswift_privateornot_swift_privatetoindicate
whetherthefunction/methodisprivatetothecurrentframework,andthesecond
argumentistheindexofthecompletionhandlerparameter.
swift_async_error¶
SupportedSyntaxes¶
swift_async_error
clang::swift_async_error
clang::swift_async_error
Yes
Theswift_async_errorattributespecifieshowanerrorstatewillbe
representedinaswiftasyncmethod.It’sabitanalogoustotheswift_error
attributeforthegeneratedasyncmethod.Theswift_async_errorattribute
canindicateavarietyofdifferentwaysofrepresentinganerror.
__attribute__((swift_async_error(zero_argument,N))),specifiesthatthe
asyncmethodisconsideredtohavefailediftheNthargumenttothe
completionhandleriszero.
__attribute__((swift_async_error(nonzero_argument,N))),specifiesthat
theasyncmethodisconsideredtohavefailediftheNthargumenttothe
completionhandlerisnon-zero.
__attribute__((swift_async_error(nonnull_error))),specifiesthatthe
asyncmethodisconsideredtohavefailediftheNSError*argumenttothe
completionhandlerisnon-null.
__attribute__((swift_async_error(none))),specifiesthattheasyncmethod
cannotfail.
Forinstance:
@interfaceMyClass:NSObject
-(void)asyncMethod:(void(^)(char,int,float))handler
__attribute__((swift_async(swift_private,1)))
__attribute__((swift_async_error(zero_argument,2)));
@end
Here,theswift_asyncattributespecifiesthathandleristhecompletion
handlerforthismethod,andtheswift_async_errorattributespecifiesthat
theintparameteristheonethatrepresentstheerror.
swift_async_name¶
SupportedSyntaxes¶
swift_async_name
Yes
Theswift_async_nameattributeprovidesthenameoftheasyncoverloadfor
thegivendeclarationinSwift.Ifthisattributeisabsent,thenameis
transformedaccordingtothealgorithmbuiltintotheSwiftcompiler.
TheargumentisastringliteralthatcontainstheSwiftnameofthefunctionor
method.ThenamemaybeacompoundSwiftname.Thefunctionormethodwithsuch
anattributemusthavemorethanzeroparameters,asitslastparameteris
assumedtobeacallbackthat’seliminatedintheSwiftasyncname.
@interfaceURL
+(void)loadContentsFrom:(URL*)urlcallback:(void(^)(NSData*))data__attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
@end
swift_attr¶
SupportedSyntaxes¶
swift_attr
Yes
Theswift_attrprovidesaSwift-specificannotationforthedeclaration
towhichtheattributeappertainsto.Itcanbeusedonanydeclaration
inClang.ThiskindofannotationisignoredbyClangasitdoesn’thaveany
semanticmeaninginlanguagessupportedbyClang.TheSwiftcompilercan
interprettheseannotationsaccordingtoitsownruleswhenimportingCor
Objective-Cdeclarations.
swift_bridge¶
SupportedSyntaxes¶
swift_bridge
Theswift_bridgeattributeindicatesthatthedeclarationtowhichthe
attributeappertainsisbridgedtothenamedSwifttype.
__attribute__((__objc_root__))
@interfaceBase
-(instancetype)init;
@end
__attribute__((__swift_bridge__("BridgedI")))
@interfaceI:Base
@end
Inthisexample,theObjective-CinterfaceIwillbemadeavailabletoSwift
withthenameBridgedI.Itwouldbepossibleforthecompilertoreferto
IstillinordertobridgethetypebacktoObjective-C.
swift_bridged¶
SupportedSyntaxes¶
swift_bridged_typedef
Yes
Theswift_bridged_typedefattributeindicatesthatwhenthetypedeftowhich
theattributeappertainsisimportedintoSwift,itshouldrefertothebridged
Swifttype(e.g.Swift’sString)ratherthantheObjective-Ctypeaswritten
(e.g.NSString).
@interfaceNSString;
typedefNSString*AliasedString__attribute__((__swift_bridged_typedef__));
externvoidacceptsAliasedString(AliasedString_Nonnullparameter);
Inthiscase,thefunctionacceptsAliasedStringwillbeimportedintoSwift
asafunctionwhichacceptsaStringtypeparameter.
swift_error¶
SupportedSyntaxes¶
swift_error
Yes
Theswift_errorattributecontrolswhetheraparticularfunction(or
Objective-Cmethod)isimportedintoSwiftasathrowingfunction,andifso,
whichdynamicconventionituses.
Alloftheseconventionsexceptnonerequirethefunctiontohaveanerror
parameter.Currently,theerrorparameterisalwaysthelastparameteroftype
NSError**orCFErrorRef*.Swiftwillremovetheerrorparameterfrom
theimportedAPI.WhencallingtheAPI,Swiftwillalwayspassavalidaddress
initializedtoanullpointer.
swift_error(none)meansthatthefunctionshouldnotbeimportedas
throwing.Theerrorparameterandresulttypewillbeimportednormally.
swift_error(null_result)meansthatcallstothefunctionshouldbe
consideredtohavethrowniftheyreturnanullvalue.Thereturntypemustbe
apointertype,anditwillbeimportedintoSwiftwithanon-optionaltype.
ThisisthedefaulterrorconventionforObjective-Cmethodsthatreturn
pointers.
swift_error(zero_result)meansthatcallstothefunctionshouldbe
consideredtohavethrowniftheyreturnazeroresult.Thereturntypemustbe
anintegraltype.IfthereturntypewouldhavebeenimportedasBool,it
isinsteadimportedasVoid.Thisisthedefaulterrorconventionfor
Objective-CmethodsthatreturnatypethatwouldbeimportedasBool.
swift_error(nonzero_result)meansthatcallstothefunctionshouldbe
consideredtohavethrowniftheyreturnanon-zeroresult.Thereturntypemust
beanintegraltype.IfthereturntypewouldhavebeenimportedasBool,
itisinsteadimportedasVoid.
swift_error(nonnull_error)meansthatcallstothefunctionshouldbe
consideredtohavethrowniftheyleaveanon-nullerrorintheerrorparameter.
Thereturntypeisleftunmodified.
swift_name¶
SupportedSyntaxes¶
swift_name
Theswift_nameattributeprovidesthenameofthedeclarationinSwift.If
thisattributeisabsent,thenameistransformedaccordingtothealgorithm
builtintotheSwiftcompiler.
TheargumentisastringliteralthatcontainstheSwiftnameofthefunction,
variable,ortype.Whenrenamingafunction,thenamemaybeacompoundSwift
name.Foratype,enumconstant,property,orvariabledeclaration,thename
mustbeasimpleorqualifiedidentifier.
@interfaceURL
-(void)initWithString:(NSString*)s__attribute__((__swift_name__("URL.init(_:)")))
@end
void__attribute__((__swift_name__("squareRoot()")))sqrt(doublev){
}
swift_newtype¶
SupportedSyntaxes¶
swift_newtypeswift_wrapper
Yes
Theswift_newtypeattributeindicatesthatthetypedeftowhichthe
attributeappertainsisimportedasanewSwifttypeofthetypedef’sname.
Previously,theattributewasspeltswift_wrapper.Whilethebehaviourof
theattributeisidenticalwitheitherspelling,swift_wrapperis
deprecated,onlyexistsforcompatibilitypurposes,andshouldnotbeusedin
newcode.
swift_newtype(struct)meansthataSwiftstructwillbecreatedforthis
typedef.
swift_newtype(enum)meansthataSwiftenumwillbecreatedforthis
typedef.
//ImportUIFontTextStyleasanenumtype,withenumeratedvaluesbeing
//constants.
typedefNSString*UIFontTextStyle__attribute__((__swift_newtype__(enum)));
//ImportUIFontDescriptorFeatureKeyasastructuretype,withenumerated
//valuesbeingmembersofthetypestructure.
typedefNSString*UIFontDescriptorFeatureKey__attribute__((__swift_newtype__(struct)));
swift_objc_members¶
SupportedSyntaxes¶
swift_objc_members
Yes
ThisattributeindicatesthatSwiftsubclassesandmembersofSwiftextensions
ofthisclasswillbeimplicitlymarkedwiththe@objcMembersSwift
attribute,exposingthembacktoObjective-C.
swift_private¶
SupportedSyntaxes¶
swift_private
Declarationsmarkedwiththeswift_privateattributearehiddenfromthe
frameworkclientbutarestillmadeavailableforusewithintheframeworkor
SwiftSDKoverlay.
Thepurposeofthisattributeistopermitamoreidomaticimplementationof
declarationsinSwiftwhilehidingthenon-idiomaticone.
DeclarationAttributes¶
Owner¶
SupportedSyntaxes¶
gsl::Owner
Yes
Note
Thisattributeisexperimentalanditseffectonanalysisissubjecttochangein
afutureversionofclang.
Theattribute[[gsl::Owner(T)]]appliestostructsandclassesthatownan
objectoftypeT:
class[[gsl::Owner(int)]]IntOwner{
private:
intvalue;
public:
int*getInt(){return&value;}
};
TheargumentTisoptionalandisignored.
Thisattributemaybeusedbyanalysistoolsandhasnoeffectoncode
generation.Avoidargumentmeansthattheclasscanownanytype.
SeePointerforanexample.
Pointer¶
SupportedSyntaxes¶
gsl::Pointer
Yes
Note
Thisattributeisexperimentalanditseffectonanalysisissubjecttochangein
afutureversionofclang.
Theattribute[[gsl::Pointer(T)]]appliestostructsandclassesthatbehave
likepointerstoanobjectoftypeT:
class[[gsl::Pointer(int)]]IntPointer{
private:
int*valuePointer;
public:
int*getInt(){return&valuePointer;}
};
TheargumentTisoptionalandisignored.
Thisattributemaybeusedbyanalysistoolsandhasnoeffectoncode
generation.Avoidargumentmeansthatthepointercanpointtoanytype.
Example:
Whenconstructinganinstanceofaclassannotatedlikethis(aPointer)from
aninstanceofaclassannotatedwith[[gsl::Owner]](anOwner),
thentheanalysiswillconsiderthePointertopointinsidetheOwner.
WhentheOwner’slifetimeends,itwillconsiderthePointertobedangling.
intf(){
IntPointerP;
if(true){
IntOwnerO(7);
P=IntPointer(O);//P"pointsinto"O
}//Pisdangling
returnP.get();//error:UsingadanglingPointer.
}
__single_inhertiance,__multiple_inheritance,__virtual_inheritance¶
SupportedSyntaxes¶
__single_inheritance__multiple_inheritance__virtual_inheritance__unspecified_inheritance
Thiscollectionofkeywordsisenabledunder-fms-extensionsandcontrols
thepointer-to-memberrepresentationusedon*-*-win32targets.
The*-*-win32targetsutilizeapointer-to-memberrepresentationwhich
variesinsizeandalignmentdependingonthedefinitionoftheunderlying
class.
However,thisisproblematicwhenaforwarddeclarationisonlyavailableand
nodefinitionhasbeenmadeyet.Insuchcases,Clangisforcedtoutilizethe
mostgeneralrepresentationthatisavailabletoit.
Thesekeywordsmakeitpossibletouseapointer-to-memberrepresentationother
thanthemostgeneraloneregardlessofwhetherornotthedefinitionwillever
bepresentinthecurrenttranslationunit.
Thisfamilyofkeywordsbelongbetweentheclass-keyandclass-name:
struct__single_inheritanceS;
intS::*i;
structS{};
Thiskeywordcanbeappliedtoclasstemplatesbutonlyhasaneffectwhenused
onfullspecializations:
templatestruct__single_inheritanceA;//warning:inheritancemodelignoredonprimarytemplate
templatestruct__multiple_inheritanceA;//warning:inheritancemodelignoredonpartialspecialization
template<>struct__single_inheritanceA;
Notethatchoosinganinheritancemodellessgeneralthanstrictlynecessaryis
anerror:
struct__multiple_inheritanceS;//error:inheritancemodeldoesnotmatchdefinition
intS::*i;
structS{};
asm¶
SupportedSyntaxes¶
asm__asm__
Thisattributecanbeusedonafunctionorvariabletospecifyitssymbolname.
Onsometargets,allCsymbolsareprefixedbydefaultwithasinglecharacter,
typically_.Thiswasdonehistoricallytodistinguishthemfromsymbols
usedbyotherlanguages.(ThisprefixisalsoaddedtothestandardItanium
C++ABIprefixon“mangled”symbolnames,sothate.g.onsuchtargetsthetrue
symbolnameforaC++variabledeclaredasintcppvar;wouldbe
__Z6cppvar;notethetwounderscores.)Thisprefixisnotaddedtothe
symbolnamesspecifiedbytheasmattribute;programmerswishingtomatcha
Csymbolnamemustcompensateforthis.
Forexample,considerthefollowingCcode:
intvar1asm("altvar")=1;//"altvar"insymboltable.
intvar2=1;//"_var2"insymboltable.
voidfunc1(void)asm("altfunc");
voidfunc1(void){}//"altfunc"insymboltable.
voidfunc2(void){}//"_func2"insymboltable.
Clang’simplementationofthisattributeiscompatiblewithGCC’s,documentedhere.
Whileitispossibletousethisattributetonameaspecialsymbolused
internallybythecompiler,suchasanLLVMintrinsic,thisisneither
recommendednorsupportedandmaycausethecompilertocrashormiscompile.
Userswhowishtogainaccesstointrinsicbehaviorarestronglyencouragedto
requestnewbuiltinfunctions.
deprecated¶
SupportedSyntaxes¶
deprecated
gnu::deprecateddeprecated
gnu::deprecateddeprecated
deprecated
Thedeprecatedattributecanbeappliedtoafunction,avariable,ora
type.Thisisusefulwhenidentifyingfunctions,variables,ortypesthatare
expectedtoberemovedinafutureversionofaprogram.
Considerthefunctiondeclarationforahypotheticalfunctionf:
voidf(void)__attribute__((deprecated("message","replacement")));
Whenspelledas__attribute__((deprecated)),thedeprecatedattributecanhave
twooptionalstringarguments.Thefirstoneisthemessagetodisplaywhen
emittingthewarning;thesecondoneenablesthecompilertoprovideaFix-It
toreplacethedeprecatednamewithanewname.Otherwise,whenspelledas
[[gnu::deprecated]]or[[deprecated]],theattributecanhaveoneoptional
stringargumentwhichisthemessagetodisplaywhenemittingthewarning.
empty_bases¶
SupportedSyntaxes¶
empty_bases
Theempty_basesattributepermitsthecompilertoutilizethe
empty-base-optimizationmorefrequently.
Thisattributeonlyappliestostruct,class,anduniontypes.
ItisonlysupportedwhenusingtheMicrosoftC++ABI.
enum_extensibility¶
SupportedSyntaxes¶
enum_extensibility
clang::enum_extensibility
clang::enum_extensibility
Yes
Attributeenum_extensibilityisusedtodistinguishbetweenenumdefinitions
thatareextensibleandthosethatarenot.Theattributecantakeeither
closedoropenasanargument.closedindicatesavariableofthe
enumtypetakesavaluethatcorrespondstooneoftheenumeratorslistedinthe
enumdefinitionor,whentheenumisannotatedwithflag_enum,avaluethat
canbeconstructedusingvaluescorrespondingtotheenumerators.open
indicatesavariableoftheenumtypecantakeanyvaluesallowedbythe
standardandinstructsclangtobemorelenientwhenissuingwarnings.
enum__attribute__((enum_extensibility(closed)))ClosedEnum{
A0,A1
};
enum__attribute__((enum_extensibility(open)))OpenEnum{
B0,B1
};
enum__attribute__((enum_extensibility(closed),flag_enum))ClosedFlagEnum{
C0=1<<0,C1=1<<1
};
enum__attribute__((enum_extensibility(open),flag_enum))OpenFlagEnum{
D0=1<<0,D1=1<<1
};
voidfoo1(){
enumClosedEnumce;
enumOpenEnumoe;
enumClosedFlagEnumcfe;
enumOpenFlagEnumofe;
ce=A1;//nowarnings
ce=100;//warningissued
oe=B1;//nowarnings
oe=100;//nowarnings
cfe=C0|C1;//nowarnings
cfe=C0|C1|4;//warningissued
ofe=D0|D1;//nowarnings
ofe=D0|D1|4;//nowarnings
}
external_source_symbol¶
SupportedSyntaxes¶
external_source_symbol
clang::external_source_symbol
clang::external_source_symbol
Yes
Theexternal_source_symbolattributespecifiesthatadeclarationoriginates
fromanexternalsourceanddescribesthenatureofthatsource.
ThefactthatClangiscapableofrecognizingdeclarationsthatweredefined
externallycanbeusedtoprovidebettertoolingsupportformixed-language
projectsorprojectsthatrelyonauto-generatedcode.Forinstance,anIDEthat
usesClangandthatsupportsmixed-languageprojectscanusethisattributeto
provideacorrect‘jump-to-definition’feature.Foraconcreteexample,
consideraprotocolthat’sdefinedinaSwiftfile:
@objcpublicprotocolSwiftProtocol{
funcmethod()
}
ThisprotocolcanbeusedfromObjective-Ccodebyincludingaheaderfilethat
wasgeneratedbytheSwiftcompiler.Thedeclarationsinthatheadercanuse
theexternal_source_symbolattributetomakeClangawareofthefact
thatSwiftProtocolactuallyoriginatesfromaSwiftmodule:
__attribute__((external_source_symbol(language="Swift",defined_in="module")))
@protocolSwiftProtocol
@required
-(void)method;
@end
Consequently,when‘jump-to-definition’isperformedatalocationthat
referencesSwiftProtocol,theIDEcanjumptotheoriginaldefinitionin
theSwiftsourcefileratherthanjumpingtotheObjective-Cdeclarationinthe
auto-generatedheaderfile.
Theexternal_source_symbolattributeisacomma-separatedlistthatincludes
clausesthatdescribetheoriginandthenatureoftheparticulardeclaration.
Thoseclausescanbe:
language=string-literal
Thenameofthesourcelanguageinwhichthisdeclarationwasdefined.
defined_in=string-literal
Thenameofthesourcecontainerinwhichthedeclarationwasdefined.The
exactdefinitionofsourcecontainerislanguage-specific,e.g.Swift’s
sourcecontainersaremodules,sodefined_inshouldspecifytheSwift
modulename.
generated_declaration
Thisdeclarationwasautomaticallygeneratedbysometool.
Theclausescanbespecifiedinanyorder.Theclausesthatarelistedaboveare
alloptional,buttheattributehastohaveatleastoneclause.
flag_enum¶
SupportedSyntaxes¶
flag_enum
clang::flag_enum
clang::flag_enum
Yes
Thisattributecanbeaddedtoanenumeratortosignaltothecompilerthatit
isintendedtobeusedasaflagtype.Thiswillcausethecompilertoassume
thattherangeofthetypeincludesallofthevaluesthatyoucangetby
manipulatingbitsoftheenumeratorwhenissuingwarnings.
layout_version¶
SupportedSyntaxes¶
layout_version
Thelayout_versionattributerequeststhatthecompilerutilizetheclass
layoutrulesofaparticularcompilerversion.
Thisattributeonlyappliestostruct,class,anduniontypes.
ItisonlysupportedwhenusingtheMicrosoftC++ABI.
lto_visibility_public¶
SupportedSyntaxes¶
lto_visibility_public
clang::lto_visibility_public
clang::lto_visibility_public
Yes
SeeLTOVisibility.
managed¶
SupportedSyntaxes¶
managed
__managed__
Yes
The__managed__attributecanbeappliedtoaglobalvariabledeclarationinHIP.
Amanagedvariableisemittedasanundefinedglobalsymbolinthedevicebinaryandis
registeredby__hipRegisterManagedVariableininitfunctions.TheHIPruntimeallocates
managedmemoryandusesittodefinethesymbolwhenloadingthedevicebinary.
Amanagedvariablecanbeaccessedinbothdeviceandhostcode.
novtable¶
SupportedSyntaxes¶
novtable
Thisattributecanbeaddedtoaclassdeclarationordefinitiontosignalto
thecompilerthatconstructorsanddestructorswillnotreferencethevirtual
functiontable.ItisonlysupportedwhenusingtheMicrosoftC++ABI.
ns_error_domain¶
SupportedSyntaxes¶
ns_error_domain
Yes
InCocoaframeworksinObjective-C,onecangrouprelatederrorcodesinenums
andcategorizetheseenumswitherrordomains.
Thens_error_domainattributeindicatesaglobalNSStringor
CFStringconstantrepresentingtheerrordomainthatanerrorcodebelongs
to.Forpointeruniquenessandcodesizethisisaconstantsymbol,nota
literal.
Thedomainanderrorcodeneedtobeusedtogether.Thens_error_domain
attributelinkserrorcodestotheirdomainatthesourcelevel.
Thismetadataisusefulfordocumentationpurposes,forstaticanalysis,andfor
improvinginteroperabilitybetweenObjective-CandSwift.Itisnotusedfor
codegenerationinObjective-C.
Forexample:
#defineNS_ERROR_ENUM(_type,_name,_domain)\
enum_name:_type_name;enum__attribute__((ns_error_domain(_domain)))_name:_type
externNSString*constMyErrorDomain;
typedefNS_ERROR_ENUM(unsignedchar,MyErrorEnum,MyErrorDomain){
MyErrFirst,
MyErrSecond,
};
objc_boxable¶
SupportedSyntaxes¶
objc_boxable
clang::objc_boxable
clang::objc_boxable
Yes
Structsandunionsmarkedwiththeobjc_boxableattributecanbeused
withtheObjective-Cboxedexpressionsyntax,@(...).
Usage:__attribute__((objc_boxable)).Thisattribute
canonlybeplacedonadeclarationofatrivially-copyablestructorunion:
struct__attribute__((objc_boxable))some_struct{
inti;
};
union__attribute__((objc_boxable))some_union{
inti;
floatf;
};
typedefstruct__attribute__((objc_boxable))_some_structsome_struct;
//...
some_structss;
NSValue*boxed=@(ss);
objc_direct¶
SupportedSyntaxes¶
objc_direct
clang::objc_direct
clang::objc_direct
Yes
Theobjc_directattributecanbeusedtomarkanObjective-Cmethodas
beingdirect.Adirectmethodistreatedstaticallylikeanordinarymethod,
butdynamicallyitbehavesmorelikeaCfunction.Thislowerssomeofthecosts
associatedwiththemethodbutalsosacrificessomeoftheordinarycapabilities
ofObjective-Cmethods.
Amessagesendofadirectmethodcallstheimplementationdirectly,asifit
wereaCfunction,ratherthanusingordinaryObjective-Cmethoddispatch.This
issubstantiallyfasterandpotentiallyallowstheimplementationtobeinlined,
butitalsomeansthemethodcannotbeoverriddeninsubclassesorreplaced
dynamically,asordinaryObjective-Cmethodscan.
Furthermore,adirectmethodisnotlistedintheclass’smethodlists.This
substantiallyreducesthecode-sizeoverheadofthemethodbutalsomeansit
cannotbecalleddynamicallyusingordinaryObjective-Cmethoddispatchatall;
inparticular,thismeansthatitcannotoverrideasuperclassmethodorsatisfy
aprotocolrequirement.
Becauseadirectmethodcannotbeoverridden,itisanerrortoperform
asupermessagesendofone.
Althoughamessagesendofadirectmethodcausesthemethodtobecalled
directlyasifitwereaCfunction,itstillobeysObjective-Csemanticsinother
ways:
Ifthereceiverisnil,themessagesenddoesnothingandreturnsthezerovalue
forthereturntype.
Amessagesendofadirectclassmethodwillcausetheclasstobeinitialized,
includingcallingthe+initializemethodifpresent.
Theimplicit_cmdparametercontainingthemethod’sselectorisstilldefined.
Inordertominimizecode-sizecosts,theimplementationwillnotemitareference
totheselectoriftheparameterisunusedwithinthemethod.
Symbolsfordirectmethodimplementationsareimplicitlygivenhidden
visibility,meaningthattheycanonlybecalledwithinthesamelinkageunit.
Itisanerrortodoanyofthefollowing:
declareadirectmethodinaprotocol,
declareanoverrideofadirectmethodwithamethodinasubclass,
declareanoverrideofanon-directmethodwithadirectmethodinasubclass,
declareamethodwithdifferentdirectnessindifferentclassinterfaces,or
implementanon-directmethod(asdeclaredinanyclassinterface)withadirectmethod.
Ifanyoftheseruleswouldbeviolatedifeverymethoddefinedinan
@implementationwithinasinglelinkageunitweredeclaredinan
appropriateclassinterface,theprogramisill-formedwithnodiagnostic
required.Ifaviolationofthisruleisnotdiagnosed,behaviorremains
well-defined;thisparagraphissimplyreservingtherighttodiagnosesuch
conflictsinthefuture,nottotreatthemasundefinedbehavior.
Additionally,Clangwillwarnaboutany@selectorexpressionthat
namesaselectorthatisonlyknowntobeusedfordirectmethods.
Forthepurposeoftheserules,a“classinterface”includesaclass’sprimary
@interfaceblock,itsclassextensions,itscategories,itsdeclaredprotocols,
andalltheclassinterfacesofitssuperclasses.
AnObjective-Cpropertycanbedeclaredwiththedirectproperty
attribute.Ifadirectpropertydeclarationcausesanimplicitdeclarationof
agetterorsettermethod(thatis,ifthegivenmethodisnotexplicitly
declaredelsewhere),themethodisdeclaredtobedirect.
Someprogrammersmaywishtomakemanymethodsdirectatonce.Inorder
tosimplifythis,theobjc_direct_membersattributeisprovided;seeits
documentationformoreinformation.
objc_direct_members¶
SupportedSyntaxes¶
objc_direct_members
clang::objc_direct_members
clang::objc_direct_members
Yes
Theobjc_direct_membersattributecanbeplacedonanObjective-C
@interfaceor@implementationtomarkthatmethodsdeclared
thereinshouldbeconsidereddirectbydefault.Seethedocumentation
forobjc_directformoreinformationaboutdirectmethods.
Whenobjc_direct_membersisplacedonan@interfaceblock,every
methodintheblockisconsideredtobedeclaredasdirect.Thisincludesany
implicitmethoddeclarationsintroducedbypropertydeclarations.Ifthemethod
redeclaresanon-directmethod,thedeclarationisill-formed,exactlyasifthe
methodwasannotatedwiththeobjc_directattribute.
Whenobjc_direct_membersisplacedonan@implementationblock,
methodsdefinedintheblockareconsideredtobedeclaredasdirectunless
theyhavebeenpreviouslydeclaredasnon-directinanyinterfaceoftheclass.
Thisincludestheimplicitmethoddefinitionsintroducedbysynthesized
properties,includingauto-synthesizedproperties.
objc_non_runtime_protocol¶
SupportedSyntaxes¶
objc_non_runtime_protocol
clang::objc_non_runtime_protocol
clang::objc_non_runtime_protocol
Yes
Theobjc_non_runtime_protocolattributecanbeusedtomarkthatan
Objective-Cprotocolisonlyusedduringstatictype-checkinganddoesn’tneed
toberepresenteddynamically.Thisavoidsseveralsmallcode-sizeandrun-time
overheadsassociatedwithhandlingtheprotocol’smetadata.Anon-runtime
protocolcannotbeusedastheoperandofa@protocolexpression,and
dynamicattemptstofinditwithobjc_getProtocolwillfail.
Ifanon-runtimeprotocolinheritsfromanyordinaryprotocols,classesand
derivedprotocolsthatdeclareconformancetothenon-runtimeprotocolwill
dynamicallylisttheirconformancetothosebareprotocols.
objc_nonlazy_class¶
SupportedSyntaxes¶
objc_nonlazy_class
clang::objc_nonlazy_class
clang::objc_nonlazy_class
Yes
ThisattributecanbeaddedtoanObjective-C@interfaceor
@implementationdeclarationtoaddtheclasstothelistofnon-lazily
initializedclasses.Anon-lazyclasswillbeinitializedeagerlywhenthe
Objective-Cruntimeisloaded.Thisisrequiredforcertainsystemclasseswhich
haveinstancesallocatedinnon-standardways,suchastheclassesforblocks
andconstantstrings.Addingthisattributeisessentiallyequivalentto
providingatrivial+loadmethodbutavoidsthe(fairlysmall)load-time
overheadsassociatedwithdefiningandcallingsuchamethod.
objc_runtime_name¶
SupportedSyntaxes¶
objc_runtime_name
clang::objc_runtime_name
clang::objc_runtime_name
Yes
Bydefault,theObjective-Cinterfaceorprotocolidentifierisused
inthemetadatanameforthatobject.Theobjc_runtime_name
attributeallowsannotatedinterfacesorprotocolstousethe
specifiedstringargumentintheobject’smetadatanameinsteadofthe
defaultname.
Usage:__attribute__((objc_runtime_name("MyLocalName"))).Thisattribute
canonlybeplacedbeforean@protocolor@interfacedeclaration:
__attribute__((objc_runtime_name("MyLocalName")))
@interfaceMessage
@end
objc_runtime_visible¶
SupportedSyntaxes¶
objc_runtime_visible
clang::objc_runtime_visible
clang::objc_runtime_visible
Yes
ThisattributespecifiesthattheObjective-Cclasstowhichitappliesis
visibletotheObjective-Cruntimebutnottothelinker.Classesannotated
withthisattributecannotbesubclassedandcannothavecategoriesdefinedfor
them.
objc_subclassing_restricted¶
SupportedSyntaxes¶
objc_subclassing_restricted
clang::objc_subclassing_restricted
clang::objc_subclassing_restricted
Yes
ThisattributecanbeaddedtoanObjective-C@interfacedeclarationto
ensurethatthisclasscannotbesubclassed.
preferred_name¶
SupportedSyntaxes¶
preferred_name
clang::preferred_name
Thepreferred_nameattributecanbeappliedtoaclasstemplate,and
specifiesapreferredwayofnamingaspecializationofthetemplate.The
preferrednamewillbeusedwheneverthecorrespondingtemplatespecialization
wouldotherwisebeprintedinadiagnosticorsimilarcontext.
Thepreferrednamemustbeatypedefortypealiasdeclarationthatreferstoa
specializationoftheclasstemplate(notincludinganytypequalifiers).In
generalthisrequiresthetemplatetobedeclaredatleasttwice.Forexample:
templatestructbasic_string;
usingstring=basic_string;
usingwstring=basic_string;
templatestruct[[clang::preferred_name(string),
clang::preferred_name(wstring)]]basic_string{
//...
};
randomize_layout,no_randomize_layout¶
SupportedSyntaxes¶
no_randomize_layout
gnu::no_randomize_layout
gnu::no_randomize_layout
Yes
Theattributerandomize_layout,whenattachedtoaCstructure,selectsit
forstructurelayoutfieldrandomization;acompile-timehardeningtechnique.A
“seed”value,isspecifiedviathe-frandomize-layout-seed=commandlineflag.
Forexample:
SEED=`od-An-tx8-N32/dev/urandom|tr-d'\n'`
make...CFLAGS="-frandomize-layout-seed=$SEED"...
Youcanalsosupplytheseedinafilewith-frandomize-layout-seed-file=.
Forexample:
od-An-tx8-N32/dev/urandom|tr-d'\n'>/tmp/seed_file.txt
make...CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt"...
Therandomizationisdeterministicbasedforagivenseed,sotheentire
programshouldbecompiledwiththesameseed,butkeeptheseedsafe
otherwise.
Theattributeno_randomize_layout,whenattachedtoaCstructure,
instructsthecompilerthatthisstructureshouldnothaveitsfieldlayout
randomized.
randomize_layout,no_randomize_layout¶
SupportedSyntaxes¶
randomize_layout
gnu::randomize_layout
gnu::randomize_layout
Yes
Theattributerandomize_layout,whenattachedtoaCstructure,selectsit
forstructurelayoutfieldrandomization;acompile-timehardeningtechnique.A
“seed”value,isspecifiedviathe-frandomize-layout-seed=commandlineflag.
Forexample:
SEED=`od-An-tx8-N32/dev/urandom|tr-d'\n'`
make...CFLAGS="-frandomize-layout-seed=$SEED"...
Youcanalsosupplytheseedinafilewith-frandomize-layout-seed-file=.
Forexample:
od-An-tx8-N32/dev/urandom|tr-d'\n'>/tmp/seed_file.txt
make...CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt"...
Therandomizationisdeterministicbasedforagivenseed,sotheentire
programshouldbecompiledwiththesameseed,butkeeptheseedsafe
otherwise.
Theattributeno_randomize_layout,whenattachedtoaCstructure,
instructsthecompilerthatthisstructureshouldnothaveitsfieldlayout
randomized.
selectany¶
SupportedSyntaxes¶
selectany
gnu::selectany
gnu::selectany
selectany
Thisattributeappertainstoaglobalsymbol,causingittohaveaweak
definition(
linkonce
),allowingthelinkertoselectanydefinition.
Formoreinformationsee
gccdocumentation
ormsvcdocumentation.
transparent_union¶
SupportedSyntaxes¶
transparent_union
gnu::transparent_union
gnu::transparent_union
Thisattributecanbeappliedtoauniontochangethebehaviorofcallsto
functionsthathaveanargumentwithatransparentuniontype.Thecompiler
behaviorischangedinthefollowingmanner:
Avaluewhosetypeisanymemberofthetransparentunioncanbepassedasan
argumentwithouttheneedtocastthatvalue.
Theargumentispassedtothefunctionusingthecallingconventionofthe
firstmemberofthetransparentunion.Consequently,allthemembersofthe
transparentunionshouldhavethesamecallingconventionasitsfirstmember.
TransparentunionsarenotsupportedinC++.
trivial_abi¶
SupportedSyntaxes¶
trivial_abi
clang::trivial_abi
Yes
Thetrivial_abiattributecanbeappliedtoaC++class,struct,orunion.
ItinstructsthecompilertopassandreturnthetypeusingtheCABIforthe
underlyingtypewhenthetypewouldotherwisebeconsiderednon-trivialforthe
purposeofcalls.
Aclassannotatedwithtrivial_abicanhavenon-trivialdestructorsor
copy/moveconstructorswithoutautomaticallybecomingnon-trivialforthe
purposesofcalls.Forexample:
//Aistrivialforthepurposesofcallsbecause``trivial_abi``makesthe
//user-providedspecialfunctionstrivial.
struct__attribute__((trivial_abi))A{
~A();
A(constA&);
A(A&&);
intx;
};
//B'sdestructorandcopy/moveconstructorareconsideredtrivialforthe
//purposeofcallsbecauseAistrivial.
structB{
Aa;
};
Ifatypeistrivialforthepurposesofcalls,hasanon-trivialdestructor,
andispassedasanargumentbyvalue,theconventionisthatthecalleewill
destroytheobjectbeforereturning.
Ifatypeistrivialforthepurposeofcalls,itisassumedtobetrivially
relocatableforthepurposeof__is_trivially_relocatable.
Attributetrivial_abihasnoeffectinthefollowingcases:
Theclassdirectlydeclaresavirtualbaseorvirtualmethods.
Copyconstructorsandmoveconstructorsoftheclassarealldeleted.
Theclasshasabaseclassthatisnon-trivialforthepurposesofcalls.
Theclasshasanon-staticdatamemberwhosetypeisnon-trivialforthe
purposesofcalls,whichincludes:
classesthatarenon-trivialforthepurposesofcalls
__weak-qualifiedtypesinObjective-C++
arraysofanyoftheabove
using_if_exists¶
SupportedSyntaxes¶
using_if_exists
clang::using_if_exists
Theusing_if_existsattributeappliestoausing-declaration.Itallows
programmerstoimportadeclarationthatpotentiallydoesnotexist,instead
deferringanyerrorstothepointofuse.Forinstance:
namespaceempty_namespace{};
__attribute__((using_if_exists))
usingempty_namespace::does_not_exist;//noerror!
does_not_existx;//error:useofunresolved'using_if_exists'
TheC++spellingoftheattribte([[clang::using_if_exists]])isalso
supportedasaclangextension,sinceISOC++doesn’tsupportattributesinthis
position.Iftheentityreferredtobytheusing-declarationisfoundbyname
lookup,theattributehasnoeffect.Thisattributeisusefulforlibraries
(primarily,libc++)thatwishtoredeclareasetofdeclarationsinanother
namespace,whentheavailabilityofthosedeclarationsisdifficultor
impossibletodetectatcompiletimewiththepreprocessor.
weak¶
SupportedSyntaxes¶
weak
gnu::weak
gnu::weak
Yes
Insupportedoutputformatstheweakattributecanbeusedto
specifythatavariableorfunctionshouldbeemittedasasymbolwith
weak(ifadefinition)orextern_weak(ifadeclarationofan
externalsymbol)linkage.
Ifthereisanon-weakdefinitionofthesymbolthelinkerwillselect
thatovertheweak.Theymusthavesametypeandalignment(variables
mustalsohavethesamesize),butmayhaveadifferentvalue.
Iftherearemultipleweakdefinitionsofsamesymbol,butnonon-weak
definition,theyshouldhavesametype,size,alignmentandvalue,the
linkerwillselectoneofthem(seealsoselectanyattribute).
Iftheweakattributeisappliedtoaconstqualifiedvariable
definitionthatvariableisnolongerconsideracompiletimeconstant
asitsvaluecanchangeduringlinking(ordynamiclinking).This
meansthatitcane.gnolongerbepartofaninitializerexpression.
constintANSWER__attribute__((weak))=42;
/*Thisfunctionmaybereplacedlink-time*/
__attribute__((weak))voiddebug_log(constchar*msg)
{
fprintf(stderr,"DEBUG:%s\n",msg);
}
intmain(intargc,constchar**argv)
{
debug_log("Startingup...");
/*Thismayprintsomethingelsethan"6*7=42",
ifthereisanon-weakdefinitionof"ANSWER"in
anobjectlinkedin*/
printf("6*7=%d\n",ANSWER);
return0;
}
Ifanexternaldeclarationismarkedweakandthatsymboldoesnot
existduringlinking(possiblydynamic)theaddressofthesymbolwill
evaluatetoNULL.
voidmay_not_exist(void)__attribute__((weak));
intmain(intargc,constchar**argv)
{
if(may_not_exist){
may_not_exist();
}else{
printf("Functiondidnotexist\n");
}
return0;
}
FieldAttributes¶
no_unique_address¶
SupportedSyntaxes¶
no_unique_address
Theno_unique_addressattributeallowstailpaddinginanon-staticdata
membertooverlapothermembersoftheenclosingclass(andinthespecial
casewhenthetypeisempty,permitsittofullyoverlapothermembers).
Thefieldislaidoutasifabaseclasswereencounteredatthecorresponding
pointwithintheclass(exceptthatitdoesnotshareavptrwiththeenclosing
object).
Exampleusage:
templatestructmy_vector{
T*p;
[[no_unique_address]]Allocalloc;
//...
};
static_assert(sizeof(my_vector>)==sizeof(int*));
[[no_unique_address]]isastandardC++20attribute.Clangsupportsitsuse
inC++11onwards.
FunctionAttributes¶
#pragmaompdeclaresimd¶
SupportedSyntaxes¶
ompdeclaresimd
Thedeclaresimdconstructcanbeappliedtoafunctiontoenablethecreation
ofoneormoreversionsthatcanprocessmultipleargumentsusingSIMD
instructionsfromasingleinvocationinaSIMDloop.Thedeclaresimd
directiveisadeclarativedirective.Theremaybemultipledeclaresimd
directivesforafunction.Theuseofadeclaresimdconstructonafunction
enablesthecreationofSIMDversionsoftheassociatedfunctionthatcanbe
usedtoprocessmultipleargumentsfromasingleinvocationfromaSIMDloop
concurrently.
Thesyntaxofthedeclaresimdconstructisasfollows:
#pragmaompdeclaresimd[clause[[,]clause]...]new-line
[#pragmaompdeclaresimd[clause[[,]clause]...]new-line]
[...]
functiondefinitionordeclaration
whereclauseisoneofthefollowing:
simdlen(length)
linear(argument-list[:constant-linear-step])
aligned(argument-list[:alignment])
uniform(argument-list)
inbranch
notinbranch
#pragmaompdeclaretarget¶
SupportedSyntaxes¶
ompdeclaretarget
Thedeclaretargetdirectivespecifiesthatvariablesandfunctionsaremapped
toadeviceforOpenMPoffloadmechanism.
Thesyntaxofthedeclaretargetdirectiveisasfollows:
#pragmaompdeclaretargetnew-line
declarations-definition-seq
#pragmaompenddeclaretargetnew-line
or
#pragmaompdeclaretarget(extended-list)new-line
or
#pragmaompdeclaretargetclause[[,]clause...]new-line
whereclauseisoneofthefollowing:
to(extended-list)
link(list)
device_type(host|nohost|any)
#pragmaompdeclarevariant¶
SupportedSyntaxes¶
ompdeclarevariant
Thedeclarevariantdirectivedeclaresaspecializedvariantofabase
functionandspecifiesthecontextinwhichthatspecializedvariantisused.
Thedeclarevariantdirectiveisadeclarativedirective.
Thesyntaxofthedeclarevariantconstructisasfollows:
#pragmaompdeclarevariant(variant-func-id)clausenew-line
[#pragmaompdeclarevariant(variant-func-id)clausenew-line]
[...]
functiondefinitionordeclaration
whereclauseisoneofthefollowing:
match(context-selector-specification)
andwherevariant-func-idisthenameofafunctionvariantthatiseithera
baselanguageidentifieror,forC++,atemplate-id.
Clangprovidesthefollowingcontextselectorextensions,usedvia
implementation={extension(EXTENSION)}:
match_all
match_any
match_none
disable_implicit_base
allow_templates
Thematchextensionschangewhentheentirecontextselectorisconsidereda
matchforanOpenMPcontext.Thedefaultisall,withnonenotraitinthe
selectorisallowedtobeintheOpenMPcontext,withanyasingletraitin
boththeselectorandOpenMPcontextissufficient.Onlyasinglematch
extensiontraitisallowedpercontextselector.
Thedisableextensionsremovedefaulteffectsofthebegindeclarevariant
appliedtoadefinition.Ifdisable_implicit_baseisgiven,wewillnot
introduceanimplicitbasefunctionforavariantifnobasefunctionwas
found.Thevariantisstillgeneratedbutwillneverbecalled,duetothe
absenceofabasefunctionandconsequentlycallstoabasefunction.
Theallowextensionschangewhenthebegindeclarevarianteffectis
appliedtoadefinition.Ifallow_templatesisgiven,templatefunction
definitionsareconsideredasspecializationsofexistingorassumedtemplate
declarationswiththesamename.Thetemplateparametersforthebasefunctions
areusedtoinstantiatethespecialization.
SV_GroupIndex¶
SupportedSyntaxes¶
SV_GroupIndex
TheSV_GroupIndexsemantic,whenappliedtoaninputparameter,specifiesa
databindingtomapthegroupindextothespecifiedparameter.Thisattribute
isonlysupportedincomputeshaders.
Thefulldocumentationisavailablehere:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
_Noreturn¶
SupportedSyntaxes¶
_Noreturn
Afunctiondeclaredas_Noreturnshallnotreturntoitscaller.The
compilerwillgenerateadiagnosticforafunctiondeclaredas_Noreturn
thatappearstobecapableofreturningtoitscaller.Despitebeingatype
specifier,the_Noreturnattributecannotbespecifiedonafunction
pointertype.
abi_tag¶
SupportedSyntaxes¶
abi_tag
gnu::abi_tag
Yes
Theabi_tagattributecanbeappliedtoafunction,variable,classor
inlinenamespacedeclarationtomodifythemanglednameoftheentity.Itgives
theabilitytodistinguishbetweendifferentversionsofthesameentitybut
withdifferentABIversionssupported.Forexample,anewerversionofaclass
couldhaveadifferentsetofdatamembersandthushaveadifferentsize.Using
theabi_tagattribute,itispossibletohavedifferentmanglednamesfor
aglobalvariableoftheclasstype.Therefore,theoldcodecouldkeepusing
theoldmanglednameandthenewcodewillusethenewmanglednamewithtags.
acquire_capability,acquire_shared_capability¶
SupportedSyntaxes¶
acquire_capabilityacquire_shared_capabilityexclusive_lock_functionshared_lock_function
clang::acquire_capabilityclang::acquire_shared_capability
Marksafunctionasacquiringacapability.
alloc_align¶
SupportedSyntaxes¶
alloc_align
gnu::alloc_align
gnu::alloc_align
Use__attribute__((alloc_align())onafunction
declarationtospecifythatthereturnvalueofthefunction(whichmustbea
pointertype)isatleastasalignedasthevalueoftheindicatedparameter.The
parameterisgivenbyitsindexinthelistofformalparameters;thefirst
parameterhasindex1unlessthefunctionisaC++non-staticmemberfunction,
inwhichcasethefirstparameterhasindex2toaccountfortheimplicitthis
parameter.
//Thereturnedpointerhasthealignmentspecifiedbythefirstparameter.
void*a(size_talign)__attribute__((alloc_align(1)));
//Thereturnedpointerhasthealignmentspecifiedbythesecondparameter.
void*b(void*v,size_talign)__attribute__((alloc_align(2)));
//Thereturnedpointerhasthealignmentspecifiedbythesecondvisible
//parameter,howeveritmustbeadjustedfortheimplicit'this'parameter.
void*Foo::b(void*v,size_talign)__attribute__((alloc_align(3)));
Notethatthisattributemerelyinformsthecompilerthatafunctionalways
returnsasufficientlyalignedpointer.Itdoesnotcausethecompilerto
emitcodetoenforcethatalignment.Thebehaviorisundefinedifthereturned
pointerisnotsufficientlyaligned.
alloc_size¶
SupportedSyntaxes¶
alloc_size
gnu::alloc_size
gnu::alloc_size
Thealloc_sizeattributecanbeplacedonfunctionsthatreturnpointersin
ordertohinttothecompilerhowmanybytesofmemorywillbeavailableatthe
returnedpointer.alloc_sizetakesoneortwoarguments.
alloc_size(N)impliesthatargumentnumberNequalsthenumberof
availablebytesatthereturnedpointer.
alloc_size(N,M)impliesthattheproductofargumentnumberNand
argumentnumberMequalsthenumberofavailablebytesatthereturned
pointer.
Argumentnumbersare1-based.
Anexampleofhowtousealloc_size
void*my_malloc(inta)__attribute__((alloc_size(1)));
void*my_calloc(inta,intb)__attribute__((alloc_size(1,2)));
intmain(){
void*constp=my_malloc(100);
assert(__builtin_object_size(p,0)==100);
void*consta=my_calloc(20,5);
assert(__builtin_object_size(a,0)==100);
}
Note
ThisattributeworksdifferentlyinclangthanitdoesinGCC.
Specifically,clangwillonlytraceconstpointers(asabove);wegiveup
onpointersthatarenotmarkedasconst.Inthevastmajorityofcases,
thisisunimportant,becauseLLVMhassupportforthealloc_size
attribute.However,thismaycausemildlyunintuitivebehaviorwhenusedwith
otherattributes,suchasenable_if.
allocator¶
SupportedSyntaxes¶
allocator
The__declspec(allocator)attributeisappliedtofunctionsthatallocate
memory,suchasoperatornewinC++.WhenCodeViewdebuginformationisemitted
(enabledbyclang-gcodevieworclang-cl/Z7),Clangwillattemptto
recordthecodeoffsetofheapallocationcallsitesinthedebuginfo.Itwill
alsorecordthetypebeingallocatedusingsomelocalheuristics.TheVisual
Studiodebuggerusesthisinformationtoprofilememoryusage.
Thisattributedoesnotaffectoptimizationsinanyway,unlikeGCC’s
__attribute__((malloc)).
always_inline,__force_inline¶
SupportedSyntaxes¶
always_inline
gnu::always_inlineclang::always_inline
gnu::always_inlineclang::always_inline
__forceinline
Yes
Inliningheuristicsaredisabledandinliningisalwaysattemptedregardlessof
optimizationlevel.
[[clang::always_inline]]spellingcanbeusedasastatementattribute;other
spellingsoftheattributearenotsupportedonstatements.Ifastatementis
marked[[clang::always_inline]]andcontainscalls,thecompilerattempts
toinlinethosecalls.
intexample(void){
inti;
[[clang::always_inline]]foo();//attemptstoinlinefoo
[[clang::always_inline]]i=bar();//attemptstoinlinebar
[[clang::always_inline]]returnf(42,baz(bar()));//attemptstoinlineeverything
}
Adeclarationstatement,whichisastatement,isnotastatementthatcanhavean
attributeassociatedwithit(theattributeappliestothedeclaration,notthe
statementinthatcase).Sothisusecasewillnotwork:
intexample(void){
[[clang::always_inline]]inti=bar();
returni;
}
Thisattributedoesnotguaranteethatinlinesubstitutionactuallyoccurs.
Note:applyingthisattributetoacoroutineatthe-O0optimizationlevel
hasnoeffect;otheroptimizationlevelsmayonlypartiallyinlineandresultina
diagnostic.
SeealsotheMicrosoftDocsonInlineFunctions,theGCCCommonFunction
Attributedocs,andtheGCCInlinedocs.
artificial¶
SupportedSyntaxes¶
artificial
gnu::artificial
gnu::artificial
Theartificialattributecanbeappliedtoaninlinefunction.Ifsucha
functionisinlined,theattributeindicatesthatdebuggersshouldassociate
theresultinginstructionswiththecallsite,ratherthanwiththe
correspondinglinewithintheinlinedcallee.
assert_capability,assert_shared_capability¶
SupportedSyntaxes¶
assert_capabilityassert_shared_capability
clang::assert_capabilityclang::assert_shared_capability
Marksafunctionthatdynamicallytestswhetheracapabilityisheld,andhalts
theprogramifitisnotheld.
assume¶
SupportedSyntaxes¶
assume
clang::assume
clang::assume
Yes
Clangsupportsthe__attribute__((assume("assumption")))attributeto
provideadditionalinformationtotheoptimizer.Thestring-literal,here
“assumption”,willbeattachedtothefunctiondeclarationsuchthatlater
analysisandoptimizationpassescanassumethe“assumption”tohold.
Thisissimilarto__builtin_assumebut
insteadofanexpressionthatcanbeassumedtobenon-zero,theassumptionis
expressedasastringanditholdsfortheentirefunction.
Afunctioncanhavemultipleassumeattributesandtheypropagatefromprior
declarationstolaterdefinitions.Multipleassumptionsareaggregatedintoa
singlecommaseparatedstring.Thus,onecanprovidemultipleassumptionsvia
acommaseparatedstring,i.a.,
__attribute__((assume("assumption1,assumption2"))).
WhileLLVMpluginsmightprovidemoreassumptionstrings,thedefaultLLVM
optimizationpassesareawareofthefollowingassumptions:
"omp_no_openmp"
"omp_no_openmp_routines"
"omp_no_parallelism"
TheOpenMPstandarddefinesthemeaningofOpenMPassumptions(“omp_XYZ”is
spelled“XYZ”intheOpenMP5.1Standard).
assume_aligned¶
SupportedSyntaxes¶
assume_aligned
gnu::assume_aligned
gnu::assume_aligned
Yes
Use__attribute__((assume_aligned([,]))onafunction
declarationtospecifythatthereturnvalueofthefunction(whichmustbea
pointertype)hasthespecifiedoffset,inbytes,fromanaddresswiththe
specifiedalignment.Theoffsetistakentobezeroifomitted.
//Thereturnedpointervaluehas32-bytealignment.
void*a()__attribute__((assume_aligned(32)));
//Thereturnedpointervalueis4bytesgreaterthananaddresshaving
//32-bytealignment.
void*b()__attribute__((assume_aligned(32,4)));
Notethatthisattributeprovidesinformationtothecompilerregardinga
conditionthatthecodealreadyensuresistrue.Itdoesnotcausethecompiler
toenforcetheprovidedalignmentassumption.
availability¶
SupportedSyntaxes¶
availability
clang::availability
clang::availability
Yes
Theavailabilityattributecanbeplacedondeclarationstodescribethe
lifecycleofthatdeclarationrelativetooperatingsystemversions.Consider
thefunctiondeclarationforahypotheticalfunctionf:
voidf(void)__attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
TheavailabilityattributestatesthatfwasintroducedinmacOS10.4,
deprecatedinmacOS10.6,andobsoletedinmacOS10.7.Thisinformation
isusedbyClangtodeterminewhenitissafetousef:forexample,if
ClangisinstructedtocompilecodeformacOS10.5,acalltof()
succeeds.IfClangisinstructedtocompilecodeformacOS10.6,thecall
succeedsbutClangemitsawarningspecifyingthatthefunctionisdeprecated.
Finally,ifClangisinstructedtocompilecodeformacOS10.7,thecall
failsbecausef()isnolongeravailable.
Theavailabilityattributeisacomma-separatedliststartingwiththe
platformnameandthenincludingclausesspecifyingimportantmilestonesinthe
declaration’slifetime(inanyorder)alongwithadditionalinformation.Those
clausescanbe:
introduced=version
Thefirstversioninwhichthisdeclarationwasintroduced.
deprecated=version
Thefirstversioninwhichthisdeclarationwasdeprecated,meaningthat
usersshouldmigrateawayfromthisAPI.
obsoleted=version
Thefirstversioninwhichthisdeclarationwasobsoleted,meaningthatit
wasremovedcompletelyandcannolongerbeused.
unavailable
Thisdeclarationisneveravailableonthisplatform.
message=string-literal
AdditionalmessagetextthatClangwillprovidewhenemittingawarningor
erroraboutuseofadeprecatedorobsoleteddeclaration.Usefultodirect
userstoreplacementAPIs.
replacement=string-literal
AdditionalmessagetextthatClangwillusetoprovideFix-Itwhenemitting
awarningaboutuseofadeprecateddeclaration.TheFix-Itwillreplace
thedeprecateddeclarationwiththenewdeclarationspecified.
Multipleavailabilityattributescanbeplacedonadeclaration,whichmay
correspondtodifferentplatforms.Formostplatforms,theavailability
attributewiththeplatformcorrespondingtothetargetplatformwillbeused;
anyotherswillbeignored.However,theavailabilityforwatchOSand
tvOScanbeimplicitlyinferredfromaniOSavailabilityattribute.
Anyexplicitavailabilityattributesforthoseplatformsarestillpreferredover
theimplicitlyinferredavailabilityattributes.Ifnoavailabilityattribute
specifiesavailabilityforthecurrenttargetplatform,theavailability
attributesareignored.Supportedplatformsare:
ios
Apple’siOSoperatingsystem.Theminimumdeploymenttargetisspecifiedby
the-mios-version-min=*version*or-miphoneos-version-min=*version*
command-linearguments.
macos
Apple’smacOSoperatingsystem.Theminimumdeploymenttargetis
specifiedbythe-mmacosx-version-min=*version*command-lineargument.
macosxissupportedforbackward-compatibilityreasons,butitis
deprecated.
tvos
Apple’stvOSoperatingsystem.Theminimumdeploymenttargetisspecifiedby
the-mtvos-version-min=*version*command-lineargument.
watchos
Apple’swatchOSoperatingsystem.Theminimumdeploymenttargetisspecifiedby
the-mwatchos-version-min=*version*command-lineargument.
driverkit
Apple’sDriverKituserspacekernelextensions.Theminimumdeploymenttarget
isspecifiedaspartofthetriple.
Adeclarationcantypicallybeusedevenwhendeployingbacktoaplatform
versionpriortowhenthedeclarationwasintroduced.Whenthishappens,the
declarationisweaklylinked,
asiftheweak_importattributewereaddedtothedeclaration.A
weakly-linkeddeclarationmayormaynotbepresentarun-time,andaprogram
candeterminewhetherthedeclarationispresentbycheckingwhetherthe
addressofthatdeclarationisnon-NULL.
TheflagstrictdisallowsusingAPIwhendeployingbacktoa
platformversionpriortowhenthedeclarationwasintroduced.An
attempttousesuchAPIbeforeitsintroductioncausesaharderror.
Weakly-linkingisalmostalwaysabetterAPIchoice,sinceitallows
userstoqueryavailabilityatruntime.
Iftherearemultipledeclarationsofthesameentity,theavailability
attributesmusteithermatchonaper-platformbasisorlater
declarationsmustnothaveavailabilityattributesforthat
platform.Forexample:
voidg(void)__attribute__((availability(macos,introduced=10.4)));
voidg(void)__attribute__((availability(macos,introduced=10.4)));//okay,matches
voidg(void)__attribute__((availability(ios,introduced=4.0)));//okay,addsanewplatform
voidg(void);//okay,inheritsbothmacosandiosavailabilityfromabove.
voidg(void)__attribute__((availability(macos,introduced=10.5)));//error:mismatch
Whenonemethodoverridesanother,theoverridingmethodcanbemorewidelyavailablethantheoverriddenmethod,e.g.,:
@interfaceA
-(id)method__attribute__((availability(macos,introduced=10.4)));
-(id)method2__attribute__((availability(macos,introduced=10.4)));
@end
@interfaceB:A
-(id)method__attribute__((availability(macos,introduced=10.3)));//okay:methodmovedintobaseclasslater
-(id)method__attribute__((availability(macos,introduced=10.5)));//error:thismethodwasavailableviathebaseclassin10.4
@end
StartingwiththemacOS10.12SDK,theAPI_AVAILABLEmacrofrom
cansimplifythespelling:
@interfaceA
-(id)methodAPI_AVAILABLE(macos(10.11)));
-(id)otherMethodAPI_AVAILABLE(macos(10.11),ios(11.0));
@end
Availabilityattributescanalsobeappliedusinga#pragmaclangattribute.
Anyexplicitavailabilityattributewhoseplatformcorrespondstothetarget
platformisappliedtoadeclarationregardlessoftheavailabilityattributes
specifiedinthepragma.Forexample,inthecodebelow,
hasExplicitAvailabilityAttributewillusethemacOSavailability
attributethatisspecifiedwiththedeclaration,whereas
getsThePragmaAvailabilityAttributewillusethemacOSavailability
attributethatisappliedbythepragma.
#pragmaclangattributepush(__attribute__((availability(macOS,introduced=10.12))),apply_to=function)
voidgetsThePragmaAvailabilityAttribute(void);
voidhasExplicitAvailabilityAttribute(void)__attribute__((availability(macos,introduced=10.4)));
#pragmaclangattributepop
ForplatformslikewatchOSandtvOS,whoseavailabilityattributescan
beimplicitlyinferredfromaniOSavailabilityattribute,thelogicis
slightlymorecomplex.Theexplicitandthepragma-appliedavailability
attributeswhoseplatformcorrespondstothetargetplatformareappliedas
describedinthepreviousparagraph.However,theimplicitlyinferredattributes
areappliedtoadeclarationonlywhenthereisnoexplicitorpragma-applied
availabilityattributewhoseplatformcorrespondstothetargetplatform.For
example,thefunctionbelowwillreceivethetvOSavailabilityfromthe
pragmaratherthanusingtheinferrediOSavailabilityfromthedeclaration:
#pragmaclangattributepush(__attribute__((availability(tvOS,introduced=12.0))),apply_to=function)
voidgetsThePragmaTVOSAvailabilityAttribute(void)__attribute__((availability(iOS,introduced=11.0)));
#pragmaclangattributepop
Thecompilerisalsoabletoapplyimplicitlyinferredattributesfromapragma
aswell.Forexample,whentargetingtvOS,thefunctionbelowwillreceive
atvOSavailabilityattributethatisimplicitlyinferredfromtheiOS
availabilityattributeappliedbythepragma:
#pragmaclangattributepush(__attribute__((availability(iOS,introduced=12.0))),apply_to=function)
voidinfersTVOSAvailabilityFromPragma(void);
#pragmaclangattributepop
Theimplicitattributesthatareinferredfromexplicitlyspecifiedattributes
whoseplatformcorrespondstothetargetplatformareappliedtothedeclaration
evenifthereisanavailabilityattributethatcanbeinferredfromapragma.
Forexample,thefunctionbelowwillreceivethetvOS,introduced=11.0
availabilitythatisinferredfromtheattributeonthedeclarationratherthan
inferringavailabilityfromthepragma:
#pragmaclangattributepush(__attribute__((availability(iOS,unavailable))),apply_to=function)
voidinfersTVOSAvailabilityFromAttributeNextToDeclaration(void)
__attribute__((availability(iOS,introduced=11.0)));
#pragmaclangattributepop
Alsoseethedocumentationfor@available
btf_decl_tag¶
SupportedSyntaxes¶
btf_decl_tag
clang::btf_decl_tag
clang::btf_decl_tag
Yes
Clangsupportsthe__attribute__((btf_decl_tag("ARGUMENT")))attributefor
alltargets.Thisattributemaybeattachedtoastruct/union,struct/union
field,function,functionparameter,variableortypedefdeclaration.If-gis
specified,theARGUMENTinfowillbepreservedinIRandbeemittedto
dwarf.ForBPFtargets,theARGUMENTinfowillbeemittedto.BTFELF
sectiontoo.
callback¶
SupportedSyntaxes¶
callback
clang::callback
clang::callback
Yes
Thecallbackattributespecifiesthattheannotatedfunctionmayinvokethe
specifiedcallbackzeroormoretimes.Thecallback,aswellasthepassed
arguments,areidentifiedbytheirparameternameorposition(startingwith
1!)intheannotatedfunction.Thefirstpositionintheattributeidentifies
thecallbackcallee,thefollowingpositionsdeclaredescribeitsarguments.
Thecallbackcalleeisrequiredtobecallablewiththenumber,andorder,of
thespecifiedarguments.Theindex0,ortheidentifierthis,isusedto
representanimplicit“this”pointerinclassmethods.Ifthereisnoimplicit
“this”pointeritshallnotbereferenced.Theindex‘-1’,orthename“__”,
representsanunknowncallbackcalleeargument.Thiscanbeavaluewhichis
notpresentinthedeclaredparameterlist,oronethatis,butispotentially
inspected,captured,ormodified.Parameternamesandindicescanbemixedin
thecallbackattribute.
Thecallbackattribute,whichisdirectlytranslatedtocallback
metadata,makethe
connectionbetweenthecalltotheannotatedfunctionandthecallbackcallee.
Thiscanenableinterproceduraloptimizationswhichwereotherwiseimpossible.
Ifafunctionparameterismentionedinthecallbackattribute,throughits
position,itisundefinedifthatparameterisusedforanythingotherthanthe
actualcallback.Inspected,captured,ormodifiedparametersshallnotbe
listedinthecallbackmetadata.
Exampleencodingsforthecallbackperformedbypthread_createareshown
below.Theexplicitattributeannotationindicatesthatthethirdparameter
(start_routine)iscalledzeroormoretimesbythepthread_createfunction,
andthatthefourthparameter(arg)ispassedalong.Notethatthecallback
behaviorofpthread_createisautomaticallyrecognizedbyClang.Inaddition,
thedeclarationsof__kmpc_fork_teamsand__kmpc_fork_call,generatedfor
#pragmaomptargetteamsand#pragmaompparallel,respectively,arealso
automaticallyrecognizedasbrokerfunctions.Furtherfunctionsmightbeadded
inthefuture.
__attribute__((callback(start_routine,arg)))
intpthread_create(pthread_t*thread,constpthread_attr_t*attr,
void*(*start_routine)(void*),void*arg);
__attribute__((callback(3,4)))
intpthread_create(pthread_t*thread,constpthread_attr_t*attr,
void*(*start_routine)(void*),void*arg);
carries_dependency¶
SupportedSyntaxes¶
carries_dependency
carries_dependency
Yes
Thecarries_dependencyattributespecifiesdependencypropagationintoand
outoffunctions.
WhenspecifiedonafunctionorObjective-Cmethod,thecarries_dependency
attributemeansthatthereturnvaluecarriesadependencyoutofthefunction,
sothattheimplementationneednotconstrainorderinguponreturnfromthat
function.Implementationsofthefunctionanditscallermaychoosetopreserve
dependenciesinsteadofemittingmemoryorderinginstructionssuchasfences.
Note,thisattributedoesnotchangethemeaningoftheprogram,butmayresult
ingenerationofmoreefficientcode.
cf_consumed¶
SupportedSyntaxes¶
cf_consumed
clang::cf_consumed
clang::cf_consumed
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
cf_returns_not_retained¶
SupportedSyntaxes¶
cf_returns_not_retained
clang::cf_returns_not_retained
clang::cf_returns_not_retained
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
cf_returns_retained¶
SupportedSyntaxes¶
cf_returns_retained
clang::cf_returns_retained
clang::cf_returns_retained
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
cfi_canonical_jump_table¶
SupportedSyntaxes¶
cfi_canonical_jump_table
clang::cfi_canonical_jump_table
clang::cfi_canonical_jump_table
Yes
Use__attribute__((cfi_canonical_jump_table))onafunctiondeclarationto
makethefunction’sCFIjumptablecanonical.SeetheCFIdocumentationformoredetails.
clang::builtin_alias,clang_builtin_alias¶
SupportedSyntaxes¶
clang_builtin_alias
clang::builtin_alias
clang::builtin_alias
Yes
ThisattributeisusedintheimplementationoftheCintrinsics.
ItallowstheCintrinsicfunctionstobedeclaredusingthenamesdefined
intargetbuiltins,andstillberecognizedasclangbuiltinsequivalenttothe
underlyingname.Forexample,riscv_vector.hdeclaresthefunctionvadd
with__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1))).
Thisensuresthatbothfunctionsarerecognizedasthatclangbuiltin,
andinthelattercase,thechoiceofwhichbuiltintoidentifythe
functionascanbedeferreduntilafteroverloadresolution.
ThisattributecanonlybeusedtosetupthealiasesforcertainARM/RISC-V
Cintrinsicfunctions;itisintendedforuseonlyinsidearm_*.hand
riscv_*.handisnotageneralmechanismfordeclaringarbitraryaliases
forclangbuiltinfunctions.
clang_arm_builtin_alias¶
SupportedSyntaxes¶
__clang_arm_builtin_alias
clang::__clang_arm_builtin_alias
clang::__clang_arm_builtin_alias
Yes
ThisattributeisusedintheimplementationoftheACLEintrinsics.
Itallowstheintrinsicfunctionsto
bedeclaredusingthenamesdefinedinACLE,andstillberecognized
asclangbuiltinsequivalenttotheunderlyingname.Forexample,
arm_mve.hdeclaresthefunctionvaddq_u32with
__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32))),
andsimilarly,oneofthetype-overloadeddeclarationsofvaddq
willhavethesameattribute.Thisensuresthatbothfunctionsare
recognizedasthatclangbuiltin,andinthelattercase,thechoice
ofwhichbuiltintoidentifythefunctionascanbedeferreduntil
afteroverloadresolution.
ThisattributecanonlybeusedtosetupthealiasesforcertainArm
intrinsicfunctions;itisintendedforuseonlyinsidearm_*.h
andisnotageneralmechanismfordeclaringarbitraryaliasesfor
clangbuiltinfunctions.
Inordertoavoidduplicatingtheattributedefinitionsforsimilar
purposeforotherarchitecture,thereisageneralformforthe
attributeclang_builtin_alias.
cmse_nonsecure_entry¶
SupportedSyntaxes¶
cmse_nonsecure_entry
Yes
Thisattributedeclaresafunctionthatcanbecalledfromnon-securestate,or
fromsecurestate.Enteringfromandreturningtonon-securestatewouldswitch
toandfromsecurestate,respectively,andpreventflowofinformation
tonon-securestate,exceptviareturnvalues.SeeARMv8-MSecurityExtensions:
RequirementsonDevelopmentTools-EngineeringSpecificationDocumentationformoreinformation.
code_seg¶
SupportedSyntaxes¶
code_seg
The__declspec(code_seg)attributeenablestheplacementofcodeintoseparate
namedsegmentsthatcanbepagedorlockedinmemoryindividually.Thisattribute
isusedtocontroltheplacementofinstantiatedtemplatesandcompiler-generated
code.Seethedocumentationfor__declspec(code_seg)onMSDN.
convergent¶
SupportedSyntaxes¶
convergent
clang::convergent
clang::convergent
Yes
Theconvergentattributecanbeplacedonafunctiondeclaration.Itis
translatedintotheLLVMconvergentattribute,whichindicatesthatthecall
instructionsofafunctionwiththisattributecannotbemadecontrol-dependent
onanyadditionalvalues.
InlanguagesdesignedforSPMD/SIMTprogrammingmodel,e.g.OpenCLorCUDA,
thecallinstructionsofafunctionwiththisattributemustbeexecutedby
allworkitemsorthreadsinaworkgrouporsubgroup.
Thisattributeisdifferentfromnoduplicatebecauseitallowsduplicating
functioncallsifitcanbeprovedthattheduplicatedfunctioncallsare
notmadecontrol-dependentonanyadditionalvalues,e.g.,unrollingaloop
executedbyallworkitems.
Sampleusage:
voidconvfunc(void)__attribute__((convergent));
//SettingitasaC++11attributeisalsovalidinaC++program.
//voidconvfunc(void)[[clang::convergent]];
cpu_dispatch¶
SupportedSyntaxes¶
cpu_dispatch
clang::cpu_dispatch
clang::cpu_dispatch
cpu_dispatch
Yes
Thecpu_specificandcpu_dispatchattributesareusedtodefineand
resolvemultiversionedfunctions.Thisformofmultiversioningprovidesa
mechanismfordeclaringversionsacrosstranslationunitsandmanually
specifyingtheresolvedfunctionlist.AspecifiedCPUdefinesasetofminimum
featuresthatarerequiredforthefunctiontobecalled.Theresultofthisis
thatfutureprocessorsexecutethemostrestrictiveversionofthefunctionthe
newprocessorcanexecute.
Inaddition,unliketheICCimplementationofthisfeature,theselectionofthe
versiondoesnotconsiderthemanufacturerormicroarchitectureoftheprocessor.
Ittestssolelythelistoffeaturesthatarebothsupportedbythespecified
processorandpresentinthecompiler-rtlibrary.Thiscanbesurprisingattimes,
astheruntimeprocessormaybefromacompletelydifferentmanufacturer,aslong
asitsupportsthesamefeatureset.
Thiscanadditionallybesurprising,assomeprocessorsareindistringuishablefrom
othersbasedonthelistoftestablefeatures.Whenthishappens,thevariant
isselectedinanunspecifiedmanner.
Functionversionsaredefinedwithcpu_specific,whichtakesoneormoreCPU
namesasaparameter.Forexample:
//Declaresanddefinestheivybridgeversionofsingle_cpu.
__attribute__((cpu_specific(ivybridge)))
voidsingle_cpu(void){}
//Declaresanddefinestheatomversionofsingle_cpu.
__attribute__((cpu_specific(atom)))
voidsingle_cpu(void){}
//Declaresanddefinesboththeivybridgeandatomversionofmulti_cpu.
__attribute__((cpu_specific(ivybridge,atom)))
voidmulti_cpu(void){}
Adispatching(orresolving)functioncanbedeclaredanywhereinaproject’s
sourcecodewithcpu_dispatch.ThisattributetakesoneormoreCPUnames
asaparameter(likecpu_specific).Functionsmarkedwithcpu_dispatch
arenotexpectedtobedefined,onlydeclared.Ifsuchamarkedfunctionhasa
definition,anysideeffectsofthefunctionareignored;trivialfunction
bodiesarepermissibleforICCcompatibility.
//Createsaresolverforsingle_cpuabove.
__attribute__((cpu_dispatch(ivybridge,atom)))
voidsingle_cpu(void){}
//Createsaresolverformulti_cpu,butaddsa3rdversiondefinedinanother
//translationunit.
__attribute__((cpu_dispatch(ivybridge,atom,sandybridge)))
voidmulti_cpu(void){}
Notethatitispossibletohavearesolvingfunctionthatdispatchesbasedon
moreorfeweroptionsthanarepresentintheprogram.Specifyingfewerwill
resultintheomittedoptionsnotbeingconsideredduringresolution.Specifying
aversionforresolutionthatisn’tdefinedintheprogramwillresultina
linkingfailure.
ItisalsopossibletospecifyaCPUnameofgenericwhichwillberesolved
iftheexecutingprocessordoesn’tsatisfythefeaturesrequiredintheCPU
name.Thebehaviorofaprogramexecutingonaprocessorthatdoesn’tsatisfy
anyoptionofamultiversionedfunctionisundefined.
cpu_specific¶
SupportedSyntaxes¶
cpu_specific
clang::cpu_specific
clang::cpu_specific
cpu_specific
Yes
Thecpu_specificandcpu_dispatchattributesareusedtodefineand
resolvemultiversionedfunctions.Thisformofmultiversioningprovidesa
mechanismfordeclaringversionsacrosstranslationunitsandmanually
specifyingtheresolvedfunctionlist.AspecifiedCPUdefinesasetofminimum
featuresthatarerequiredforthefunctiontobecalled.Theresultofthisis
thatfutureprocessorsexecutethemostrestrictiveversionofthefunctionthe
newprocessorcanexecute.
Inaddition,unliketheICCimplementationofthisfeature,theselectionofthe
versiondoesnotconsiderthemanufacturerormicroarchitectureoftheprocessor.
Ittestssolelythelistoffeaturesthatarebothsupportedbythespecified
processorandpresentinthecompiler-rtlibrary.Thiscanbesurprisingattimes,
astheruntimeprocessormaybefromacompletelydifferentmanufacturer,aslong
asitsupportsthesamefeatureset.
Thiscanadditionallybesurprising,assomeprocessorsareindistringuishablefrom
othersbasedonthelistoftestablefeatures.Whenthishappens,thevariant
isselectedinanunspecifiedmanner.
Functionversionsaredefinedwithcpu_specific,whichtakesoneormoreCPU
namesasaparameter.Forexample:
//Declaresanddefinestheivybridgeversionofsingle_cpu.
__attribute__((cpu_specific(ivybridge)))
voidsingle_cpu(void){}
//Declaresanddefinestheatomversionofsingle_cpu.
__attribute__((cpu_specific(atom)))
voidsingle_cpu(void){}
//Declaresanddefinesboththeivybridgeandatomversionofmulti_cpu.
__attribute__((cpu_specific(ivybridge,atom)))
voidmulti_cpu(void){}
Adispatching(orresolving)functioncanbedeclaredanywhereinaproject’s
sourcecodewithcpu_dispatch.ThisattributetakesoneormoreCPUnames
asaparameter(likecpu_specific).Functionsmarkedwithcpu_dispatch
arenotexpectedtobedefined,onlydeclared.Ifsuchamarkedfunctionhasa
definition,anysideeffectsofthefunctionareignored;trivialfunction
bodiesarepermissibleforICCcompatibility.
//Createsaresolverforsingle_cpuabove.
__attribute__((cpu_dispatch(ivybridge,atom)))
voidsingle_cpu(void){}
//Createsaresolverformulti_cpu,butaddsa3rdversiondefinedinanother
//translationunit.
__attribute__((cpu_dispatch(ivybridge,atom,sandybridge)))
voidmulti_cpu(void){}
Notethatitispossibletohavearesolvingfunctionthatdispatchesbasedon
moreorfeweroptionsthanarepresentintheprogram.Specifyingfewerwill
resultintheomittedoptionsnotbeingconsideredduringresolution.Specifying
aversionforresolutionthatisn’tdefinedintheprogramwillresultina
linkingfailure.
ItisalsopossibletospecifyaCPUnameofgenericwhichwillberesolved
iftheexecutingprocessordoesn’tsatisfythefeaturesrequiredintheCPU
name.Thebehaviorofaprogramexecutingonaprocessorthatdoesn’tsatisfy
anyoptionofamultiversionedfunctionisundefined.
diagnose_as_builtin¶
SupportedSyntaxes¶
diagnose_as_builtin
clang::diagnose_as_builtin
clang::diagnose_as_builtin
Yes
Thediagnose_as_builtinattributeindicatesthatFortifydiagnosticsareto
beappliedtothedeclaredfunctionasifitwerethefunctionspecifiedbythe
attribute.Thebuiltinfunctionwhosediagnosticsaretobemimickedshouldbe
given.Inaddition,theorderinwhichargumentsshouldbeappliedmustalso
begiven.
Forexample,theattributecanbeusedasfollows.
__attribute__((diagnose_as_builtin(__builtin_memset,3,2,1)))
void*mymemset(intn,intc,void*s){
//...
}
Thisindicatesthatcallstomymemsetshouldbediagnosedasiftheywere
callsto__builtin_memset.Thearguments3,2,1indicatebyindexthe
orderinwhichargumentsofmymemsetshouldbeappliedto
__builtin_memset.Thethirdargumentshouldbeappliedfirst,thenthe
second,andthenthefirst.Thus(whenFortifywarningsareenabled)thecall
mymemset(n,c,s)willdiagnoseoverflowsasifitwerethecall
__builtin_memset(s,c,n).
Forvariadicfunctions,thevariadicargumentsmustcomeinthesameorderas
theywouldtothebuiltinfunction,afterallnormalarguments.Forinstance,
todiagnoseanewfunctionasifitweresscanf,wecanusetheattributeas
follows.
__attribute__((diagnose_as_builtin(sscanf,1,2)))
intmysscanf(constchar*str,constchar*format,...){
//...
}
Thenthecallmysscanf(“abcdef”,“%4s%4s”,buf1,buf2)willbediagnosedas
ifitwerethecallsscanf(“abcdef”,“%4s%4s”,buf1,buf2).
Thisattributecannotbeappliedtonon-staticmemberfunctions.
diagnose_if¶
SupportedSyntaxes¶
diagnose_if
Thediagnose_ifattributecanbeplacedonfunctiondeclarationstoemit
warningsorerrorsatcompile-timeifcallstotheattributedfunctionmeet
certainuser-definedcriteria.Forexample:
intabs(inta)
__attribute__((diagnose_if(a>=0,"Redundantabscall","warning")));
intmust_abs(inta)
__attribute__((diagnose_if(a>=0,"Redundantabscall","error")));
intval=abs(1);//warning:Redundantabscall
intval2=must_abs(1);//error:Redundantabscall
intval3=abs(val);
intval4=must_abs(val);//Becauserun-timechecksarenotemittedfor
//diagnose_ifattributes,thisexecuteswithout
//issue.
diagnose_ifiscloselyrelatedtoenable_if,withafewkeydifferences:
Overloadresolutionisnotawareofdiagnose_ifattributes:they’re
consideredonlyafterweselectthebestcandidatefromagivencandidateset.
Functiondeclarationsthatdifferonlyintheirdiagnose_ifattributesare
consideredtoberedeclarationsofthesamefunction(notoverloads).
Iftheconditionprovidedtodiagnose_ifcannotbeevaluated,no
diagnosticwillbeemitted.
Otherwise,diagnose_ifisessentiallythelogicalnegationofenable_if.
Asaresultofbulletnumbertwo,diagnose_ifattributeswillstackonthe
samefunction.Forexample:
intfoo()__attribute__((diagnose_if(1,"diag1","warning")));
intfoo()__attribute__((diagnose_if(1,"diag2","warning")));
intbar=foo();//warning:diag1
//warning:diag2
int(*fooptr)(void)=foo;//warning:diag1
//warning:diag2
constexprintsupportsAPILevel(intN){returnN<5;}
intbaz(inta)
__attribute__((diagnose_if(!supportsAPILevel(10),
"UpgradetoAPIlevel10tousebaz","error")));
intbaz(inta)
__attribute__((diagnose_if(!a,"0isnotrecommended.","warning")));
int(*bazptr)(int)=baz;//error:UpgradetoAPIlevel10tousebaz
intv=baz(0);//error:UpgradetoAPIlevel10tousebaz
Queryforthisfeaturewith__has_attribute(diagnose_if).
disable_sanitizer_instrumentation¶
SupportedSyntaxes¶
disable_sanitizer_instrumentation
clang::disable_sanitizer_instrumentation
clang::disable_sanitizer_instrumentation
Yes
Usethedisable_sanitizer_instrumentationattributeonafunction,
Objective-Cmethod,orglobalvariable,tospecifythatnosanitizer
instrumentationshouldbeapplied.
Thisisnotthesameas__attribute__((no_sanitize(...))),whichdepending
onthetoolmaystillinsertinstrumentationtopreventfalsepositivereports.
disable_tail_calls¶
SupportedSyntaxes¶
disable_tail_calls
clang::disable_tail_calls
clang::disable_tail_calls
Yes
Thedisable_tail_callsattributeinstructsthebackendtonotperformtail
calloptimizationinsidethemarkedfunction.
Forexample:
intcallee(int);
intfoo(inta)__attribute__((disable_tail_calls)){
returncallee(a);//Thiscallisnottail-calloptimized.
}
Markingvirtualfunctionsasdisable_tail_callsislegal.
intcallee(int);
classBase{
public:
[[clang::disable_tail_calls]]virtualintfoo1(){
returncallee();//Thiscallisnottail-calloptimized.
}
};
classDerived1:publicBase{
public:
intfoo1()override{
returncallee();//Thiscallistail-calloptimized.
}
};
enable_if¶
SupportedSyntaxes¶
enable_if
Yes
Note
Somefeaturesofthisattributeareexperimental.Themeaningof
multipleenable_ifattributesonasingledeclarationissubjecttochangein
afutureversionofclang.Also,theABIisnotstandardizedandthename
manglingmaychangeinfutureversions.Toavoidthat,useasmlabels.
Theenable_ifattributecanbeplacedonfunctiondeclarationstocontrol
whichoverloadisselectedbasedonthevaluesofthefunction’sarguments.
Whencombinedwiththeoverloadableattribute,thisfeatureisalso
availableinC.
intisdigit(intc);
intisdigit(intc)__attribute__((enable_if(c<=-1||c>255,"chosenwhen'c'isoutofrange")))__attribute__((unavailable("'c'musthavethevalueofanunsignedcharorEOF")));
voidfoo(charc){
isdigit(c);
isdigit(10);
isdigit(-10);//resultsinacompile-timeerror.
}
Theenable_ifattributetakestwoarguments,thefirstisanexpressionwritten
intermsofthefunctionparameters,thesecondisastringexplainingwhythis
overloadcandidatecouldnotbeselectedtobedisplayedindiagnostics.The
expressionispartofthefunctionsignatureforthepurposesofdetermining
whetheritisaredeclaration(followingtherulesusedwhendetermining
whetheraC++templatespecializationisODR-equivalent),butisnotpartof
thetype.
Theenable_ifexpressionisevaluatedasifitwerethebodyofa
bool-returningconstexprfunctiondeclaredwiththeargumentsofthefunction
itisbeingappliedto,thencalledwiththeparametersatthecallsite.Ifthe
resultisfalseorcouldnotbedeterminedthroughconstantexpression
evaluation,thenthisoverloadwillnotbechosenandtheprovidedstringmay
beusedinadiagnosticifthecompilefailsasaresult.
Becausetheenable_ifexpressionisanunevaluatedcontext,therearenoglobal
statechanges,northeabilitytopassinformationfromtheenable_if
expressiontothefunctionbody.Forexample,supposewewantcallsto
strnlen(strbuf,maxlen)toresolvetostrnlen_chk(strbuf,maxlen,sizeof
strbuf)onlyifthesizeofstrbufcanbedetermined:
__attribute__((always_inline))
staticinlinesize_tstrnlen(constchar*s,size_tmaxlen)
__attribute__((overloadable))
__attribute__((enable_if(__builtin_object_size(s,0)!=-1))),
"chosenwhenthebuffersizeisknownbut'maxlen'isnot")))
{
returnstrnlen_chk(s,maxlen,__builtin_object_size(s,0));
}
Multipleenable_ifattributesmaybeappliedtoasingledeclaration.Inthis
case,theenable_ifexpressionsareevaluatedfromlefttorightinthe
followingmanner.First,thecandidateswhoseenable_ifexpressionsevaluateto
falseorcannotbeevaluatedarediscarded.Iftheremainingcandidatesdonot
shareODR-equivalentenable_ifexpressions,theoverloadresolutionis
ambiguous.Otherwise,enable_ifoverloadresolutioncontinueswiththenext
enable_ifattributeonthecandidatesthathavenotbeendiscardedandhave
remainingenable_ifattributes.Inthisway,wepickthemostspecific
overloadoutofanumberofviableoverloadsusingenable_if.
voidf()__attribute__((enable_if(true,"")));//#1
voidf()__attribute__((enable_if(true,"")))__attribute__((enable_if(true,"")));//#2
voidg(inti,intj)__attribute__((enable_if(i,"")));//#1
voidg(inti,intj)__attribute__((enable_if(j,"")))__attribute__((enable_if(true)));//#2
Inthisexample,acalltof()isalwaysresolvedto#2,asthefirstenable_if
expressionisODR-equivalentforbothdeclarations,but#1doesnothaveanother
enable_ifexpressiontocontinueevaluating,sothenextroundofevaluationhas
onlyasinglecandidate.Inacalltog(1,1),thecallisambiguouseventhough
#2hasmoreenable_ifattributes,becausethefirstenable_ifexpressionsare
notODR-equivalent.
Queryforthisfeaturewith__has_attribute(enable_if).
Notethatfunctionswithoneormoreenable_ifattributesmaynothave
theiraddresstaken,unlessalloftheconditionsspecifiedbysaid
enable_ifareconstantsthatevaluatetotrue.Forexample:
constintTrueConstant=1;
constintFalseConstant=0;
intf(inta)__attribute__((enable_if(a>0,"")));
intg(inta)__attribute__((enable_if(a==0||a!=0,"")));
inth(inta)__attribute__((enable_if(1,"")));
inti(inta)__attribute__((enable_if(TrueConstant,"")));
intj(inta)__attribute__((enable_if(FalseConstant,"")));
voidfn(){
int(*ptr)(int);
ptr=&f;//error:'a>0'isnotalwaystrue
ptr=&g;//error:'a==0||a!=0'isnotatruthyconstant
ptr=&h;//OK:1isatruthyconstant
ptr=&i;//OK:'TrueConstant'isatruthyconstant
ptr=&j;//error:'FalseConstant'isaconstant,butnottruthy
}
Becauseenable_ifevaluationhappensduringoverloadresolution,
enable_ifmaygiveunintuitiveresultswhenusedwithtemplates,depending
onwhenoverloadsareresolved.Intheexamplebelow,clangwillemita
diagnosticaboutnoviableoverloadsforfooinbar,butnotinbaz:
doublefoo(inti)__attribute__((enable_if(i>0,"")));
void*foo(inti)__attribute__((enable_if(i<=0,"")));
template
autobar(){returnfoo(I);}
template
autobaz(){returnfoo(T::number);}
structWithNumber{constexprstaticintnumber=1;};
voidcallThem(){
bar();
baz();
}
Thisisbecause,inbar,fooisresolvedpriortotemplate
instantiation,sothevalueforIisn’tknown(thus,bothenable_if
conditionsforfoofail).However,inbaz,fooisresolvedduring
templateinstantiation,sothevalueforT::numberisknown.
enforce_tcb¶
SupportedSyntaxes¶
enforce_tcb
clang::enforce_tcb
clang::enforce_tcb
Yes
Theenforce_tcbattributecanbeplacedonfunctionstoenforcethata
trustedcomputebase(TCB)doesnotcalloutoftheTCB.Thisgeneratesa
warningeverytimeafunctionnotmarkedwithanenforce_tcbattributeis
calledfromafunctionwiththeenforce_tcbattribute.Afunctionmaybea
partofmultipleTCBs.Invocationsthroughfunctionpointersarecurrently
notchecked.BuiltinsareconsideredtoapartofeveryTCB.
enforce_tcb(Name)indicatesthatthisfunctionisapartoftheTCBnamedName
enforce_tcb_leaf¶
SupportedSyntaxes¶
enforce_tcb_leaf
clang::enforce_tcb_leaf
clang::enforce_tcb_leaf
Yes
Theenforce_tcb_leafattributesatisfiestherequirementenforcedby
enforce_tcbforthemarkedfunctiontobeinthenamedTCBbutdoesnot
continuetocheckthefunctionscalledfromwithintheleaffunction.
enforce_tcb_leaf(Name)indicatesthatthisfunctionisapartoftheTCBnamedName
error,warning¶
SupportedSyntaxes¶
errorwarning
gnu::errorgnu::warning
gnu::errorgnu::warning
Yes
Theerrorandwarningfunctionattributescanbeusedtospecifya
customdiagnostictobeemittedwhenacalltosuchafunctionisnot
eliminatedviaoptimizations.Thiscanbeusedtocreatecompiletime
assertionsthatdependonoptimizations,whileprovidingdiagnostics
pointingtopreciselocationsofthecallsiteinthesource.
__attribute__((warning("ohno")))voiddontcall();
voidfoo(){
if(someCompileTimeAssertionThatsTrue)
dontcall();//Warning
dontcall();//Warning
if(someCompileTimeAssertionThatsFalse)
dontcall();//NoWarning
sizeof(dontcall());//NoWarning
}
exclude_from_explicit_instantiation¶
SupportedSyntaxes¶
exclude_from_explicit_instantiation
clang::exclude_from_explicit_instantiation
clang::exclude_from_explicit_instantiation
Yes
Theexclude_from_explicit_instantiationattributeopts-outamemberofa
classtemplatefrombeingpartofexplicittemplateinstantiationsofthat
classtemplate.Thismeansthatanexplicitinstantiationwillnotinstantiate
membersoftheclasstemplatemarkedwiththeattribute,butalsothatcode
whereanexterntemplatedeclarationoftheenclosingclasstemplateisvisible
willnottakeforgrantedthatanexternalinstantiationoftheclasstemplate
wouldprovidethosemembers(whichwouldotherwisebealinkerror,sincethe
explicitinstantiationwon’tprovidethosemembers).Forexample,let’ssaywe
don’twantthedata()methodtobepartoflibc++’sABI.Tomakesureit
isnotexportedfromthedylib,wegiveithiddenvisibility:
//in
template
classbasic_string{
public:
__attribute__((__visibility__("hidden")))
constvalue_type*data()constnoexcept{...}
};
templateclassbasic_string;
Sinceanexplicittemplateinstantiationdeclarationforbasic_string
isprovided,thecompilerisfreetoassumethatbasic_string::data()
willbeprovidedbyanothertranslationunit,anditisfreetoproducean
externalcalltothisfunction.However,sincedata()hashiddenvisibility
andtheexplicittemplateinstantiationisprovidedinasharedlibrary(as
opposedtosimplyanothertranslationunit),basic_string::data()
won’tbefoundandalinkerrorwillensue.Thishappensbecausethecompiler
assumesthatbasic_string::data()ispartoftheexplicittemplate
instantiationdeclaration,whenitreallyisn’t.Totellthecompilerthat
data()isnotpartoftheexplicittemplateinstantiationdeclaration,the
exclude_from_explicit_instantiationattributecanbeused:
//in
template
classbasic_string{
public:
__attribute__((__visibility__("hidden")))
__attribute__((exclude_from_explicit_instantiation))
constvalue_type*data()constnoexcept{...}
};
templateclassbasic_string;
Now,thecompilerwon’tassumethatbasic_string::data()isprovided
externallydespitetherebeinganexplicittemplateinstantiationdeclaration:
thecompilerwillimplicitlyinstantiatebasic_string::data()inthe
TUswhereitisused.
Thisattributecanbeusedonstaticandnon-staticmemberfunctionsofclass
templates,staticdatamembersofclasstemplatesandmemberclassesofclass
templates.
export_name¶
SupportedSyntaxes¶
export_name
clang::export_name
clang::export_name
Yes
Clangsupportsthe__attribute__((export_name()))
attributefortheWebAssemblytarget.Thisattributemaybeattachedtoa
functiondeclaration,whereitmodifieshowthesymbolistobeexported
fromthelinkedWebAssembly.
WebAssemblyfunctionsareexportedviastringname.Bydefaultwhenasymbol
isexported,theexportnameforC/C++symbolsarethesameastheirC/C++
symbolnames.Thisattributecanbeusedtooverridethedefaultbehavior,and
requestaspecificstringnamebeusedinstead.
flatten¶
SupportedSyntaxes¶
flatten
gnu::flatten
gnu::flatten
Yes
Theflattenattributecausescallswithintheattributedfunctionto
beinlinedunlessitisimpossibletodoso,forexampleifthebodyofthe
calleeisunavailableorifthecalleehasthenoinlineattribute.
force_align_arg_pointer¶
SupportedSyntaxes¶
force_align_arg_pointer
gnu::force_align_arg_pointer
gnu::force_align_arg_pointer
Usethisattributetoforcestackalignment.
Legacyx86codeuses4-bytestackalignment.NeweralignedSSEinstructions
(like‘movaps’)thatworkwiththestackrequireoperandstobe16-bytealigned.
Thisattributerealignsthestackinthefunctionprologuetomakesurethe
stackcanbeusedwithSSEinstructions.
Notethatthex86_64ABIforces16-bytestackalignmentatthecallsite.
Becauseofthis,‘force_align_arg_pointer’isnotneededonx86_64,exceptin
rarecaseswherethecallerdoesnotalignthestackproperly(e.g.flow
jumpsfromi386archcode).
__attribute__((force_align_arg_pointer))
voidf(){
...
}
format¶
SupportedSyntaxes¶
format
gnu::format
gnu::format
Clangsupportstheformatattribute,whichindicatesthatthefunction
acceptsaprintforscanf-likeformatstringandcorresponding
argumentsorava_listthatcontainsthesearguments.
PleaseseeGCCdocumentationaboutformatattributetofinddetails
aboutattributesyntax.
Clangimplementstwokindsofcheckswiththisattribute.
Clangchecksthatthefunctionwiththeformatattributeiscalledwith
aformatstringthatusesformatspecifiersthatareallowed,andthat
argumentsmatchtheformatstring.Thisisthe-Wformatwarning,itis
onbydefault.
Clangchecksthattheformatstringargumentisaliteralstring.Thisis
the-Wformat-nonliteralwarning,itisoffbydefault.
ClangimplementsthismostlythesamewayasGCC,butthereisadifference
forfunctionsthatacceptava_listargument(forexample,vprintf).
GCCdoesnotemit-Wformat-nonliteralwarningforcallstosuch
functions.Clangdoesnotwarniftheformatstringcomesfromafunction
parameter,wherethefunctionisannotatedwithacompatibleattribute,
otherwiseitwarns.Forexample:
__attribute__((__format__(__scanf__,1,3)))
voidfoo(constchar*s,char*buf,...){
va_listap;
va_start(ap,buf);
vprintf(s,ap);//warning:formatstringisnotastringliteral
}
Inthiscasewewarnbecausescontainsaformatstringfora
scanf-likefunction,butitispassedtoaprintf-likefunction.
Iftheattributeisremoved,clangstillwarns,becausetheformatstringis
notastringliteral.
Anotherexample:
__attribute__((__format__(__printf__,1,3)))
voidfoo(constchar*s,char*buf,...){
va_listap;
va_start(ap,buf);
vprintf(s,ap);//warning
}
InthiscaseClangdoesnotwarnbecausetheformatstringsand
thecorrespondingargumentsareannotated.Iftheargumentsare
incorrect,thecalleroffoowillreceiveawarning.
gnu_inline¶
SupportedSyntaxes¶
gnu_inline
gnu::gnu_inline
gnu::gnu_inline
Yes
Thegnu_inlinechangesthemeaningofexterninlinetouseGNUinline
semantics,meaning:
Ifanydeclarationthatisdeclaredinlineisnotdeclaredextern,
thentheinlinekeywordisjustahint.Inparticular,anout-of-line
definitionisstillemittedforafunctionwithexternallinkage,evenifall
callsitesareinlined,unlikeinC99andC++inlinesemantics.
Ifalldeclarationsthataredeclaredinlinearealsodeclared
extern,thenthefunctionbodyispresentonlyforinliningandno
out-of-lineversionisemitted.
Someimportantconsequences:staticinlineemitsanout-of-line
versionifneeded,aplaininlinedefinitionemitsanout-of-lineversion
always,andanexterninlinedefinition(inaheader)followedbya
(non-extern)inlinedeclarationinasourcefileemitsanout-of-line
versionofthefunctioninthatsourcefilebutprovidesthefunctionbodyfor
inliningtoallincludersoftheheader.
Either__GNUC_GNU_INLINE__(GNUinlinesemantics)or
__GNUC_STDC_INLINE__(C99semantics)willbedefined(theyaremutually
exclusive).If__GNUC_STDC_INLINE__isdefined,thenthegnu_inline
functionattributecanbeusedtogetGNUinlinesemanticsonaperfunction
basis.If__GNUC_GNU_INLINE__isdefined,thenthetranslationunitis
alreadybeingcompiledwithGNUinlinesemanticsastheimplieddefault.Itis
unspecifiedwhichmacroisdefinedinaC++compilation.
GNUinlinesemanticsarethedefaultbehaviorwith-std=gnu89,
-std=c89,-std=c94,or-fgnu89-inline.
guard¶
SupportedSyntaxes¶
guard
CodecanindicateCFGchecksarenotwantedwiththe__declspec(guard(nocf))
attribute.ThisdirectsthecompilertonotinsertanyCFGchecksfortheentire
function.Thisapproachistypicallyusedonlysparinglyinspecificsituations
wheretheprogrammerhasmanuallyinserted“CFG-equivalent”protection.The
programmerknowsthattheyarecallingthroughsomeread-onlyfunctiontable
whoseaddressisobtainedthroughread-onlymemoryreferencesandforwhichthe
indexismaskedtothefunctiontablelimit.Thisapproachmayalsobeapplied
tosmallwrapperfunctionsthatarenotinlinedandthatdonothingmorethan
makeacallthroughafunctionpointer.Sinceincorrectusageofthisdirective
cancompromisethesecurityofCFG,theprogrammermustbeverycarefulusing
thedirective.Typically,thisusageislimitedtoverysmallfunctionsthat
onlycallonefunction.
ControlFlowGuarddocumentation
ifunc¶
SupportedSyntaxes¶
ifunc
gnu::ifunc
gnu::ifunc
Yes
__attribute__((ifunc("resolver")))isusedtomarkthattheaddressofa
declarationshouldberesolvedatruntimebycallingaresolverfunction.
Thesymbolnameoftheresolverfunctionisgiveninquotes.Afunctionwith
thisname(aftermangling)mustbedefinedinthecurrenttranslationunit;it
maybestatic.Theresolverfunctionshouldreturnapointer.
Theifuncattributemayonlybeusedonafunctiondeclaration.Afunction
declarationwithanifuncattributeisconsideredtobeadefinitionofthe
declaredentity.Theentitymustnothaveweaklinkage;forexample,inC++,
itcannotbeappliedtoadeclarationifadefinitionatthatlocationwouldbe
consideredinline.
Notalltargetssupportthisattribute.ELFtargetsupportdependsonboththe
linkerandruntimelinker,andisavailableinatleastlld4.0andlater,
binutils2.20.1andlater,glibcv2.11.1andlater,andFreeBSD9.1andlater.
Non-ELFtargetscurrentlydonotsupportthisattribute.
import_module¶
SupportedSyntaxes¶
import_module
clang::import_module
clang::import_module
Yes
Clangsupportsthe__attribute__((import_module()))
attributefortheWebAssemblytarget.Thisattributemaybeattachedtoa
functiondeclaration,whereitmodifieshowthesymbolistobeimported
withintheWebAssemblylinkingenvironment.
WebAssemblyimportsuseatwo-levelnamespacescheme,consistingofamodule
name,whichtypicallyidentifiesamodulefromwhichtoimport,andafield
name,whichtypicallyidentifiesafieldfromthatmoduletoimport.By
default,modulenamesforC/C++symbolsareassignedautomaticallybythe
linker.Thisattributecanbeusedtooverridethedefaultbehavior,and
requestaspecificmodulenamebeusedinstead.
import_name¶
SupportedSyntaxes¶
import_name
clang::import_name
clang::import_name
Yes
Clangsupportsthe__attribute__((import_name()))
attributefortheWebAssemblytarget.Thisattributemaybeattachedtoa
functiondeclaration,whereitmodifieshowthesymbolistobeimported
withintheWebAssemblylinkingenvironment.
WebAssemblyimportsuseatwo-levelnamespacescheme,consistingofamodule
name,whichtypicallyidentifiesamodulefromwhichtoimport,andafield
name,whichtypicallyidentifiesafieldfromthatmoduletoimport.By
default,fieldnamesforC/C++symbolsarethesameastheirC/C++symbol
names.Thisattributecanbeusedtooverridethedefaultbehavior,and
requestaspecificfieldnamebeusedinstead.
internal_linkage¶
SupportedSyntaxes¶
internal_linkage
clang::internal_linkage
clang::internal_linkage
Yes
Theinternal_linkageattributechangesthelinkagetypeofthedeclaration
tointernal.ThisissimilartoC-stylestatic,butcanbeusedonclasses
andclassmethods.Whenappliedtoaclassdefinition,thisattributeaffects
allmethodsandstaticdatamembersofthatclass.Thiscanbeusedtocontain
theABIofaC++librarybyexcludingunwantedclassmethodsfromtheexport
tables.
interrupt(ARM)¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
ClangsupportstheGNUstyle__attribute__((interrupt("TYPE")))attributeon
ARMtargets.Thisattributemaybeattachedtoafunctiondefinitionand
instructsthebackendtogenerateappropriatefunctionentry/exitcodesothat
itcanbeuseddirectlyasaninterruptserviceroutine.
Theparameterpassedtotheinterruptattributeisoptional,butif
provideditmustbeastringliteralwithoneofthefollowingvalues:“IRQ”,
“FIQ”,“SWI”,“ABORT”,“UNDEF”.
Thesemanticsareasfollows:
IfthefunctionisAAPCS,Clanginstructsthebackendtorealignthestackto
8bytesonentry.ThisisageneralrequirementoftheAAPCSatpublic
interfaces,butmaynotholdwhenanexceptionistaken.Doingthisallows
otherAAPCSfunctionstobecalled.
IftheCPUisM-classthisisallthatneedstobedonesincethearchitecture
itselfisdesignedinsuchawaythatfunctionsobeyingthenormalAAPCSABI
constraintsarevalidexceptionhandlers.
IftheCPUisnotM-class,theprologueandepiloguearemodifiedtosaveall
non-bankedregistersthatareused,sothatuponreturntheuser-modestate
willnotbecorrupted.Notethattoavoidunnecessaryoverhead,only
general-purpose(integer)registersaresavedinthisway.IfVFPoperations
areneeded,thatstatemustbesavedmanually.
Specifically,interruptkindsotherthan“FIQ”willsaveallcoreregisters
except“lr”and“sp”.“FIQ”interruptswillsaver0-r7.
IftheCPUisnotM-class,thereturninstructionischangedtooneofthe
canonicalsequencespermittedbythearchitectureforexceptionreturn.Where
possiblethefunctionitselfwillmakethenecessary“lr”adjustmentssothat
the“preferredreturnaddress”isselected.
Unfortunatelythecompilerisunabletomakethisguaranteeforan“UNDEF”
handler,wheretheoffsetfrom“lr”tothepreferredreturnaddressdependson
theexecutionstateofthecodewhichgeneratedtheexception.Inthiscase
asequenceequivalentto“movspc,lr”willbeused.
interrupt(AVR)¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
Yes
ClangsupportstheGNUstyle__attribute__((interrupt))attributeon
AVRtargets.Thisattributemaybeattachedtoafunctiondefinitionandinstructs
thebackendtogenerateappropriatefunctionentry/exitcodesothatitcanbeused
directlyasaninterruptserviceroutine.
OntheAVR,thehardwaregloballydisablesinterruptswhenaninterruptisexecuted.
ThefirstinstructionofaninterrupthandlerdeclaredwiththisattributeisaSEI
instructiontore-enableinterrupts.Seealsothesignalattributethat
doesnotinsertaSEIinstruction.
interrupt(MIPS)¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
Yes
ClangsupportstheGNUstyle__attribute__((interrupt("ARGUMENT")))attributeon
MIPStargets.Thisattributemaybeattachedtoafunctiondefinitionandinstructs
thebackendtogenerateappropriatefunctionentry/exitcodesothatitcanbeused
directlyasaninterruptserviceroutine.
Bydefault,thecompilerwillproduceafunctionprologueandepiloguesuitablefor
aninterruptserviceroutinethathandlesanExternalInterruptController(eic)
generatedinterrupt.Thisbehaviorcanbeexplicitlyrequestedwiththe“eic”
argument.
Otherwise,forusewithvectoredinterruptmode,theargumentpassedshouldbe
oftheform“vector=LEVEL”whereLEVELisoneofthefollowingvalues:
“sw0”,“sw1”,“hw0”,“hw1”,“hw2”,“hw3”,“hw4”,“hw5”.Thecompilerwill
thensettheinterruptmasktothecorrespondinglevelwhichwillmaskall
interruptsuptoandincludingtheargument.
Thesemanticsareasfollows:
TheprologueismodifiedsothattheExceptionProgramCounter(EPC)and
Statuscoprocessorregistersaresavedtothestack.Theinterruptmaskis
setsothatthefunctioncanonlybeinterruptedbyahigherpriority
interrupt.TheepiloguewillrestorethepreviousvaluesofEPCandStatus.
Theprologueandepiloguearemodifiedtosaveandrestoreallnon-kernel
registersasnecessary.
TheFPUisdisabledintheprologue,asthefloatingpointerregistersarenot
spilledtothestack.
Thefunctionreturnsequenceischangedtouseanexceptionreturninstruction.
Theparametersetstheinterruptmaskforthefunctioncorrespondingtothe
interruptlevelspecified.Ifnomaskisspecifiedtheinterruptmask
defaultsto“eic”.
interrupt(RISCV)¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
Yes
ClangsupportstheGNUstyle__attribute__((interrupt))attributeonRISCV
targets.Thisattributemaybeattachedtoafunctiondefinitionandinstructs
thebackendtogenerateappropriatefunctionentry/exitcodesothatitcanbe
useddirectlyasaninterruptserviceroutine.
Permissiblevaluesforthisparameterareuser,supervisor,
andmachine.Ifthereisnoparameter,thenitdefaultstomachine.
Repeatedinterruptattributeonthesamedeclarationwillcauseawarning
tobeemitted.Incaseofrepeateddeclarations,thelastoneprevails.
Referto:
https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
https://riscv.org/specifications/privileged-isa/
TheRISC-VInstructionSetManualVolumeII:PrivilegedArchitecture
Version1.10.
kernel¶
SupportedSyntaxes¶
kernel
Yes
__attribute__((kernel))isusedtomarkakernelfunctionin
RenderScript.
InRenderScript,kernelfunctionsareusedtoexpressdata-parallel
computations.TheRenderScriptruntimeefficientlyparallelizeskernel
functionstorunoncomputationalresourcessuchasmulti-coreCPUsandGPUs.
SeetheRenderScriptdocumentationformoreinformation.
lifetimebound¶
SupportedSyntaxes¶
lifetimebound
clang::lifetimebound
Thelifetimeboundattributeonafunctionparameterorimplicitobject
parameterindicatesthatobjectsthatarereferredtobythatparametermay
alsobereferredtobythereturnvalueoftheannotatedfunction(or,fora
parameterofaconstructor,bythevalueoftheconstructedobject).Itisonly
supportedinC++.
Bydefault,areferenceisconsideredtorefertoitsreferencedobject,a
pointerisconsideredtorefertoitspointee,astd::initializer_list
isconsideredtorefertoitsunderlyingarray,andaggregates(arraysand
simplestructs)areconsideredtorefertoallobjectsthattheir
transitivesubobjectsreferto.
Clangwarnsifitisabletodetectthatanobjectorreferencerefersto
anotherobjectwithashorterlifetime.Forexample,Clangwillwarnifa
functionreturnsareferencetoalocalvariable,orifareferenceisboundto
atemporaryobjectwhoselifetimeisnotextended.Byusingthe
lifetimeboundattribute,thisdeterminationcanbeextendedtolookthrough
user-declaredfunctions.Forexample:
//Returnsm[key]ifkeyispresent,ordefault_valueifnot.
template
constU&get_or_default(conststd::map&m[[clang::lifetimebound]],
constT&key,/*note,notlifetimebound*/
constU&default_value[[clang::lifetimebound]]);
std::map<:string>m;
//warning:temporary"bar"sthatmightbeboundtolocalreference'val'
//willbedestroyedattheendofthefull-expression
conststd::string&val=get_or_default(m,"foo"s,"bar"s);
//Nowarninginthiscase.
std::stringdef_val="bar"s;
conststd::string&val=get_or_default(m,"foo"s,def_val);
Theattributecanbeappliedtotheimplicitthisparameterofamember
functionbywritingtheattributeafterthefunctiontype:
structstring{
//Thereturnedpointershouldnotoutlive``*this``.
constchar*data()const[[clang::lifetimebound]];
};
ThisattributeisinspiredbytheC++committeepaperP0936R0,butdoesnotaffectwhethertemporaryobjects
havetheirlifetimesextended.
long_call,far¶
SupportedSyntaxes¶
long_callfar
gnu::long_callgnu::far
gnu::long_callgnu::far
Yes
Clangsupportsthe__attribute__((long_call)),__attribute__((far)),
and__attribute__((near))attributesonMIPStargets.Theseattributesmay
onlybeaddedtofunctiondeclarationsandchangethecodegenerated
bythecompilerwhendirectlycallingthefunction.Thenearattribute
allowscallstothefunctiontobemadeusingthejalinstruction,which
requiresthefunctiontobelocatedinthesamenaturallyaligned256MB
segmentasthecaller.Thelong_callandfarattributesaresynonyms
andrequiretheuseofadifferentcallsequencethatworksregardless
ofthedistancebetweenthefunctions.
Theseattributeshavenoeffectforposition-independentcode.
Theseattributestakepriorityovercommandlineswitchessuch
as-mlong-callsand-mno-long-calls.
malloc¶
SupportedSyntaxes¶
malloc
gnu::malloc
gnu::malloc
restrict
Yes
Themallocattributeindicatesthatthefunctionactslikeasystemmemory
allocationfunction,returningapointertoallocatedstoragedisjointfromthe
storageforanyotherobjectaccessibletothecaller.
micromips¶
SupportedSyntaxes¶
micromips
gnu::micromips
gnu::micromips
Yes
ClangsupportstheGNUstyle__attribute__((micromips))and
__attribute__((nomicromips))attributesonMIPStargets.Theseattributes
maybeattachedtoafunctiondefinitionandinstructsthebackendtogenerate
ornottogeneratemicroMIPScodeforthatfunction.
Theseattributesoverridethe-mmicromipsand-mno-micromipsoptions
onthecommandline.
mig_server_routine¶
SupportedSyntaxes¶
mig_server_routine
clang::mig_server_routine
clang::mig_server_routine
Yes
TheMachInterfaceGeneratorrelease-on-successconventiondictates
functionsthatfollowittoonlyreleaseargumentspassedtothemwhenthey
return“success”(akern_return_terrorcodethatindicatesthat
noerrorshaveoccurred).OtherwisethereleaseisperformedbytheMIGclient
thatcalledthefunction.Theannotation__attribute__((mig_server_routine))
isappliedinordertospecifywhichfunctionsareexpectedtofollowthe
convention.ThisallowstheStaticAnalyzertofindbugscausedbyviolationsof
thatconvention.Theattributewouldnormallyappearontheforwarddeclaration
oftheactualserverroutineintheMIGserverheader,butitmayalsobe
addedtoarbitraryfunctionsthatneedtofollowthesameconvention-for
example,ausercanaddthemtoauxiliaryfunctionscalledbytheserverroutine
thathavetheirreturnvalueoftypekern_return_tunconditionallyreturned
fromtheroutine.TheattributecanbeappliedtoC++methods,andinthiscase
itwillbeautomaticallyappliedtooverridesifthemethodisvirtual.The
attributecanalsobewrittenusingC++11syntax:[[mig::server_routine]].
min_vector_width¶
SupportedSyntaxes¶
min_vector_width
clang::min_vector_width
clang::min_vector_width
Yes
Clangsupportsthe__attribute__((min_vector_width(width)))attribute.This
attributemaybeattachedtoafunctionandinformsthebackendthatthis
functiondesiresvectorsofatleastthiswidthtobegenerated.Target-specific
maximumvectorwidthsstillapply.Thismeansevenifyouaskforsomething
largerthanthetargetsupports,youwillonlygetwhatthetargetsupports.
Thisattributeismeanttobeahinttocontroltargetheuristicsthatmay
generatenarrowervectorsthanwhatthetargethardwaresupports.
ThisiscurrentlyusedbytheX86targettoallowsomeCPUsthatsupport512-bit
vectorstobelimitedtousing256-bitvectorstoavoidfrequencypenalties.
Thisiscurrentlyenabledwiththe-prefer-vector-width=256commandline
option.Themin_vector_widthattributecanbeusedtopreventthebackend
fromtryingtosplitvectoroperationstomatchtheprefer-vector-width.All
X86vectorintrinsicsfromx86intrin.halreadysetthisattribute.Additionally,
useofanyoftheX86-specificvectorbuiltinswillimplicitlysetthis
attributeonthecallingfunction.Theintentisthatexplicitlywritingvector
codeusingtheX86intrinsicswillpreventprefer-vector-widthfrom
affectingthecode.
minsize¶
SupportedSyntaxes¶
minsize
clang::minsize
clang::minsize
Yes
Thisfunctionattributeindicatesthatoptimizationpassesandcodegeneratorpasses
makechoicesthatkeepthefunctioncodesizeassmallaspossible.Optimizationsmay
alsosacrificeruntimeperformanceinordertominimizethesizeofthegeneratedcode.
no_builtin¶
SupportedSyntaxes¶
no_builtin
clang::no_builtin
clang::no_builtin
Yes
The__attribute__((no_builtin))issimilartothe-fno-builtinflag
exceptitisspecifictothebodyofafunction.Theattributemayalsobe
appliedtoavirtualfunctionbuthasnoeffectonthebehaviorofoverriding
functionsinaderivedclass.
Itacceptsoneormorestringscorrespondingtothespecificnamesofthe
builtinstodisable(e.g.“memcpy”,“memset”).
Iftheattributeisusedwithoutparametersitwilldisableallbuitinsat
once.
//Thecompilerisnotallowedtoaddanybuiltintofoo'sbody.
voidfoo(char*data,size_tcount)__attribute__((no_builtin)){
//Thecompilerisnotallowedtoconverttheloopinto
//`__builtin_memset(data,0xFE,count);`.
for(size_ti=0;in){
foo();
}else{
bar();
}
getspossiblymodifiedbysomeoptimizationsintocodesimilartothis:
if(a>n){
nodupfunc();
foo();
}else{
nodupfunc();
bar();
}
wherethecallto“nodupfunc”isduplicatedandsunkintothetwobranches
ofthecondition.
noinline¶
SupportedSyntaxes¶
noinline
gnu::noinlineclang::noinline
gnu::noinlineclang::noinline
noinline
__noinline__
Yes
Thisfunctionattributesuppressestheinliningofafunctionatthecallsites
ofthefunction.
[[clang::noinline]]spellingcanbeusedasastatementattribute;other
spellingsoftheattributearenotsupportedonstatements.Ifastatementis
marked[[clang::noinline]]andcontainscalls,thosecallsinsidethe
statementwillnotbeinlinedbythecompiler.
__noinline__canbeusedasakeywordinCUDA/HIPlanguages.Thisisto
avoiddiagnosticsduetousageof__attribute__((__noinline__))
with__noinline__definedasamacroas__attribute__((noinline)).
intexample(void){
intr;
[[clang::noinline]]foo();
[[clang::noinline]]r=bar();
returnr;
}
nomicromips¶
SupportedSyntaxes¶
nomicromips
gnu::nomicromips
gnu::nomicromips
Yes
ClangsupportstheGNUstyle__attribute__((micromips))and
__attribute__((nomicromips))attributesonMIPStargets.Theseattributes
maybeattachedtoafunctiondefinitionandinstructsthebackendtogenerate
ornottogeneratemicroMIPScodeforthatfunction.
Theseattributesoverridethe-mmicromipsand-mno-micromipsoptions
onthecommandline.
noreturn,_Noreturn¶
SupportedSyntaxes¶
noreturn
noreturn_Noreturn
Yes
Afunctiondeclaredas[[noreturn]]shallnotreturntoitscaller.The
compilerwillgenerateadiagnosticforafunctiondeclaredas[[noreturn]]
thatappearstobecapableofreturningtoitscaller.
The[[_Noreturn]]spellingisdeprecatedandonlyexiststoeasecode
migrationforcodeusing[[noreturn]]afterincluding.
not_tail_called¶
SupportedSyntaxes¶
not_tail_called
clang::not_tail_called
clang::not_tail_called
Yes
Thenot_tail_calledattributepreventstail-calloptimizationonstatically
boundcalls.Objective-cmethods,andfunctionsmarkedasalways_inline
cannotbemarkedasnot_tail_called.
Forexample,itpreventstail-calloptimizationinthefollowingcase:
int__attribute__((not_tail_called))foo1(int);
intfoo2(inta){
returnfoo1(a);//Notail-calloptimizationondirectcalls.
}
However,itdoesn’tpreventtail-calloptimizationinthiscase:
int__attribute__((not_tail_called))foo1(int);
intfoo2(inta){
int(*fn)(int)=&foo1;
//not_tail_calledhasnoeffectonanindirectcallevenifthecallcan
//beresolvedatcompiletime.
return(*fn)(a);
}
Generally,markinganoverridingvirtualfunctionasnot_tail_calledis
notuseful,becausethisattributeisapropertyofthestatictype.Calls
madethroughapointerorreferencetothebaseclasstypewillrespect
thenot_tail_calledattributeofthebaseclass’smemberfunction,
regardlessoftheruntimedestinationofthecall:
structFoo{virtualvoidf();};
structBar:Foo{
[[clang::not_tail_called]]voidf()override;
};
voidcallera(Bar&bar){
Foo&foo=bar;
//not_tail_calledhasnoeffectonhere,eventhoughthe
//underlyingmethodisffromBar.
foo.f();
bar.f();//Notail-calloptimizationonhere.
}
nothrow¶
SupportedSyntaxes¶
nothrow
gnu::nothrow
gnu::nothrow
nothrow
Yes
ClangsupportstheGNUstyle__attribute__((nothrow))andMicrosoftstyle
__declspec(nothrow)attributeasanequivalentofnoexceptonfunction
declarations.Thisattributeinformsthecompilerthattheannotatedfunction
doesnotthrowanexception.Thispreventsexception-unwinding.Thisattribute
isparticularlyusefulonfunctionsintheCStandardLibrarythatare
guaranteedtonotthrowanexception.
ns_consumed¶
SupportedSyntaxes¶
ns_consumed
clang::ns_consumed
clang::ns_consumed
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
ns_consumes_self¶
SupportedSyntaxes¶
ns_consumes_self
clang::ns_consumes_self
clang::ns_consumes_self
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
ns_returns_autoreleased¶
SupportedSyntaxes¶
ns_returns_autoreleased
clang::ns_returns_autoreleased
clang::ns_returns_autoreleased
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
ns_returns_not_retained¶
SupportedSyntaxes¶
ns_returns_not_retained
clang::ns_returns_not_retained
clang::ns_returns_not_retained
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
ns_returns_retained¶
SupportedSyntaxes¶
ns_returns_retained
clang::ns_returns_retained
clang::ns_returns_retained
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
numthreads¶
SupportedSyntaxes¶
ThenumthreadsattributeappliestoHLSLshaderswhereexplcitthreadcounts
arerequired.TheX,Y,andZvaluesprovidedtotheattribute
dictatethethreadid.TotalnumberofthreadsexecutedisX*Y*Z.
Thefulldocumentationisavailablehere:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads
objc_method_family¶
SupportedSyntaxes¶
objc_method_family
clang::objc_method_family
clang::objc_method_family
Yes
ManymethodsinObjective-Chaveconventionalmeaningsdeterminedbytheir
selectors.Itissometimesusefultobeabletomarkamethodashavinga
particularconventionalmeaningdespitenothavingtherightselector,oras
nothavingtheconventionalmeaningthatitsselectorwouldsuggest.Forthese
usecases,weprovideanattributetospecificallydescribethe“methodfamily”
thatamethodbelongsto.
Usage:__attribute__((objc_method_family(X))),whereXisoneof
none,alloc,copy,init,mutableCopy,ornew.This
attributecanonlybeplacedattheendofamethoddeclaration:
-(NSString*)initMyStringValue__attribute__((objc_method_family(none)));
Userswhodonotwishtochangetheconventionalmeaningofamethod,andwho
merelywanttodocumentitsnon-standardretainandreleasesemantics,should
usetheretainingbehaviorattributes(ns_returns_retained,
ns_returns_not_retained,etc).
Queryforthisfeaturewith__has_attribute(objc_method_family).
objc_requires_super¶
SupportedSyntaxes¶
objc_requires_super
clang::objc_requires_super
clang::objc_requires_super
Yes
SomeObjective-Cclassesallowasubclasstooverrideaparticularmethodina
parentclassbutexpectthattheoverridingmethodalsocallstheoverridden
methodintheparentclass.Forthesecases,weprovideanattributeto
designatethatamethodrequiresa“calltosuper”intheoverriding
methodinthesubclass.
Usage:__attribute__((objc_requires_super)).Thisattributecanonly
beplacedattheendofamethoddeclaration:
-(void)foo__attribute__((objc_requires_super));
Thisattributecanonlybeappliedthemethoddeclarationswithinaclass,and
notaprotocol.Currentlythisattributedoesnotenforceanyplacementof
wherethecalloccursintheoverridingmethod(suchasinthecaseof
-deallocwherethecallmustappearattheend).Itchecksonlythatit
exists.
NotethatonbothOSXandiOSthattheFoundationframeworkprovidesa
conveniencemacroNS_REQUIRES_SUPERthatprovidessyntacticsugarforthis
attribute:
-(void)fooNS_REQUIRES_SUPER;
Thismacroisconditionallydefineddependingonthecompiler’ssupportfor
thisattribute.Ifthecompilerdoesnotsupporttheattributethemacro
expandstonothing.
Operationally,whenamethodhasthisannotationthecompilerwillwarnifthe
implementationofanoverrideinasubclassdoesnotcallsuper.Forexample:
warning:methodpossiblymissinga[superAnnotMeth]call
-(void)AnnotMeth{};
^
optnone¶
SupportedSyntaxes¶
optnone
clang::optnone
clang::optnone
Yes
Theoptnoneattributesuppressesessentiallyalloptimizations
onafunctionormethod,regardlessoftheoptimizationlevelappliedto
thecompilationunitasawhole.Thisisparticularlyusefulwhenyou
needtodebugaparticularfunction,butitisinfeasibletobuildthe
entireapplicationwithoutoptimization.Avoidingoptimizationonthe
specifiedfunctioncanimprovethequalityofthedebugginginformation
forthatfunction.
Thisattributeisincompatiblewiththealways_inlineandminsize
attributes.
os_consumed¶
SupportedSyntaxes¶
os_consumed
clang::os_consumed
clang::os_consumed
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
os_consumes_this¶
SupportedSyntaxes¶
os_consumes_this
clang::os_consumes_this
clang::os_consumes_this
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
os_returns_not_retained¶
SupportedSyntaxes¶
os_returns_not_retained
clang::os_returns_not_retained
clang::os_returns_not_retained
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
os_returns_retained¶
SupportedSyntaxes¶
os_returns_retained
clang::os_returns_retained
clang::os_returns_retained
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
os_returns_retained_on_non_zero¶
SupportedSyntaxes¶
os_returns_retained_on_non_zero
clang::os_returns_retained_on_non_zero
clang::os_returns_retained_on_non_zero
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
os_returns_retained_on_zero¶
SupportedSyntaxes¶
os_returns_retained_on_zero
clang::os_returns_retained_on_zero
clang::os_returns_retained_on_zero
Yes
ThebehaviorofafunctionwithrespecttoreferencecountingforFoundation
(Objective-C),CoreFoundation(C)andOSObject(C++)isdeterminedbyanaming
convention(e.g.functionsstartingwith“get”areassumedtoreturnat
+0).
Itcanbeoverriddenusingafamilyofthefollowingattributes.In
Objective-C,theannotation__attribute__((ns_returns_retained))appliedto
afunctioncommunicatesthattheobjectisreturnedat+1,andthecaller
isresponsibleforfreeingit.
Similarly,theannotation__attribute__((ns_returns_not_retained))
specifiesthattheobjectisreturnedat+0andtheownershipremainswith
thecallee.
Theannotation__attribute__((ns_consumes_self))specifiesthat
theObjective-Cmethodcallconsumesthereferencetoself,e.g.by
attachingittoasuppliedparameter.
Additionally,parameterscanhaveanannotation
__attribute__((ns_consumed)),whichspecifiesthatpassinganownedobject
asthatparametereffectivelytransferstheownership,andthecallerisno
longerresponsibleforit.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
InCprogramsusingCoreFoundation,asimilarsetofattributes:
__attribute__((cf_returns_not_retained)),
__attribute__((cf_returns_retained))and__attribute__((cf_consumed))
havethesamerespectivesemanticswhenappliedtoCoreFoundationobjects.
TheseattributesaffectcodegenerationwheninteractingwithARCcode,and
theyareusedbytheClangStaticAnalyzer.
Finally,inC++interactingwithXNUkernel(objectsinheritingfromOSObject),
thesameattributefamilyispresent:
__attribute__((os_returns_not_retained)),
__attribute__((os_returns_retained))and__attribute__((os_consumed)),
withthesamerespectivesemantics.
Similarto__attribute__((ns_consumes_self)),
__attribute__((os_consumes_this))specifiesthatthemethodcallconsumes
thereferenceto“this”(e.g.,whenattachingittoadifferentobjectsupplied
asaparameter).
Outparameters(parametersthefunctionismeanttowriteinto,
eitherviapointers-to-pointersorreferences-to-pointers)
maybeannotatedwith__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))whichspecifiesthattheobject
writtenintotheoutparametershould(orrespectivelyshouldnot)bereleased
afteruse.
Sinceoftenoutparametersmayormaynotbewrittendependingontheexit
codeofthefunction,
annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))specifythat
anoutparameterat+1iswrittenifandonlyifthefunctionreturnsazero
(respectivelynon-zero)errorcode.
Observethatreturn-code-dependentoutparameterannotationsareonly
availableforretainedoutparameters,asnon-retainedobjectdonothavetobe
releasedbythecallee.
TheseattributesareonlyusedbytheClangStaticAnalyzer.
ThefamilyofattributesX_returns_X_retainedcanbeaddedtofunctions,
C++methods,andObjective-Cmethodsandproperties.
AttributesX_consumedcanbeaddedtoparametersofmethods,functions,
andObjective-Cmethods.
overloadable¶
SupportedSyntaxes¶
overloadable
clang::overloadable
clang::overloadable
Yes
ClangprovidessupportforC++functionoverloadinginC.Functionoverloading
inCisintroducedusingtheoverloadableattribute.Forexample,one
mightprovideseveraloverloadedversionsofatgsinfunctionthatinvokes
theappropriatestandardfunctioncomputingthesineofavaluewithfloat,
double,orlongdoubleprecision:
#include
float__attribute__((overloadable))tgsin(floatx){returnsinf(x);}
double__attribute__((overloadable))tgsin(doublex){returnsin(x);}
longdouble__attribute__((overloadable))tgsin(longdoublex){returnsinl(x);}
Giventhesedeclarations,onecancalltgsinwithafloatvalueto
receiveafloatresult,withadoubletoreceiveadoubleresult,
etc.FunctionoverloadinginCfollowstherulesofC++functionoverloading
topickthebestoverloadgiventhecallarguments,withafewC-specific
semantics:
Conversionfromfloatordoubletolongdoubleisrankedasa
floating-pointpromotion(perC99)ratherthanasafloating-pointconversion
(asinC++).
AconversionfromapointeroftypeT*toapointeroftypeU*is
consideredapointerconversion(withconversionrank)ifTandUare
compatibletypes.
AconversionfromtypeTtoavalueoftypeUispermittedifT
andUarecompatibletypes.Thisconversionisgiven“conversion”rank.
Ifnoviablecandidatesareotherwiseavailable,weallowaconversionfroma
pointeroftypeT*toapointeroftypeU*,whereTandUare
incompatible.Thisconversionisrankedbelowallothertypesofconversions.
Pleasenote:UlackingqualifiersthatarepresentonTissufficient
forTandUtobeincompatible.
Thedeclarationofoverloadablefunctionsisrestrictedtofunction
declarationsanddefinitions.Ifafunctionismarkedwiththeoverloadable
attribute,thenalldeclarationsanddefinitionsoffunctionswiththatname,
exceptforatmostone(seethenotebelowaboutunmarkedoverloads),musthave
theoverloadableattribute.Inaddition,redeclarationsofafunctionwith
theoverloadableattributemusthavetheoverloadableattribute,and
redeclarationsofafunctionwithouttheoverloadableattributemustnot
havetheoverloadableattribute.e.g.,
intf(int)__attribute__((overloadable));
floatf(float);//error:declarationof"f"musthavethe"overloadable"attribute
intf(int);//error:redeclarationof"f"musthavethe"overloadable"attribute
intg(int)__attribute__((overloadable));
intg(int){}//error:redeclarationof"g"mustalsohavethe"overloadable"attribute
inth(int);
inth(int)__attribute__((overloadable));//error:declarationof"h"mustnot
//havethe"overloadable"attribute
Functionsmarkedoverloadablemusthaveprototypes.Therefore,the
followingcodeisill-formed:
inth()__attribute__((overloadable));//error:hdoesnothaveaprototype
However,overloadablefunctionsareallowedtouseaellipsisevenifthere
arenonamedparameters(asispermittedinC++).Thisfeatureisparticularly
usefulwhencombinedwiththeunavailableattribute:
voidhoneypot(...)__attribute__((overloadable,unavailable));//callingmeisanerror
Functionsdeclaredwiththeoverloadableattributehavetheirnamesmangled
accordingtothesamerulesasC++functionnames.Forexample,thethree
tgsinfunctionsinourmotivatingexamplegetthemanglednames
_Z5tgsinf,_Z5tgsind,and_Z5tgsine,respectively.Therearetwo
caveatstothisuseofnamemangling:
FutureversionsofClangmaychangethenamemanglingoffunctionsoverloaded
inC,soyoushouldnotdependonanspecificmangling.Tobecompletely
safe,westronglyurgetheuseofstaticinlinewithoverloadable
functions.
TheoverloadableattributehasalmostnomeaningwhenusedinC++,
becausenameswillalreadybemangledandfunctionsarealreadyoverloadable.
However,whenanoverloadablefunctionoccurswithinanextern"C"
linkagespecification,it’snamewillbemangledinthesamewayasit
wouldinC.
Forthepurposeofbackwardscompatibility,atmostonefunctionwiththesame
nameasotheroverloadablefunctionsmayomittheoverloadable
attribute.Inthiscase,thefunctionwithouttheoverloadableattribute
willnothaveitsnamemangled.
Forexample:
//NoteswithmanglednamesassumeItaniummangling.
intf(int);
intf(double)__attribute__((overloadable));
voidfoo(){
f(5);//Emitsacalltof(not_Z1fi,asitwouldwithanoverloadthat
//wasmarkedwithoverloadable).
f(1.0);//Emitsacallto_Z1fd.
}
Supportforunmarkedoverloadsisnotpresentinsomeversionsofclang.Youmay
queryforitusing__has_extension(overloadable_unmarked).
Queryforthisattributewith__has_attribute(overloadable).
patchable_function_entry¶
SupportedSyntaxes¶
patchable_function_entry
gnu::patchable_function_entry
gnu::patchable_function_entry
Yes
__attribute__((patchable_function_entry(N,M)))isusedtogenerateMNOPs
beforethefunctionentryandN-MNOPsafterthefunctionentry.Thisattribute
takesprecedenceoverthecommandlineoption-fpatchable-function-entry=N,M.
Mdefaultsto0ifomitted.
Thisattributeisonlysupportedon
aarch64/aarch64-be/riscv32/riscv64/i386/x86-64targets.
preserve_access_index¶
SupportedSyntaxes¶
preserve_access_index
clang::preserve_access_index
clang::preserve_access_index
Yes
Clangsupportsthe__attribute__((preserve_access_index))
attributefortheBPFtarget.Thisattributemaybeattachedtoa
structoruniondeclaration,whereif-gisspecified,itenables
preservingstructorunionmemberaccessdebuginfoindicesofthis
structorunion,similartoclang__builtin_preserve_access_index().
reinitializes¶
SupportedSyntaxes¶
reinitializes
clang::reinitializes
Thereinitializesattributecanbeappliedtoanon-static,non-constC++
memberfunctiontoindicatethatthismemberfunctionreinitializestheentire
objecttoaknownstate,independentofthepreviousstateoftheobject.
Thisattributecanbeinterpretedbystaticanalyzersthatwarnaboutusesofan
objectthathasbeenleftinanindeterminatestatebyamoveoperation.Ifa
memberfunctionmarkedwiththereinitializesattributeiscalledona
moved-fromobject,theanalyzercanconcludethattheobjectisnolongerinan
indeterminatestate.
Atypicalexamplewherethisattributewouldbeusedisonfunctionsthatclear
acontainerclass:
template
classContainer{
public:
...
[[clang::reinitializes]]voidClear();
...
};
release_capability,release_shared_capability¶
SupportedSyntaxes¶
release_capabilityrelease_shared_capabilityrelease_generic_capabilityunlock_function
clang::release_capabilityclang::release_shared_capabilityclang::release_generic_capabilityclang::unlock_function
Marksafunctionasreleasingacapability.
retain¶
SupportedSyntaxes¶
retain
gnu::retain
gnu::retain
Thisattribute,whenattachedtoafunctionorvariabledefinition,prevents
sectiongarbagecollectioninthelinker.Itdoesnotpreventotherdiscard
mechanisms,suchasarchivememberselection,andCOMDATgroupresolution.
Ifthecompilerdoesnotemitthedefinition,e.g.becauseitwasnotusedin
thetranslationunitorthecompilerwasabletoeliminatealloftheuses,
thisattributehasnoeffect.Thisattributeistypicallycombinedwiththe
usedattributetoforcethedefinitiontobeemittedandpreservedintothe
finallinkedimage.
ThisattributeisonlynecessaryonELFtargets;othertargetspreventsection
garbagecollectionbythelinkerwhenusingtheusedattributealone.
Usingtheattributestogethershouldresultinconsistentbehavioracross
targets.
ThisattributerequiresthelinkertosupporttheSHF_GNU_RETAINextension.
ThissupportisavailableinGNUldandgoldasofbinutils2.36,as
wellasinld.lld13.
shader¶
SupportedSyntaxes¶
TheshadertypeattributeappliestoHLSLshaderentryfunctionsto
identifytheshadertypefortheentryfunction.
Thesyntaxis:
``[shader(string-literal)]``
wherethestringliteralisoneof:“pixel”,“vertex”,“geometry”,“hull”,
“domain”,“compute”,“raygeneration”,“intersection”,“anyhit”,“closesthit”,
“miss”,“callable”,“mesh”,“amplification”.Normallytheshadertypeisset
byshadertargetwiththe-Toptionlike-Tps_6_1.Whencompilingtoa
librarytargetlikelib_6_3,theshadertypeattributecanhelpthe
compilertoidentifytheshadertype.ItismostlyusedbyRaytracingshaders
whereshadersmustbecompiledintoalibraryandlinkedatruntime.
short_call,near¶
SupportedSyntaxes¶
short_callnear
gnu::short_callgnu::near
gnu::short_callgnu::near
Yes
Clangsupportsthe__attribute__((long_call)),__attribute__((far)),
__attribute__((short__call)),and__attribute__((near))attributes
onMIPStargets.Theseattributesmayonlybeaddedtofunctiondeclarations
andchangethecodegeneratedbythecompilerwhendirectlycalling
thefunction.Theshort_callandnearattributesaresynonymsand
allowcallstothefunctiontobemadeusingthejalinstruction,which
requiresthefunctiontobelocatedinthesamenaturallyaligned256MBsegment
asthecaller.Thelong_callandfarattributesaresynonymsand
requiretheuseofadifferentcallsequencethatworksregardless
ofthedistancebetweenthefunctions.
Theseattributeshavenoeffectforposition-independentcode.
Theseattributestakepriorityovercommandlineswitchessuch
as-mlong-callsand-mno-long-calls.
signal¶
SupportedSyntaxes¶
signal
gnu::signal
gnu::signal
Yes
ClangsupportstheGNUstyle__attribute__((signal))attributeon
AVRtargets.Thisattributemaybeattachedtoafunctiondefinitionandinstructs
thebackendtogenerateappropriatefunctionentry/exitcodesothatitcanbeused
directlyasaninterruptserviceroutine.
Interrupthandlerfunctionsdefinedwiththesignalattributedonotre-enableinterrupts.
speculative_load_hardening¶
SupportedSyntaxes¶
speculative_load_hardening
clang::speculative_load_hardening
clang::speculative_load_hardening
Yes
Thisattributecanbeappliedtoafunctiondeclarationinordertoindicate
thatSpeculativeLoadHardening
shouldbeenabledforthefunctionbody.Thiscanalsobeappliedtoamethod
inObjectiveC.Thisattributewilltakeprecedenceoverthecommandlineflagin
thecasewhere-mno-speculative-load-hardeningisspecified.
SpeculativeLoadHardeningisabest-effortmitigationagainst
informationleakattacksthatmakeuseofcontrolflow
miss-speculation-specificallymiss-speculationofwhetherabranch
istakenornot.Typicallyvulnerabilitiesenablingsuchattacksare
classifiedas“Spectrevariant#1”.Notably,thisdoesnotattemptto
mitigateagainstmiss-speculationofbranchtarget,classifiedas
“Spectrevariant#2”vulnerabilities.
Wheninlining,theattributeissticky.Inliningafunctionthat
carriesthisattributewillcausethecallertogainthe
attribute.Thisisintendedtoprovideamaximallyconservativemodel
wherethecodeinafunctionannotatedwiththisattributewillalways
(evenafterinlining)enduphardened.
sycl_kernel¶
SupportedSyntaxes¶
sycl_kernel
clang::sycl_kernel
clang::sycl_kernel
Thesycl_kernelattributespecifiesthatafunctiontemplatewillbeused
tooutlinedevicecodeandtogenerateanOpenCLkernel.
HereisacodeexampleoftheSYCLprogram,whichdemonstratesthecompiler’s
outliningjob:
intfoo(intx){return++x;}
usingnamespacecl::sycl;
queueQ;
buffera(range<1>{1024});
Q.submit([&](handler&cgh){
autoA=a.get_access<:mode::write>(cgh);
cgh.parallel_for(range<1>{1024},[=](id<1>index){
A[index]=index[0]+foo(42);
});
}
AC++functionobjectpassedtotheparallel_foriscalleda“SYCLkernel”.
ASYCLkerneldefinestheentrypointtothe“devicepart”ofthecode.The
compilerwillemitallsymbolsaccessiblefroma“kernel”.Inthiscode
example,thecompilerwillemit“foo”function.Moredetailsaboutthe
compilationoffunctionsforthedevicepartcanbefoundintheSYCL1.2.1
specificationSection6.4.
Toshowtothecompilerentrypointtothe“devicepart”ofthecode,theSYCL
runtimecanusethesycl_kernelattributeinthefollowingway:
namespacecl{
namespacesycl{
classhandler{
template
__attribute__((sycl_kernel))voidsycl_kernel_function(KernelTypeKernelFuncObj){
//...
KernelFuncObj();
}
template
voidparallel_for(rangeNumWorkItems,KernelTypeKernelFunc){
#ifdef__SYCL_DEVICE_ONLY__
sycl_kernel_function(KernelFunc);
#else
//Hostimplementation
#endif
}
};
}//namespacesycl
}//namespacecl
ThecompilerwillalsogenerateanOpenCLkernelusingthefunctionmarkedwith
thesycl_kernelattribute.
HereisthelistofSYCLdevicecompilerexpectationswithregardtothe
functionmarkedwiththesycl_kernelattribute:
Thefunctionmustbeatemplatewithatleasttwotypetemplateparameters.
ThecompilergeneratesanOpenCLkernelandusesthefirsttemplateparameter
asauniquenameforthegeneratedOpenCLkernel.Thehostapplicationuses
thisuniquenametoinvoketheOpenCLkernelgeneratedfortheSYCLkernel
specializedbythisnameandsecondtemplateparameterKernelType(which
mightbeanunnamedfunctionobjecttype).
Thefunctionmusthaveatleastoneparameter.Thefirstparameteris
requiredtobeafunctionobjecttype(namedorunnamedi.e.lambda).The
compilerusesfunctionobjecttypefieldstogenerateOpenCLkernel
parameters.
Thefunctionmustreturnvoid.Thecompilerreusesthebodyofmarkedfunctionsto
generatetheOpenCLkernelbody,andtheOpenCLkernelmustreturnvoid.
TheSYCLkernelinthepreviouscodesamplemeetstheseexpectations.
target¶
SupportedSyntaxes¶
target
gnu::target
gnu::target
Yes
ClangsupportstheGNUstyle__attribute__((target("OPTIONS")))attribute.
Thisattributemaybeattachedtoafunctiondefinitionandinstructs
thebackendtousedifferentcodegenerationoptionsthanwerepassedonthe
commandline.
Thecurrentsetofoptionscorrespondtotheexisting“subtargetfeatures”for
thetargetwithorwithouta“-mno-”infrontcorrespondingtotheabsence
ofthefeature,aswellasarch="CPU"whichwillchangethedefault“CPU”
forthefunction.
ForX86,theattributealsoallowstune="CPU"tooptimizethegenerated
codeforthegivenCPUwithoutchangingtheavailableinstructions.
ForAArch64,theattributealsoallowsthe“branch-protection=”option,
wherethepermissibleargumentsandtheireffectoncodegenerationarethesame
asforthecommand-lineoption-mbranch-protection.
Example“subtargetfeatures”fromthex86backendinclude:“mmx”,“sse”,“sse4.2”,
“avx”,“xop”andlargelycorrespondtothemachinespecificoptionshandledby
thefrontend.
Additionally,thisattributesupportsfunctionmultiversioningforELFbased
x86/x86-64targets,whichcanbeusedtocreatemultipleimplementationsofthe
samefunctionthatwillberesolvedatruntimebasedonthepriorityoftheir
targetattributestrings.Afunctionisconsideredamultiversionedfunction
ifeithertwodeclarationsofthefunctionhavedifferenttargetattribute
strings,orifithasatargetattributestringofdefault.For
example:
__attribute__((target("arch=atom")))
voidfoo(){}//willbecalledon'atom'processors.
__attribute__((target("default")))
voidfoo(){}//willbecalledonanyotherprocessors.
Allmultiversionedfunctionsmustcontainadefault(fallback)
implementation,otherwiseusagesofthefunctionareconsideredinvalid.
Additionally,afunctionmaynotbecomemultiversionedafteritsfirstuse.
target_clones¶
SupportedSyntaxes¶
target_clones
gnu::target_clones
gnu::target_clones
Yes
Clangsupportsthetarget_clones("OPTIONS")attribute.Thisattributemaybe
attachedtoafunctiondeclarationandcausesfunctionmultiversioning,where
multipleversionsofthefunctionwillbeemittedwithdifferentcode
generationoptions.Additionally,theseversionswillberesolvedatruntime
basedonthepriorityoftheirattributeoptions.Alltarget_clonefunctions
areconsideredmultiversionedfunctions.
Allmultiversionedfunctionsmustcontainadefault(fallback)
implementation,otherwiseusagesofthefunctionareconsideredinvalid.
Additionally,afunctionmaynotbecomemultiversionedafteritsfirstuse.
Theoptionstotarget_clonescaneitherbeatarget-specificarchitecture
(specifiedasarch=CPU),oroneofalistofsubtargetfeatures.
Example“subtargetfeatures”fromthex86backendinclude:“mmx”,“sse”,“sse4.2”,
“avx”,“xop”andlargelycorrespondtothemachinespecificoptionshandledby
thefrontend.
Theversionscaneitherbelistedasacomma-separatedsequenceofstring
literalsorasasinglestringliteralcontainingacomma-separatedlistof
versions.ForcompatibilitywithGCC,thetwoformatscanbemixed.For
example,thefollowingwillemit4versionsofthefunction:
__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
voidfoo(){}
try_acquire_capability,try_acquire_shared_capability¶
SupportedSyntaxes¶
try_acquire_capabilitytry_acquire_shared_capability
clang::try_acquire_capabilityclang::try_acquire_shared_capability
Marksafunctionthatattemptstoacquireacapability.Thisfunctionmayfailto
actuallyacquirethecapability;theyacceptaBooleanvaluedetermining
whetheracquiringthecapabilitymeanssuccess(true),orfailingtoacquire
thecapabilitymeanssuccess(false).
used¶
SupportedSyntaxes¶
used
gnu::used
gnu::used
Thisattribute,whenattachedtoafunctionorvariabledefinition,indicates
thattheremaybereferencestotheentitywhicharenotapparentinthesource
code.Forexample,itmaybereferencedfrominlineasm,oritmaybe
foundthroughadynamicsymbolorsectionlookup.
Thecompilermustemitthedefinitionevenifitappearstobeunused,andit
mustnotapplyoptimizationswhichdependonfullyunderstandinghowtheentity
isused.
Whetherthisattributehasanyeffectonthelinkerdependsonthetargetand
thelinker.Mostlinkerssupportthefeatureofsectiongarbagecollection
(--gc-sections),alsoknownas“deadstripping”(ld64-dead_strip)or
discardingunreferencedsections(link.exe/OPT:REF).OnCOFFandMach-O
targets(WindowsandAppleplatforms),theusedattributepreventssymbols
frombeingremovedbylinkersectionGC.OnELFtargets,ithasnoeffectonits
own,andthelinkermayremovethedefinitionifitisnototherwisereferenced.
ThislinkerGCcanbeavoidedbyalsoaddingtheretainattribute.Note
thatretainrequiresspecialsupportfromthelinker;seethatattribute’s
documentationforfurtherinformation.
xray_always_instrument,xray_never_instrument,xray_log_args¶
SupportedSyntaxes¶
xray_always_instrumentxray_never_instrument
clang::xray_always_instrumentclang::xray_never_instrument
clang::xray_always_instrumentclang::xray_never_instrument
Yes
__attribute__((xray_always_instrument))or
[[clang::xray_always_instrument]]isusedtomarkmemberfunctions(inC++),
methods(inObjectiveC),andfreefunctions(inC,C++,andObjectiveC)tobe
instrumentedwithXRay.Thiswillcausethefunctiontoalwayshavespaceat
thebeginningandexitpointstoallowforruntimepatching.
Conversely,__attribute__((xray_never_instrument))or
[[clang::xray_never_instrument]]willinhibittheinsertionofthese
instrumentationpoints.
Ifafunctionhasneitheroftheseattributes,theybecomesubjecttotheXRay
heuristicsusedtodeterminewhetherafunctionshouldbeinstrumentedor
otherwise.
__attribute__((xray_log_args(N)))or[[clang::xray_log_args(N)]]is
usedtopreserveNfunctionargumentsfortheloggingfunction.Currently,
onlyN==1issupported.
xray_always_instrument,xray_never_instrument,xray_log_args¶
SupportedSyntaxes¶
xray_log_args
clang::xray_log_args
clang::xray_log_args
Yes
__attribute__((xray_always_instrument))or
[[clang::xray_always_instrument]]isusedtomarkmemberfunctions(inC++),
methods(inObjectiveC),andfreefunctions(inC,C++,andObjectiveC)tobe
instrumentedwithXRay.Thiswillcausethefunctiontoalwayshavespaceat
thebeginningandexitpointstoallowforruntimepatching.
Conversely,__attribute__((xray_never_instrument))or
[[clang::xray_never_instrument]]willinhibittheinsertionofthese
instrumentationpoints.
Ifafunctionhasneitheroftheseattributes,theybecomesubjecttotheXRay
heuristicsusedtodeterminewhetherafunctionshouldbeinstrumentedor
otherwise.
__attribute__((xray_log_args(N)))or[[clang::xray_log_args(N)]]is
usedtopreserveNfunctionargumentsfortheloggingfunction.Currently,
onlyN==1issupported.
zero_call_used_regs¶
SupportedSyntaxes¶
zero_call_used_regs
gnu::zero_call_used_regs
gnu::zero_call_used_regs
Yes
Thisattribute,whenattachedtoafunction,causesthecompilertozeroa
subsetofallcall-usedregistersbeforethefunctionreturns.It’susedto
increaseprogramsecuritybyeithermitigatingReturn-OrientedProgramming
(ROP)attacksorpreventinginformationleakagethroughregisters.
Theterm“call-used”meansregisterswhicharenotguaranteedtobepreserved
unchangedforthecallerbythecurrentcallingconvention.Thiscouldalsobe
describedas“caller-saved”or“notcallee-saved”.
Thechoiceparametersgivestheprogrammerflexibilitytochoosethesubset
ofthecall-usedregisterstobezeroed:
skipdoesn’tzeroanycall-usedregisters.Thischoiceoverridesany
command-linearguments.
usedonlyzeroscall-usedregistersusedinthefunction.Byused,we
meanaregisterwhosecontentshavebeensetorreferencedinthefunction.
used-gpronlyzeroscall-usedGPRregistersusedinthefunciton.
used-argonlyzeroscall-usedregistersusedtopassargumentstothe
function.
used-gpr-argonlyzeroscall-usedGPRregistersusedtopassargumentsto
thefunction.
allzerosallcall-usedregisters.
all-gprzerosallcall-usedGPRregisters.
all-argzerosallcall-usedregistersusedtopassargumentstothe
function.
all-gpr-argzerosallcall-usedGPRregistersusedtopassargumentsto
thefunction.
Thedefaultfortheattributeiscontolledbythe-fzero-call-used-regs
flag.
HandleAttributes¶
Handlesareawaytoidentifyresourceslikefiles,sockets,andprocesses.
Theyaremoreopaquethanpointersandwidelyusedinsystemprogramming.They
havesimilarriskssuchasneverreleasingaresourceassociatedwithahandle,
attemptingtouseahandlethatwasalreadyreleased,ortryingtoreleasea
handletwice.Usingtheannotationsbelowitispossibletomaketheownership
ofthehandlesclear:whoseresponsibilityistoreleasethem.Theycanalso
aidstaticanalysistoolstofindbugs.
acquire_handle¶
SupportedSyntaxes¶
acquire_handle
clang::acquire_handle
clang::acquire_handle
Yes
Ifthisannotationisonafunctionorafunctiontypeitisassumedtoreturn
anewhandle.Incasethisannotationisonanoutputparameter,
thefunctionisassumedtofillthecorrespondingargumentwithanew
handle.Theattributerequiresastringliteralargumentwhichusedto
identifythehandlewithlaterusesofuse_handleor
release_handle.
//OutputargumentsfromZircon.
zx_status_tzx_socket_create(uint32_toptions,
zx_handle_t__attribute__((acquire_handle("zircon")))*out0,
zx_handle_t*out1[[clang::acquire_handle("zircon")]]);
//Returnedhandle.
[[clang::acquire_handle("tag")]]intopen(constchar*path,intoflag,...);
intopen(constchar*path,intoflag,...)__attribute__((acquire_handle("tag")));
release_handle¶
SupportedSyntaxes¶
release_handle
clang::release_handle
clang::release_handle
Yes
Ifafunctionparameterisannotatedwithrelease_handle(tag)itisassumedto
closethehandle.Itisalsoassumedtorequireanopenhandletoworkwith.The
attributerequiresastringliteralargumenttoidentifythehandlebeingreleased.
zx_status_tzx_handle_close(zx_handle_thandle[[clang::release_handle("tag")]]);
use_handle¶
SupportedSyntaxes¶
use_handle
clang::use_handle
clang::use_handle
Yes
Afunctiontakingahandlebyvaluemightclosethehandle.Ifafunction
parameterisannotatedwithuse_handle(tag)itisassumedtonottochange
thestateofthehandle.Itisalsoassumedtorequireanopenhandletoworkwith.
Theattributerequiresastringliteralargumenttoidentifythehandlebeingused.
zx_status_tzx_port_wait(zx_handle_thandle[[clang::use_handle("zircon")]],
zx_time_tdeadline,
zx_port_packet_t*packet);
NullabilityAttributes¶
Whetheraparticularpointermaybe“null”isanimportantconcernwhenworking
withpointersintheCfamilyoflanguages.Thevariousnullabilityattributes
indicatewhetheraparticularpointercanbenullornot,whichmakesAPIsmore
expressiveandcanhelpstaticanalysistoolsidentifybugsinvolvingnull
pointers.Clangsupportsseveralkindsofnullabilityattributes:the
nonnullandreturns_nonnullattributesindicatewhichfunctionor
methodparametersandresulttypescanneverbenull,whilenullabilitytype
qualifiersindicatewhichpointertypescanbenull(_Nullable)orcannot
benull(_Nonnull).
Thenullability(type)qualifiersexpresswhetheravalueofagivenpointer
typecanbenull(the_Nullablequalifier),doesn’thaveadefinedmeaning
fornull(the_Nonnullqualifier),orforwhichthepurposeofnullis
unclear(the_Null_unspecifiedqualifier).Becausenullabilityqualifiers
areexpressedwithinthetypesystem,theyaremoregeneralthanthe
nonnullandreturns_nonnullattributes,allowingonetoexpress(for
example)anullablepointertoanarrayofnonnullpointers.Nullability
qualifiersarewrittentotherightofthepointertowhichtheyapply.For
example:
//Nomeaningfulresultwhen'ptr'isnull(here,ithappenstobeundefinedbehavior).
intfetch(int*_Nonnullptr){return*ptr;}
//'ptr'maybenull.
intfetch_or_zero(int*_Nullableptr){
returnptr?*ptr:0;
}
//Anullablepointertonon-nullpointerstoconstcharacters.
constchar*join_strings(constchar*_Nonnull*_Nullablestrings,unsignedn);
InObjective-C,thereisanalternatespellingforthenullabilityqualifiers
thatcanbeusedinObjective-Cmethodsandpropertiesusingcontext-sensitive,
non-underscoredkeywords.Forexample:
@interfaceNSView:NSResponder
-(nullableNSView*)ancestorSharedWithView:(nonnullNSView*)aView;
@property(assign,nullable)NSView*superview;
@property(readonly,nonnull)NSArray*subviews;
@end
_Nonnull¶
SupportedSyntaxes¶
_Nonnull
The_Nonnullnullabilityqualifierindicatesthatnullisnotameaningful
valueforavalueofthe_Nonnullpointertype.Forexample,givena
declarationsuchas:
intfetch(int*_Nonnullptr);
acalleroffetchshouldnotprovideanullvalue,andthecompilerwill
produceawarningifitseesaliteralnullvaluepassedtofetch.Note
that,unlikethedeclarationattributenonnull,thepresenceof
_Nonnulldoesnotimplythatpassingnullisundefinedbehavior:fetch
isfreetoconsidernullundefinedbehavioror(perhapsfor
backward-compatibilityreasons)defensivelyhandlenull.
_Null_unspecified¶
SupportedSyntaxes¶
_Null_unspecified
The_Null_unspecifiednullabilityqualifierindicatesthatneitherthe
_Nonnullnor_Nullablequalifiersmakesenseforaparticularpointer
type.Itisusedprimarilytoindicatethattheroleofnullwithspecific
pointersinanullability-annotatedheaderisunclear,e.g.,dueto
overly-compleximplementationsorhistoricalfactorswithalong-livedAPI.
_Nullable¶
SupportedSyntaxes¶
_Nullable
The_Nullablenullabilityqualifierindicatesthatavalueofthe
_Nullablepointertypecanbenull.Forexample,given:
intfetch_or_zero(int*_Nullableptr);
acalleroffetch_or_zerocanprovidenull.
_Nullable_result¶
SupportedSyntaxes¶
_Nullable_result
The_Nullable_resultnullabilityqualifiermeansthatavalueofthe
_Nullable_resultpointercanbenil,justlike_Nullable.Wherethis
attributediffersfrom_Nullableiswhenit’susedonaparametertoa
completionhandlerinaSwiftasyncmethod.Forinstance,here:
-(void)fetchSomeDataWithID:(int)identifier
completionHandler:(void(^)(Data*_Nullable_resultresult,NSError*error))completionHandler;
ThismethodasynchronouslycallscompletionHandlerwhenthedatais
available,orcallsitwithanerror._Nullable_resultindicatestothe
Swiftimporterthatthisistheuncommoncasewhereresultcangetnil
evenifnoerrorhasoccurred,andwillthereforeimportitasaSwiftoptional
type.Otherwise,ifresultwasannotatedwith_Nullable,theSwift
importerwillassumethatresultwillalwaysbenon-nilunlessanerror
occurred.
nonnull¶
SupportedSyntaxes¶
nonnull
gnu::nonnull
gnu::nonnull
Thenonnullattributeindicatesthatsomefunctionparametersmustnotbe
null,andcanbeusedinseveraldifferentways.It’soriginalusage
(fromGCC)
isasafunction(orObjective-Cmethod)attributethatspecifieswhich
parametersofthefunctionarenonnullinacomma-separatedlist.Forexample:
externvoid*my_memcpy(void*dest,constvoid*src,size_tlen)
__attribute__((nonnull(1,2)));
Here,thenonnullattributeindicatesthatparameters1and2
cannothaveanullvalue.Omittingtheparenthesizedlistofparameterindices
meansthatallparametersofpointertypecannotbenull:
externvoid*my_memcpy(void*dest,constvoid*src,size_tlen)
__attribute__((nonnull));
Clangalsoallowsthenonnullattributetobeplaceddirectlyonafunction
(orObjective-Cmethod)parameter,eliminatingtheneedtospecifythe
parameterindexaheadoftype.Forexample:
externvoid*my_memcpy(void*dest__attribute__((nonnull)),
constvoid*src__attribute__((nonnull)),size_tlen);
Notethatthenonnullattributeindicatesthatpassingnulltoanon-null
parameterisundefinedbehavior,whichtheoptimizermaytakeadvantageofto,
e.g.,removenullchecks.The_Nonnulltypequalifierindicatesthata
pointercannotbenullinamoregeneralmanner(becauseitispartofthetype
system)anddoesnotimplyundefinedbehavior,makingitmorewidelyapplicable.
returns_nonnull¶
SupportedSyntaxes¶
returns_nonnull
gnu::returns_nonnull
gnu::returns_nonnull
Yes
Thereturns_nonnullattributeindicatesthataparticularfunction(or
Objective-Cmethod)alwaysreturnsanon-nullpointer.Forexample,a
particularsystemmallocmightbedefinedtoterminateaprocesswhen
memoryisnotavailableratherthanreturninganullpointer:
externvoid*malloc(size_tsize)__attribute__((returns_nonnull));
Thereturns_nonnullattributeimpliesthatreturninganullpointeris
undefinedbehavior,whichtheoptimizermaytakeadvantageof.The_Nonnull
typequalifierindicatesthatapointercannotbenullinamoregeneralmanner
(becauseitispartofthetypesystem)anddoesnotimplyundefinedbehavior,
makingitmorewidelyapplicable
OpenCLAddressSpaces¶
Theaddressspacequalifiermaybeusedtospecifytheregionofmemorythatis
usedtoallocatetheobject.OpenCLsupportsthefollowingaddressspaces:
__generic(generic),__global(global),__local(local),__private(private),
__constant(constant).
__constantintc=...;
__genericint*foo(globalint*g){
__localint*l;
privateintp;
...
returnl;
}
MoredetailscanbefoundintheOpenCLClanguageSpecv2.0,Section6.5.
[[clang::opencl_global_device]],[[clang::opencl_global_host]]¶
SupportedSyntaxes¶
opencl_global_device
clang::opencl_global_device
clang::opencl_global_device
Theglobal_deviceandglobal_hostaddressspaceattributesspecifythat
anobjectisallocatedinglobalmemoryonthedevice/host.Ithelpsto
distinguishUSM(UnifiedSharedMemory)pointersthataccessglobaldevice
memoryfromthosethataccessglobalhostmemory.Thesenewaddressspacesare
asubsetofthe__global/opencl_globaladdressspace,thefulladdressspace
setmodelforOpenCL2.0withtheextensionlooksasfollows:
generic->global->host
->device
->private
->local
constant
Asglobal_deviceandglobal_hostareasubsetof
__global/opencl_globaladdressspacesitisallowedtoconvert
global_deviceandglobal_hostaddressspacesto
__global/opencl_globaladdressspaces(followingISO/IECTR180375.1.3
“Addressspacenestingandrulesforpointers”).
[[clang::opencl_global_device]],[[clang::opencl_global_host]]¶
SupportedSyntaxes¶
opencl_global_host
clang::opencl_global_host
clang::opencl_global_host
Theglobal_deviceandglobal_hostaddressspaceattributesspecifythat
anobjectisallocatedinglobalmemoryonthedevice/host.Ithelpsto
distinguishUSM(UnifiedSharedMemory)pointersthataccessglobaldevice
memoryfromthosethataccessglobalhostmemory.Thesenewaddressspacesare
asubsetofthe__global/opencl_globaladdressspace,thefulladdressspace
setmodelforOpenCL2.0withtheextensionlooksasfollows:
generic->global->host
->device
->private
->local
constant
Asglobal_deviceandglobal_hostareasubsetof
__global/opencl_globaladdressspacesitisallowedtoconvert
global_deviceandglobal_hostaddressspacesto
__global/opencl_globaladdressspaces(followingISO/IECTR180375.1.3
“Addressspacenestingandrulesforpointers”).
__constant,constant,[[clang::opencl_constant]]¶
SupportedSyntaxes¶
opencl_constant
clang::opencl_constant
clang::opencl_constant
__constantconstant
Theconstantaddressspaceattributesignalsthatanobjectislocatedin
aconstant(non-modifiable)memoryregion.Itisavailabletoallworkitems.
Anytypecanbeannotatedwiththeconstantaddressspaceattribute.Objects
withtheconstantaddressspacequalifiercanbedeclaredinanyscopeandmust
haveaninitializer.
__generic,generic,[[clang::opencl_generic]]¶
SupportedSyntaxes¶
opencl_generic
clang::opencl_generic
clang::opencl_generic
__genericgeneric
ThegenericaddressspaceattributeisonlyavailablewithOpenCLv2.0andlater.
Itcanbeusedwithpointertypes.Variablesinglobalandlocalscopeand
functionparametersinnon-kernelfunctionscanhavethegenericaddressspace
typeattribute.Itisintendedtobeaplaceholderforanyotheraddressspace
exceptfor‘__constant’inOpenCLcodewhichcanbeusedwithmultipleaddress
spaces.
__global,global,[[clang::opencl_global]]¶
SupportedSyntaxes¶
opencl_global
clang::opencl_global
clang::opencl_global
__globalglobal
Theglobaladdressspaceattributespecifiesthatanobjectisallocatedin
globalmemory,whichisaccessiblebyallworkitems.Thecontentstoredinthis
memoryareapersistsbetweenkernelexecutions.Pointertypestotheglobal
addressspaceareallowedasfunctionparametersorlocalvariables.Starting
withOpenCLv2.0,theglobaladdressspacecanbeusedwithglobal(program
scope)variablesandstaticlocalvariableaswell.
__local,local,[[clang::opencl_local]]¶
SupportedSyntaxes¶
opencl_local
clang::opencl_local
clang::opencl_local
__locallocal
Thelocaladdressspacespecifiesthatanobjectisallocatedinthelocal(work
group)memoryarea,whichisaccessibletoallworkitemsinthesamework
group.Thecontentstoredinthismemoryregionisnotaccessibleafter
thekernelexecutionends.Inakernelfunctionscope,anyvariablecanbein
thelocaladdressspace.Inotherscopes,onlypointertypestothelocaladdress
spaceareallowed.Localaddressspacevariablescannothaveaninitializer.
__private,private,[[clang::opencl_private]]¶
SupportedSyntaxes¶
opencl_private
clang::opencl_private
clang::opencl_private
__privateprivate
Theprivateaddressspacespecifiesthatanobjectisallocatedintheprivate
(workitem)memory.Otherworkitemscannotaccessthesamememoryareaandits
contentisdestroyedafterworkitemexecutionends.Localvariablescanbe
declaredintheprivateaddressspace.Functionargumentsarealwaysinthe
privateaddressspace.Kernelfunctionargumentsofapointeroranarraytype
cannotpointtotheprivateaddressspace.
StatementAttributes¶
#pragmaclangloop¶
SupportedSyntaxes¶
clangloopunrollnounrollunroll_and_jamnounroll_and_jam
The#pragmaclangloopdirectiveallowsloopoptimizationhintstobe
specifiedforthesubsequentloop.Thedirectiveallowspipeliningtobe
disabled,orvectorization,vectorpredication,interleaving,andunrollingto
beenabledordisabled.Vectorwidth,vectorpredication,interleavecount,
unrollingcount,andtheinitiationintervalforpipeliningcanbeexplicitly
specified.Seelanguageextensions
fordetails.
#pragmaunroll,#pragmanounroll¶
SupportedSyntaxes¶
clangloopunrollnounrollunroll_and_jamnounroll_and_jam
Loopunrollingoptimizationhintscanbespecifiedwith#pragmaunrolland
#pragmanounroll.Thepragmaisplacedimmediatelybeforeafor,while,
do-while,orc++11range-basedforloop.GCC’sloopunrollinghints
#pragmaGCCunrolland#pragmaGCCnounrollarealsosupportedandhave
identicalsemanticsto#pragmaunrolland#pragmanounroll.
Specifying#pragmaunrollwithoutaparameterdirectstheloopunrollerto
attempttofullyunrolltheloopifthetripcountisknownatcompiletimeand
attempttopartiallyunrolltheloopifthetripcountisnotknownatcompile
time:
#pragmaunroll
for(...){
...
}
Specifyingtheoptionalparameter,#pragmaunroll_value_,directsthe
unrollertounrolltheloop_value_times.Theparametermayoptionallybe
enclosedinparentheses:
#pragmaunroll16
for(...){
...
}
#pragmaunroll(16)
for(...){
...
}
Specifying#pragmanounrollindicatesthattheloopshouldnotbeunrolled:
#pragmanounroll
for(...){
...
}
#pragmaunrolland#pragmaunroll_value_haveidenticalsemanticsto
#pragmaclangloopunroll(full)and
#pragmaclangloopunroll_count(_value_)respectively.#pragmanounroll
isequivalentto#pragmaclangloopunroll(disable).See
languageextensions
forfurtherdetailsincludinglimitationsoftheunrollhints.
__read_only,__write_only,__read_write(read_only,write_only,read_write)¶
SupportedSyntaxes¶
__read_onlyread_only__write_onlywrite_only__read_writeread_write
Theaccessqualifiersmustbeusedwithimageobjectargumentsorpipearguments
todeclareiftheyarebeingreadorwrittenbyakernelorfunction.
Theread_only/__read_only,write_only/__write_onlyandread_write/__read_write
namesarereservedforuseasaccessqualifiersandshallnotbeusedotherwise.
kernelvoid
foo(read_onlyimage2d_timageA,
write_onlyimage2d_timageB){
...
}
IntheaboveexampleimageAisaread-only2Dimageobject,andimageBisa
write-only2Dimageobject.
Theread_write(or__read_write)qualifiercannotbeusedwithpipe.
MoredetailscanbefoundintheOpenCLClanguageSpecv2.0,Section6.6.
fallthrough¶
SupportedSyntaxes¶
fallthrough
fallthroughclang::fallthroughgnu::fallthrough
fallthroughgnu::fallthrough
Thefallthrough(orclang::fallthrough)attributeisused
toannotateintentionalfall-through
betweenswitchlabels.Itcanonlybeappliedtoanullstatementplacedata
pointofexecutionbetweenanystatementandthenextswitchlabel.Itis
commontomarktheseplaceswithaspecificcomment,butthisattributeis
meanttoreplacecommentswithamorestrictannotation,whichcanbechecked
bythecompiler.Thisattributedoesn’tchangesemanticsofthecodeandcan
beusedwhereveranintendedfall-throughoccurs.Itisdesignedtomimic
control-flowstatementslikebreak;,soitcanbeplacedinmostplaces
wherebreak;can,butonlyiftherearenostatementsontheexecutionpath
betweenitandthenextswitchlabel.
Bydefault,Clangdoesnotwarnonunannotatedfallthroughfromoneswitch
casetoanother.Diagnosticsonfallthroughwithoutacorrespondingannotation
canbeenabledwiththe-Wimplicit-fallthroughargument.
Hereisanexample:
//compilewith-Wimplicit-fallthrough
switch(n){
case22:
case33://nowarning:nostatementsbetweencaselabels
f();
case44://warning:unannotatedfall-through
g();
[[clang::fallthrough]];
case55://nowarning
if(x){
h();
break;
}
else{
i();
[[clang::fallthrough]];
}
case66://nowarning
p();
[[clang::fallthrough]];//warning:fallthroughannotationdoesnot
//directlyprecedecaselabel
q();
case77://warning:unannotatedfall-through
r();
}
intel_reqd_sub_group_size¶
SupportedSyntaxes¶
intel_reqd_sub_group_size
Yes
Theoptionalattributeintel_reqd_sub_group_sizecanbeusedtoindicatethat
thekernelmustbecompiledandexecutedwiththespecifiedsubgroupsize.When
thisattributeispresent,get_max_sub_group_size()isguaranteedtoreturnthe
specifiedintegervalue.Thisisimportantforthecorrectnessofmanysubgroup
algorithms,andinsomecasesmaybeusedbythecompilertogeneratemoreoptimal
code.Seecl_intel_required_subgroup_size
fordetails.
likelyandunlikely¶
SupportedSyntaxes¶
likely
clang::likely
Thelikelyandunlikelyattributesareusedascompilerhints.
Theattributesareusedtoaidthecompilertodeterminewhichbranchis
likelyorunlikelytobetaken.Thisisdonebymarkingthebranchsubstatement
withoneofthetwoattributes.
Itisn’tallowedtoannotateasinglestatementwithbothlikelyand
unlikely.Annotatingthetrueandfalsebranchofanif
statementwiththesamelikelihoodattributewillresultinadiagnosticand
theattributesareignoredonbothbranches.
Inaswitchstatementit’sallowedtoannotatemultiplecaselabels
orthedefaultlabelwiththesamelikelihoodattribute.Thismakes
*alllabelswithoutanattributehaveaneutrallikelihood,
*alllabelsmarked[[likely]]haveanequallypositivelikelihood,and
*alllabelsmarked[[unlikely]]haveanequallynegativelikelihood.
Theneutrallikelihoodisthemorelikelyofpathexecutionthanthenegative
likelihood.Thepositivelikelihoodisthemorelikelyofpathofexecution
thantheneutrallikelihood.
Theseattributeshavenoeffectonthegeneratedcodewhenusing
PGO(Profile-GuidedOptimization)oratoptimizationlevel0.
InClang,theattributeswillbeignoredifthey’renotplacedon
*thecaseordefaultlabelofaswitchstatement,
*oronthesubstatementofaniforelsestatement,
*oronthesubstatementofanfororwhilestatement.
TheC++Standardrecommendstohonorthemoneverystatementinthe
pathofexecution,butthatcanbeconfusing:
if(b){
[[unlikely]]--b;//Inthepathofexecution,
//thisbranchisconsideredunlikely.
}
if(b){
--b;
if(b)
return;
[[unlikely]]--b;//Notinthepathofexecution,
}//thebranchhasnolikelihoodinformation.
if(b){
--b;
foo(b);
//Whetherornotthenextstatementisinthepathofexecutiondepends
//onthedeclarationoffoo():
//Inthepathofexecution:voidfoo(int);
//Notinthepathofexecution:[[noreturn]]voidfoo(int);
//Thismeansthelikelihoodofthebranchdependsonthedeclaration
//offoo().
[[unlikely]]--b;
}
Belowaresomeexampleusagesofthelikelihoodattributesandtheireffects:
if(b)[[likely]]{//Placementonthefirststatementinthebranch.
//Thecompilerwilloptimizetoexecutethecodehere.
}else{
}
if(b)
[[unlikely]]b++;//Placementonthefirststatementinthebranch.
else{
//Thecompilerwilloptimizetoexecutethecodehere.
}
if(b){
[[unlikely]]b++;//Placementonthesecondstatementinthebranch.
}//Theattributewillbeignored.
if(b)[[likely]]{
[[unlikely]]b++;//Nocontradictionsincethesecondattribute
}//isignored.
if(b)
;
else[[likely]]{
//Thecompilerwilloptimizetoexecutethecodehere.
}
if(b)
;
else
//Thecompilerwilloptimizetoexecutethenextstatement.
[[likely]]b=f();
if(b)[[likely]];//Bothbranchesarelikely.Adiagnosticisissued
else[[likely]];//andtheattributesareignored.
if(b)
[[likely]]inti=5;//Issuesadiagnosticsincetheattribute
//isn'tallowedonadeclaration.
switch(i){
[[likely]]case1://Thisvalueislikely
...
break;
[[unlikely]]case2://Thisvalueisunlikely
...
[[fallthrough]];
case3://Nolikelihoodattribute
...
[[likely]]break;//Noeffect
case4:[[likely]]{//attributeonsubstatementhasnoeffect
...
break;
}
[[unlikely]]default://Allothervaluesareunlikely
...
break;
}
switch(i){
[[likely]]case0://Thisvalueandcodepathislikely
...
[[fallthrough]];
case1://Nolikelihoodattribute,codepathisneutral
break;//fallingthroughhasnoeffectonthelikelihood
case2://Nolikelihoodattribute,codepathisneutral
[[fallthrough]];
[[unlikely]]default://Thisvalueandcodepatharebothunlikely
break;
}
for(inti=0;i!=size;++i)[[likely]]{
...//Theloopisthelikelypathofexecution
}
for(constauto&E:Elements)[[likely]]{
...//Theloopisthelikelypathofexecution
}
while(i!=size)[[unlikely]]{
...//Theloopistheunlikelypathofexecution
}//Thegeneratedcodewilloptimizetoskiptheloopbody
while(true)[[unlikely]]{
...//Theattributehasnoeffect
}//Clangelidesthecomparisonandgeneratesaninfinite
//loop
likelyandunlikely¶
SupportedSyntaxes¶
unlikely
clang::unlikely
Thelikelyandunlikelyattributesareusedascompilerhints.
Theattributesareusedtoaidthecompilertodeterminewhichbranchis
likelyorunlikelytobetaken.Thisisdonebymarkingthebranchsubstatement
withoneofthetwoattributes.
Itisn’tallowedtoannotateasinglestatementwithbothlikelyand
unlikely.Annotatingthetrueandfalsebranchofanif
statementwiththesamelikelihoodattributewillresultinadiagnosticand
theattributesareignoredonbothbranches.
Inaswitchstatementit’sallowedtoannotatemultiplecaselabels
orthedefaultlabelwiththesamelikelihoodattribute.Thismakes
*alllabelswithoutanattributehaveaneutrallikelihood,
*alllabelsmarked[[likely]]haveanequallypositivelikelihood,and
*alllabelsmarked[[unlikely]]haveanequallynegativelikelihood.
Theneutrallikelihoodisthemorelikelyofpathexecutionthanthenegative
likelihood.Thepositivelikelihoodisthemorelikelyofpathofexecution
thantheneutrallikelihood.
Theseattributeshavenoeffectonthegeneratedcodewhenusing
PGO(Profile-GuidedOptimization)oratoptimizationlevel0.
InClang,theattributeswillbeignoredifthey’renotplacedon
*thecaseordefaultlabelofaswitchstatement,
*oronthesubstatementofaniforelsestatement,
*oronthesubstatementofanfororwhilestatement.
TheC++Standardrecommendstohonorthemoneverystatementinthe
pathofexecution,butthatcanbeconfusing:
if(b){
[[unlikely]]--b;//Inthepathofexecution,
//thisbranchisconsideredunlikely.
}
if(b){
--b;
if(b)
return;
[[unlikely]]--b;//Notinthepathofexecution,
}//thebranchhasnolikelihoodinformation.
if(b){
--b;
foo(b);
//Whetherornotthenextstatementisinthepathofexecutiondepends
//onthedeclarationoffoo():
//Inthepathofexecution:voidfoo(int);
//Notinthepathofexecution:[[noreturn]]voidfoo(int);
//Thismeansthelikelihoodofthebranchdependsonthedeclaration
//offoo().
[[unlikely]]--b;
}
Belowaresomeexampleusagesofthelikelihoodattributesandtheireffects:
if(b)[[likely]]{//Placementonthefirststatementinthebranch.
//Thecompilerwilloptimizetoexecutethecodehere.
}else{
}
if(b)
[[unlikely]]b++;//Placementonthefirststatementinthebranch.
else{
//Thecompilerwilloptimizetoexecutethecodehere.
}
if(b){
[[unlikely]]b++;//Placementonthesecondstatementinthebranch.
}//Theattributewillbeignored.
if(b)[[likely]]{
[[unlikely]]b++;//Nocontradictionsincethesecondattribute
}//isignored.
if(b)
;
else[[likely]]{
//Thecompilerwilloptimizetoexecutethecodehere.
}
if(b)
;
else
//Thecompilerwilloptimizetoexecutethenextstatement.
[[likely]]b=f();
if(b)[[likely]];//Bothbranchesarelikely.Adiagnosticisissued
else[[likely]];//andtheattributesareignored.
if(b)
[[likely]]inti=5;//Issuesadiagnosticsincetheattribute
//isn'tallowedonadeclaration.
switch(i){
[[likely]]case1://Thisvalueislikely
...
break;
[[unlikely]]case2://Thisvalueisunlikely
...
[[fallthrough]];
case3://Nolikelihoodattribute
...
[[likely]]break;//Noeffect
case4:[[likely]]{//attributeonsubstatementhasnoeffect
...
break;
}
[[unlikely]]default://Allothervaluesareunlikely
...
break;
}
switch(i){
[[likely]]case0://Thisvalueandcodepathislikely
...
[[fallthrough]];
case1://Nolikelihoodattribute,codepathisneutral
break;//fallingthroughhasnoeffectonthelikelihood
case2://Nolikelihoodattribute,codepathisneutral
[[fallthrough]];
[[unlikely]]default://Thisvalueandcodepatharebothunlikely
break;
}
for(inti=0;i!=size;++i)[[likely]]{
...//Theloopisthelikelypathofexecution
}
for(constauto&E:Elements)[[likely]]{
...//Theloopisthelikelypathofexecution
}
while(i!=size)[[unlikely]]{
...//Theloopistheunlikelypathofexecution
}//Thegeneratedcodewilloptimizetoskiptheloopbody
while(true)[[unlikely]]{
...//Theattributehasnoeffect
}//Clangelidesthecomparisonandgeneratesaninfinite
//loop
musttail¶
SupportedSyntaxes¶
musttail
clang::musttail
clang::musttail
Ifareturnstatementismarkedmusttail,thisindicatesthatthe
compilermustgenerateatailcallfortheprogramtobecorrect,evenwhen
optimizationsaredisabled.Thisguaranteesthatthecallwillnotcause
unboundedstackgrowthifitispartofarecursivecycleinthecallgraph.
Ifthecalleeisavirtualfunctionthatisimplementedbyathunk,thereis
noguaranteeingeneralthatthethunktail-callstheimplementationofthe
virtualfunction,sosuchacallinarecursivecyclecanstillresultin
unboundedstackgrowth.
clang::musttailcanonlybeappliedtoareturnstatementwhosevalue
istheresultofafunctioncall(evenfunctionsreturningvoidmustuse
return,althoughnovalueisreturned).Thetargetfunctionmusthavethe
samenumberofargumentsasthecaller.Thetypesofthereturnvalueandall
argumentsmustbesimilaraccordingtoC++rules(differingonlyincv
qualifiersorarraysize),includingtheimplicit“this”argument,ifany.
Anyvariablesinscope,includingallargumentstothefunctionandthe
returnvaluemustbetriviallydestructible.Thecallingconventionofthe
callerandcalleemustmatch,andtheymustnotbevariadicfunctionsorhave
oldstyleK&RCfunctiondeclarations.
nomerge¶
SupportedSyntaxes¶
nomerge
clang::nomerge
clang::nomerge
Yes
Ifastatementismarkednomergeandcontainscallexpressions,thosecall
expressionsinsidethestatementwillnotbemergedduringoptimization.This
attributecanbeusedtopreventtheoptimizerfromobscuringthesource
locationofcertaincalls.Forexample,itwillpreventtailmergingotherwise
identicalcodesequencesthatraiseanexceptionorterminatetheprogram.Tail
mergingnormallyreducestheprecisionofsourcelocationinformation,making
stacktraceslessusefulfordebugging.Thisattributegivestheusercontrol
overthetradeoffbetweencodesizeanddebuginformationprecision.
nomergeattributecanalsobeusedasfunctionattributetopreventall
callstothespecifiedfunctionfrommerging.Ithasnoeffectonindirect
calls.
opencl_unroll_hint¶
SupportedSyntaxes¶
opencl_unroll_hint
Theopencl_unroll_hintattributequalifiercanbeusedtospecifythataloop
(for,whileanddoloops)canbeunrolled.Thisattributequalifiercanbe
usedtospecifyfullunrollingorpartialunrollingbyaspecifiedamount.
Thisisacompilerhintandthecompilermayignorethisdirective.See
OpenCLv2.0
s6.11.5fordetails.
suppress¶
SupportedSyntaxes¶
gsl::suppress
The[[gsl::suppress]]attributesuppressesspecific
clang-tidydiagnosticsforrulesoftheC++CoreGuidelinesinaportable
way.Theattributecanbeattachedtodeclarations,statements,andat
namespacescope.
[[gsl::suppress("Rh-public")]]
voidf_(){
int*p;
[[gsl::suppress("type")]]{
p=reinterpret_cast(7);
}
}
namespaceN{
[[clang::suppress("type","bounds")]];
...
}
sycl_special_class¶
SupportedSyntaxes¶
sycl_special_class
clang::sycl_special_class
clang::sycl_special_class
Yes
SYCLdefinessomespecialclasses(accessor,sampler,andstream)whichrequire
specifichandlingduringthegenerationoftheSPIRentrypoint.
The__attribute__((sycl_special_class))attributeisusedinSYCL
headerstoindicatethataclassorastructneedsaspecifichandlingwhen
itispassedfromhosttodevice.
Specialclasseswillhaveamandatory__initmethodandanoptional
__finalizemethod(the__finalizemethodisusedonlywiththe
streamtype).Kernelparameterstypesareextractfromthe__initmethod
parameters.Thekernelfunctionargumentslistisderivedfromthe
argumentsofthe__initmethod.Theargumentsofthe__initmethodare
copiedintothekernelfunctionargumentlistandthe__initand
__finalizemethodsarecalledatthebeginningandtheendofthekernel,
respectively.
The__initand__finalizemethodsmustbedefinedinsidethe
specialclass.
Pleasenotethatthisisanattributethatisusedasaninternal
implementationdetailandnotintendedtobeusedbyexternalusers.
Thesyntaxoftheattributeisasfollows:
class__attribute__((sycl_special_class))accessor{};
class[[clang::sycl_special_class]]accessor{};
Thisisacodeexamplethatillustratestheuseoftheattribute:
class__attribute__((sycl_special_class))SpecialType{
intF1;
intF2;
void__init(intf1){
F1=f1;
F2=f1;
}
void__finalize(){}
public:
SpecialType()=default;
intgetF2()const{returnF2;}
};
intmain(){
SpecialTypeT;
cgh.single_task([=]{
T.getF2();
});
}
ThiswouldtriggerthefollowingkernelentrypointintheAST:
void__sycl_kernel(intf1){
SpecialTypeT;
T.__init(f1);
...
T.__finalize()
}
TypeAttributes¶
__ptr32¶
SupportedSyntaxes¶
__ptr32
The__ptr32qualifierrepresentsanativepointerona32-bitsystem.Ona
64-bitsystem,apointerwith__ptr32isextendedtoa64-bitpointer.The
__sptrand__uptrqualifierscanbeusedtospecifywhetherthepointer
issignextendedorzeroextended.Thisqualifierisenabledunder
-fms-extensions.
__ptr64¶
SupportedSyntaxes¶
__ptr64
The__ptr64qualifierrepresentsanativepointerona64-bitsystem.Ona
32-bitsystem,a__ptr64pointeristruncatedtoa32-bitpointer.This
qualifierisenabledunder-fms-extensions.
__sptr¶
SupportedSyntaxes¶
__sptr
The__sptrqualifierspecifiesthata32-bitpointershouldbesign
extendedwhenconvertedtoa64-bitpointer.
__uptr¶
SupportedSyntaxes¶
__uptr
The__uptrqualifierspecifiesthata32-bitpointershouldbezero
extendedwhenconvertedtoa64-bitpointer.
align_value¶
SupportedSyntaxes¶
align_value
Yes
Thealign_valueattributecanbeaddedtothetypedefofapointertypeorthe
declarationofavariableofpointerorreferencetype.Itspecifiesthatthe
pointerwillpointto,orthereferencewillbindto,onlyobjectswithat
leasttheprovidedalignment.Thisalignmentvaluemustbesomepositivepower
of2.
typedefdouble*aligned_double_ptr__attribute__((align_value(64)));
voidfoo(double&x__attribute__((align_value(128)),
aligned_double_ptry){...}
Ifthepointervaluedoesnothavethespecifiedalignmentatruntime,the
behavioroftheprogramisundefined.
annotate_type¶
SupportedSyntaxes¶
clang::annotate_type
clang::annotate_type
Thisattributeisusedtoaddannotationstotypes,typicallyforusebystatic
analysistoolsthatarenotintegratedintothecoreClangcompiler(e.g.,
Clang-Tidychecksorout-of-treeClang-basedtools).Itisacounterparttothe
annotateattribute,whichservesthesamepurpose,butfordeclarations.
Theattributetakesamandatorystringliteralargumentspecifyingthe
annotationcategoryandanarbitrarynumberofoptionalargumentsthatprovide
additionalinformationspecifictotheannotationcategory.Theoptional
argumentsmustbeconstantexpressionsofarbitrarytype.
Forexample:
int*[[clang::annotate("category1","foo",1)]]f(int[[clang::annotate("category2")]]*);
Theattributedoesnothaveanyeffectonthesemanticsofthetypesystem,
neithertypecheckingrules,norruntimesemantics.Inparticular:
std::is_sameistrueforalltypes
T.
Itisnotpermissibleforoverloadedfunctionsortemplatespecializations
todiffermerelybyanannotate_typeattribute.
Thepresenceofanannotate_typeattributewillnotaffectname
mangling.
arm_sve_vector_bits¶
SupportedSyntaxes¶
arm_sve_vector_bits
Thearm_sve_vector_bits(N)attributeisdefinedbytheArmCLanguage
Extensions(ACLE)forSVE.Itisusedtodefinefixed-length(VLST)variantsof
sizelesstypes(VLAT).
Forexample:
#include
#if__ARM_FEATURE_SVE_BITS==512
typedefsvint32_tfixed_svint32_t__attribute__((arm_sve_vector_bits(512)));
#endif
Createsatypefixed_svint32_tthatisafixed-lengthvariantof
svint32_tthatcontainsexactly512-bits.Unlikesvint32_t,thistype
canbeusedinglobals,structs,unions,andarrays,allofwhichare
unsupportedforsizelesstypes.
TheattributecanbeattachedtoasingleSVEvector(suchassvint32_t)or
totheSVEpredicatetypesvbool_t,thisexcludestupletypessuchas
svint32x4_t.Thebehavioroftheattributeisundefinedunless
N==__ARM_FEATURE_SVE_BITS,theimplementationdefinedfeaturemacrothatis
enabledunderthe-msve-vector-bitsflag.
FormoreinformationSeeArmCLanguageExtensionsforSVEformoreinformation.
btf_type_tag¶
SupportedSyntaxes¶
btf_type_tag
clang::btf_type_tag
clang::btf_type_tag
Clangsupportsthe__attribute__((btf_type_tag("ARGUMENT")))attributefor
alltargets.Itonlyhaseffectwhen-gisspecifiedonthecommandlineand
iscurrentlysilentlyignoredwhennotappliedtoapointertype(note:this
scenariomaybediagnosedinthefuture).
TheARGUMENTstringwillbepreservedinIRandemittedtoDWARFforthe
typesusedinvariabledeclarations,functiondeclarations,ortypedef
declarations.
ForBPFtargets,theARGUMENTstringwillalsobeemittedto.BTFELF
section.
clang_arm_mve_strict_polymorphism¶
SupportedSyntaxes¶
__clang_arm_mve_strict_polymorphism
clang::__clang_arm_mve_strict_polymorphism
clang::__clang_arm_mve_strict_polymorphism
ThisattributeisusedintheimplementationoftheACLEintrinsicsfortheArm
MVEinstructionset.ItisusedtodefinethevectortypesusedbytheMVE
intrinsics.
Itseffectistomodifythebehaviorofavectortypewithrespecttofunction
overloading.Ifacandidatefunctionforoverloadresolutionhasaparameter
typewiththisattribute,thentheselectionofthatcandidatefunctionwillbe
disallowediftheactualargumentcanonlybeconvertedviaalaxvector
conversion.TheaimistopreventspuriousambiguityinARMMVEpolymorphic
intrinsics.
voidoverloaded(uint16x8_tvector,uint16_tscalar);
voidoverloaded(int32x4_tvector,int32_tscalar);
uint16x8_tmyVector;
uint16_tmyScalar;
//myScalarispromotedtoint32_tasasideeffectoftheaddition,
//soiflaxvectorconversionsareconsideredformyVector,then
//thetwooverloadsareequallygood(oneargumentconversion
//each).Butifthevectorhasthe__clang_arm_mve_strict_polymorphism
//attribute,onlytheuint16x8_t,uint16_toverloadwillmatch.
overloaded(myVector,myScalar+1);
However,thisattributedoesnotprohibitlaxvectorconversionsincontexts
otherthanoverloading.
uint16x8_tfunction();
//Thisisstillpermittedwithlaxvectorconversionenabled,even
//ifthevectortypeshave__clang_arm_mve_strict_polymorphism
int32x4_tresult=function();
cmse_nonsecure_call¶
SupportedSyntaxes¶
cmse_nonsecure_call
Thisattributedeclaresanon-securefunctiontype.Whencompilingforsecure
state,acalltosuchafunctionwouldswitchfromsecuretonon-securestate.
Allnon-securefunctioncallsmusthappenonlythroughafunctionpointer,and
anon-securefunctiontypeshouldonlybeusedasabasetypeofapointer.
SeeARMv8-MSecurityExtensions:RequirementsonDevelopment
Tools-EngineeringSpecificationDocumentationformoreinformation.
device_builtin_surface_type¶
SupportedSyntaxes¶
device_builtin_surface_type
__device_builtin_surface_type__
Yes
Thedevice_builtin_surface_typeattributecanbeappliedtoaclass
templatewhendeclaringthesurfacereference.Asurfacereferencevariable
couldbeaccessedonthehostsideand,onthedeviceside,mightbetranslated
intoaninternalsurfaceobject,whichisestablishedthroughsurfacebindand
unbindruntimeAPIs.
device_builtin_texture_type¶
SupportedSyntaxes¶
device_builtin_texture_type
__device_builtin_texture_type__
Yes
Thedevice_builtin_texture_typeattributecanbeappliedtoaclass
templatewhendeclaringthetexturereference.Atexturereferencevariable
couldbeaccessedonthehostsideand,onthedeviceside,mightbetranslated
intoaninternaltextureobject,whichisestablishedthroughtexturebindand
unbindruntimeAPIs.
noderef¶
SupportedSyntaxes¶
noderef
clang::noderef
clang::noderef
Thenoderefattributecausesclangtodiagnosedereferencesofannotatedpointertypes.
Thisisideallyusedwithpointersthatpointtospecialmemorywhichcannotberead
fromorwrittento,butallowingforthepointertobeusedinpointerarithmetic.
Thefollowingareexamplesofvalidexpressionswheredereferencesarediagnosed:
int__attribute__((noderef))*p;
intx=*p;//warning
int__attribute__((noderef))**p2;
x=**p2;//warning
int*__attribute__((noderef))*p3;
p=*p3;//warning
structS{
inta;
};
structS__attribute__((noderef))*s;
x=s->a;//warning
x=(*s).a;//warning
Notalldereferencesmaydiagnoseawarningifthevaluedirectedbythepointermaynotbe
accessed.Thefollowingareexamplesofvalidexpressionswheremaynotbediagnosed:
int*q;
int__attribute__((noderef))*p;
q=&*p;
q=*&p;
structS{
inta;
};
structS__attribute__((noderef))*s;
p=&s->a;
p=&(*s).a;
noderefiscurrentlyonlysupportedforpointersandarraysandnotusable
forreferencesorObjective-Cobjectpointers.
objc_class_stub¶
SupportedSyntaxes¶
objc_class_stub
clang::objc_class_stub
clang::objc_class_stub
Yes
ThisattributespecifiesthattheObjective-Cclasstowhichitappliesis
instantiatedatruntime.
Unlike__attribute__((objc_runtime_visible)),aclasshavingthisattribute
stillhasa“classstub”thatisvisibletothelinker.Thisallowscategories
tobedefined.Staticmessagesendswiththeclassasareceiveruseaspecial
accesspatterntoensuretheclassislazilyinstantiatedfromtheclassstub.
Classesannotatedwiththisattributecannotbesubclassedandcannothave
implementationsdefinedforthem.Thisattributeisintendedforusein
Swift-generatedheadersforclassesdefinedinSwift.
AddingorremovingthisattributetoaclassisanABI-breakingchange.
TypeSafetyChecking¶
Clangsupportsadditionalattributestoenablecheckingtypesafetyproperties
thatcan’tbeenforcedbytheCtypesystem.Toseewarningsproducedbythese
checks,ensurethat-Wtype-safetyisenabled.Usecasesinclude:
MPIlibraryimplementations,wheretheseattributesenablecheckingthat
thebuffertypematchesthepassedMPI_Datatype;
forHDF5librarythereisasimilarusecasetoMPI;
checkingtypesofvariadicfunctions’argumentsforfunctionslike
fcntl()andioctl().
Youcandetectsupportfortheseattributeswith__has_attribute().For
example:
#ifdefined(__has_attribute)
#if__has_attribute(argument_with_type_tag)&&\
__has_attribute(pointer_with_type_tag)&&\
__has_attribute(type_tag_for_datatype)
#defineATTR_MPI_PWT(buffer_idx,type_idx)__attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
/*...othermacros...*/
#endif
#endif
#if!defined(ATTR_MPI_PWT)
#defineATTR_MPI_PWT(buffer_idx,type_idx)
#endif
intMPI_Send(void*buf,intcount,MPI_Datatypedatatype/*,otherargsomitted*/)
ATTR_MPI_PWT(1,3);
argument_with_type_tag¶
SupportedSyntaxes¶
argument_with_type_tagpointer_with_type_tag
clang::argument_with_type_tagclang::pointer_with_type_tag
clang::argument_with_type_tagclang::pointer_with_type_tag
Use__attribute__((argument_with_type_tag(arg_kind,arg_idx,
type_tag_idx)))onafunctiondeclarationtospecifythatthefunction
acceptsatypetagthatdeterminesthetypeofsomeotherargument.
Thisattributeisprimarilyusefulforcheckingargumentsofvariadicfunctions
(pointer_with_type_tagcanbeusedinmostnon-variadiccases).
Intheattributeprototypeabove:
arg_kindisanidentifierthatshouldbeusedwhenannotatingall
applicabletypetags.
arg_idxprovidesthepositionofafunctionargument.Theexpectedtypeof
thisfunctionargumentwillbedeterminedbythefunctionargumentspecified
bytype_tag_idx.Inthecodeexamplebelow,“3”meansthatthetypeofthe
function’sthirdargumentwillbedeterminedbytype_tag_idx.
type_tag_idxprovidesthepositionofafunctionargument.Thisfunction
argumentwillbeatypetag.Thetypetagwilldeterminetheexpectedtypeof
theargumentspecifiedbyarg_idx.Inthecodeexamplebelow,“2”means
thatthetypetagassociatedwiththefunction’ssecondargumentshouldagree
withthetypeoftheargumentspecifiedbyarg_idx.
Forexample:
intfcntl(intfd,intcmd,...)
__attribute__((argument_with_type_tag(fcntl,3,2)));
//Thefunction'ssecondargumentwillbeatypetag;thistypetagwill
//determinetheexpectedtypeofthefunction'sthirdargument.
pointer_with_type_tag¶
SupportedSyntaxes¶
argument_with_type_tagpointer_with_type_tag
clang::argument_with_type_tagclang::pointer_with_type_tag
clang::argument_with_type_tagclang::pointer_with_type_tag
Use__attribute__((pointer_with_type_tag(ptr_kind,ptr_idx,type_tag_idx)))
onafunctiondeclarationtospecifythatthefunctionacceptsatypetagthat
determinesthepointeetypeofsomeotherpointerargument.
Intheattributeprototypeabove:
ptr_kindisanidentifierthatshouldbeusedwhenannotatingall
applicabletypetags.
ptr_idxprovidesthepositionofafunctionargument;thisfunction
argumentwillhaveapointertype.Theexpectedpointeetypeofthispointer
typewillbedeterminedbythefunctionargumentspecifiedby
type_tag_idx.Inthecodeexamplebelow,“1”meansthatthepointeetype
ofthefunction’sfirstargumentwillbedeterminedbytype_tag_idx.
type_tag_idxprovidesthepositionofafunctionargument;thisfunction
argumentwillbeatypetag.Thetypetagwilldeterminetheexpectedpointee
typeofthepointerargumentspecifiedbyptr_idx.Inthecodeexample
below,“3”meansthatthetypetagassociatedwiththefunction’sthird
argumentshouldagreewiththepointeetypeofthepointerargumentspecified
byptr_idx.
Forexample:
typedefintMPI_Datatype;
intMPI_Send(void*buf,intcount,MPI_Datatypedatatype/*,otherargsomitted*/)
__attribute__((pointer_with_type_tag(mpi,1,3)));
//Thefunction's3rdargumentwillbeatypetag;thistypetagwill
//determinetheexpectedpointeetypeofthefunction's1stargument.
type_tag_for_datatype¶
SupportedSyntaxes¶
type_tag_for_datatype
clang::type_tag_for_datatype
clang::type_tag_for_datatype
Whendeclaringavariable,use
__attribute__((type_tag_for_datatype(kind,type)))tocreateatypetagthat
istiedtothetypeargumentgiventotheattribute.
Intheattributeprototypeabove:
kindisanidentifierthatshouldbeusedwhenannotatingallapplicable
typetags.
typeindicatesthenameofthetype.
Clangsupportsannotatingtypetagsoftwoforms.
Typetagthatisareferencetoadeclaredidentifier.
Use__attribute__((type_tag_for_datatype(kind,type)))whendeclaringthat
identifier:
typedefintMPI_Datatype;
externstructmpi_datatypempi_datatype_int
__attribute__((type_tag_for_datatype(mpi,int)));
#defineMPI_INT((MPI_Datatype)&mpi_datatype_int)
//&mpi_datatype_intisatypetag.Itistiedtotype"int".
Typetagthatisanintegralliteral.
Declareastaticconstvariablewithaninitializervalueandattach
__attribute__((type_tag_for_datatype(kind,type)))onthatdeclaration:
typedefintMPI_Datatype;
staticconstMPI_Datatypempi_datatype_int
__attribute__((type_tag_for_datatype(mpi,int)))=42;
#defineMPI_INT((MPI_Datatype)42)
//Thenumber42isatypetag.Itistiedtotype"int".
Thetype_tag_for_datatypeattributealsoacceptsanoptionalthirdargument
thatdetermineshowthetypeofthefunctionargumentspecifiedbyeither
arg_idxorptr_idxiscomparedagainstthetypeassociatedwiththetype
tag.(Recallthatfortheargument_with_type_tagattribute,thetypeofthe
functionargumentspecifiedbyarg_idxiscomparedagainstthetype
associatedwiththetypetag.Alsorecallthatforthepointer_with_type_tag
attribute,thepointeetypeofthefunctionargumentspecifiedbyptr_idxis
comparedagainstthetypeassociatedwiththetypetag.)Therearetwosupported
valuesforthisoptionalthirdargument:
layout_compatiblewillcausetypestobecomparedaccordingto
layout-compatibilityrules(InC++11[class.mem]p17,18,seethe
layout-compatibilityrulesfortwostandard-layoutstructtypesandfortwo
standard-layoutuniontypes).Thisisusefulwhencreatingatypetag
associatedwithastructoruniontype.Forexample:
/*Inmpi.h*/
typedefintMPI_Datatype;
structinternal_mpi_double_int{doubled;inti;};
externstructmpi_datatypempi_datatype_double_int
__attribute__((type_tag_for_datatype(mpi,
structinternal_mpi_double_int,layout_compatible)));
#defineMPI_DOUBLE_INT((MPI_Datatype)&mpi_datatype_double_int)
intMPI_Send(void*buf,intcount,MPI_Datatypedatatype,...)
__attribute__((pointer_with_type_tag(mpi,1,3)));
/*Inusercode*/
structmy_pair{doublea;intb;};
structmy_pair*buffer;
MPI_Send(buffer,1,MPI_DOUBLE_INT/*,...*/);//nowarningbecausethe
//layoutofmy_pairis
//compatiblewiththatof
//internal_mpi_double_int
structmy_int_pair{inta;intb;}
structmy_int_pair*buffer2;
MPI_Send(buffer2,1,MPI_DOUBLE_INT/*,...*/);//warningbecausethe
//layoutofmy_int_pair
//doesnotmatchthatof
//internal_mpi_double_int
must_be_nullspecifiesthatthefunctionargumentspecifiedbyeither
arg_idx(fortheargument_with_type_tagattribute)orptr_idx(for
thepointer_with_type_tagattribute)shouldbeanullpointerconstant.
Thesecondargumenttothetype_tag_for_datatypeattributeisignored.For
example:
/*Inmpi.h*/
typedefintMPI_Datatype;
externstructmpi_datatypempi_datatype_null
__attribute__((type_tag_for_datatype(mpi,void,must_be_null)));
#defineMPI_DATATYPE_NULL((MPI_Datatype)&mpi_datatype_null)
intMPI_Send(void*buf,intcount,MPI_Datatypedatatype,...)
__attribute__((pointer_with_type_tag(mpi,1,3)));
/*Inusercode*/
structmy_pair{doublea;intb;};
structmy_pair*buffer;
MPI_Send(buffer,1,MPI_DATATYPE_NULL/*,...*/);//warning:MPI_DATATYPE_NULL
//wasspecifiedbutbuffer
//isnotanullpointer
Undocumented¶
ThissectionlistsattributeswhicharerecognizedbyClang,butwhichare
currentlymissingdocumentation.
Alignas,align,alignas,aligned¶
SupportedSyntaxes¶
aligned
gnu::aligned
gnu::aligned
align
alignas_Alignas
Nodocumentation.
NSObject¶
SupportedSyntaxes¶
NSObject
clang::NSObject
clang::NSObject
Nodocumentation.
__kindof¶
SupportedSyntaxes¶
__kindof
Nodocumentation.
acquired_after¶
SupportedSyntaxes¶
acquired_after
Nodocumentation.
acquired_before¶
SupportedSyntaxes¶
acquired_before
Nodocumentation.
address_space¶
SupportedSyntaxes¶
address_space
clang::address_space
clang::address_space
Nodocumentation.
alias¶
SupportedSyntaxes¶
alias
gnu::alias
gnu::alias
Yes
Nodocumentation.
amdgpu_kernel¶
SupportedSyntaxes¶
amdgpu_kernel
clang::amdgpu_kernel
clang::amdgpu_kernel
Nodocumentation.
analyzer_noreturn¶
SupportedSyntaxes¶
analyzer_noreturn
Nodocumentation.
annotate¶
SupportedSyntaxes¶
annotate
clang::annotate
clang::annotate
Yes
Nodocumentation.
assert_exclusive_lock¶
SupportedSyntaxes¶
assert_exclusive_lock
Nodocumentation.
assert_shared_lock¶
SupportedSyntaxes¶
assert_shared_lock
Nodocumentation.
blocks¶
SupportedSyntaxes¶
blocks
clang::blocks
clang::blocks
Nodocumentation.
capability,shared_capability¶
SupportedSyntaxes¶
capabilityshared_capability
clang::capabilityclang::shared_capability
Yes
Nodocumentation.
cdecl¶
SupportedSyntaxes¶
cdecl
gnu::cdecl
gnu::cdecl
__cdecl_cdecl
Nodocumentation.
cf_audited_transfer¶
SupportedSyntaxes¶
cf_audited_transfer
clang::cf_audited_transfer
clang::cf_audited_transfer
Yes
Nodocumentation.
cf_unknown_transfer¶
SupportedSyntaxes¶
cf_unknown_transfer
clang::cf_unknown_transfer
clang::cf_unknown_transfer
Yes
Nodocumentation.
cleanup¶
SupportedSyntaxes¶
cleanup
gnu::cleanup
gnu::cleanup
Yes
Nodocumentation.
cold¶
SupportedSyntaxes¶
cold
gnu::cold
gnu::cold
Yes
Nodocumentation.
common¶
SupportedSyntaxes¶
common
gnu::common
gnu::common
Yes
Nodocumentation.
const¶
SupportedSyntaxes¶
const__const
gnu::constgnu::__const
gnu::constgnu::__const
Nodocumentation.
constant¶
SupportedSyntaxes¶
constant
__constant__
Yes
Nodocumentation.
constructor¶
SupportedSyntaxes¶
constructor
gnu::constructor
gnu::constructor
Yes
Nodocumentation.
consumable_auto_cast_state¶
SupportedSyntaxes¶
consumable_auto_cast_state
clang::consumable_auto_cast_state
Yes
Nodocumentation.
consumable_set_state_on_read¶
SupportedSyntaxes¶
consumable_set_state_on_read
clang::consumable_set_state_on_read
Yes
Nodocumentation.
destructor¶
SupportedSyntaxes¶
destructor
gnu::destructor
gnu::destructor
Yes
Nodocumentation.
device¶
SupportedSyntaxes¶
device
__device__
Yes
Nodocumentation.
exclusive_locks_required,requires_capability,requires_shared_capability,shared_locks_required¶
SupportedSyntaxes¶
requires_capabilityexclusive_locks_requiredrequires_shared_capabilityshared_locks_required
clang::requires_capabilityclang::exclusive_locks_requiredclang::requires_shared_capabilityclang::shared_locks_required
Nodocumentation.
exclusive_trylock_function¶
SupportedSyntaxes¶
exclusive_trylock_function
Nodocumentation.
ext_vector_type¶
SupportedSyntaxes¶
ext_vector_type
Nodocumentation.
format_arg¶
SupportedSyntaxes¶
format_arg
gnu::format_arg
gnu::format_arg
Nodocumentation.
global¶
SupportedSyntaxes¶
global
__global__
Yes
Nodocumentation.
guarded_by¶
SupportedSyntaxes¶
guarded_by
Nodocumentation.
guarded_var¶
SupportedSyntaxes¶
guarded_var
clang::guarded_var
Nodocumentation.
host¶
SupportedSyntaxes¶
host
__host__
Yes
Nodocumentation.
hot¶
SupportedSyntaxes¶
hot
gnu::hot
gnu::hot
Yes
Nodocumentation.
ibaction¶
SupportedSyntaxes¶
ibaction
clang::ibaction
clang::ibaction
Yes
Nodocumentation.
iboutlet¶
SupportedSyntaxes¶
iboutlet
clang::iboutlet
clang::iboutlet
Nodocumentation.
iboutletcollection¶
SupportedSyntaxes¶
iboutletcollection
clang::iboutletcollection
clang::iboutletcollection
Nodocumentation.
intel_ocl_bicc¶
SupportedSyntaxes¶
intel_ocl_bicc
clang::intel_ocl_bicc
Nodocumentation.
interrupt¶
SupportedSyntaxes¶
interrupt
Nodocumentation.
interrupt¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
Nodocumentation.
interrupt¶
SupportedSyntaxes¶
interrupt
gnu::interrupt
gnu::interrupt
Nodocumentation.
kernel¶
SupportedSyntaxes¶
__kernelkernel
Nodocumentation.
launch_bounds¶
SupportedSyntaxes¶
launch_bounds
__launch_bounds__
Yes
Nodocumentation.
lock_returned¶
SupportedSyntaxes¶
lock_returned
Nodocumentation.
lockable¶
SupportedSyntaxes¶
lockable
Yes
Nodocumentation.
locks_excluded¶
SupportedSyntaxes¶
locks_excluded
Nodocumentation.
matrix_type¶
SupportedSyntaxes¶
matrix_type
clang::matrix_type
clang::matrix_type
Nodocumentation.
may_alias¶
SupportedSyntaxes¶
may_alias
gnu::may_alias
gnu::may_alias
Nodocumentation.
mips16¶
SupportedSyntaxes¶
mips16
gnu::mips16
gnu::mips16
Yes
Nodocumentation.
mode¶
SupportedSyntaxes¶
mode
gnu::mode
gnu::mode
Nodocumentation.
ms_struct¶
SupportedSyntaxes¶
ms_struct
gnu::ms_struct
gnu::ms_struct
Yes
Nodocumentation.
naked¶
SupportedSyntaxes¶
naked
gnu::naked
gnu::naked
naked
Yes
Nodocumentation.
neon_polyvector_type¶
SupportedSyntaxes¶
neon_polyvector_type
clang::neon_polyvector_type
clang::neon_polyvector_type
Nodocumentation.
neon_vector_type¶
SupportedSyntaxes¶
neon_vector_type
clang::neon_vector_type
clang::neon_vector_type
Nodocumentation.
no_instrument_function¶
SupportedSyntaxes¶
no_instrument_function
gnu::no_instrument_function
gnu::no_instrument_function
Yes
Nodocumentation.
no_thread_safety_analysis¶
SupportedSyntaxes¶
no_thread_safety_analysis
clang::no_thread_safety_analysis
clang::no_thread_safety_analysis
Yes
Nodocumentation.
nocommon¶
SupportedSyntaxes¶
nocommon
gnu::nocommon
gnu::nocommon
Yes
Nodocumentation.
nomips16¶
SupportedSyntaxes¶
nomips16
gnu::nomips16
gnu::nomips16
Yes
Nodocumentation.
noreturn¶
SupportedSyntaxes¶
noreturn
gnu::noreturn
gnu::noreturn
noreturn
Nodocumentation.
objc_arc_weak_reference_unavailable¶
SupportedSyntaxes¶
objc_arc_weak_reference_unavailable
clang::objc_arc_weak_reference_unavailable
clang::objc_arc_weak_reference_unavailable
Yes
Nodocumentation.
objc_bridge¶
SupportedSyntaxes¶
objc_bridge
clang::objc_bridge
clang::objc_bridge
Yes
Nodocumentation.
objc_bridge_mutable¶
SupportedSyntaxes¶
objc_bridge_mutable
clang::objc_bridge_mutable
clang::objc_bridge_mutable
Yes
Nodocumentation.
objc_bridge_related¶
SupportedSyntaxes¶
objc_bridge_related
clang::objc_bridge_related
clang::objc_bridge_related
Yes
Nodocumentation.
objc_designated_initializer¶
SupportedSyntaxes¶
objc_designated_initializer
clang::objc_designated_initializer
clang::objc_designated_initializer
Yes
Nodocumentation.
objc_exception¶
SupportedSyntaxes¶
objc_exception
clang::objc_exception
clang::objc_exception
Yes
Nodocumentation.
objc_gc¶
SupportedSyntaxes¶
objc_gc
clang::objc_gc
clang::objc_gc
Nodocumentation.
objc_independent_class¶
SupportedSyntaxes¶
objc_independent_class
clang::objc_independent_class
clang::objc_independent_class
Nodocumentation.
objc_ownership¶
SupportedSyntaxes¶
objc_ownership
clang::objc_ownership
clang::objc_ownership
Nodocumentation.
objc_precise_lifetime¶
SupportedSyntaxes¶
objc_precise_lifetime
clang::objc_precise_lifetime
clang::objc_precise_lifetime
Yes
Nodocumentation.
objc_protocol_requires_explicit_implementation¶
SupportedSyntaxes¶
objc_protocol_requires_explicit_implementation
clang::objc_protocol_requires_explicit_implementation
clang::objc_protocol_requires_explicit_implementation
Yes
Nodocumentation.
objc_requires_property_definitions¶
SupportedSyntaxes¶
objc_requires_property_definitions
clang::objc_requires_property_definitions
clang::objc_requires_property_definitions
Yes
Nodocumentation.
objc_returns_inner_pointer¶
SupportedSyntaxes¶
objc_returns_inner_pointer
clang::objc_returns_inner_pointer
clang::objc_returns_inner_pointer
Yes
Nodocumentation.
objc_root_class¶
SupportedSyntaxes¶
objc_root_class
clang::objc_root_class
clang::objc_root_class
Yes
Nodocumentation.
ownership_holds,ownership_returns,ownership_takes¶
SupportedSyntaxes¶
ownership_holdsownership_returnsownership_takes
clang::ownership_holdsclang::ownership_returnsclang::ownership_takes
clang::ownership_holdsclang::ownership_returnsclang::ownership_takes
Nodocumentation.
packed¶
SupportedSyntaxes¶
packed
gnu::packed
gnu::packed
Nodocumentation.
pascal¶
SupportedSyntaxes¶
pascal
clang::pascal
clang::pascal
__pascal_pascal
Nodocumentation.
pt_guarded_by¶
SupportedSyntaxes¶
pt_guarded_by
Nodocumentation.
pt_guarded_var¶
SupportedSyntaxes¶
pt_guarded_var
clang::pt_guarded_var
Nodocumentation.
pure¶
SupportedSyntaxes¶
pure
gnu::pure
gnu::pure
Nodocumentation.
reqd_work_group_size¶
SupportedSyntaxes¶
reqd_work_group_size
Yes
Nodocumentation.
returns_twice¶
SupportedSyntaxes¶
returns_twice
gnu::returns_twice
gnu::returns_twice
Yes
Nodocumentation.
scoped_lockable¶
SupportedSyntaxes¶
scoped_lockable
clang::scoped_lockable
Yes
Nodocumentation.
sentinel¶
SupportedSyntaxes¶
sentinel
gnu::sentinel
gnu::sentinel
Nodocumentation.
shared¶
SupportedSyntaxes¶
shared
__shared__
Yes
Nodocumentation.
shared_trylock_function¶
SupportedSyntaxes¶
shared_trylock_function
Nodocumentation.
sysv_abi¶
SupportedSyntaxes¶
sysv_abi
gnu::sysv_abi
gnu::sysv_abi
Nodocumentation.
type_visibility¶
SupportedSyntaxes¶
type_visibility
clang::type_visibility
clang::type_visibility
Nodocumentation.
unavailable¶
SupportedSyntaxes¶
unavailable
clang::unavailable
clang::unavailable
Nodocumentation.
uuid¶
SupportedSyntaxes¶
uuid
Nodocumentation.
vec_type_hint¶
SupportedSyntaxes¶
vec_type_hint
Yes
Nodocumentation.
vecreturn¶
SupportedSyntaxes¶
vecreturn
clang::vecreturn
Yes
Nodocumentation.
vector_size¶
SupportedSyntaxes¶
vector_size
gnu::vector_size
gnu::vector_size
Nodocumentation.
visibility¶
SupportedSyntaxes¶
visibility
gnu::visibility
gnu::visibility
Nodocumentation.
warn_unused¶
SupportedSyntaxes¶
warn_unused
gnu::warn_unused
gnu::warn_unused
Yes
Nodocumentation.
weak_import¶
SupportedSyntaxes¶
weak_import
clang::weak_import
clang::weak_import
Nodocumentation.
weakref¶
SupportedSyntaxes¶
weakref
gnu::weakref
gnu::weakref
Yes
Nodocumentation.
work_group_size_hint¶
SupportedSyntaxes¶
work_group_size_hint
Yes
Nodocumentation.
VariableAttributes¶
always_destroy¶
SupportedSyntaxes¶
always_destroy
clang::always_destroy
Yes
Thealways_destroyattributespecifiesthatavariablewithstaticorthread
storagedurationshouldhaveitsexit-timedestructorrun.Thisattributeisthe
defaultunlessclangwasinvokedwith-fno-c++-static-destructors.
called_once¶
SupportedSyntaxes¶
called_once
clang::called_once
clang::called_once
Yes
Thecalled_onceattributespecifiesthattheannotatedfunctionormethod
parameterisinvokedexactlyonceonallexecutionpaths.Itonlyapplies
toparameterswithfunction-liketypes,i.e.functionpointersorblocks.This
conceptisparticularlyusefulforasynchronousprograms.
Clangimplementsacheckforcalled_onceparameters,
-Wcalled-once-parameter.Itisonbydefaultandfindsthefollowing
violations:
Parameterisnotcalledatall.
Parameteriscalledmorethanonce.
Parameterisnotcalledononeoftheexecutionpaths.
Inthelattercase,Clangpinpointsthepathwhereparameterisnotinvoked
byshowingthecontrol-flowstatementwherethepathdiverges.
voidfooWithCallback(void(^callback)(void)__attribute__((called_once))){
if(somePredicate()){
...
callback();
}esle{
callback();//OK:callbackiscalledoneverypath
}
}
voidbarWithCallback(void(^callback)(void)__attribute__((called_once))){
if(somePredicate()){
...
callback();//note:previouscallishere
}
callback();//warning:callbackiscalledtwice
}
voidfoobarWithCallback(void(^callback)(void)__attribute__((called_once))){
if(somePredicate()){//warning:callbackisnotcalledwhenconditionisfalse
...
callback();
}
}
ThisattributeisusefulforAPIdeveloperswhowanttodouble-checkifthey
implementedtheirmethodcorrectly.
dllexport¶
SupportedSyntaxes¶
dllexport
gnu::dllexport
gnu::dllexport
dllexport
Yes
The__declspec(dllexport)attributedeclaresavariable,function,or
Objective-Cinterfacetobeexportedfromthemodule.Itisavailableunderthe
-fdeclspecflagforcompatibilitywithvariouscompilers.Theprimaryuse
isforCOFFobjectfileswhichexplicitlyspecifywhatinterfacesareavailable
forexternaluse.SeethedllexportdocumentationonMSDNformore
information.
dllimport¶
SupportedSyntaxes¶
dllimport
gnu::dllimport
gnu::dllimport
dllimport
Yes
The__declspec(dllimport)attributedeclaresavariable,function,or
Objective-Cinterfacetobeimportedfromanexternalmodule.Itisavailable
underthe-fdeclspecflagforcompatibilitywithvariouscompilers.The
primaryuseisforCOFFobjectfileswhichexplicitlyspecifywhatinterfaces
areimportedfromexternalmodules.SeethedllimportdocumentationonMSDN
formoreinformation.
Notethatadllimportfunctionmaystillbeinlined,ifitsdefinitionis
availableanditdoesn’treferenceanynon-dllimportfunctionsorglobal
variables.
init_priority¶
SupportedSyntaxes¶
init_priority
gnu::init_priority
Yes
InC++,theorderinwhichglobalvariablesareinitializedacrosstranslation
unitsisunspecified,unliketheorderingwithinasingletranslationunit.The
init_priorityattributeallowsyoutospecifyarelativeorderingforthe
initializationofobjectsdeclaredatnamespacescopeinC++.Thepriorityis
givenasanintegerconstantexpressionbetween101and65535(inclusive).
Prioritiesoutsideofthatrangearereservedforusebytheimplementation.A
lowervalueindicatesahigherpriorityofinitialization.Notethatonlythe
relativeorderingofvaluesisimportant.Forexample:
structSomeType{SomeType();};
__attribute__((init_priority(200)))SomeTypeObj1;
__attribute__((init_priority(101)))SomeTypeObj2;
Obj2willbeinitializedbeforeObj1despitetheusualorderof
initializationbeingtheopposite.
ThisattributeisonlysupportedforC++andObjective-C++andisignoredin
otherlanguagemodes.Currently,thisattributeisnotimplementedonz/OS.
init_seg¶
SupportedSyntaxes¶
init_seg
Theattributeappliedbypragmainit_seg()controlsthesectioninto
whichglobalinitializationfunctionpointersareemitted.Itisonly
availablewith-fms-extensions.Typically,thisfunctionpointeris
emittedinto.CRT$XCUonWindows.Theusercanchangetheorderof
initializationbyusingadifferentsectionnamewiththesame
.CRT$XCprefixandasuffixthatsortslexicographicallybeforeor
afterthestandard.CRT$XCUsections.Seetheinit_seg
documentationonMSDNformoreinformation.
leaf¶
SupportedSyntaxes¶
leaf
gnu::leaf
gnu::leaf
Yes
Theleafattributeisusedasacompilerhinttoimprovedataflowanalysis
inlibraryfunctions.Functionsmarkedwiththeleafattributearenotallowed
tojumpbackintothecaller’stranslationunit,whetherthroughinvokinga
callbackfunction,anexternalfunctioncall,useoflongjmp,orothermeans.
Therefore,theycannotuseormodifyanydatathatdoesnotescapethecallerfunction’s
compilationunit.
Formoreinformationsee
gccdocumentation
loader_uninitialized¶
SupportedSyntaxes¶
loader_uninitialized
clang::loader_uninitialized
clang::loader_uninitialized
Yes
Theloader_uninitializedattributecanbeplacedonglobalvariablesto
indicatethatthevariabledoesnotneedtobezeroinitializedbytheloader.
Onmosttargets,zero-initializationdoesnotincuranyadditionalcost.
Forexample,mostgeneralpurposeoperatingsystemsdeliberatelyensure
thatallmemoryisproperlyinitializedinordertoavoidleakingprivileged
informationfromthekernelorotherprograms.However,sometargets
donotmakethisguarantee,andonthesetargets,avoidinganunnecessary
zero-initializationcanhaveasignificantimpactonloadtimesand/orcode
size.
Adeclarationwiththisattributeisanon-tentativedefinitionjustasifit
providedaninitializer.Variableswiththisattributeareconsideredtobe
uninitializedinthesamesenseasalocalvariable,andtheprogramsmust
writetothembeforereadingfromthem.Ifthevariable’stypeisaC++class
typewithanon-trivialdefaultconstructor,oranarraythereof,thisattribute
onlysuppressesthestaticzero-initializationofthevariable,notthedynamic
initializationprovidedbyexecutingthedefaultconstructor.
maybe_unused,unused¶
SupportedSyntaxes¶
unused
maybe_unusedgnu::unused
gnu::unusedmaybe_unused
Whenpassingthe-WunusedflagtoClang,entitiesthatareunusedbythe
programmaybediagnosed.The[[maybe_unused]](or
__attribute__((unused)))attributecanbeusedtosilencesuchdiagnostics
whentheentitycannotberemoved.Forinstance,alocalvariablemayexist
solelyforuseinanassert()statement,whichmakesthelocalvariable
unusedwhenNDEBUGisdefined.
Theattributemaybeappliedtothedeclarationofaclass,atypedef,a
variable,afunctionormethod,afunctionparameter,anenumeration,an
enumerator,anon-staticdatamember,oralabel.
no_destroy¶
SupportedSyntaxes¶
no_destroy
clang::no_destroy
Yes
Theno_destroyattributespecifiesthatavariablewithstaticorthread
storagedurationshouldn’thaveitsexit-timedestructorrun.Annotatingevery
staticandthreaddurationvariablewiththisattributeisequivalentto
invokingclangwith-fno-c++-static-destructors.
Ifavariableisdeclaredwiththisattribute,clangdoesn’taccesscheckor
generatethetype’sdestructor.Ifyouhaveatypethatyouonlywanttobe
annotatedwithno_destroy,youcanthereforedeclarethedestructorprivate:
structonly_no_destroy{
only_no_destroy();
private:
~only_no_destroy();
};
[[clang::no_destroy]]only_no_destroyglobal;//fine!
Notethatdestructorsarestillrequiredforsubobjectsofaggregatesannotated
withthisattribute.Thisisbecausepreviouslyconstructedsubobjectsneedto
bedestroyedifanexceptiongetsthrownbeforetheinitializationofthe
completeobjectiscomplete.Forinstance:
voidf(){
try{
[[clang::no_destroy]]
staticonly_no_destroyarray[10];//error,only_no_destroyhasaprivatedestructor.
}catch(...){
//Handletheerror
}
}
Here,iftheconstructionofarray[9]failswithanexception,array[0..8]
willbedestroyed,sotheelement’sdestructorneedstobeaccessible.
nodebug¶
SupportedSyntaxes¶
nodebug
gnu::nodebug
gnu::nodebug
Yes
Thenodebugattributeallowsyoutosuppressdebugginginformationfora
functionormethod,foravariablethatisnotaparameteroranon-static
datamember,orforatypedeforusingdeclaration.
noescape¶
SupportedSyntaxes¶
noescape
clang::noescape
clang::noescape
Yes
noescapeplacedonafunctionparameterofapointertypeisusedtoinform
thecompilerthatthepointercannotescape:thatis,noreferencetotheobject
thepointerpointstothatisderivedfromtheparametervaluewillsurvive
afterthefunctionreturns.Usersareresponsibleformakingsureparameters
annotatedwithnoescapedonotactuallyescape.Callingfree()onsuch
aparameterdoesnotconstituteanescape.
Forexample:
int*gp;
voidnonescapingFunc(__attribute__((noescape))int*p){
*p+=100;//OK.
}
voidescapingFunc(__attribute__((noescape))int*p){
gp=p;//NotOK.
}
Additionally,whentheparameterisablockpointer
,thesamerestriction
appliestocopiesoftheblock.Forexample:
typedefvoid(^BlockTy)();
BlockTyg0,g1;
voidnonescapingFunc(__attribute__((noescape))BlockTyblock){
block();//OK.
}
voidescapingFunc(__attribute__((noescape))BlockTyblock){
g0=block;//NotOK.
g1=Block_copy(block);//NotOKeither.
}
nosvm¶
SupportedSyntaxes¶
nosvm
Yes
OpenCL2.0supportstheoptional__attribute__((nosvm))qualifierfor
pointervariable.Itinformsthecompilerthatthepointerdoesnotrefer
toasharedvirtualmemoryregion.SeeOpenCLv2.0s6.7.2fordetails.
SinceitisnotwidelyusedandhasbeenremovedfromOpenCL2.1,itisignored
byClang.
objc_externally_retained¶
SupportedSyntaxes¶
objc_externally_retained
clang::objc_externally_retained
clang::objc_externally_retained
Yes
Theobjc_externally_retainedattributecanbeappliedtostronglocal
variables,functions,methods,orblockstooptinto
externally-retainedsemantics.
Whenappliedtothedefinitionofafunction,method,orblock,everyparameter
ofthefunctionwithimplicitstrongretainableobjectpointertypeis
consideredexternally-retained,andbecomesconst.Byexplicitlyannotating
aparameterwith__strong,youcanoptbackintothedefault
non-externally-retainedbehaviorforthatparameter.Forinstance,
first_paramisexternally-retainedbelow,butnotsecond_param:
__attribute__((objc_externally_retained))
voidf(NSArray*first_param,__strongNSArray*second_param){
//...
}
Likewise,whenappliedtoastronglocalvariable,thatvariablebecomes
constandisconsideredexternally-retained.
Whencompiledwithout-fobjc-arc,thisattributeisignored.
pass_object_size,pass_dynamic_object_size¶
SupportedSyntaxes¶
pass_object_sizepass_dynamic_object_size
clang::pass_object_sizeclang::pass_dynamic_object_size
clang::pass_object_sizeclang::pass_dynamic_object_size
Yes
Note
Themanglingoffunctionswithparametersthatareannotatedwith
pass_object_sizeissubjecttochange.Youcangetaroundthisby
using__asm__("foo")toexplicitlynameyourfunctions,thuspreserving
yourABI;also,non-overloadableCfunctionswithpass_object_sizeare
notmangled.
Thepass_object_size(Type)attributecanbeplacedonfunctionparametersto
instructclangtocall__builtin_object_size(param,Type)ateachcallsite
ofsaidfunction,andimplicitlypasstheresultofthiscallinasaninvisible
argumentoftypesize_tdirectlyaftertheparameterannotatedwith
pass_object_size.Clangwillalsoreplaceanycallsto
__builtin_object_size(param,Type)inthefunctionbysaidimplicit
parameter.
Exampleusage:
intbzero1(char*constp__attribute__((pass_object_size(0))))
__attribute__((noinline)){
inti=0;
for(/**/;i