GCC(1)
โจ GCC(1) โจ โ GNU project C and C++ compiler ๐
okay so bestie, this is the manual page for GCC(1), brought to you by GNU. It's literally the GNU project C and C++ compiler, and she's iconic. ๐
NAME ๐
gcc โ GNU project C and C++ compiler ๐
SYNOPSIS ๐ฆ
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Real talk: only the most useful options are listed here; see below for the remainder. And g++ accepts mostly the same options as gcc. So don't panic. ๐ซถ
DESCRIPTION ๐
When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The "overall options" allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler. It's giving pipeline realness. โจ
Other options are passed on to one or more stages of processing. Some options control the preprocessor and others the compiler itself. Yet other options control the assembler and linker; most of these are not documented here, since you rarely need to use any of them. Lowkey, you won't miss them. ๐
Most of the command-line options that you can use with GCC are useful for C programs; when an option is only useful with another language (usually C++), the explanation says so explicitly. If the description for a particular option does not mention a source language, you can use that option with all supported languages. No language gatekeeping here. ๐
The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead. Periodt. ๐
The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. The way one hyphen changes everything. ๐ญ
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant. So don't just yolo the order, bestie. ๐ธ
Many options have long names starting with -f or with -W---for example, -fmove-loop-invariants, -Wformat and so on. Most of these have both positive and negative forms; the negative form of -ffoo is -fno-foo. This manual documents only one of these two forms, whichever one is not the default. Keep that in mind. ๐ง
Some options take one or more arguments typically separated either by a space or by the equals sign (=) from the option name. Unless documented otherwise, an argument can be either numeric or a string. Numeric arguments must typically be small unsigned decimal or hexadecimal integers. Hexadecimal arguments must begin with the 0x prefix. Arguments to options that specify a size threshold of some sort may be arbitrarily large decimal or hexadecimal integers followed by a byte size suffix designating a multiple of bytes such as "kB" and "KiB" for kilobyte and kibibyte, respectively, "MB" and "MiB" for megabyte and mebibyte, "GB" and "GiB" for gigabyte and gigibyte, and so on. Such arguments are designated by byte-size in the following text. Refer to the NIST, IEC, and other relevant national and international standards for the full listing and explanation of the binary and decimal byte size prefixes. Not me citing standards but ok. ๐
OPTIONS โจ
Option Summary ๐
Here is a summary of all the options, grouped by type. Explanations are in the following sections. So grab your strawberry matcha, bestie. ๐
Overall Options ๐
-c -S -E -o file -dumpbase dumpbase -dumpbase-ext auxdropsuf
-dumpdir dumppfx -x language -v -### --help[=class[,...]]
--target-help --version -pass-exit-codes -pipe -specs=file
-wrapper @file -ffile-prefix-map=old=new -fcanon-prefix-map
-fplugin=file -fplugin-arg-name=arg -fdump-ada-spec[-slim]
-fada-spec-parent=unit -fdump-go-spec=file
C Language Options ๐
-ansi -std=standard -aux-info filename -fno-asm -fno-builtin
-fno-builtin-function -fcond-mismatch -ffreestanding -fgimple
-fgnu-tm -fgnu89-inline -fhosted -flax-vector-conversions
-fms-extensions -foffload=arg -foffload-options=arg -fopenacc
-fopenacc-dim=geom -fopenmp -fopenmp-simd
-fopenmp-target-simd-clone[=device-type]
-fpermitted-flt-eval-methods=standard -fplan9-extensions
-fsigned-bitfields -funsigned-bitfields -fsigned-char
-funsigned-char -fstrict-flex-arrays[=n] -fsso-struct=endianness
C++ Language Options ๐ฆ
-fabi-version=n -fno-access-control -faligned-new=n
-fargs-in-order=n -fchar8_t -fcheck-new -fconstexpr-depth=n
-fconstexpr-cache-depth=n -fconstexpr-loop-limit=n
-fconstexpr-ops-limit=n -fno-elide-constructors
-fno-enforce-eh-specs -fno-gnu-keywords -fno-implicit-templates
-fno-implicit-inline-templates -fno-implement-inlines
-fmodule-header[=kind] -fmodule-only -fmodules-ts
-fmodule-implicit-inline -fno-module-lazy
-fmodule-mapper=specification -fmodule-version-ignore
-fms-extensions -fnew-inheriting-ctors -fnew-ttp-matching
-fno-nonansi-builtins -fnothrow-opt -fno-operator-names
-fno-optional-diags -fpermissive -fno-pretty-templates -fno-rtti
-fsized-deallocation -ftemplate-backtrace-limit=n -ftemplate-depth=n
-fno-threadsafe-statics -fuse-cxa-atexit -fno-weak -nostdinc++
-fvisibility-inlines-hidden -fvisibility-ms-compat
-fext-numeric-literals -flang-info-include-translate[=header]
-flang-info-include-translate-not -flang-info-module-cmi[=module]
-stdlib=libstdc++,libc++ -Wabi-tag -Wcatch-value -Wcatch-value=n
-Wno-class-conversion -Wclass-memaccess -Wcomma-subscript
-Wconditionally-supported -Wno-conversion-null
-Wctad-maybe-unsupported -Wctor-dtor-privacy -Wdangling-reference
-Wno-delete-incomplete -Wdelete-non-virtual-dtor
-Wno-deprecated-array-compare -Wdeprecated-copy
-Wdeprecated-copy-dtor -Wno-deprecated-enum-enum-conversion
-Wno-deprecated-enum-float-conversion -Weffc++ -Wno-exceptions
-Wextra-semi -Wno-inaccessible-base -Wno-inherited-variadic-ctor
-Wno-init-list-lifetime -Winvalid-constexpr
-Winvalid-imported-macros -Wno-invalid-offsetof -Wno-literal-suffix
-Wmismatched-new-delete -Wmismatched-tags -Wmultiple-inheritance
-Wnamespaces -Wnarrowing -Wnoexcept -Wnoexcept-type
-Wnon-virtual-dtor -Wpessimizing-move -Wno-placement-new
-Wplacement-new=n -Wrange-loop-construct -Wredundant-move
-Wredundant-tags -Wreorder -Wregister -Wstrict-null-sentinel
-Wno-subobject-linkage -Wtemplates -Wno-non-template-friend
-Wold-style-cast -Woverloaded-virtual -Wno-pmf-conversions
-Wself-move -Wsign-promo -Wsized-deallocation
-Wsuggest-final-methods -Wsuggest-final-types -Wsuggest-override
-Wno-terminate -Wuseless-cast -Wno-vexing-parse
-Wvirtual-inheritance -Wno-virtual-move-assign -Wvolatile
-Wzero-as-null-pointer-constant
Objective-C and Objective-C++ Language Options ๐ธ
-fconstant-string-class=class-name -fgnu-runtime -fnext-runtime
-fno-nil-receivers -fobjc-abi-version=n -fobjc-call-cxx-cdtors
-fobjc-direct-dispatch -fobjc-exceptions -fobjc-gc -fobjc-nilcheck
-fobjc-std=objc1 -fno-local-ivars
-fivar-visibility=[public|protected|private|package]
-freplace-objc-classes -fzero-link -gen-decls -Wassign-intercept
-Wno-property-assign-default -Wno-protocol -Wobjc-root-class
-Wselector -Wstrict-selector-match -Wundeclared-selector
Diagnostic Message Formatting Options โจ
-fmessage-length=n -fdiagnostics-plain-output
-fdiagnostics-show-location=[once|every-line]
-fdiagnostics-color=[auto|never|always]
-fdiagnostics-urls=[auto|never|always]
-fdiagnostics-format=[text|sarif-stderr|sarif-file|json|json-stderr|json-file]
-fno-diagnostics-show-option -fno-diagnostics-show-caret
-fno-diagnostics-show-labels -fno-diagnostics-show-line-numbers
-fno-diagnostics-show-cwe -fno-diagnostics-show-rule
-fdiagnostics-minimum-margin-width=width
-fdiagnostics-parseable-fixits -fdiagnostics-generate-patch
-fdiagnostics-show-template-tree -fno-elide-type
-fdiagnostics-path-format=[none|separate-events|inline-events]
-fdiagnostics-show-path-depths -fno-show-column
-fdiagnostics-column-unit=[display|byte]
-fdiagnostics-column-origin=origin
-fdiagnostics-escape-format=[unicode|bytes]
And that's just the summary, bestie. The explanations are in the following sections. More options incoming in the next parts โ stay tuned. ๐
โจ Warning Options โจ
okay bestie, this is the big one ๐ the warning-flag constellation. it's a lot of flags, they all go straight on the command line, and some of them are -Wno- twins that are just the off-switch version of their sibling. no skimming, we're going through every single one. ๐
-fsyntax-only-fmax-errors=n-Wpedantic-pedantic-errors-w-Wextra-Wall-Wabi=n-Waddress-Wno-address-of-packed-member-Waggregate-return-Walloc-size-larger-than=byte-size-Walloc-zero-Walloca-Walloca-larger-than=byte-size-Wno-aggressive-loop-optimizations-Warith-conversion-Warray-bounds-Warray-bounds=n-Warray-compare-Wno-attributes-Wattribute-alias=n-Wno-attribute-alias-Wno-attribute-warning
not the -Wabi=n sitting right there next to -Wall like it belongs ๐ญ anyway, moving on, the alphabet is long and she does not care about our feelings.
-Wbidi-chars=[none|unpaired|any|ucn]-Wbool-compare-Wbool-operation-Wno-builtin-declaration-mismatch-Wno-builtin-macro-redefined-Wc90-c99-compat-Wc99-c11-compat-Wc11-c2x-compat-Wc++-compat-Wc++11-compat-Wc++14-compat-Wc++17-compat-Wc++20-compat-Wno-c++11-extensions-Wno-c++14-extensions-Wno-c++17-extensions-Wno-c++20-extensions-Wno-c++23-extensions-Wcast-align-Wcast-align=strict-Wcast-function-type-Wcast-qual-Wchar-subscripts-Wclobbered-Wcomment-Wno-complain-wrong-lang-Wconversion-Wno-coverage-mismatch-Wno-cpp-Wdangling-else-Wdangling-pointer-Wdangling-pointer=n
the whole -Wc++11-compat โ -Wc++20-compat lineup is giving boy band, they all show up together every time ๐ and yes, there's a -Wno- version of the extensions flags too, one per standard, because of course there is.
-Wdate-time-Wno-deprecated-Wno-deprecated-declarations-Wno-designated-init-Wdisabled-optimization-Wno-discarded-array-qualifiers-Wno-discarded-qualifiers-Wno-div-by-zero-Wdouble-promotion-Wduplicated-branches-Wduplicated-cond-Wempty-body-Wno-endif-labels-Wenum-compare-Wenum-conversion-Wenum-int-mismatch-Werror-Werror=*-Wexpansion-to-defined-Wfatal-errors-Wfloat-conversion-Wfloat-equal-Wformat-Wformat=2-Wno-format-contains-nul-Wno-format-extra-args-Wformat-nonliteral-Wformat-overflow=n-Wformat-security-Wformat-signedness-Wformat-truncation=n-Wformat-y2k-Wframe-address-Wframe-larger-than=byte-size
-Werror is the main character of this whole section ngl, and -Werror=* is her wildcard twin. the -Wformat-* cluster is a whole investigative journalism subplot, and there's genuinely a -Wformat-y2k in there, iconic, no notes ๐ธ
-Wno-free-nonheap-object-Wno-if-not-aligned-Wno-ignored-attributes-Wignored-qualifiers-Wno-incompatible-pointer-types-Wimplicit-Wimplicit-fallthrough-Wimplicit-fallthrough=n-Wno-implicit-function-declaration-Wno-implicit-int-Winfinite-recursion-Winit-self-Winline-Wno-int-conversion-Wint-in-bool-context-Wno-int-to-pointer-cast-Wno-invalid-memory-model-Winvalid-pch-Winvalid-utf8-Wno-unicode-Wjump-misses-init-Wlarger-than=byte-size-Wlogical-not-parentheses-Wlogical-op-Wlong-long-Wno-lto-type-mismatch-Wmain-Wmaybe-uninitialized-Wmemset-elt-size-Wmemset-transposed-args-Wmisleading-indentation-Wmissing-attributes-Wmissing-braces-Wmissing-field-initializers-Wmissing-format-attribute-Wmissing-include-dirs-Wmissing-noreturn-Wno-missing-profile-Wno-multichar-Wmultistatement-macros-Wnonnull-Wnonnull-compare-Wnormalized=[none|id|nfc|nfkc]-Wnull-dereference-Wno-odr
the -Wmissing-* saga is so long at this point, every time i think it's done there's another one ๐ญ and yes, -Wno-int-conversion and -Wno-int-to-pointer-cast are two different flags, do not @ me.
-Wopenacc-parallelism-Wopenmp-simd-Wno-overflow-Woverlength-strings-Wno-override-init-side-effects-Wpacked-Wno-packed-bitfield-compat-Wpacked-not-aligned-Wpadded-Wparentheses-Wno-pedantic-ms-format-Wpointer-arith-Wno-pointer-compare-Wno-pointer-to-int-cast-Wno-pragmas-Wno-prio-ctor-dtor-Wredundant-decls-Wrestrict-Wno-return-local-addr-Wreturn-type-Wno-scalar-storage-order-Wsequence-point-Wshadow-Wshadow=global-Wshadow=local-Wshadow=compatible-local-Wno-shadow-ivar-Wno-shift-count-negative-Wno-shift-count-overflow-Wshift-negative-value-Wno-shift-overflow-Wshift-overflow=n-Wsign-compare-Wsign-conversion-Wno-sizeof-array-argument-Wsizeof-array-div-Wsizeof-pointer-div-Wsizeof-pointer-memaccess-Wstack-protector-Wstack-usage=byte-size-Wstrict-aliasing-Wstrict-aliasing=n-Wstrict-overflow-Wstrict-overflow=n-Wstring-compare-Wno-stringop-overflow-Wno-stringop-overread-Wno-stringop-truncation-Wstrict-flex-arrays-Wsuggest-attribute=[pure|const|noreturn|format|malloc]-Wswitch-Wno-switch-bool-Wswitch-default-Wswitch-enum-Wno-switch-outside-range-Wno-switch-unreachable-Wsync-nand-Wsystem-headers-Wtautological-compare-Wtrampolines-Wtrigraphs-Wtrivial-auto-var-init-Wtsan-Wtype-limits
-Wshadow really said "i contain multitudes" with her =global, =local and =compatible-local variants ๐ฆ and the -Wsizeof-* squad is quietly doing the most helpful work in the building, love her for that.
-Wundef-Wuninitialized-Wunknown-pragmas-Wunsuffixed-float-constants-Wunused-Wunused-but-set-parameter-Wunused-but-set-variable-Wunused-const-variable-Wunused-const-variable=n-Wunused-function-Wunused-label-Wunused-local-typedefs-Wunused-macros-Wunused-parameter-Wno-unused-result-Wunused-value-Wunused-variable-Wno-varargs-Wvariadic-macros-Wvector-operation-performance-Wvla-Wvla-larger-than=byte-size-Wno-vla-larger-than-Wvolatile-register-var-Wwrite-strings-Wxor-used-as-pow-Wzero-length-bounds
the entire -Wunused-* nation, rise up ๐ซถ you are the reason our codebases are clean and our vibes are immaculate, and -Wunused-const-variable=n is right there next to her twin like a matching set. periodt. and with -Wzero-length-bounds the warning list finally, finally runs out of alphabet ๐ฅ
โจ Static Analyzer Options โจ
okay so the static analyzer is basically gcc putting on its detective hat ๐ต๏ธโ๏ธ and this is her whole control panel. flags first, then the -fdump-* ones she uses to write down everything she found, then a truly enormous pile of -Wno-analyzer-* switches. here we go, all of them, in order:
-fanalyzer-fanalyzer-call-summaries-fanalyzer-checker=name-fno-analyzer-feasibility-fanalyzer-fine-grained-fno-analyzer-state-merge-fno-analyzer-state-purge-fno-analyzer-suppress-followups-fanalyzer-transitivity-fno-analyzer-undo-inlining-fanalyzer-verbose-edges-fanalyzer-verbose-state-changes-fanalyzer-verbosity=level-fdump-analyzer-fdump-analyzer-callgraph-fdump-analyzer-exploded-graph-fdump-analyzer-exploded-nodes-fdump-analyzer-exploded-nodes-2-fdump-analyzer-exploded-nodes-3-fdump-analyzer-exploded-paths-fdump-analyzer-feasibility-fdump-analyzer-json-fdump-analyzer-state-purge-fdump-analyzer-stderr-fdump-analyzer-supergraph-fdump-analyzer-untracked
three different exploded-nodes dumps, bestie ๐ญ -fdump-analyzer-exploded-nodes, -fdump-analyzer-exploded-nodes-2 and -fdump-analyzer-exploded-nodes-3 โ she really said one is not enough. and now the big warning wall:
-Wno-analyzer-double-fclose-Wno-analyzer-double-free-Wno-analyzer-exposure-through-output-file-Wno-analyzer-exposure-through-uninit-copy-Wno-analyzer-fd-access-mode-mismatch-Wno-analyzer-fd-double-close-Wno-analyzer-fd-leak-Wno-analyzer-fd-phase-mismatch-Wno-analyzer-fd-type-mismatch-Wno-analyzer-fd-use-after-close-Wno-analyzer-fd-use-without-check-Wno-analyzer-file-leak-Wno-analyzer-free-of-non-heap-Wno-analyzer-imprecise-fp-arithmetic-Wno-analyzer-infinite-recursion-Wno-analyzer-jump-through-null-Wno-analyzer-malloc-leak-Wno-analyzer-mismatching-deallocation-Wno-analyzer-null-argument-Wno-analyzer-null-dereference-Wno-analyzer-out-of-bounds-Wno-analyzer-possible-null-argument-Wno-analyzer-possible-null-dereference-Wno-analyzer-putenv-of-auto-var-Wno-analyzer-shift-count-negative-Wno-analyzer-shift-count-overflow-Wno-analyzer-stale-setjmp-buffer-Wno-analyzer-tainted-allocation-size-Wno-analyzer-tainted-assertion-Wno-analyzer-tainted-array-index-Wno-analyzer-tainted-divisor-Wno-analyzer-tainted-offset-Wno-analyzer-tainted-size-Wanalyzer-too-complex-Wno-analyzer-unsafe-call-within-signal-handler-Wno-analyzer-use-after-free-Wno-analyzer-use-of-pointer-in-stale-stack-frame-Wno-analyzer-use-of-uninitialized-value-Wno-analyzer-va-arg-type-mismatch-Wno-analyzer-va-list-exhausted-Wno-analyzer-va-list-leak-Wno-analyzer-va-list-use-after-va-end-Wno-analyzer-write-to-const-Wno-analyzer-write-to-string-literal
the whole -Wno-analyzer-fd-* family is giving file-descriptor true crime documentary ๐ and -Wanalyzer-too-complex is the one flag in the bunch without a -Wno- twin, she stands alone, main character energy fr fr.
โจ C and Objective-C-only Warning Options โจ
these ones are โจexclusiveโจ โ C and Objective-C only, no C++ girlies allowed at this party ๐ here's every single one:
-Wbad-function-cast-Wmissing-declarations-Wmissing-parameter-type-Wmissing-prototypes-Wnested-externs-Wold-style-declaration-Wold-style-definition-Wstrict-prototypes-Wtraditional-Wtraditional-conversion-Wdeclaration-after-statement-Wpointer-sign
note how -Wold-style-declaration and -Wold-style-definition are two separate flags ๐ they are not the same, do not merge them, they will know. and -Wtraditional has her own little friend -Wtraditional-conversion tagging along, obsessed with them honestly.
โจ Debugging Options โจ
debugging girlies this one's for you ๐โจ this is the whole -g extended universe โ every flavour of debug info, every -gno- counterweight, and a bunch of -f flags that came to live here too. all of them, in order:
-g-glevel-gdwarf-gdwarf-version-gbtf-gctf-gctflevel-ggdb-grecord-gcc-switches-gno-record-gcc-switches-gstrict-dwarf-gno-strict-dwarf-gas-loc-support-gno-as-loc-support-gas-locview-support-gno-as-locview-support-gcolumn-info-gno-column-info-gdwarf32-gdwarf64-gstatement-frontiers-gno-statement-frontiers-gvariable-location-views-gno-variable-location-views-ginternal-reset-location-views-gno-internal-reset-location-views-ginline-points-gno-inline-points-gvms-gz[=type]-gsplit-dwarf-gdescribe-dies-gno-describe-dies-fdebug-prefix-map=old=new-fdebug-types-section-fno-eliminate-unused-debug-types-femit-struct-debug-baseonly-femit-struct-debug-reduced-femit-struct-debug-detailed[=spec-list]-fno-eliminate-unused-debug-symbols-femit-class-debug-always-fno-merge-debug-strings-fno-dwarf2-cfi-asm-fvar-tracking-fvar-tracking-assignments
see how every -g-something has a -gno--something staring back at her? ๐ฆ that's the whole vibe of this section โ on, off, on, off, like a little debug-info light switch rave. also -fno-eliminate-unused-debug-types and -fno-eliminate-unused-debug-symbols are different flags, bestie, don't let the near-identical names gaslight you ๐ญ and there's a [=spec-list] hiding on -femit-struct-debug-detailed, keep that bracket, she bites if you drop it ๐
โก Optimization Options โก
bestie. babes. buckle UP. this is the big one, the optimization menu, the little list of every knob that decides how hard the compiler is gonna try. some of these are iconic, some of these are chaos, and you can absolutely mix and match them, so let's just read through the whole lineup together. no descriptions yet โ this is the guest list, the actual โจloreโจ per flag shows up later. ๐
-faggressive-loop-optimizations-falign-functions[=n[:m:[n2[:m2]]]]-falign-jumps[=n[:m:[n2[:m2]]]]-falign-labels[=n[:m:[n2[:m2]]]]-falign-loops[=n[:m:[n2[:m2]]]]-fno-allocation-dce-fallow-store-data-races-fassociative-math-fauto-profile-fauto-profile[=path]-fauto-inc-dec-fbranch-probabilities-fcaller-saves-fcombine-stack-adjustments-fconserve-stack-fcompare-elim-fcprop-registers-fcrossjumping-fcse-follow-jumps-fcse-skip-blocks-fcx-fortran-rules-fcx-limited-range-fdata-sections-fdce-fdelayed-branch-fdelete-null-pointer-checks-fdevirtualize-fdevirtualize-speculatively-fdevirtualize-at-ltrans-fdse-fearly-inlining-fipa-sra-fexpensive-optimizations-ffat-lto-objects-ffast-math-ffinite-math-only-ffloat-store-fexcess-precision=style-ffinite-loops-fforward-propagate-ffp-contract=style-ffunction-sections-fgcse-fgcse-after-reload-fgcse-las-fgcse-lm-fgraphite-identity-fgcse-sm-fhoist-adjacent-loads-fif-conversion-fif-conversion2-findirect-inlining-finline-functions-finline-functions-called-once-finline-limit=n-finline-small-functions-fipa-modref-fipa-cp-fipa-cp-clone-fipa-bit-cp-fipa-vrp-fipa-pta-fipa-profile-fipa-pure-const-fipa-reference-fipa-reference-addressable-fipa-stack-alignment-fipa-icf-fira-algorithm=algorithm-flive-patching=level-fira-region=region-fira-hoist-pressure-fira-loop-pressure-fno-ira-share-save-slots-fno-ira-share-spill-slots-fisolate-erroneous-paths-dereference-fisolate-erroneous-paths-attribute-fivopts-fkeep-inline-functions-fkeep-static-functions-fkeep-static-consts-flimit-function-alignment-flive-range-shrinkage-floop-block-floop-interchange-floop-strip-mine-floop-unroll-and-jam-floop-nest-optimize-floop-parallelize-all-flra-remat-flto-flto-compression-level-flto-partition=alg-fmerge-all-constants-fmerge-constants-fmodulo-sched-fmodulo-sched-allow-regmoves-fmove-loop-invariants-fmove-loop-stores-fno-branch-count-reg-fno-defer-pop-fno-fp-int-builtin-inexact-fno-function-cse-fno-guess-branch-probability-fno-inline-fno-math-errno-fno-peephole-fno-peephole2-fno-printf-return-value-fno-sched-interblock-fno-sched-spec-fno-signed-zeros-fno-toplevel-reorder-fno-trapping-math-fno-zero-initialized-in-bss-fomit-frame-pointer-foptimize-sibling-calls-fpartial-inlining-fpeel-loops-fpredictive-commoning-fprefetch-loop-arrays-fprofile-correction-fprofile-use-fprofile-use=path-fprofile-partial-training-fprofile-values-fprofile-reorder-functions-freciprocal-math-free-frename-registers-freorder-blocks-freorder-blocks-algorithm=algorithm-freorder-blocks-and-partition-freorder-functions-frerun-cse-after-loop-freschedule-modulo-scheduled-loops-frounding-math-fsave-optimization-record-fsched2-use-superblocks-fsched-pressure-fsched-spec-load-fsched-spec-load-dangerous-fsched-stalled-insns-dep[=n]-fsched-stalled-insns[=n]-fsched-group-heuristic-fsched-critical-path-heuristic-fsched-spec-insn-heuristic-fsched-rank-heuristic-fsched-last-insn-heuristic-fsched-dep-count-heuristic-fschedule-fusion-fschedule-insns-fschedule-insns2-fsection-anchors-fselective-scheduling-fselective-scheduling2-fsel-sched-pipelining-fsel-sched-pipelining-outer-loops-fsemantic-interposition-fshrink-wrap-fshrink-wrap-separate-fsignaling-nans-fsingle-precision-constant-fsplit-ivs-in-unroller-fsplit-loops-fsplit-paths-fsplit-wide-types-fsplit-wide-types-early-fssa-backprop-fssa-phiopt-fstdarg-opt-fstore-merging-fstrict-aliasing-fipa-strict-aliasing-fthread-jumps-ftracer-ftree-bit-ccp-ftree-builtin-call-dce-ftree-ccp-ftree-ch-ftree-coalesce-vars-ftree-copy-prop-ftree-dce-ftree-dominator-opts-ftree-dse-ftree-forwprop-ftree-fre-fcode-hoisting-ftree-loop-if-convert-ftree-loop-im-ftree-phiprop-ftree-loop-distribution-ftree-loop-distribute-patterns-ftree-loop-ivcanon-ftree-loop-linear-ftree-loop-optimize-ftree-loop-vectorize-ftree-parallelize-loops=n-ftree-pre-ftree-partial-pre-ftree-pta-ftree-reassoc-ftree-scev-cprop-ftree-sink-ftree-slsr-ftree-sra-ftree-switch-conversion-ftree-tail-merge-ftree-ter-ftree-vectorize-ftree-vrp-ftrivial-auto-var-init-funconstrained-commons-funit-at-a-time-funroll-all-loops-funroll-loops-funsafe-math-optimizations-funswitch-loops-fipa-ra-fvariable-expansion-in-unroller-fvect-cost-model-fvpt-fweb-fwhole-program-fwpa-fuse-linker-plugin-fzero-call-used-regs--param name=value-O-O0-O1-O2-O3-Os-Ofast-Og-Oz
and yes, that whole list is real, and yes, you can pass more than one, and yes, it's giving compiler goblin energy and we love her for it. ๐ซถ
๐งช Program Instrumentation Options ๐งช
these are the "hey bestie, let's watch what this code is actually doing at runtime" flags โ profiling, coverage, sanitizers, stack protection, and all the little spy-cams you can bolt onto a binary. ๐
-p-pg-fprofile-arcs--coverage-ftest-coverage-fprofile-abs-path-fprofile-dir=path-fprofile-generate-fprofile-generate=path-fprofile-info-section-fprofile-info-section=name-fprofile-note=path-fprofile-prefix-path=path-fprofile-update=method-fprofile-filter-files=regex-fprofile-exclude-files=regex-fprofile-reproducible=[multithreaded|parallel-runs|serial]-fsanitize=style-fsanitize-recover-fsanitize-recover=style-fsanitize-trap-fsanitize-trap=style-fasan-shadow-offset=number-fsanitize-sections=s1,s2,...-fsanitize-undefined-trap-on-error-fbounds-check-fcf-protection=[full|branch|return|none|check]-fharden-compares-fharden-conditional-branches-fstack-protector-fstack-protector-all-fstack-protector-strong-fstack-protector-explicit-fstack-check-fstack-limit-register=reg-fstack-limit-symbol=sym-fno-stack-limit-fsplit-stack-fvtable-verify=[std|preinit|none]-fvtv-counts-fvtv-debug-finstrument-functions-finstrument-functions-once-finstrument-functions-exclude-function-list=sym,sym,...-finstrument-functions-exclude-file-list=file,file,...-fprofile-prefix-map=old=new
๐ธ Preprocessor Options ๐ธ
the before-times. the era of #define and vibes. this whole group is about how the source gets chewed up before it ever becomes real code โ macro definitions, include paths, charset stuff, dependency generation, all of it. ๐
-Aquestion=answer-A-question[=answer]-C-CC-Dmacro[=defn]-dD-dI-dM-dN-dU-fdebug-cpp-fdirectives-only-fdollars-in-identifiers-fexec-charset=charset-fextended-identifiers-finput-charset=charset-flarge-source-files-fmacro-prefix-map=old=new-fmax-include-depth=depth-fno-canonical-system-headers-fpch-deps-fpch-preprocess-fpreprocessed-ftabstop=width-ftrack-macro-expansion-fwide-exec-charset=charset-fworking-directory-H-imacros file-include file-M-MD-MF-MG-MM-MMD-MP-MQ-MT-Mno-modules-no-integrated-cpp-P-pthread-remap-traditional-traditional-cpp-trigraphs-Umacro-undef-Wp,option-Xpreprocessor option
๐ง Assembler Options ๐ง
just two, bestie, and they're both "hey, pass this straight through to the assembler, k thanks". short and sweet. โจ
-Wa,option-Xassembler option
๐ Linker Options ๐
the part where all your little object files finally hold hands and become one executable. linking!! the moment of truth!! ๐
object-file-name-fuse-ld=linker-llibrary-nostartfiles-nodefaultlibs-nolibc-nostdlib-nostdlib++-e entry--entry=entry-pie-pthread-r-rdynamic-s-static-static-pie-static-libgcc-static-libstdc++-static-libasan-static-libtsan-static-liblsan-static-libubsan-shared-shared-libgcc-symbolic-T script-Wl,option-Xlinker option-u symbol-z keyword
๐ Directory Options ๐
where does the compiler go looking for stuff? include dirs, lib dirs, sysroots, prefixes, plugins โ this is the map of everywhere she's allowed to rummage. ๐บ๏ธ
-Bprefix-Idir-I--idirafter dir-imacros file-imultilib dir-iplugindir=dir-iprefix file-iquote dir-isysroot dir-isystem dir-iwithprefix dir-iwithprefixbefore dir-Ldir-no-canonical-prefixes--no-sysroot-suffix-nostdinc-nostdinc++--sysroot=dir
๐ Code Generation Options ๐
the juicy ABI-and-layout zone. calling conventions, struct returns, PIC/PIE, visibility, TLS models, all the "how exactly does the generated code behave" choices live right here. ๐
-fcall-saved-reg-fcall-used-reg-ffixed-reg-fexceptions-fnon-call-exceptions-fdelete-dead-exceptions-funwind-tables-fasynchronous-unwind-tables-fno-gnu-unique-finhibit-size-directive-fcommon-fno-ident-fpcc-struct-return-fpic-fPIC-fpie-fPIE-fno-plt-fno-jump-tables-fno-bit-tests-frecord-gcc-switches-freg-struct-return-fshort-enums-fshort-wchar-fverbose-asm-fpack-struct[=n]-fleading-underscore-ftls-model=model-fstack-reuse=reuse_level-ftrampolines-ftrapv-fwrapv-fvisibility=[default|internal|hidden|protected]-fstrict-volatile-bitfields-fsync-libcalls
๐ ๏ธ Developer Options ๐ ๏ธ
okay this is the backstage pass section. dumps, debug counters, pass disabling/enabling, timing reports, memory reports, and a truly alarming number of ways to peer directly into the compiler's soul. if you're the kind of person who reads compiler IR for fun โ hi, you're the main character. ๐ญ๐
-dletters-dumpspecs-dumpmachine-dumpversion-dumpfullversion-fcallgraph-info[=su,da]-fchecking-fchecking=n-fdbg-cnt-list-fdbg-cnt=counter-value-list-fdisable-ipa-pass_name-fdisable-rtl-pass_name-fdisable-rtl-pass-name=range-list-fdisable-tree-pass_name-fdisable-tree-pass-name=range-list-fdump-debug-fdump-earlydebug-fdump-noaddr-fdump-unnumbered-fdump-unnumbered-links-fdump-final-insns[=file]-fdump-ipa-all-fdump-ipa-cgraph-fdump-ipa-inline-fdump-lang-all-fdump-lang-switch-fdump-lang-switch-options-fdump-lang-switch-options=filename-fdump-passes-fdump-rtl-pass-fdump-rtl-pass=filename-fdump-statistics-fdump-tree-all-fdump-tree-switch-fdump-tree-switch-options-fdump-tree-switch-options=filename-fcompare-debug[=opts]-fcompare-debug-second-fenable-kind-pass-fenable-kind-pass=range-list-fira-verbose=n-flto-report-flto-report-wpa-fmem-report-wpa-fmem-report-fpre-ipa-mem-report-fpost-ipa-mem-report-fopt-info-fopt-info-options[=file]-fmultiflags-fprofile-report-frandom-seed=string-fsched-verbose=n-fsel-sched-verbose-fsel-sched-dump-cfg-fsel-sched-pipelining-verbose-fstats-fstack-usage-ftime-report-ftime-report-details-fvar-tracking-assignments-toggle-gtoggle-print-file-name=library-print-libgcc-file-name-print-multi-directory-print-multi-lib-print-multi-os-directory-print-prog-name=program-print-search-dirs-Q-print-sysroot-print-sysroot-headers-suffix-save-temps-save-temps=cwd-save-temps=obj-time[=file]
๐งธ Machine-Dependent Options
okay bestie, deep breath ๐ this is the part of the page where GCC opens its entire wardrobe and shows you every single chip family it can dress for. Every target gets its own private stash of flags. None of them are described here, they're just... listed. So here they all are, in order, exactly as GCC names them. No skipping. We're going through the whole closet. โจ
๐ซ AArch64 Options
the AArch64 girlies are served โ look at all these:
-mabi=nameยท-mbig-endianยท-mlittle-endianยท-mgeneral-regs-only-mcmodel=tinyยท-mcmodel=smallยท-mcmodel=large-mstrict-alignยท-mno-strict-alignยท-momit-leaf-frame-pointer-mtls-dialect=descยท-mtls-dialect=traditionalยท-mtls-size=size-mfix-cortex-a53-835769ยท-mfix-cortex-a53-843419-mlow-precision-recip-sqrtยท-mlow-precision-sqrtยท-mlow-precision-div-mpc-relative-literal-loads-msign-return-address=scope-mbranch-protection=none|standard|pac-ret[+leaf +b-key]|bti-mharden-sls=opts-march=nameยท-mcpu=nameยท-mtune=name-moverride=stringยท-mverbose-cost-dump-mstack-protector-guard=guardยท-mstack-protector-guard-reg=sysregยท-mstack-protector-guard-offset=offset-mtrack-speculationยท-moutline-atomics
๐ฆ Adapteva Epiphany Options
tiny parallel-computing fairy vibes ๐ง:
-mhalf-reg-fileยท-mprefer-short-insn-regs-mbranch-cost=numยท-mcmoveยท-mnops=numยท-msoft-cmpsf-msplit-lohiยท-mpost-incยท-mpost-modifyยท-mstack-offset=num-mround-nearestยท-mlong-callsยท-mshort-callsยท-msmall16-mfp-mode=modeยท-mvect-doubleยท-max-vect-align=num-msplit-vecmove-earlyยท-m1reg-reg
๐ AMD GCN Options
short, sweet, to the point, periodt:
-march=gpuยท-mtune=gpuยท-mstack-size=bytes
๐ ARC Options
an absolute icon of a list, genuinely obsessed:
-mbarrel-shifterยท-mjli-alwaysยท-mcpu=cpuยท-mA6ยท-mARC600ยท-mA7ยท-mARC700-mdpfpยท-mdpfp-compactยท-mdpfp-fastยท-mno-dpfp-lrsr-meaยท-mno-mpyยท-mmul32x16ยท-mmul64ยท-matomicยท-mnorm-mspfpยท-mspfp-compactยท-mspfp-fastยท-msimdยท-msoft-floatยท-mswap-mcrcยท-mdsp-packaยท-mdvbfยท-mlockยท-mmac-d16ยท-mmac-24ยท-mrtscยท-mswape-mtelephonyยท-mxyยท-misizeยท-mannotate-alignยท-marclinuxยท-marclinux_prof-mlong-callsยท-mmedium-callsยท-msdata-mirq-ctrl-savedยท-mrgf-banked-regsยท-mlpc-width=widthยท-G num-mvolatile-cacheยท-mtp-regno=regnoยท-malign-callยท-mauto-modify-reg-mbbit-peepholeยท-mno-brccยท-mcase-vector-pcrelยท-mcompact-casesi-mno-cond-execยท-mearly-cbranchsiยท-mexpand-adddiยท-mindexed-loads-mlraยท-mlra-priority-noneยท-mlra-priority-compactยท-mlra-priority-noncompact-mmillicodeยท-mmixed-codeยท-mq-classยท-mRcqยท-mRcw-msize-level=levelยท-mtune=cpuยท-mmultcost=num-mcode-density-frameยท-munalign-prob-threshold=probability-mmpy-option=multoยท-mdiv-remยท-mcode-densityยท-mll64ยท-mfpu=fpu-mrf16ยท-mbranch-index
๐ ARM Options
the main character of embedded, no cap:
-mapcs-frameยท-mno-apcs-frame-mabi=name-mapcs-stack-checkยท-mno-apcs-stack-check-mapcs-reentrantยท-mno-apcs-reentrant-mgeneral-regs-only-msched-prologยท-mno-sched-prolog-mlittle-endianยท-mbig-endianยท-mbe8ยท-mbe32-mfloat-abi=nameยท-mfp16-format=name-mthumb-interworkยท-mno-thumb-interwork-mcpu=nameยท-march=nameยท-mfpu=nameยท-mtune=name-mprint-tune-infoยท-mstructure-size-boundary=nยท-mabort-on-noreturn-mlong-callsยท-mno-long-calls-msingle-pic-baseยท-mno-single-pic-baseยท-mpic-register=reg-mnop-fun-dllimportยท-mpoke-function-name-mthumbยท-marmยท-mflip-thumb-mtpcs-frameยท-mtpcs-leaf-frame-mcaller-super-interworkingยท-mcallee-super-interworking-mtp=nameยท-mtls-dialect=dialect-mword-relocations-mfix-cortex-m3-ldrdยท-mfix-cortex-a57-aes-1742098ยท-mfix-cortex-a72-aes-1655431-munaligned-accessยท-mneon-for-64bitsยท-mslow-flash-data-masm-syntax-unifiedยท-mrestrict-itยท-mverbose-cost-dump-mpure-codeยท-mcmseยท-mfix-cmse-cve-2021-35465-mstack-protector-guard=guardยท-mstack-protector-guard-offset=offset-mfdpic-mbranch-protection=none|standard|pac-ret[+leaf] [+bti]|bti[+pac-ret[+leaf]]
๐ AVR Options
microcontroller cutie behavior ๐:
-mmcu=mcuยท-mabsdataยท-maccumulate-args-mbranch-cost=costยท-mcall-prologuesยท-mgas-isr-prologues-mint8ยท-mdouble=bitsยท-mlong-double=bitsยท-mn_flash=size-mno-interruptsยท-mmain-is-OS_taskยท-mrelaxยท-mrmwยท-mstrict-Xยท-mtiny-stack-mfract-convert-truncateยท-mshort-callsยท-mskip-bug-nodevicelibยท-nodevicespecs-Waddr-space-convertยท-Wmisspelled-isr
๐ซถ Blackfin Options
lowkey a whole novel:
-mcpu=cpu[-sirevision]ยท-msim-momit-leaf-frame-pointerยท-mno-omit-leaf-frame-pointer-mspecld-anomalyยท-mno-specld-anomalyยท-mcsync-anomalyยท-mno-csync-anomaly-mlow-64kยท-mno-low64kยท-mstack-check-l1-mid-shared-libraryยท-mno-id-shared-libraryยท-mshared-library-id=n-mleaf-id-shared-libraryยท-mno-leaf-id-shared-library-msep-dataยท-mno-sep-data-mlong-callsยท-mno-long-calls-mfast-fpยท-minline-plt-mmulticoreยท-mcoreaยท-mcorebยท-msdramยท-micplb
๐ธ C6X Options
small but mighty โจ:
-mbig-endianยท-mlittle-endian-march=cpuยท-msim-msdata=sdata-type
๐ง CRIS Options
-mcpu=cpuยท-march=cpuยท-mtune=cpu-mmax-stack-frame=n-metrax4ยท-metrax100-mpdebugยท-mcc-initยท-mno-side-effects-mstack-alignยท-mdata-alignยท-mconst-align-m32-bitยท-m16-bitยท-m8-bit-mno-prologue-epilogueยท-melfยท-maoutยท-simยท-sim2-mmul-bug-workaroundยท-mno-mul-bug-workaround
๐ C-SKY Options
-march=archยท-mcpu=cpu-mbig-endianยท-EBยท-mlittle-endianยท-EL-mhard-floatยท-msoft-floatยท-mfpu=fpuยท-mdouble-floatยท-mfdivdu-mfloat-abi=name-melrwยท-mistackยท-mmpยท-mcpยท-mcacheยท-msecurityยท-mtrust-mdspยท-medspยท-mvdsp-mdivยท-msmartยท-mhigh-registersยท-manchorยท-mpushpopยท-mmultiple-stld-mconstpoolยท-mstack-sizeยท-mccrt-mbranch-cost=nยท-mcse-ccยท-msched-prologยท-msim
๐ Darwin Options
a dramatic amount, and yes some of them genuinely appear twice, that's just how it is, we don't edit the queen:
-all_loadยท-allowable_clientยท-archยท-arch_errors_fatalยท-arch_only-bind_at_loadยท-bundleยท-bundle_loaderยท-client_name-compatibility_versionยท-current_versionยท-dead_strip-dependency-fileยท-dylib_fileยท-dylinker_install_name-dynamicยท-dynamiclibยท-exported_symbols_listยท-filelist-flat_namespaceยท-force_cpusubtype_ALLยท-force_flat_namespace-headerpad_max_install_namesยท-iframeworkยท-image_baseยท-initยท-install_name-keep_private_externsยท-multi_moduleยท-multiply_definedยท-multiply_defined_unused-noall_loadยท-no_dead_strip_inits_and_termsยท-nofixprebinding-nomultidefsยท-noprebindยท-noseglinkeditยท-pagezero_size-prebindยท-prebind_all_twolevel_modulesยท-private_bundleยท-read_only_relocs-sectalignยท-sectobjectsymbolsยท-whyloadยท-seg1addrยท-sectcreate-sectobjectsymbolsยท-sectorderยท-segaddrยท-segs_read_only_addrยท-segs_read_write_addr-seg_addr_tableยท-seg_addr_table_filenameยท-seglinkeditยท-segprot-segs_read_only_addrยท-segs_read_write_addr-single_moduleยท-staticยท-sub_libraryยท-sub_umbrella-twolevel_namespaceยท-umbrellaยท-undefinedยท-unexported_symbols_list-weak_reference_mismatchesยท-whatsloaded-Fยท-gusedยท-gfull-mmacosx-version-min=versionยท-mkernelยท-mone-byte-bool
โญ DEC Alpha Options
vintage icon energy:
-mno-fp-regsยท-msoft-floatยท-mieeeยท-mieee-with-inexactยท-mieee-conformant-mfp-trap-mode=modeยท-mfp-rounding-mode=modeยท-mtrap-precision=mode-mbuild-constantsยท-mcpu=cpu-typeยท-mtune=cpu-type-mbwxยท-mmaxยท-mfixยท-mcixยท-mfloat-vaxยท-mfloat-ieee-mexplicit-relocsยท-msmall-dataยท-mlarge-dataยท-msmall-textยท-mlarge-text-mmemory-latency=time
๐ฆ eBPF Options
kernel-baddie core ๐:
-mbig-endianยท-mlittle-endian-mkernel=versionยท-mframe-limit=bytesยท-mxbpf-mco-reยท-mno-co-re-mjmpextยท-mjmp32ยท-malu32-mcpu=version
๐ FR30 Options
-msmall-modelยท-mno-lsim
๐ง FT32 Options
-msimยท-mlraยท-mnodivยท-mft32bยท-mcompressยท-mnopm
๐ FRV Options
-mgpr-32ยท-mgpr-64ยท-mfpr-32ยท-mfpr-64-mhard-floatยท-msoft-float-malloc-ccยท-mfixed-cc-mdwordยท-mno-dword-mdoubleยท-mno-double-mmediaยท-mno-media-mmuladdยท-mno-muladd-mfdpicยท-minline-pltยท-mgprel-roยท-multilib-library-picยท-mlinked-fp-mlong-callsยท-malign-labelsยท-mlibrary-pic-macc-4ยท-macc-8-mpackยท-mno-packยท-mno-eflags-mcond-moveยท-mno-cond-move-moptimize-membarยท-mno-optimize-membar-msccยท-mno-scc-mcond-execยท-mno-cond-exec-mvliw-branchยท-mno-vliw-branch-mmulti-cond-execยท-mno-multi-cond-exec-mnested-cond-execยท-mno-nested-cond-exec-mtomcat-stats-mTLSยท-mtls-mcpu=cpu
๐ง GNU/Linux Options
the libc-picking girlies:
-mglibcยท-muclibcยท-mmuslยท-mbionic-mandroidยท-tno-android-ccยท-tno-android-ld
๐ป H8/300 Options
-mrelaxยท-mhยท-msยท-mnยท-mexrยท-mno-exrยท-mint32ยท-malign-300
๐ HPPA Options
-march=architecture-typeยท-matomic-libcalls-mbig-switchยท-mcaller-copies-mdisable-fpregsยท-mdisable-indexing-morderedยท-mfast-indirect-calls-mgasยท-mgnu-ldยท-mhp-ld-mfixed-range=register-rangeยท-mcoherent-ldcw-mjump-in-delayยท-mlinker-optยท-mlong-callsยท-mlong-load-store-mno-atomic-libcallsยท-mno-disable-fpregsยท-mno-disable-indexing-mno-fast-indirect-callsยท-mno-gasยท-mno-jump-in-delay-mno-long-load-storeยท-mno-portable-runtimeยท-mno-soft-floatยท-mno-space-regs-msoft-float-mpa-risc-1-0ยท-mpa-risc-1-1ยท-mpa-risc-2-0-mportable-runtimeยท-mschedule=cpu-typeยท-mspace-regsยท-msoft-mult-msioยท-mwsio-munix=unix-std-nolibdldยท-staticยท-threads
๐ IA-64 Options
the scheduling menu is huge, iykyk:
-mbig-endianยท-mlittle-endian-mgnu-asยท-mgnu-ldยท-mno-pic-mvolatile-asm-stopยท-mregister-names-msdataยท-mno-sdata-mconstant-gpยท-mauto-picยท-mfused-madd-minline-float-divide-min-latencyยท-minline-float-divide-max-throughputยท-mno-inline-float-divide-minline-int-divide-min-latencyยท-minline-int-divide-max-throughputยท-mno-inline-int-divide-minline-sqrt-min-latencyยท-minline-sqrt-max-throughputยท-mno-inline-sqrt-mdwarf2-asmยท-mearly-stop-bits-mfixed-range=register-rangeยท-mtls-size=tls-size-mtune=cpu-typeยท-milp32ยท-mlp64-msched-br-data-specยท-msched-ar-data-specยท-msched-control-spec-msched-br-in-data-specยท-msched-ar-in-data-specยท-msched-in-control-spec-msched-spec-ldcยท-msched-spec-control-ldc-msched-prefer-non-data-spec-insnsยท-msched-prefer-non-control-spec-insns-msched-stop-bits-after-every-cycleยท-msched-count-spec-in-critical-path-msel-sched-dont-check-control-specยท-msched-fp-mem-deps-zero-cost-msched-max-memory-insns-hard-limitยท-msched-max-memory-insns=max-insns
๐ผ LM32 Options
-mbarrel-shift-enabledยท-mdivide-enabledยท-mmultiply-enabledยท-msign-extend-enabledยท-muser-enabled
๐ฆ LoongArch Options
-march=cpu-typeยท-mtune=cpu-type-mabi=base-abi-type-mfpu=fpu-type-msoft-floatยท-msingle-floatยท-mdouble-float-mbranch-cost=n-mcheck-zero-divisionยท-mno-check-zero-division-mcond-move-intยท-mno-cond-move-int-mcond-move-floatยท-mno-cond-move-float-memcpyยท-mno-memcpy-mstrict-alignยท-mno-strict-align-mmax-inline-memcpy-size=n-mexplicit-relocsยท-mno-explicit-relocs-mdirect-extern-accessยท-mno-direct-extern-access-mcmodel=code-model-mrelaxยท-mpass-mrelax-to-as
๐ M32R/D Options
-m32r2ยท-m32rxยท-m32r-mdebug-malign-loopsยท-mno-align-loops-missue-rate=number-mbranch-cost=number-mmodel=code-size-model-type-msdata=sdata-type-mno-flush-funcยท-mflush-func=nameยท-mno-flush-trapยท-mflush-trap=number-G num
๐ฌ M32C Options
last but never least ๐ซถ:
-mcpu=cpuยท-msimยท-memregs=number
...and okay so this is the part where the manpage stops pretending to be normal, because from here it's just machine-dependent options. Like, all of them. Hundreds. One per bullet. I'm not even mad, I'm impressed. ๐ญ
heads up bestie: this whole chunk is literally just flag lists โ no descriptions attached. So I'm giving you the flags exactly as they are with max vibes and zero invented lore, because making stuff up about compiler flags is not the move. ๐
๐ง M680x0 Options ๐ง
The 680x0 block. It's giving vintage Motorola main character energy.
-march=arch-mcpu=cpu-mtune=tune-m68000-m68020-m68020-40-m68020-60-m68030-m68040-m68060-mcpu32-m5200-m5206e-m528x-m5307-m5407-mcfv4e-mbitfield-mno-bitfield-mc68000-mc68020-mnobitfield-mrtd-mno-rtd-mdiv-mno-div-mshort-mno-short-mhard-float-m68881-msoft-float-mpcrel-malign-int-mstrict-align-msep-data-mno-sep-data-mshared-library-id=n-mid-shared-library-mno-id-shared-library-mxgot-mno-xgot-mlong-jump-table-offsets
๐ฆ MCore Options ๐ฆ
-mhardlit-mno-hardlit-mdiv-mno-div-mrelax-immediates-mno-relax-immediates-mwide-bitfields-mno-wide-bitfields-m4byte-functions-mno-4byte-functions-mcallgraph-data-mno-callgraph-data-mslow-bytes-mno-slow-bytes-mno-lsim-mlittle-endian-mbig-endian-m210-m340-mstack-increment
๐ MicroBlaze Options ๐</col/>
-msoft-float-mhard-float-msmall-divides-mcpu=cpu-mmemcpy-mxl-soft-mul-mxl-soft-div-mxl-barrel-shift-mxl-pattern-compare-mxl-stack-check-mxl-gp-opt-mno-clearbss-mxl-multiply-high-mxl-float-convert-mxl-float-sqrt-mbig-endian-mlittle-endian-mxl-reorder-mxl-mode-app-model-mpic-data-is-text-relative
๐ MIPS Options ๐
Bestie. Sit down. This one is long. MIPS ate and left no crumbs. ๐ฝ๏ธ
-EL-EB-march=arch-mtune=arch-mips1-mips2-mips3-mips4-mips32-mips32r2-mips32r3-mips32r5-mips32r6-mips64-mips64r2-mips64r3-mips64r5-mips64r6-mips16-mno-mips16-mflip-mips16-minterlink-compressed-mno-interlink-compressed-minterlink-mips16-mno-interlink-mips16-mabi=abi-mabicalls-mno-abicalls-mshared-mno-shared-mplt-mno-plt-mxgot-mno-xgot-mgp32-mgp64-mfp32-mfpxx-mfp64-mhard-float-msoft-float-mno-float-msingle-float-mdouble-float-modd-spreg-mno-odd-spreg-mabs=mode-mnan=encoding-mdsp-mno-dsp-mdspr2-mno-dspr2-mmcu-mmno-mcu-meva-mno-eva-mvirt-mno-virt-mxpa-mno-xpa-mcrc-mno-crc-mginv-mno-ginv-mmicromips-mno-micromips-mmsa-mno-msa-mloongson-mmi-mno-loongson-mmi-mloongson-ext-mno-loongson-ext-mloongson-ext2-mno-loongson-ext2-mfpu=fpu-type-msmartmips-mno-smartmips-mpaired-single-mno-paired-single-mdmx-mno-mdmx-mips3d-mno-mips3d-mmt-mno-mt-mllsc-mno-llsc-mlong64-mlong32-msym32-mno-sym32-Gnum-mlocal-sdata-mno-local-sdata-mextern-sdata-mno-extern-sdata-mgpopt-mno-gopt-membedded-data-mno-embedded-data-muninit-const-in-rodata-mno-uninit-const-in-rodata-mcode-readable=setting-msplit-addresses-mno-split-addresses-mexplicit-relocs-mno-explicit-relocs-mcheck-zero-division-mno-check-zero-division-mdivide-traps-mdivide-breaks-mload-store-pairs-mno-load-store-pairs-munaligned-access-mno-unaligned-access-mmemcpy-mno-memcpy-mlong-calls-mno-long-calls-mmad-mno-mad-mimadd-mno-imadd-mfused-madd-mno-fused-madd-nocpp-mfix-24k-mno-fix-24k-mfix-r4000-mno-fix-r4000-mfix-r4400-mno-fix-r4400-mfix-r5900-mno-fix-r5900-mfix-r10000-mno-fix-r10000-mfix-rm7000-mno-fix-rm7000-mfix-vr4120-mno-fix-vr4120-mfix-vr4130-mno-fix-vr4130-mfix-sb1-mno-fix-sb1-mflush-func=func-mno-flush-func-mbranch-cost=num-mbranch-likely-mno-branch-likely-mcompact-branches=policy-mfp-exceptions-mno-fp-exceptions-mvr4130-align-mno-vr4130-align-msynci-mno-synci-mlxc1-sxc1-mno-lxc1-sxc1-mmadd4-mno-madd4-mrelax-pic-calls-mno-relax-pic-calls-mmcount-ra-address-mframe-header-opt-mno-frame-header-opt
PHEW. we survived. ๐ซถ
๐ง MMIX Options ๐ง
-mlibfuncs-mno-libfuncs-mepsilon-mno-epsilon-mabi=gnu-mabi=mmixware-mzero-extend-mknuthdiv-mtoplevel-symbols-melf-mbranch-predict-mno-branch-predict-mbase-addresses-mno-base-addresses-msingle-exit-mno-single-exit
๐ MN10300 Options ๐
-mmult-bug-mno-mult-bug-mno-am33-mam33-mam33-2-mam34-mtune=cpu-type-mreturn-pointer-on-d0-mno-crt0-mrelax-mliw-msetlb
โญ Moxie Options โญ
Tiny list, huge aura honestly.
-meb-mel-mmul.x-mno-crt0
๐ MSP430 Options ๐
-msim-masm-hex-mmcu=-mcpu=-mlarge-msmall-mrelax-mwarn-mcu-mcode-region=-mdata-region=-msilicon-errata=-msilicon-errata-warn=-mhwmult=-minrt-mtiny-printf-mmax-inline-shift=
๐ NDS32 Options ๐
-mbig-endian-mlittle-endian-mreduced-regs-mfull-regs-mcmov-mno-cmov-mext-perf-mno-ext-perf-mext-perf2-mno-ext-perf2-mext-string-mno-ext-string-mv3push-mno-v3push-m16bit-mno-16bit-misr-vector-size=num-mcache-block-size=num-march=arch-mcmodel=code-model-mctor-dtor-mrelax
๐ซง Nios II Options ๐ซง
-G num-mgpopt=option-mgpopt-mno-gpopt-mgprel-sec=regexp-mr0rel-sec=regexp-mel-meb-mno-bypass-cache-mbypass-cache-mno-cache-volatile-mcache-volatile-mno-fast-sw-div-mfast-sw-div-mhw-mul-mno-hw-mul-mhw-mulx-mno-hw-mulx-mno-hw-div-mhw-div-mcustom-insn=N-mno-custom-insn-mcustom-fpu-cfg=name-mhal-msmallc-msys-crt0=name-msys-lib=name-march=arch-mbmx-mno-bmx-mcdx-mno-cdx
๐ฅ๏ธ Nvidia PTX Options ๐ฅ๏ธ
Short and sweet, we love a low-effort icon.
-m64-mmainkernel-moptimize
๐ OpenRISC Options ๐
-mboard=name-mnewlib-mhard-mul-mhard-div-msoft-mul-msoft-div-msoft-float-mhard-float-mdouble-float-munordered-float-mcmov-mror-mrori-msext-msfimm-mshftimm-mcmodel=code-model
๐๏ธ PDP-11 Options ๐๏ธ
Retro. Vintage. Nostalgic. The PDP-11 is lowkey the grandmother of us all. โจ
-mfpu-msoft-float-mac0-mno-ac0-m40-m45-m10-mint32-mno-int16-mint16-mno-int32-msplit-munix-asm-mdec-asm-mgnu-asm-mlra
๐ PowerPC Options ๐
okay so this one is literally just a redirect and honestly? respect the delegation.
See RS/6000 and PowerPC Options.
๐ง PRU Options ๐ง
-mmcu=mcu-minrt-mno-relax-mloop-mabi=variant
๐ธ RISC-V Options ๐ธ
-mbranch-cost=N-instruction-mplt-mno-plt-mabi=ABI-string-mfdiv-mno-fdiv-mdiv-mno-div-misa-spec=ISA-spec-string-march=ISA-string-mtune=processor-string-mpreferred-stack-boundary=num-msmall-data-limit=N-bytes-msave-restore-mno-save-restore-mshorten-memrefs-mno-shorten-memrefs-mstrict-align-mno-strict-align-mcmodel=medlow-mcmodel=medany-mexplicit-relocs-mno-explicit-relocs-mrelax-mno-relax-mriscv-attribute-mno-riscv-attribute-malign-data=type-mbig-endian-mlittle-endian-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mcsr-check-mno-csr-check-minline-atomics-mno-inline-atomics
๐ RL78 Options ๐
-msim-mmul=none-mmul=g13-mmul=g14-mallregs-mcpu=g10-mcpu=g13-mcpu=g14-mg10-mg13-mg14-m64bit-doubles-m32bit-doubles-msave-mduc-in-interrupts
๐ RS/6000 and PowerPC Options ๐
and HERE is the beast. the moment we've all been waiting for. PowerPC said "let me cook" and produced an entire grocery list. ๐ฅ
-mcpu=cpu-type-mtune=cpu-type-mcmodel=code-model-mpowerpc64-maltivec-mno-altivec-mpowerpc-gpopt-mno-powerpc-gpopt-mpowerpc-gfxopt-mno-powerpc-gfxopt-mmfcrf-mno-mfcrf-mpopcntb-mno-popcntb-mpopcntd-mno-popcntd-mfprnd-mno-fprnd-mcmpb-mno-cmpb-mhard-dfp-mno-hard-dfp-mfull-toc-mminimal-toc-mno-fp-in-toc-mno-sum-in-toc-m64-m32-mxl-compat-mno-xl-compat-mpe-malign-power-malign-natural-msoft-float-mhard-float-mmultiple-mno-multiple-mupdate-mno-update-mavoid-indexed-addresses-mno-avoid-indexed-addresses-mfused-madd-mno-fused-madd-mbit-align-mno-bit-align-mstrict-align-mno-strict-align-mrelocatable-mno-relocatable-mrelocatable-lib-mno-relocatable-lib-mtoc-mno-toc-mlittle-mlittle-endian-mbig-mbig-endian-mdynamic-no-pic-mswdiv-msingle-pic-base-mprioritize-restricted-insns=priority-msched-costly-dep=dependence_type-minsert-sched-nops=scheme-mcall-aixdesc-mcall-eabi-mcall-freebsd-mcall-linux-mcall-netbsd-mcall-openbsd-mcall-sysv-mcall-sysv-eabi-mcall-sysv-noeabi-mtraceback=traceback_type-maix-struct-return-msvr4-struct-return-mabi=abi-type-msecure-plt-mbss-plt-mlongcall-mno-longcall-mpltseq-mno-pltseq-mblock-move-inline-limit=num-mblock-compare-inline-limit=num-mblock-compare-inline-loop-limit=num-mno-block-ops-unaligned-vsx-mstring-compare-inline-limit=num-misel-mno-isel-mvrsave-mno-vrsave-mmulhw-mno-mulhw-mdlmzb-mno-dlmzb-mprototype-mno-prototype-msim-mmvme-mads-myellowknife-memb-msdata-msdata=opt-mreadonly-in-sdata-mvxworks-G num-mrecip-mrecip=opt-mno-recip-mrecip-precision-mno-recip-precision-mveclibabi=type-mfriz-mno-friz-mpointers-to-nested-functions-mno-pointers-to-nested-functions-msave-toc-indirect-mno-save-toc-indirect-mpower8-fusion-mno-mpower8-fusion-mpower8-vector-mno-power8-vector-mcrypto-mno-crypto-mhtm-mno-htm-mquad-memory-mno-quad-memory-mquad-memory-atomic-mno-quad-memory-atomic-mcompat-align-parm-mno-compat-align-parm-mfloat128-mno-float128-mfloat128-hardware-mno-float128-hardware-mgnu-attribute-mno-gnu-attribute-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mprefixed-mno-prefixed-mpcrel-mno-pcrel-mmma-mno-mmma-mrop-protect-mno-rop-protect-mprivileged-mno-privileged
iconic behaviour, truly. ๐โจ
๐ RX Options ๐
-m64bit-doubles-m32bit-doubles-fpu-nofpu-mcpu=-mbig-endian-data-mlittle-endian-data-msmall-data-msim-mno-sim-mas100-syntax-mno-as100-syntax-mrelax-mmax-constant-size=-mint-register=-mpid-mallow-string-insns-mno-allow-string-insns-mjsr-mno-warn-multiple-fast-interrupts-msave-acc-in-interrupts
๐ S/390 and zSeries Options ๐
Last one of this batch and it's giving mainframe drama, which is honestly so valid. ๐๏ธ
-mtune=cpu-type-march=cpu-type-mhard-float-msoft-float-mhard-dfp-mno-hard-dfp-mlong-double-64-mlong-double-128-mbackchain-mno-backchain-mpacked-stack-mno-packed-stack-msmall-exec-mno-small-exec-mmvcle-mno-mvcle-m64-m31-mdebug-mno-debug-mesa-mzarch-mhtm-mvx-mzvector-mtpf-trace-mno-tpf-trace-mtpf-trace-skip-mno-tpf-trace-skip-mfused-madd-mno-fused-madd-mwarn-framesize-mwarn-dynamicstack-mstack-size-mstack-guard-mhotpatch=halfwords,halfwords
๐ธ SH Options ๐ธ
okay so the SH (SuperH) crew got a whole fleet of vibe-selectors: -m1, -m2, -m2e, -m2a-nofpu, -m2a-single-only, -m2a-single, -m2a, -m3, -m3e, -m4-nofpu, -m4-single-only, -m4-single, -m4, -m4a-nofpu, -m4a-single-only, -m4a-single, -m4a, -m4al, -mb, -ml, -mdalign, -mrelax, -mbigtable, -mfmovd, -mrenesas, -mno-renesas, -mnomacsave, -mieee, -mno-ieee, -mbitops, -misize, -minline-ic_invalidate, -mpadstruct, -mprefergot, -musermode, -multcost=number, -mdiv=strategy, -mdivsi3_libfunc=name, -mfixed-range=register-range, -maccumulate-outgoing-args, -matomic-model=atomic-model, -mbranch-cost=num, -mzdcbranch, -mno-zdcbranch, -mcbranch-force-delay-slot, -mfused-madd, -mno-fused-madd, -mfsca, -mno-fsca, -mfsrra, -mno-fsrra, -mpretend-cmove, -mtas. periodt โจ
๐ Solaris 2 Options ๐
-mclear-hwcap/-mno-clear-hwcap-mimpure-text/-mno-impure-text-pthreads
that little lineup above โจ
๐ฅ SPARC Options ๐ฅ
-mcpu=cpu-type-mtune=cpu-type-mcmodel=code-model-mmemory-model=mem-model-m32-m64-mapp-regs/-mno-app-regs-mfaster-structs/-mno-faster-structs-mflat/-mno-flat-mfpu/-mno-fpu-mhard-float/-msoft-float-mhard-quad-float/-msoft-quad-float-mstack-bias/-mno-stack-bias-mstd-struct-return/-mno-std-struct-return-munaligned-doubles/-mno-unaligned-doubles-muser-mode/-mno-user-mode-mv8plus/-mno-v8plus-mvis/-mno-vis-mvis2/-mno-vis2-mvis3/-mno-vis3-mvis4/-mno-vis4-mvis4b/-mno-vis4b-mcbcond/-mno-cbcond-mfmaf/-mno-fmaf-mfsmuld/-mno-fsmuld-mpopc/-mno-popc-msubxc/-mno-subxc-mfix-at697f-mfix-ut699-mfix-ut700-mfix-gr712rc-mlra/-mno-lra
๐ System V Options ๐
-Qy-Qn-YP,paths-Ym,dir
๐ V850 Options ๐
-mlong-calls/-mno-long-calls-mep/-mno-ep-mprolog-function/-mno-prolog-function-mspace-mtda=n-msda=n-mzda=n-mapp-regs/-mno-app-regs-mdisable-callt/-mno-disable-callt-mv850e2v3-mv850e2-mv850e1-mv850es-mv850e-mv850-mv850e3v5-mloop-mrelax-mlong-jumps-msoft-float/-mhard-float-mgcc-abi/-mrh850-abi-mbig-switch
๐ฆ VAX Options ๐ฆ
-mg-mgnu-munix-mlra
๐ง Visium Options ๐ง
-mdebug-msim-mfpu/-mno-fpu-mhard-float/-msoft-float-mcpu=cpu-type-mtune=cpu-type-msv-mode/-muser-mode
๐ VMS Options ๐
-mvms-return-codes-mdebug-main=prefix-mmalloc64-mpointer-size=size
๐ VxWorks Options ๐
-mrtp-non-static-Bstatic-Bdynamic-Xbind-lazy-Xbind-now
๐ x86 Options ๐
bestie. sit down. this list is long and it's giving encyclopaedia:
-mtune=cpu-type-march=cpu-type-mtune-ctrl=feature-list-mdump-tune-features-mno-default-mfpmath=unit-masm=dialect-mno-fancy-math-387-mno-fp-ret-in-387-m80387/-mhard-float-msoft-float-mno-wide-multiply-mrtd-malign-double-mpreferred-stack-boundary=num-mincoming-stack-boundary=num-mcld-mcx16-msahf-mmovbe-mcrc32-mmwait-mrecip/-mrecip=opt-mvzeroupper-mprefer-avx128-mprefer-vector-width=opt-mmove-max=bits-mstore-max=bits-mmmx-msse-msse2-msse3-mssse3-msse4.1-msse4.2-msse4-mavx-mavx2-mavx512f-mavx512pf-mavx512er-mavx512cd-mavx512vl-mavx512bw-mavx512dq-mavx512ifma-mavx512vbmi-msha-maes-mpclmul-mfsgsbase-mrdrnd-mf16c-mfma-mpconfig-mwbnoinvd-mptwrite-mprefetchwt1-mclflushopt-mclwb-mxsavec-mxsaves-msse4a-m3dnow-m3dnowa-mpopcnt-mabm-mbmi-mtbm-mfma4-mxop-madx-mlzcnt-mbmi2-mfxsr-mxsave-mxsaveopt-mrtm-mhle-mlwp-mmwaitx-mclzero-mpku-mthreads-mgfni-mvaes-mwaitpkg-mshstk-mmanual-endbr-mcet-switch-mforce-indirect-call-mavx512vbmi2-mavx512bf16-menqcmd-mvpclmulqdq-mavx512bitalg-mmovdiri-mmovdir64b-mavx512vpopcntdq-mavx5124fmaps-mavx512vnni-mavx5124vnniw-mprfchw-mrdpid-mrdseed-msgx-mavx512vp2intersect-mserialize-mtsxldtrk-mamx-tile-mamx-int8-mamx-bf16-muintr-mhreset-mavxvnni-mavx512fp16-mavxifma-mavxvnniint8-mavxneconvert-mcmpccxadd-mamx-fp16-mprefetchi-mraoint-mamx-complex-mcldemote-mms-bitfields-mno-align-stringops-minline-all-stringops-minline-stringops-dynamically-mstringop-strategy=alg-mkl/-mwidekl-mmemcpy-strategy=strategy-mmemset-strategy=strategy-mpush-args-maccumulate-outgoing-args-m128bit-long-double-m96bit-long-double-mlong-double-64-mlong-double-80-mlong-double-128-mregparm=num-msseregparm-mveclibabi=type-mvect8-ret-in-mem-mpc32-mpc64-mpc80-mdaz-ftz-mstackrealign-momit-leaf-frame-pointer-mno-red-zone-mno-tls-direct-seg-refs-mcmodel=code-model-mabi=name-maddress-mode=mode-m32-m64-mx32-m16-miamcu-mlarge-data-threshold=num-msse2avx-mfentry-mrecord-mcount-mnop-mcount-m8bit-idiv-minstrument-return=type-mfentry-name=name-mfentry-section=name-mavx256-split-unaligned-load-mavx256-split-unaligned-store-malign-data=type-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mstack-protector-guard-symbol=symbol-mgeneral-regs-only-mcall-ms2sysv-xlogues-mrelax-cmpxchg-loop-mindirect-branch=choice-mfunction-return=choice-mindirect-branch-register-mharden-sls=choice-mindirect-branch-cs-prefix-mneeded-mno-direct-extern-access-munroll-only-small-loops-mlam=choice
ate, truly. no crumbs. ๐
๐ x86 Windows Options ๐
-mconsole-mcygwin/-mno-cygwin-mdll-mnop-fun-dllimport-mthread-municode-mwin32-mwindows-fno-set-stack-executable
โญ Xstormy16 Options โญ
-msim
๐ธ Xtensa Options ๐ธ
-mconst16/-mno-const16-mfused-madd/-mno-fused-madd-mforce-no-pic-mserialize-volatile/-mno-serialize-volatile-mtext-section-literals/-mno-text-section-literals-mauto-litpools/-mno-auto-litpools-mtarget-align/-mno-target-align-mlongcalls/-mno-longcalls-mabi=abi-type-mextra-l32r-costs=cycles
๐ zSeries Options ๐
zSeries bestie, your moment is elsewhere โ head to S/390 and zSeries Options. that's literally the whole note. ๐ซถ
โจ Options Controlling the Kind of Output โจ
okay so compilation can go through up to four stages: preprocessing, compilation proper, assembly and linking โ always in that order, no skipping ahead like it's a groupchat. GCC can preprocess and compile several files either into several assembler input files, or into one assembler input file. then each assembler input file produces an object file, and linking squishes all the object files together (the freshly compiled ones and the ones you passed as input) into an executable file. iconic. ๐ฅ
For any given input file, the file name suffix determines what kind of compilation is done:
file.cโ C source code that must be preprocessed.file.iโ C source code that should not be preprocessed.file.iiโ C++ source code that should not be preprocessed.file.mโ Objective-C source code. Note that you must link with thelibobjclibrary to make an Objective-C program work.file.miโ Objective-C source code that should not be preprocessed.file.mm,file.Mโ Objective-C++ source code. Note that you must link with thelibobjclibrary to make an Objective-C++ program work. Note that.Mrefers to a literal capital M.file.miiโ Objective-C++ source code that should not be preprocessed.file.hโ C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (default), or C, C++ header file to be turned into an Ada spec (via the-fdump-ada-specswitch).file.cc,file.cp,file.cxx,file.cpp,file.CPP,file.c++,file.Cโ C++ source code that must be preprocessed. Note that in.cxx, the last two letters must both be literally x. Likewise,.Crefers to a literal capital C.file.mm,file.Mโ Objective-C++ source code that must be preprocessed.file.miiโ Objective-C++ source code that should not be preprocessed.file.hh,file.H,file.hp,file.hxx,file.hpp,file.HPP,file.h++,file.tccโ C++ header file to be turned into a precompiled header or Ada spec.file.f,file.for,file.ftnโ Fixed form Fortran source code that should not be preprocessed.file.F,file.FOR,file.fpp,file.FPP,file.FTNโ Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).file.f90,file.f95,file.f03,file.f08โ Free form Fortran source code that should not be preprocessed.file.F90,file.F95,file.F03,file.F08โ Free form Fortran source code that must be preprocessed (with the traditional preprocessor).file.goโ Go source code.file.dโ D source code.file.diโ D interface file.file.ddโ D documentation code (Ddoc).file.adsโ Ada source code file that contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). Such files are also called specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.file.sโ Assembler code.file.S,file.sxโ Assembler code that must be preprocessed.- other โ An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.
You can specify the input language explicitly with the -x option:
-xlanguage โ Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next-xoption. Possible values for language are:
c c-header cpp-output
c++ c++-header c++-system-header c++-user-header c++-cpp-output
objective-c objective-c-header objective-c-cpp-output objc-cpp-output
objective-c++ objective-c++-header objective-c++-cpp-output
objc++-cpp-output
assembler assembler-with-cpp
ada adascil adawhy
d
f77 f77-cpp-input f95 f95-cpp-input
go
modula-2 modula-2-cpp-output
rust
lto
-x noneโ Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if-xhas not been used at all).
If you only want some of the stages of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop.
lowkey important: some combinations (for example,-x cpp-output -E) instructgccto do nothing at all. like, zero. nada. it just vibes. ๐ญ
-cโ bestie, this one says: compile or assemble the source files, but do not link. The linking stage simply is not done. โจ The ultimate output is in the form of an object file for each source file.
By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.
Unrecognized input files, not requiring compilation or assembly, are ignored. (They're just there. Vibing. Not our problem. ๐ )
-Sโ stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified.
By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.
Input files that don't require compilation are ignored.
-Eโ stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. ๐
Input files that don't require preprocessing are ignored.
-ofile โ place the primary output in file file. Yes it says file twice, no I did not write that, it's literally what it says, and honestly iconic of it. ๐ This applies to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.
If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output.
Though -o names only the primary output, it also affects the naming of auxiliary and dump outputs. See the examples below. Unless overridden, both auxiliary outputs and dump outputs are placed in the same directory as the primary output. In auxiliary outputs, the suffix of the input file is replaced with that of the auxiliary output file type; in dump outputs, the suffix of the dump file is appended to the input file suffix. In compilation commands, the base name of both auxiliary and dump outputs is that of the primary output; in compile and link commands, the primary output name, minus the executable suffix, is combined with the input file name. If both share the same base name, disregarding the suffix, the result of the combination is that base name, otherwise, they are concatenated, separated by a dash.
Like, watch this:
gcc -c foo.c ...
will use foo.o as the primary output, and place aux outputs and dumps next to it, e.g., aux file foo.dwo for -gsplit-dwarf, and dump file foo.c.???r.final for -fdump-rtl-final.
If a non-linker output file is explicitly specified, aux and dump files by default take the same base name:
gcc -c foo.c -o dir/foobar.o ...
will name aux outputs dir/foobar.* and dump outputs dir/foobar.c.*.
A linker output will instead prefix aux and dump outputs:
gcc foo.c bar.c -o dir/foobar ...
will generally name aux outputs dir/foobar-foo.* and dir/foobar-bar.*, and dump outputs dir/foobar-foo.c.* and dir/foobar-bar.c.*.
The one exception to the above is when the executable shares the base name with the single input:
gcc foo.c -o dir/foo ...
in which case aux outputs are named dir/foo.* and dump outputs named dir/foo.c.*.
The location and the names of auxiliary and dump outputs can be adjusted by the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj.
-dumpbasedumpbase โ this option sets the base name for auxiliary and dump output files. It does not affect the name of the primary output file. Intermediate outputs, when preserved, are not regarded as primary outputs, but as auxiliary outputs:
gcc -save-temps -S foo.c
saves the (no longer) temporary preprocessed file in foo.i, and then compiles to the (implied) output file foo.s, whereas:
gcc -save-temps -dumpbase save-foo -c foo.c
preprocesses to in save-foo.i, compiles to save-foo.s (now an intermediate, thus auxiliary output), and then assembles to the (implied) output file foo.o.
Absent this option, dump and aux files take their names from the input file, or from the (non-linker) output file, if one is explicitly specified: dump output files (e.g. those requested by -fdump-* options) with the input name suffix, and aux output files (those requested by other non-dump options, e.g. "-save-temps", "-gsplit-dwarf", "-fcallgraph-info") without it.
Similar suffix differentiation of dump and aux outputs can be attained for explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf.
If dumpbase is explicitly specified with any directory component, any dumppfx specification (e.g. -dumpdir or -save-temps=*) is ignored, and instead of appending to it, dumpbase fully overrides it:
gcc foo.c -c -o dir/foo.o -dumpbase alt/foo \
-dumpdir pfx- -save-temps=cwd ...
creates auxiliary and dump outputs named alt/foo.*, disregarding dir/ in -o, the ./ prefix implied by -save-temps=cwd, and pfx- in -dumpdir.
When -dumpbase is specified in a command that compiles multiple inputs, or that compiles and then links, it may be combined with dumppfx, as specified under -dumpdir. Then, each input file is compiled using the combined dumppfx, and default values for dumpbase and auxdropsuf are computed for each input file:
gcc foo.c bar.c -c -dumpbase main ...
creates foo.o and bar.o as primary outputs, and avoids overwriting the auxiliary and dump outputs by using the dumpbase as a prefix, creating auxiliary and dump outputs named main-foo.* and main-bar.*.
An empty string specified as dumpbase avoids the influence of the output basename in the naming of auxiliary and dump outputs during compilation, computing default values :
gcc -c foo.c -o dir/foobar.o -dumpbase " ...
will name aux outputs dir/foo.* and dump outputs dir/foo.c.*. Note how their basenames are taken from the input name, but the directory still defaults to that of the output.
The empty-string dumpbase does not prevent the use of the output basename for outputs during linking:
gcc foo.c bar.c -o dir/foobar -dumpbase " -flto ...
The compilation of the source files will name auxiliary outputs dir/foo.* and dir/bar.*, and dump outputs dir/foo.c.* and dir/bar.c.*. LTO recompilation during linking will use dir/foobar. as the prefix for dumps and auxiliary files.
-dumpbase-extauxdropsuf โ when forming the name of an auxiliary (but not a dump) output file, drop trailing auxdropsuf from dumpbase before appending any suffixes. If not specified, this option defaults to the suffix of a default dumpbase, i.e., the suffix of the input file when-dumpbaseis not present in the command line, or dumpbase is combined with dumppfx.
gcc foo.c -c -o dir/foo.o -dumpbase x-foo.c -dumpbase-ext .c ...
creates dir/foo.o as the main output, and generates auxiliary outputs in dir/x-foo.*, taking the location of the primary output, and dropping the .c suffix from the dumpbase. Dump outputs retain the suffix: dir/x-foo.c.*.
This option is disregarded if it does not match the suffix of a specified dumpbase, except as an alternative to the executable suffix when appending the linker output base name to dumppfx, as specified below:
gcc foo.c bar.c -o main.out -dumpbase-ext .out ...
creates main.out as the primary output, and avoids overwriting the auxiliary and dump outputs by using the executable name minus auxdropsuf as a prefix, creating auxiliary outputs named main-foo.* and main-bar.* and dump outputs named main-foo.c.* and main-bar.c.*.
-dumpdirdumppfx โ when forming the name of an auxiliary or dump output file, use dumppfx as a prefix:
gcc -dumpdir pfx- -c foo.c ...
creates foo.o as the primary output, and auxiliary outputs named pfx-foo.*, combining the given dumppfx with the default dumpbase derived from the default primary output, derived in turn from the input name. Dump outputs also take the input name suffix: pfx-foo.c.*.
If dumppfx is to be used as a directory name, it must end with a directory separator:
gcc -dumpdir dir/ -c foo.c -o obj/bar.o ...
creates obj/bar.o as the primary output, and auxiliary outputs named dir/bar.*, combining the given dumppfx with the default dumpbase derived from the primary output name. Dump outputs also take the input name suffix: dir/bar.c.*.
It defaults to the location of the output file, unless the output file is a special file like "/dev/null". Options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option. In case multiple such options are given, the last one prevails:
gcc -dumpdir pfx- -c foo.c -save-temps=obj ...
outputs foo.o, with auxiliary outputs named foo.* because -save-temps=* overrides the dumppfx given by the earlier -dumpdir option. It does not matter that =obj is the default for -save-temps, nor that the output directory is implicitly the current directory. Dump outputs are named foo.c.*.
When compiling from multiple input files, if -dumpbase is specified, dumpbase, minus a auxdropsuf suffix, and a dash are appended to (or override, if containing any directory components) an explicit or defaulted dumppfx, so that each of the multiple compilations gets differently-named aux and dump outputs.
gcc foo.c bar.c -c -dumpdir dir/pfx- -dumpbase main ...
outputs auxiliary dumps to dir/pfx-main-foo.* and dir/pfx-main-bar.*, appending dumpbase- to dumppfx. Dump outputs retain the input file suffix: dir/pfx-main-foo.c.* and dir/pfx-main-bar.c.*, respectively. Contrast with the single-input compilation:
gcc foo.c -c -dumpdir dir/pfx- -dumpbase main ...
that, applying -dumpbase to a single source, does not compute and append a separate dumpbase per input file. Its auxiliary and dump outputs go in dir/pfx-main.*.
okay bestie we're in the โจlink-time partโจ of the dumpdir/dumpbase saga and honestly it EATS ๐
so like, when you're compiling AND then linking from multiple input files, a dumppfx (whether it got there by default or you said it out loud) also goes through that whole dumpbase- transformation from before โ think of the compilation of foo.c and bar.c up top, except with no -c in sight. ๐
And if you gave the compiler neither -dumpdir nor -dumpbase? Then the linker output base name โ minus auxdropsuf if you specified one, or the executable suffix otherwise โ gets a lil dash tacked on and gets appended to the default dumppfx instead. โญ
BUT โ and this is the plot twist โ unlike the earlier linking cases:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...
does not append the output name main to dumppfx, and that's because -dumpdir was explicitly specified, periodt. The goal here is that your explicitly-specified dumppfx is allowed to already contain the specified output name as part of the prefix, if that's the vibe you want. Only an explicitly-specified -dumpbase gets combined with it, so that we don't just straight up discard a meaningful option. ๐
When you're compiling and then linking from a single input file, the linker output base name only gets appended to the default dumppfx (same as above) if it doesn't share its base name with that one single input file name. The single-input linking cases above already covered this โ but not the scenario with an explicit -dumpdir that inhibits the combination, even if -save-temps=* tries to override it:
gcc foo.c -dumpdir alt/pfx- -o dir/main.exe -save-temps=cwd ...
Auxiliary outputs get named foo.*, and dump outputs get named foo.c.*, in the current working directory as ultimately requested by -save-temps=cwd. slay, tidy, consistent ๐ฆ
โจ Summing It All Up โจ
Here's the intuitive-but-slightly-imprecise data flow, bestie โ it's giving flow chart energy:
- The primary output name gets broken into a directory part and a basename part.
dumppfxis set to the former โ unless it's overridden by-dumpdiror-save-temps=*.dumpbaseis set to the latter โ unless it's overriden by-dumpbase.- If there are multiple inputs or linking, this
dumpbasemay be combined withdumppfxand taken from each input file. - Auxiliary output names for each input are formed by combining
dumppfx,dumpbaseminus suffix, and the auxiliary output suffix. - Dump output names are only different in that the suffix from
dumpbaseis retained. ๐
๐ Auxiliary and Dump Outputs During LTO Recompilation ๐
okay this bit is niche but you NEED it: when it comes to auxiliary and dump outputs created during LTO recompilation, a combination of dumppfx and dumpbase โ as given, or as derived from the linker output name but not from inputs, even in cases where this combination wouldn't otherwise be used as such โ is passed down with a trailing period replacing the compiler-added dash (if there was one), as a -dumpdir option to lto-wrapper. ๐ซถ Being involved in linking, this program doesn't normally get any -dumpbase and -dumpbase-ext, and it ignores them. iconic behaviour honestly
And when lto-wrapper is running sub-compilers? It appends LTO stage names to the dumppfx it received, makes sure that thing contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. ๐ง
๐ THE REST OF THE OPTIONS ๐
-vโ prints (to standard error output, heads up) all the commands that actually got executed to run the stages of compilation. It also prints the version number of the compiler driver program, plus the version of the preprocessor and of the compiler proper. receipts, basically ๐งพ-###โ like-v, except the commands are not executed, and the arguments get quoted unless they contain only alphanumeric characters or"./-_". Super useful for shell scripts that wanna capture the command lines the driver generates. โจ--helpโ prints (on standard output) a description of the command-line options thatgccunderstands. ๐ If you also specified-v, then--helpgets passed along to the various processesgccinvokes too, so they can each show off the command-line options they accept. And if-Wextrawas also specified (prior to the--helpoption, note it), then command-line options that have no documentation associated with them get displayed as well. no option left behind--target-helpโ prints (on standard output) a description of the target-specific command-line options for each tool. For some targets, extra target-specific information may also get printed. ๐ฏ
--help={class|[^]qualifier}[,...]
prints (on standard output) a description of the command-line options the compiler understands that fit into all the specified classes and qualifiers. Here are the supported classes:
optimizersโ display all of the optimization options supported by the compiler. ๐ฅwarningsโ display all of the options controlling warning messages produced by the compiler.targetโ display target-specific options. Unlike--target-helpthough, the target-specific options of the linker and assembler are not displayed, because those tools don't currently support the extended--help=syntax. ๐ญparamsโ display the values recognized by the--paramoption.languageโ display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, you need to select thecommonclass instead.commonโ display the options that are common to all languages.
And these are the supported qualifiers:
undocumentedโ display only those options that are undocumented. the secret menu ๐joinedโ display options taking an argument that appears after an equal sign in the same continuous piece of text, like:--help=target.separateโ display options taking an argument that appears as a separate word following the original option, like:-o output-file.
So for example, to display all the undocumented target-specific switches supported by the compiler, use:
--help=target,undocumented
The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e., ones that are either on or off and that do not take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
Careful bestie: the argument to --help= should not consist solely of inverted qualifiers. ๐จ
Combining several classes is possible, although this usually restricts the output so much that there's literally nothing to display. ngl that's kind of the point One case where it does work, though, is when one of the classes is target. For example, to display all the target-specific optimization options, use:
--help=target,optimizers
The --help= option can be repeated on the command line, and each successive use displays its requested class of options, skipping those that have already been displayed. If --help is also specified anywhere on the command line, then it takes precedence over any --help= option. periodt. ๐
If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= changes. Instead of describing the displayed options, you get an indication of whether the option is enabled, disabled, or set to a specific value โ assuming the compiler knows this at the point where the --help= option is used. ๐
Here's a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi= 2
-mabort-on-noreturn [disabled]
-mapcs [disabled]
The output is sensitive to the effects of previous command-line options, so for example it's possible to find out which optimizations are enabled at -O2 by using:
-Q -O2 --help=optimizers
Alternatively you can discover which binary optimizations are enabled by -O3 by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
the diff-and-grep combo is genuinely so satisfying, look at her go ๐
--versionโ display the version number and copyrights of the invoked GCC. ๐-pass-exit-codesโ normally thegccprogram exits with code1if any phase of the compiler returns a non-success return code. If you specify-pass-exit-codes, thengccinstead returns with the numerically highest error produced by any phase that returned an error indication. Heads up: the C, C++, and Fortran front ends return4if an internal compiler error is encountered. ๐ญ-pipeโ use pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe; but the GNU assembler has no trouble. ๐ง we love a cooperative assembler-specs=fileโ process file after the compiler reads in the standard specs file, so you can override the defaults that thegccdriver program uses when figuring out what switches to pass tocc1,cc1plus,as,ld, etc. More than one-specs=filecan be specified on the command line, and they're processed in order, from left to right. โก๏ธ-wrapperโ invoke all subcommands under a wrapper program. The name of the wrapper program and its parameters get passed as a comma-separated list. ๐ซถ
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 becomes gdb --args cc1 .... debugging but make it main character energy ๐
-ffile-prefix-map=old=newโ when compiling files residing in directory old, record any references to them in the result of the compilation as if the files resided in directory new instead. Specifying this option is equivalent to specifying all the individual-f*-prefix-mapoptions. This can be used to make reproducible builds that are location independent. ๐ธ Directories referenced by directives are not affected by these options, though. See also-fmacro-prefix-map,-fdebug-prefix-map,-fprofile-prefix-mapand-fcanon-prefix-map. โญ-fcanon-prefix-mapโ for the-f*-prefix-mapoptions, normally comparison of the old prefix against the filename that would normally be referenced in the result of the compilation is done using textual comparison of the prefixes โ or ignoring character case for case insensitive filesystems, and considering slashes and backslashes as equal on DOS based filesystems. The-fcanon-prefix-mapcauses such comparisons to be done on canonicalized paths of old and the referenced filename. ๐ฆ canonicalization, but cute-fplugin=name.soโ bestie, this loads the plugin code in filename.so, which is assumed to be a shared object that the compiler willdlopen. The base name of the shared object file is what identifies the plugin for argument parsing (peep-fplugin-arg-name-key=valuebelow). Every plugin should define the callback functions specified in the Plugins API. ๐-fplugin-arg-name-key=valueโ defines an argument calledkeywith a value ofvaluefor the plugin calledname. slay.-fdump-ada-spec[-slim]โ for C and C++ source and include files, this generates corresponding Ada specs. iconic behavior honestly.-fada-spec-parent=unitโ in conjunction with-fdump-ada-spec[-slim]above, this generates Ada specs as child units of parentunit. ๐ซถ-fdump-go-spec=fileโ for input files in any language, this generates corresponding Go declarations infile. It makes Goconst,type,var, andfuncdeclarations, which may be a useful way to start writing a Go interface to code written in some other language. no cap.@fileโ reads command-line options fromfile. The options read are inserted in place of the original@fileoption. Iffiledoes not exist, or cannot be read, then the option will be treated literally, and not removed. Options infileare separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional@fileoptions; any such options will be processed recursively. ๐
โจ Compiling C++ Programs โจ
C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx; C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc; and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc). she knows what she's doing.
However, the use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed with the name c++.
When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs. flexible queen.
โจ Options Controlling C Dialect โจ
The following options control the dialect of C (or languages derived from C, such as C++, Objective-C and Objective-C++) that the compiler accepts:
-ansiโ In C mode, this is equivalent to-std=c90. In C++ mode, it is equivalent to-std=c++98.
This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as unix and vax that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.
The alternate keywords __asm__, __extension__, __inline__ and __typeof__ continue to work despite -ansi. You would not want to use them in an ISO C program, of course, but it is useful to put them in header files that might be included in compilations done with -ansi. Alternate predefined macros such as __unix__ and __vax__ are also available, with or without -ansi.
The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -Wpedantic is required in addition to -ansi.
The macro __STRICT_ANSI__ is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things.
Functions that are normally built in but do not have semantics defined by ISO C (such as alloca and ffs) are not built-in functions when -ansi is used. ๐
-std=โ Determine the language standard. This option is currently only supported when compiling C or C++.
The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, such as the asm and typeof keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a ?: expression. On the other hand, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard. As a result, some strict-conforming programs may be rejected. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not.
A value for this option must be provided; possible values are
c90,c89,iso9899:1990โ Support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as-ansifor C code.iso9899:199409โ ISO C90 as modified in amendment 1.c99,c9x,iso9899:1999,iso9899:199xโ ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). Seehttps://gcc.gnu.org/c99status.htmlfor more information. The namesc9xandiso9899:199xare deprecated.c11,c1x,iso9899:2011โ ISO C11, the 2011 revision of the ISO C standard. This standard is substantially completely supported, modulo bugs, floating-point issues (mainly but not entirely relating to optional C11 features from Annexes F and G) and the optional Annexes K (Bounds-checking interfaces) and L (Analyzability). The namec1xis deprecated.c17,c18,iso9899:2017,iso9899:2018โ ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is same as C11 except for corrections of defects (all of which are also applied with-std=c11) and a new value of__STDC_VERSION__, and so is supported to the same extent as C11.c2xโ The next version of the ISO C standard, still under development. The support for this version is experimental and incomplete.gnu90,gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99,gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11,gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17,gnu18โ GNU dialect of ISO C17. This is the default for C code.gnu2xโ The next version of the ISO C standard, still under development, plus GNU extensions. The support for this version is experimental and incomplete.c++98,c++03โ The 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code.gnu++98,gnu++03โ GNU dialect of-std=c++98.c++11,c++0xโ The 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11,gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14,c++1yโ The 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14,gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17,c++1zโ The 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17,gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code. The namegnu++1zis deprecated.c++20,c++2aโ The 2020 ISO C++ standard plus amendments. Support is experimental, and could change in incompatible ways in future releases. The namec++2ais deprecated.gnu++20,gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2b,c++23โ The next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.gnu++2b,gnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
-aux-info filenameโ Output to the given filename prototyped declarations for all functions declared and/or defined in a translation unit, including those in header files. This option is silently ignored in any language other than C.
Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration. ๐
-fno-asmโ bestie, this one tells GCC to STOP treatingasm,inlineandtypeoflike keywords, which means your code is free to use those exact words as identifiers instead ๐ . If you still want the keyword behaviour, just use the underscored versions:__asm__,__inline__and__typeof__. Also, in C,-ansiimplies-fno-asm(surprise!).
In C++, inline is a standard keyword and is not affected by this switch at all โ so if that's the vibe you're going for, you probably want -fno-gnu-keywords instead, which disables typeof but leaves asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only hits the asm and typeof keywords, because inline is a standard keyword in ISO C99. And in C2X mode (-std=c2x or -std=gnu2x), it only touches asm, since typeof is a standard keyword in ISO C2X. the way the keyword list keeps shrinking ๐ญ
-fno-builtin-fno-builtin-functionโ okay so these two say: don't recognize built-in functions that don't start with the__builtin_prefix ๐ซโจ.
Normally GCC generates special code to handle certain built-in functions way more efficiently โ for example, calls to alloca may become single instructions that adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, and you can't change the behaviour of the functions by linking with a different library. that's the tradeoff, no cap ๐ญ
Plus, once a function is recognized as built-in, GCC may use info about it to warn you about problems with calls to it, or to generate more efficient code even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory. iconic behaviour honestly.
With the -fno-builtin-function option, only the built-in function function is disabled. And heads up: function must not begin with __builtin_. If you name a function that isn't built-in in this version of GCC, the option is just ignored (no drama, it moves on ๐). There is no corresponding -fbuiltin-function option, so if you want to enable built-in functions selectively while using -fno-builtin or -ffreestanding, you may define macros such as:
#define abs(n) __builtin_abs ((n))
#define strcpy(d, s) __builtin_strcpy ((d), (s))
-fcond-mismatchโ lets you have conditional expressions with mismatched types in the second and third arguments, and the value of such an expression isvoid. This option is not supported for C++ ๐.-ffreestandingโ asserting that compilation targets a freestanding environment, which implies-fno-builtin. A freestanding environment is one where the standard library may not exist, and program startup may not necessarily be atmainโ the most obvious example being an OS kernel ๐. This is equivalent to-fno-hosted.-fgimpleโ enables parsing of function definitions marked with__GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes. lowkey niche but okay ๐ง-fgnu-tmโ when you specify this, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes. Please note that not all architectures are supported for this feature, bestie ๐.
For more information on GCC's support for transactional memory,
Note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). โ ๏ธ
-fgnu89-inlineโ tells GCC to use the traditional GNU semantics forinlinefunctions when in C99 mode. Using this option is roughly equivalent to adding thegnu_inlinefunction attribute to all inline functions. cute and efficient ๐
The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behaviour โ nothing new, just the usual). But it is not supported in -std=c90 or -std=gnu90 mode.
The preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions. very handy, iykyk ๐
-fhostedโ asserts that compilation targets a hosted environment, which implies-fbuiltin. A hosted environment is one where the entire standard library is available, and in whichmainhas a return type ofint. Examples are nearly everything except a kernel ๐. This is equivalent to-fno-freestanding.-flax-vector-conversionsโ allows implicit conversions between vectors with differing numbers of elements and/or incompatible element types. okay but listen: this option should not be used for new code, fr fr ๐ซ.-fms-extensionsโ accepts some non-standard constructs used in Microsoft header files.
In C++ code, this allows member names in structures to be similar to previous type declarations, like:
typedef int UOW;
struct ABC {
UOW UOW;
};
Some cases of unnamed fields in structures and unions are only accepted with this option. Note that this option is off for all targets except for x86 targets using ms-abi.
-foffload=disable-foffload=default-foffload=target-listโ specify for which OpenMP and OpenACC offload targets code should be generated โจ. The default behaviour, equivalent to-foffload=default, is to generate code for all supported offload targets. The-foffload=disableform generates code only for the host fallback, while-foffload=target-listgenerates code only for the specified comma-separated list of offload targets.
Offload targets are specified in GCC's internal target-triplet format. You can run the compiler with -v to show the list of configured offload targets under OFFLOAD_TARGET_NAMES ๐.
-foffload-options=options-foffload-options=target-triplet-list=optionsโ with-foffload-options=options, GCC passes the specified options to the compilers for all enabled offloading targets. You can specify options that apply only to a specific target or targets by using the-foffload-options=target-list=optionsform. The target-list is a comma-separated list in the same format as for the-foffload=option ๐ซถ.
Typical command lines are
-foffload-options=-lgfortran -foffload-options=-lm
-foffload-options="-lgfortran -lm" -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906 -foffload-options=-lm
-fopenaccโ enables handling of OpenACC directives#pragma accin C/C++ and!$accin Fortran ๐ฅ. When-fopenaccis specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6 <https://www.openacc.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread.-fopenacc-dim=geomโ specifies the default compute dimensions for parallel offload regions that don't explicitly specify them. The geom value is a triple of:-separated sizes, in ordergang,workerand,vector. A size can be omitted to use a target-specific default value ๐ .-fopenmpโ enables handling of OpenMP directives#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran ๐. When-fopenmpis specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5 <https://www.openmp.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread. Also,-fopenmpimplies-fopenmp-simd.-fopenmp-simdโ enables handling of OpenMP'ssimd,declare simd,declare reduction,assume,ordered,scan,loopdirectives and combined or composite directives withsimdas a constituent, using#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran ๐ธ. Other OpenMP directives are just ignored, bestie, we don't see them ๐.-fopenmp-target-simd-clone-fopenmp-target-simd-clone=device-typeโ in addition to generating SIMD clones for functions marked with thedeclare simddirective, GCC also generates clones for functions marked with the OpenMPdeclare targetdirective that are suitable for vectorization when this option is in effect โก. The device-type may be one ofnone,host,nohost, andany, which correspond to keywords for thedevice_typeclause of thedeclare targetdirective; clones are generated for the intersection of devices specified.-fopenmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=anyand-fno-openmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=none.
At -O2 and higher (but not -Os or -Og) this optimization defaults to -fopenmp-target-simd-clone=nohost; otherwise it is disabled by default.
-fpermitted-flt-eval-methods=styleโ okay this one's a bit of a deep cut but stay with me ๐ง. ISO/IEC TS 18661-3 defines new permissible values forFLT_EVAL_METHODthat indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type. These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values ofFLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values ๐.
-fpermitted-flt-eval-methods specifies whether the compiler should allow only the values of FLT_EVAL_METHOD specified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3.
style is either c11 or ts-18661-3 as appropriate.
The default when in a standards compliant mode (-std=c11 or similar) is -fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11 or similar) is -fpermitted-flt-eval-methods=ts-18661-3. periodt ๐
-fplan9-extensionsโ accepts some non-standard constructs used in Plan 9 code ๐.
This enables -fms-extensions, permits passing pointers to structures with anonymous fields to functions that expect pointers to elements of the type of the field, and permits referring to anonymous fields declared using a typedef. Note: this is only supported for C, not C++ ๐ซ.
-fsigned-bitfields,-funsigned-bitfields,-fno-signed-bitfields,-fno-unsigned-bitfieldsโ these four decide whether a bit-field is signed or unsigned when the declaration just... doesn't say"signed"or"unsigned"anywhere ๐. Default vibes? signed, because it's consistent โ the basic integer types like"int"are signed types, so bit-fields match the family. ๐ซถ-fsigned-charโ let the type"char"be signed, exactly like"signed char".
Heads up bestie: this is literally equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. And the other way round too โ -fno-signed-char is equivalent to -funsigned-char. Flip, flip, flip. ๐ฆ
-funsigned-charโ let the type"char"be unsigned, like"unsigned char".
Every kind of machine has its own default for what "char" should be. It's either like "unsigned char" by default or like "signed char" by default. No universal answer, it's giving platform-dependent ๐
.
Ideally, a portable program should always use "signed char" or "unsigned char" whenever it actually cares about the signedness of an object. But like... tons of programs out there just use plain "char" and expect it to be signed, or expect it to be unsigned, depending on whatever machines they were originally written for. This option (and its inverse) is your rescue mission: it lets you make such a program work with the opposite default. ๐ฅ
And a lil detail that matters: the type "char" is always a distinct type from each of "signed char" or "unsigned char", even though its behavior is always just like one of those two. Distinct. Not the same. Periodt. โจ
-fstrict-flex-arraysโ controls when a trailing array of a structure gets treated as a flexible array member, for the purpose of accessing the elements of such an array. ๐
The positive form is equivalent to -fstrict-flex-arrays=3, the strictest โ a trailing array is treated as a flexible array member only when it's declared as a flexible array member per C99 standard onwards. The negative form is equivalent to -fstrict-flex-arrays=0, the least strict โ all trailing arrays of structures get treated as flexible array members. Choose your chaos level lol ๐
-fstrict-flex-arrays=levelโ same deal, but now you're driving ๐. Controls when a trailing array of a structure is treated as a flexible array member for the purpose of accessing the elements of such an array. The value oflevelcontrols the level of strictness.
The possible values of level are the same as for the "strict_flex_array" attribute.
And you can control this behavior for one specific trailing array field of a structure by using the variable attribute "strict_flex_array" attribute. Targeted. Surgical. Iconic. ๐
-fsso-struct=endiannessโ sets the default scalar storage order of structures and unions to the specified endianness. The accepted values arebig-endian,little-endianandnativefor the native endianness of the target (which is the default). This option is not supported for C++. ๐
โ ๏ธ Warning, bestie, for real: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it, if the specified endianness is not the native endianness of the target. Binary incompatible. That means it will not talk to the other code. Do not do this casually. ๐ญ
๐ Options Controlling C++ Dialect ๐
This section is all about the command-line options that are only meaningful for C++ programs ๐. But plot twist โ you can also use most of the GNU compiler options no matter what language your program is in. For example, you might compile a file firstClass.C like this:
g++ -g -fstrict-enums -O -c firstClass.C
In this example, only -fstrict-enums is an option meant only for C++ programs; you can use the other options with any language supported by GCC. Multi-talented. ๐
Also, some options for compiling C programs, such as -std, are also relevant for C++ programs. Sharing is caring. ๐ซถ
Here is a list of options that are only for compiling C++ programs:
-fabi-version=nโ use version n of the C++ ABI. The default is version0.
Version 0 refers to the version conforming most closely to the C++ ABI specification. Therefore, the ABI obtained using version 0 will change in different versions of G++ as ABI bugs are fixed. Yes, the default is the moving target. That's just how it is. ๐ญ
Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.
Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.
Version 3 corrects an error in mangling a constant address as a template argument.
Version 4, which first appeared in G++ 4.5, implements a standard mangling for vector types.
Version 5, which first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.
Version 6, which first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.
Version 7, which first appeared in G++ 4.8, treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.
Version 8, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
Version 9, which first appeared in G++ 5.2, corrects the alignment of "nullptr_t".
Version 10, which first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).
Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors.
Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Oopsie. ๐
Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. Cleanup era. โจ
Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression.
Version 15, which first appeared in G++ 10.3, corrects G++ 10 ABI tag regression.
Version 16, which first appeared in G++ 11, changes the mangling of "__alignof__" to be distinct from that of "alignof", and dependent operator names.
Version 17, which first appeared in G++ 12, fixes layout of classes that inherit from aggregate classes with default member initializers in C++14 and up.
Version 18, which first appeared in G++ 13, fixes manglings of lambdas that have additional context.
See also -Wabi. ๐
-fabi-compat-version=nโ on targets that support strong aliases, G++ works around mangling changes by creating an alias with the correct mangled name when defining a symbol with an incorrect mangled name. This switch specifies which ABI version to use for the alias.
With -fabi-version=0 (the default), this defaults to 13 (GCC 8.2 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
And the crossover rules: if this option is not provided but -Wabi=n is, then that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), then the version from this option is used for the warning. Teamwork, but make it specific. ๐
-fno-access-controlโ turn off all access checking. ๐ This switch is mainly useful for working around bugs in the access control code. It's the "we don't do rules here" flag.-faligned-newโ enable support for C++17"new"of types that require more alignment than"void* ::operator new(std::size_t)"provides. A numeric argument such as-faligned-new=32can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default ofalignof(std::max_align_t). Key word: few. ๐ซถ
This flag is enabled by default for -std=c++17.
-fchar8_t,-fno-char8_tโ enable support for"char8_t"as adopted for C++20. This includes the addition of a new"char8_t"fundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new"__cpp_char8_t"and"__cpp_lib_char8_t"feature test macros. It's a whole glow-up. ๐ธ
This option enables functions to be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
and introduces new signatures for user-defined literals:
int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;
The change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. For example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified. ๐ญ
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
-fcheck-newโ check that the pointer returned by"operator new"is non-null before attempting to modify the storage allocated. ๐ต๏ธ
This check is normally unnecessary because the C++ standard specifies that "operator new" only returns 0 if it is declared throw(), in which case the compiler always checks the return value even without this option. In all other cases, when "operator new" has a non-empty exception specification, memory exhaustion is signalled by throwing "std::bad_alloc". See also new (nothrow).
-fconceptsโ concepts time bestie!! โจ turns on support for the C++ Concepts feature so you can constrain template arguments and stop your templates from accepting literally anything with a pulse. With-std=c++20and above, Concepts are part of the language standard, so-fconceptsdefaults to on. ๐-fconcepts-tsโ some constructs that were allowed by the earlier C++ Extensions for Concepts Technical Specification,ISO 19217 (2015), but didn't make it into the standard, can additionally be enabled by this. So it's the throwback-vibes option. ๐- *
-fconstexpr-depth=n* โ sets the maximum nested evaluation depth for C++11 constexpr functions to n. A limit is needed to detect endless recursion during constant expression evaluation (otherwise your compiler just spirals forever, not the cute kind of spiral ๐). The minimum specified by the standard is512. - *
-fconstexpr-cache-depth=n* โ sets the maximum level of nested evaluation depth for C++11 constexpr functions that will be cached to n. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations ๐) against memory consumption (when the cache grows very large from highly recursive evaluations ๐ญ). The default is8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you. science experiment arc, go off. -fconstexpr-fp-exceptโ okay so Annex F of the C standard says that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value. ๐ซ This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined.
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
- *
-fconstexpr-loop-limit=n* โ sets the maximum number of iterations for a loop in C++14 constexpr functions to n. Again, a limit is needed to detect infinite loops during constant expression evaluation. The default is262144(that's1<<18for the hex girlies ๐ง). - *
-fconstexpr-ops-limit=n* โ sets the maximum number of operations during a single constexpr evaluation. Here's the tea ๐: even when the number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long. The default is33554432(1<<25). -fcontractsโ enables experimental support for the C++ Contracts feature, as briefly added to and then removed from the C++20 working paper(N4820). The implementation also includes proposed enhancements from papersP1290,P1332, andP1429. This functionality is intended mostly for those interested in experimentation towards refining the feature to get it into shape for a future C++ standard. lab-coat energy ๐ฅผโจ
On violation of a checked contract, the violation handler is called. Users can replace the violation handler by defining:
void
handle_contract_violation (const std::experimental::contract_violation&);
There are different sets of additional flags that can be used together to specify which contracts will be checked and how, for N4820 contracts, P1332 contracts, or P1429 contracts; these sets cannot be used together. (pick a lane bestie ๐ซ)
-fcontract-mode=[on|off]โ control whether any contracts have any semantics at all. Defaults toon.-fcontract-assumption-mode=[on|off]โ[N4820]control whether contracts with levelaxiomshould have theassumesemantic. Defaults toon.-fcontract-build-level=[off|default|audit]โ[N4820]specify which level of contracts to generate checks for. Defaults todefault.-fcontract-continuation-mode=[on|off]โ[N4820]control whether to allow the program to continue executing after a contract violation. That is, do checked contracts have themaybesemantic described below rather than theneversemantic. Defaults tooff.- *
-fcontract-role=<name>:<default>,<audit>,<axiom>* โ[P1332]specify the concrete semantics for each contract level of a particular contract role. - *
-fcontract-semantic=[default|audit|axiom]:<semantic>* โ[P1429]specify the concrete semantic for a particular contract level. -fcontract-strict-declarations=[on|off]โ control whether to reject adding contracts to a function after its first declaration. Defaults tooff.
The possible concrete semantics that can be specified with -fcontract-role or -fcontract-semantic are:
"ignore"โ this contract has no effect. it's giving nothing, and that's the point."assume"โ this contract is treated like C++23"[[assume]]"."check_never_continue","never","abort"โ this contract is checked. If it fails, the violation handler is called. If the handler returns,"std::terminate"is called. ๐"check_maybe_continue","maybe"โ this contract is checked. If it fails, the violation handler is called. If the handler returns, execution continues normally. ๐ซถ
-fcoroutinesโ enable support for the C++ coroutines extension (experimental). she's experimental and she knows it โจ-fno-elide-constructorsโ the C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases. This option also causes G++ to call trivial member functions which otherwise would be expanded inline. In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.-fno-enforce-eh-specsโ don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard ๐ณ, but may be useful for reducing code size in production builds, much like defining"NDEBUG". This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. So like... be normal about it.-fextern-tls-init,-fno-extern-tls-initโ the C++11 and OpenMP standards allow"thread_local"and"threadprivate"variables to have dynamic (runtime) initialization. To support this, any use of such a variable goes through a wrapper function that performs any necessary initialization. When the use and definition of the variable are in the same translation unit, this overhead can be optimized away, but when the use is in a different translation unit there is significant overhead even if the variable doesn't actually need dynamic initialization. ๐ฅฒ If the programmer can be sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because the variable is statically initialized, or a use of the variable in the defining TU will be executed before any uses in another TU), they can avoid this overhead with the-fno-extern-tls-initoption.
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init.
-ffold-simple-inlines,-fno-fold-simple-inlinesโ permit the C++ frontend to fold calls to"std::move","std::forward","std::addressof"and"std::as_const". In contrast to inlining, this means no debug information will be generated for such calls. Since these functions are rarely interesting to debug, this flag is enabled by default unless-fno-inlineis active. ๐-fno-gnu-keywordsโ do not recognize"typeof"as a keyword, so that code can use this word as an identifier. You can use the keyword"__typeof__"instead. This option is implied by the strict ISO C++ dialects:-ansi,-std=c++98,-std=c++11, etc.-fimplicit-constexprโ make inline functions implicitly constexpr, if they satisfy the requirements for a constexpr function. This option can be used in C++14 mode or later. This can result in initialization changing from dynamic to static and other optimizations. glow-up for your inline functions fr fr โจ-fno-implicit-templatesโ never emit code for non-inline templates that are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. If you use this option, you must take care to structure your code to include all the necessary explicit instantiations to avoid getting undefined symbols at link time. โ ๏ธ-fno-implicit-inline-templatesโ don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization need the same set of explicit instantiations.-fno-implement-inlinesโ to save space, do not emit out-of-line copies of inline functions controlled by"#pragma implementation". This causes linker errors if these functions are not inlined everywhere they are called. ๐ space-saving but at what cost-fmodules-ts,-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, as that is the default. Even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. the way that C++20 modules just Do That ๐-fmodule-header,-fmodule-header=user,-fmodule-header=systemโ compile a header file to create an importable header unit.-fmodule-implicit-inlineโ member functions defined in their class definitions are not implicitly inline for modular code. This is different to traditional C++ behavior, for good reasons. However, it may result in a difficulty during code porting. This option makes such function definitions implicitly inline. It does however generate an ABI incompatibility, so you must use it everywhere or nowhere ๐จ (Such definitions outside of a named module remain implicitly inline, regardless.)-fno-module-lazyโ disable lazy module importing and module mapper creation. she said no thanks to lazy, we're doing it live-fmodule-mapper=[hostname]:port[?ident]-fmodule-mapper=|program[?ident] args...-fmodule-mapper==socket[?ident]-fmodule-mapper=<>[inout][?ident]-fmodule-mapper=<in>out[?ident]-fmodule-mapper=file[?ident]
an oracle to query for module name to filename mappings ๐ฎ If unspecified the CXX_MODULE_MAPPER environment variable is used, and if that is unset, an in-process default is provided. bestie the oracle does not take walk-ins
-fmodule-onlyโ bestie, this one ONLY spits out the Compiled Module Interface and โจnothing elseโจ. No object file, no crumbs. Just the CMI, that's the whole fit.-fms-extensionsโ turns OFF theWpedanticwarnings about stuff people use in MFC, like implicitintand pulling a pointer to a member function through non-standard syntax. Basically: "yeah we know it's not kosher, we're not gonna yell about it ๐ ".-fnew-inheriting-ctorsโ switches on the P0136 glow-up to how C++11 constructor inheritance actually behaves. It's part of C++17 but it's also considered a Defect Report against C++11 and C++14, so it's retroactively iconic. It's on by default unless you go-fabi-version=10or lower (rude).-fnew-ttp-matchingโ enables the P0522 fix for Core issue 150, i.e. template template parameters and default arguments. Translation: a template with default template arguments can now be passed as an argument for a template template parameter that has fewer template parameters. Enabled by default for-std=c++17๐ซถ.-fno-nonansi-builtinsโ disables the built-in declarations of functions that ANSI/ISO C never mandated. The whole squad getting yeeted:ffs,alloca,_exit,index,bzero,conjf, and friends. No cap.-fnothrow-optโ treats athrow()exception specification like it were anoexceptspec, so the compiler can shrink or fully delete the text-size overhead compared to a function with no exception spec at all. Plot twist though: if the function has local variables whose types have non-trivial destructors, the exception spec actually makes the function smaller, because the EH cleanups for those locals can be optimized away. The semantic tea โ: an exception thrown out of a function with such a spec ends in a call toterminateinstead ofunexpected.-fno-operator-namesโ do NOT treat those operator-name keywordsand,bitand,bitor,compl,not,orandxoras synonyms-as-keywords. They're just... words now. lowercase behavior fr.-fno-optional-diagsโ kills the diagnostics that the standard literally says a compiler does not need to issue. rn the only such diagnostic G++ actually issues is the one for a name having multiple meanings within a class. that's the whole list bestie.-fpermissiveโ demotes some diagnostics about nonconformant code from errors down to warnings. So yeah, using-fpermissivelets some nonconforming code actually compile. ๐ญ live your truth.-fno-pretty-templatesโ ok so normally, when an error message points at a specialization of a function template, the compiler prints the template's signature followed by the template arguments and any typedefs or typenames in that signature (likevoid f(T) [with T = int]instead ofvoid f(int)) so it's obvious which template is being dramatic. And when an error refers to a specialization of a class template, the compiler omits any template arguments that match that template's default template arguments. If either of those behaviors makes the error HARDER to read instead of easier,-fno-pretty-templatesdisables them both. you're welcome.-fno-rttiโ disables generating info about every class with virtual functions that the C++ run-time type identification features (dynamic_castandtypeid) need. If you don't use those parts of the language, this flag saves you some space, slay. Heads up though: exception handling uses the same info, but G++ generates it as needed. Anddynamic_castcan still be used for casts that don't require run-time type information โ i.e. casts tovoid *or to unambiguous base classes.
โ ๏ธ Mixing code compiled with-frttiand code compiled with-fno-rttimay not work. For example, programs may fail to link if a class compiled with-fno-rttiis used as a base for a class compiled with-frtti. ๐ do not do this to yourself.
-fsized-deallocationโ enables the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
as introduced in C++14. Super useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. And -Wsized-deallocation will warn you about places that might wanna add a definition ๐.
-fstrict-enumsโ lets the compiler optimize using the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that fits in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value into the enumerated type. so like... only if you're being feral.-fstrong-eval-orderโ evaluates member access, array subscripting, and shift expressions left-to-right, and evaluates assignment right-to-left, as adopted for C++17. Enabled by default with-std=c++17. There's also-fstrong-eval-order=some, which enables just the ordering of member access and shift expressions, and that's the default without-std=c++17.-ftemplate-backtrace-limit=nโ sets the max number of template instantiation notes for a single warning or error to n. The default value is10. yes we're capping the backtrace, it's giving self-care โจ.-ftemplate-depth=nโ sets the maximum instantiation depth for template classes to n. You need some limit on template instantiation depth to catch endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than17(changed to1024in C++11). The default value is900, because the compiler can run out of stack space before even hitting 1024 in some situations ๐ญ. don't ask.-fno-threadsafe-staticsโ don't emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shave code size slightly in code that genuinely doesn't need to be thread-safe. only if you're sure bestie ๐ซถ.-fuse-cxa-atexitโ registers destructors for objects with static storage duration with the__cxa_atexitfunction instead of theatexitfunction. This option is required for fully standards-compliant handling of static destructors, but it only works if your C library supports__cxa_atexit. check first, no cap.-fno-use-cxa-get-exception-ptrโ don't use the__cxa_get_exception_ptrruntime routine. Doing this causesstd::uncaught_exceptionto be incorrect, but it's necessary if that runtime routine isn't available. trade-offs, babes.-fvisibility-inlines-hiddenโ this switch declares that you (the user) are not attempting to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.
The effect: GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))), so they don't show up in the export table of a DSO and don't need a PLT indirection when used inside that DSO. Turning this on can have a dramatic effect on load and link times of a DSO, because it massively shrinks the dynamic export table when the library makes heavy use of templates ๐ฅ.
The behavior of this switch is not quite the same as marking the methods hidden directly, because it does not affect static variables local to the function and doesn't make the compiler deduce that the function is defined in only one shared object.
You can mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do wanna compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility has no effect, btw.
Explicitly instantiated inline methods are unaffected by this option, since their linkage might otherwise cross a shared library boundary. special case, iconic.
-fvisibility-ms-compatโ this flag tries to use visibility settings to make GCC's C++ linkage model compatible with Microsoft Visual Studio's. it's giving diplomatic relations ๐ค.
The flag makes these changes to GCC's linkage model:
- It sets the default visibility to
hidden, like-fvisibility=hidden. - Types, but not their members, are not hidden by default.
- The One Definition Rule is relaxed for types without explicit visibility specifications that are defined in more than one shared object: those declarations are permitted if they are permitted when this option is not used.
In new code it's better to use -fvisibility=hidden and export the classes that are meant to be externally visible. Unfortunately, it's possible for code to rely โ perhaps accidentally โ on the Visual Studio behavior. ๐
Among the consequences of these changes: static data members of the same type with the same name but defined in different shared objects are different, so changing one doesn't change the other; and pointers to function members defined in different shared objects may not compare equal. When this flag is given, it's a violation of the ODR to define types with the same name differently. so like, be careful.
-fno-weakโ don't use weak symbol support, even if the linker provides it. By default G++ uses weak symbols if they're available. This option exists only for testing, and should not be used by end-users; it results in inferior code and has no benefits. It may be removed in a future release of G++. ๐จ do not touch, seriously.-fext-numeric-literals(C++ and Objective-C++ only) โ accepts imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off, those suffixes are treated as C++11 user-defined literal numeric suffixes. This is on by default for all pre-C++11 dialects and all GNU dialects:-std=c++98,-std=gnu++98,-std=gnu++11,-std=gnu++14. This option is off by default for ISO C++11 onwards (-std=c++11, ...).-nostdinc++โ don't search for header files in the standard directories specific to C++, but DO still search the other standard directories. (This option is used when building the C++ library.) so it's not a full blackout, just a C++-flavored one ๐ .-flang-info-include-translate,-flang-info-include-translate-not,-flang-info-include-translate=headerโ informs you about include translation events ๐ฃ. The first one notes accepted include translations, the second notes declined include translations. Theheaderform informs you about include translations relating to that specific header. And if header is of the form"user"or<system>, it gets resolved to a specific user or system header using the include path. iykyk.-flang-info-module-cmi,-flang-info-module-cmi=module โ bestie, this one's all about peeking at Compiled Module Interface pathnames ๐ . The plain form notes every CMI pathname that gets read. The=module form won't note the reading of one specific module's CMI. And heads up: module can be a named module **or a header-unit (you signal "header-unit" by either giving a pathname that has directory separators in it, or by wrapping the thing in"<>"or""). iykyk ๐-stdlib=libstdc++,libc++โ when G++ was configured to support this option, it lets you pick an alternate C++ runtime library โจ. Two options on the menu:libstdc++โ the default, the native C++ runtime for G++ ๐ซถlibc++โ the C++ runtime that's installed on some operating systems (like Darwin versions from Darwin11 onwards) ๐ฆ
Picking one switches G++ to use the headers from that library, and makes it emit -lstdc++ or -lc++ (respectively, obviously ๐
) whenever a C++ runtime is needed for linking.
Also, these warning options only have meaning for C++ programs ๐:
-Wabi-tag(C++ and Objective-C++ only) โ warns when a type that has an ABI tag gets used in a context that doesn't have that ABI tag. Wanna know more about ABI tags? Go see C++ Attributes ๐.-Wcomma-subscript(C++ and Objective-C++ only) โ warns about comma expressions showing up inside a subscripting expression ๐ญ. This usage got deprecated in C++20 and is gonna be removed in C++23. But plot twist: a comma expression wrapped in"( )"is not deprecated. Example:
void f(int *a, int b, int c) {
a[b,c]; // deprecated in C++20, invalid in C++23
a[(b,c)]; // OK
}
In C++23 it's actually valid to have comma-separated expressions in a subscript when an overloaded subscript operator is found and it supports the right number and types of arguments โจ. G++ will accept the formerly valid syntax for code that isn't valid in C++23 but used to be valid (though deprecated) in C++20, with a pedantic warning that you can turn off using -Wno-comma-subscript.
Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated. ๐
-Wctad-maybe-unsupported(C++ and Objective-C++ only) โ warns when you do class template argument deduction (CTAD) on a type that has no explicitly written deduction guides ๐. It points out the cases where CTAD only succeeded because the compiler synthesized the implicit deduction guides โ which might not be what the programmer actually wanted, ngl. Some style guides only allow CTAD on types that specifically "opt-in", i.e. types designed to support CTAD. You can suppress this warning with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
S(T) { }
};
// Guide with incomplete parameter type will never be considered.
S(allow_ctad_t) -> S<void>;
-Wctor-dtor-privacy(C++ and Objective-C++ only) โ warns when a class looks straight-up unusable because every constructor or destructor in it is private, and it has neither friends nor public static member functions ๐. Also warns if there are no non-private methods, and there's at least one private member function that isn't a constructor or a destructor.-Wdangling-reference(C++ and Objective-C++ only) โ warns when a reference gets bound to a temporary whose lifetime has already ended ๐ญ. Like:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling
In that example up there, two temporaries get created โ one for each argument โ and a reference to one of them gets returned. But bestie, both temporaries are destroyed at the end of the full expression, so the reference r is dangling. This warning also catches dangling references in member initializer lists:
const int& f(const int& i) { return i; }
struct S {
const int &r; // r is dangling
S() : r(f(10)) { }
};
Member functions get checked too, but only their object argument:
struct S {
const S& self () { return *this; }
};
const S& s = S().self(); // s is dangling
Some functions are safe in this respect, like "std::use_facet": they take and return a reference, but they don't return one of their arguments โ which can fool the warning ๐ตโ๐ซ. You can exclude such functions from the warning by wrapping them in a "#pragma":
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-reference"
const T& foo (const T&) { ... }
#pragma GCC diagnostic pop
-Wdangling-reference also warns about code like
auto p = std::minmax(1, 2);
where "std::minmax" returns "std::pair<const int&, const int&>", and both references dangle after the end of the full expression containing the "std::minmax" call ๐ซ .
This warning is enabled by -Wextra.
-Wdelete-non-virtual-dtor(C++ and Objective-C++ only) โ warns when"delete"is used to destroy an instance of a class that has virtual functions and a non-virtual destructor ๐จ. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class doesn't have a virtual destructor. This warning is enabled by-Wall.-Wdeprecated-copy(C++ and Objective-C++ only) โ warns that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up ๐ . This warning is enabled by-Wextra. And with-Wdeprecated-copy-dtor, it also deprecates if the class has a user-provided destructor.-Wno-deprecated-enum-enum-conversion(C++ and Objective-C++ only) โ disables the warning about the case where the usual arithmetic conversions get applied on operands where one is of enumeration type and the other is of a different enumeration type ๐. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;
-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only) โ disables the warning about the case where the usual arithmetic conversions get applied on operands where one is of enumeration type and the other is of a floating-point type ๐ฆ. This conversion was deprecated in C++20. Example time:
enum E1 { e };
enum E2 { f };
bool b = e <= 3.7;
-Wdeprecated-enum-float-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-init-list-lifetime(C++ and Objective-C++ only) โ don't warn about uses of"std::initializer_list"that are likely to result in dangling pointers ๐ญ. Because the underlying array for an"initializer_list"is handled like a normal C++ temporary object, it's genuinely easy to accidentally keep a pointer to the array past the end of the array's lifetime. For example:- If a function returns a temporary
"initializer_list", or a local"initializer_list"variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer. - If a new-expression creates an
"initializer_list", the array only lives until the end of the enclosing full-expression, so the"initializer_list"in the heap has a dangling pointer. - When an
"initializer_list"variable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement the"initializer_list"variable has a dangling pointer.
- If a function returns a temporary
// li's initial underlying array lives as long as li
std::initializer_list<int> li = { 1,2,3 };
// assignment changes li to point to a temporary array
li = { 4, 5 };
// now the temporary is gone and li has a dangling pointer
int i = li.begin()[0] // undefined behavior
- When a list constructor stores the
"begin"pointer from the"initializer_list"argument, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporary"initializer_list", the pointer is left dangling by the end of the variable declaration statement ๐.
-Winvalid-constexprโ warns when a function never produces a constant expression ๐. In C++20 and earlier, for every"constexpr"function and function template, there must be at least one set of function arguments in at least one instantiation such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression. C++23 removed that restriction, so it's possible to have a function or function template marked"constexpr"where no invocation satisfies the requirements of a core constant expression. Wild, right?
This warning is enabled as a pedantic warning by default in C++20 and earlier. In C++23, -Winvalid-constexpr can be turned on, and in that case it'll be an ordinary warning. Example:
void f (int& i);
constexpr void
g (int& i)
{
// Warns by default in C++20, in C++23 only with -Winvalid-constexpr.
f(i);
}
-Winvalid-imported-macrosโ verifies that all imported macro definitions are valid at the end of compilation โจ. This is not enabled by default, since it requires extra processing to figure out. It may be useful when you're preparing sets of header-units, to make sure the macros are consistent ๐.-Wno-literal-suffix(C++ and Objective-C++ only) โ don't warn when a string or character literal is followed by a ud-suffix that does not begin with an underscore ๐. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens, so that it stays backwards compatible with code that uses formatting macros from"<inttypes.h>". For example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
int main() {
int64_t i64 = 123;
printf("My int64: %" PRId64"\n", i64);
}
so like, in this exact case, "PRId64" is treated as a separate preprocessing token. ๐
This option also controls warnings when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization. bestie, that's the rule ๐ซถ
These warnings are enabled by default. โจ
-Wno-narrowing(C++ and Objective-C++ only) โ For C++11 and later standards, narrowing conversions are diagnosed by default, as required by the standard. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but-Wno-narrowingsuppresses the diagnostic. Note that this does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed in SFINAE contexts. ๐
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.
int i = { 2.2 }; // error: narrowing from double to int
This flag is included in -Wall and -Wc++11-compat.
-Wnoexcept(C++ and Objective-C++ only) โ Warn when anoexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e.throw()or"noexcept") but is known by the compiler to never throw an exception. the compiler is like โI know you won't throw, but the signature says otherwiseโ ๐ญ-Wnoexcept-type(C++ and Objective-C++ only) โ Warn if the C++17 feature making"noexcept"part of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat. fr fr, ABI be like that sometimes.
As an example:
template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }
In C++14, "f" calls "f<void(*)()>", but in C++17 it calls "f<void(*)()noexcept>".
-Wclass-memaccess(C++ and Objective-C++ only) โ Warn when the destination of a call to a raw memory function such as"memset"or"memcpy"is an object of class type, and when writing into such an object might bypass the class non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects may violate invariants maintained by member functions of the class. For example, the call to"memset"below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available. do NOT be out here memset-ing your std::string, bestie ๐
std::string str = "abc";
memset (&str, 0, sizeof str);
The -Wclass-memaccess option is enabled by -Wall. Explicitly casting the pointer to the class object to "void *" or to a type that can be safely accessed by the raw memory function suppresses the warning.
-Wnon-virtual-dtor(C++ and Objective-C++ only) โ Warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class, in which case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or base class. This warning is automatically enabled if-Weffc++is specified. The-Wdelete-non-virtual-dtoroption (enabled by-Wall) should be preferred because it warns about the unsafe cases without false positives. virtual destructors are the moment, periodt.-Wregister(C++ and Objective-C++ only) โ Warn on uses of the"register"storage class specifier, except when it is part of the GNU Explicit Register Variables extension. The use of the"register"keyword as storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with-std=c++17. rip register, you were iconic in C but C++ said bye ๐-Wreorder(C++ and Objective-C++ only) โ Warn when the order of member initializers given in the code does not match the order in which they must be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for "i" and "j" to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall. the compiler said โI got you, but I'm telling youโ ๐
-Wno-pessimizing-move(C++ and Objective-C++ only) โ This warning warns when a call to"std::move"prevents copy elision. A typical scenario when copy elision can occur is when returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, and is not a function parameter, and has the same type as the function return type. so like, the move is giving anti-optimization energy ๐ญ
struct T {
...
};
T fn()
{
T t;
...
return std::move (t);
}
But in this example, the "std::move" call prevents copy elision.
This warning is enabled by -Wall.
-Wno-redundant-move(C++ and Objective-C++ only) โ This warning warns about redundant calls to"std::move"; that is, when a move operation would have been performed even without the"std::move"call. This happens because the compiler is forced to treat the object as if it were an rvalue in certain situations such as returning a local variable, where copy elision isn't applicable. Consider:
struct T {
...
};
T fn(T t)
{
...
return std::move (t);
}
Here, the "std::move" call is redundant. Because G++ implements Core Issue 1579, another example is:
struct T { // convertible to U
...
};
struct U {
...
};
U fn()
{
T t;
...
return std::move (t);
}
In this example, copy elision isn't applicable because the type of the expression being returned and the function return type differ, yet G++ treats the return value as if it were designated by an rvalue.
This warning is enabled by -Wextra.
-Wrange-loop-construct(C++ and Objective-C++ only) โ This warning warns when a C++ range-based for-loop is creating an unnecessary copy. This can happen when the range declaration is not a reference, but probably should be. For example:
struct S { char arr[128]; };
void fn () {
S arr[5];
for (const auto x : arr) { ... }
}
It does not warn when the type being copied is a trivially-copyable type whose size is less than 64 bytes.
This warning also warns when a loop variable in a range-based for-loop is initialized with a value of a different type resulting in a copy. For example:
void fn() {
int arr[10];
for (const double &x : arr) { ... }
}
In the example above, in every iteration of the loop a temporary value of type "double" is created and destroyed, to which the reference "const double &" is bound.
This warning is enabled by -Wall.
-Wredundant-tags(C++ and Objective-C++ only) โ Warn about redundant class-key and enum-key in references to class types and enumerated types in contexts where the key can be eliminated without causing an ambiguity. For example:
struct foo;
struct foo *p; // warn that keyword struct can be eliminated
On the other hand, in this example there is no warning:
struct foo;
void foo (); // "hides" struct foo
void bar (struct foo&); // no warning, keyword struct is necessary
-Wno-subobject-linkage(C++ and Objective-C++ only) โ Do not warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage. If a type A depends on a type B with no or internal linkage, defining it in multiple translation units would be an ODR violation because the meaning of B is different in each translation unit. If A only appears in a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn't give this warning for types defined in the main.Cfile, as those are unlikely to have multiple definitions.-Wsubobject-linkageis enabled by default. anonymous namespace said โlet me fix that for youโ โจ-Weffc++(C++ and Objective-C++ only) โ Warn about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:- Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
- Prefer initialization to assignment in constructors.
- Have
"operator="return a reference to*this. - Don't try to return a reference when you must return an object.
- Distinguish between prefix and postfix forms of increment and decrement operators.
- Never overload
"&&","||", or",".
This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of virtual destructor in accessible non-polymorphic bases classes too.
When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings. ngl, Effective C++ is lowkey the blueprint ๐
-Wno-exceptions(C++ and Objective-C++ only) โ Disable the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. catch blocks out here playing hide and seek ๐ญ-Wstrict-null-sentinel(C++ and Objective-C++ only) โ Warn about the use of an uncasted"NULL"as sentinel. When compiling only with GCC this is a valid sentinel, as"NULL"is defined to"__null". Although it is a null pointer constant rather than a null pointer, it is guaranteed to be of the same size as a pointer. But this use is not portable across different compilers. portability said โnot on my watchโ ๐ซถ-Wno-non-template-friend(C++ and Objective-C++ only) โ Okay bestie, this one turns off warnings when you declare non-template friend functions inside a template. Back in the dinosaur age of GCC (before the ISO standard was a thing), something likefriend int foo(int)โ where the friend name is an unqualified-id โ could be seen as a specific specialization of a template function. The warning exists to catch compatibility drama, and it's enabled by default. So if you're not about that warning life, use this flag. ๐-Wold-style-cast(C++ and Objective-C++ only) โ This one yells at you if you use an old-style C cast to a non-void type in C++. Like, no bestie, the new-style casts โdynamic_cast,static_cast,reinterpret_cast, andconst_castโ are way less vulnerable to unintended effects and are so much easier to search for. It's giving safety. โจ-Woverloaded-virtual,-Woverloaded-virtual=n(C++ and Objective-C++ only) โ Warns when a function declaration hides virtual functions from a base class. Example time:
struct A {
virtual void f();
};
struct B: public A {
void f(int); // does not override
};
Here the A class version of f is hidden in B, and code like:
B* b;
b->f();
just fails to compile. Oops. If the different signatures aren't an accident, the simplest fix is to add a using-declaration to the derived class to un-hide the base function, like adding using A::f; to B.
Now the optional level suffix controls what happens when all the declarations in the derived class override virtual functions in the base class, even if not all base functions are overridden:
struct C {
virtual void f();
virtual void f(int);
};
struct D: public C {
void f(int); // does override
};
This pattern is less likely to be a mistake; if D is only used virtually, the user might have decided the base class semantics for some overloads are fine. At level 1, this case doesn't warn; at level 2, it does. -Woverloaded-virtual by itself selects level 2. Level 1 is included in -Wall. So yeah, pick your level. ๐
-Wno-pmf-conversions(C++ and Objective-C++ only) โ Disables the diagnostic for converting a bound pointer to member function to a plain pointer. So if you're doing that, this flag says "I got it, chill." ๐-Wsign-promo(C++ and Objective-C++ only) โ Warns when overload resolution chooses a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. So respect the standard, bestie. โญ-Wtemplates(C++ and Objective-C++ only) โ Warns when a primary template declaration is encountered. Some coding rules disallow templates, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so you can still use the STL. You may also instantiate or specialize templates. So it's not a total lockdown. ๐ฆ-Wmismatched-new-delete(C++ and Objective-C++ only) โ Warns for mismatches between calls tooperator neworoperator deleteand the corresponding call to the allocation or deallocation function. This includes invocations of C++operator deletewith pointers returned from either mismatched forms ofoperator new, or from other functions that allocate objects for which theoperator deleteisn't a suitable deallocator, as well as calls to other deallocation functions with pointers returned fromoperator newfor which the deallocation function isn't suitable.
For example, the delete expression in the function below is diagnosed because it doesn't match the array form of the new expression the pointer argument was returned from. Similarly, the call to free is also diagnosed.
void f ()
{
int *a = new int[n];
delete a; // warning: mismatch in array forms of expressions
char *p = new char[n];
free (p); // warning: mismatch between new and free
}
The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete. -Wmismatched-new-delete is included in -Wall. ๐ฅ
-Wmismatched-tags(C++ and Objective-C++ only) โ Warns for declarations of structs, classes, and class templates and their specializations with a class-key that does not match either the definition or the first declaration if no definition is provided. For example, the declaration ofstruct Objectin the argument list ofdrawtriggers the warning. To avoid it, either remove the redundant class-keystructor replace it withclassto match its definition.
class Object {
public:
virtual ~Object () = 0;
};
void draw (struct Object*);
It is not wrong to declare a class with the class-key struct as the example above shows. The -Wmismatched-tags option is intended to help achieve a consistent style of class declarations. In code that is intended to be portable to Windows-based compilers the warning helps prevent unresolved references due to the difference in the mangling of symbols declared with different class-keys. The option can be used either on its own or in conjunction with -Wredundant-tags. Consistency is key โจ
-Wmultiple-inheritance(C++ and Objective-C++ only) โ Warns when a class is defined with multiple direct base classes. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use multiple inheritance. So it's a vibe check, not a ban. ๐ธ-Wvirtual-inheritanceโ Warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use virtual inheritance. Same energy as the last one. ๐-Wno-virtual-move-assignโ Suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled. So only turn it off if you really know what you're doing. ๐ญ-Wnamespacesโ Warns when a namespace definition is opened. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also use using directives and qualified names. So you can still have your namespaces, just not new ones. ๐ซถ-Wno-terminate(C++ and Objective-C++ only) โ Disables the warning about a throw-expression that will immediately result in a call toterminate. So if you're throwing and you know it's gonna terminate, this shuts up the warning. Periodt. ๐-Wno-vexing-parse(C++ and Objective-C++ only) โ Warns about the most vexing parse syntactic ambiguity. This warns about the cases when a declaration looks like a variable definition, but the C++ language requires it to be interpreted as a function declaration. For instance:
void f(double a) {
int i(); // extern int i (void);
int n(int(a)); // extern int n (int);
}
Another example:
struct S { S(int); };
void f(double a) {
S x(int(a)); // extern struct S x (int);
S y(int()); // extern struct S y (int (*) (void));
S z(); // extern struct S z (void);
}
The warning will suggest options how to deal with such an ambiguity; e.g., it can suggest removing the parentheses or using braces instead. This warning is enabled by default. So it's always watching. ๐
-Wno-class-conversion(C++ and Objective-C++ only) โ Do not warn when a conversion function converts an object to the same type, to a base class of that type, or to void; such a conversion function will never be called. So if you have a useless conversion function, this flag lets you keep it without the warning. No judgement. ๐-Wvolatile(C++ and Objective-C++ only) โ Warns about deprecated uses of thevolatilequalifier. This includes postfix and prefix++and--expressions ofvolatile-qualified types, using simple assignments where the left operand is avolatile-qualified non-class type for their value, compound assignments where the left operand is avolatile-qualified non-class type,volatile-qualified function return type,volatile-qualified parameter type, and structured bindings of avolatile-qualified type. This usage was deprecated in C++20. Enabled by default with-std=c++20. So yeah, volatile is a little problematic now. โก-Wzero-as-null-pointer-constant(C++ and Objective-C++ only) โ Warns when a literal0is used as null pointer constant. This can be useful to facilitate the conversion tonullptrin C++11. So you can be modern and cute. Slay ๐-Waligned-newโ Warns about a new-expression of a type that requires greater alignment than thealignof(std::max_align_t)but uses an allocation function without an explicit alignment parameter. This option is enabled by-Wall. Normally this only warns about global allocation functions, but-Waligned-new=allalso warns about class member allocation functions. So alignment matters, bestie. ๐-Wno-placement-new,-Wplacement-new=nโ Warns about placement new expressions with undefined behavior, such as constructing an object in a buffer that is smaller than the type of the object. For example, the placement new expression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large.
char buf [64];
new (buf) int[64];
This warning is enabled by default.
-Wplacement-new=1โ This is the default warning level of-Wplacement-new. At this level the warning is not issued for some strictly undefined constructs that GCC allows as extensions for compatibility with legacy code. For example, the followingnewexpression is not diagnosed at this level even though it has undefined behavior according to the C++ standard because it writes past the end of the one-element array.
struct S { int n, a[1]; };
S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
new (s->a)int [32]();
-Wplacement-new=2โ okay so at this level, bestie, you get everything level 1 catches, plus a lil extra: it throws a diagnostic at placement new expressions that build an object inside the last member of a struct when that member's type is an array of exactly one element, and its size is smaller than the size of the object you're constructing. So yeah, the example right above would totally get flagged. But check this out โ the construct below leans on the flexible member array extension to dodge the warning at level 2:
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
-Wcatch-value-Wcatch-value=n(C++ and Objective-C++ only) โ this one yells at catch handlers that don't catch by reference. With-Wcatch-value=1(that's-Wcatch-valuefor short, slay) it warns about polymorphic class types getting caught by value. With-Wcatch-value=2it's all class types caught by value. With-Wcatch-value=3it's literally every type that isn't caught by reference. And-Wcatch-valuecomes enabled by-Wall๐ .-Wconditionally-supported(C++ and Objective-C++ only) โ warns for conditionally-supported constructs (C++11 [intro.defs]).-Wno-delete-incomplete(C++ and Objective-C++ only) โ do not warn when you delete a pointer to an incomplete type, which, oof, may cause undefined behavior at runtime. This warning is enabled by default, so this flag is the "stop telling me" button.-Wextra-semi(C++, Objective-C++ only) โ warns about redundant semicolons after in-class function definitions. Yes queen, extra semis get called out.-Wno-inaccessible-base(C++, Objective-C++ only) โ controls warnings when a base class is inaccessible inside a class derived from it, because of ambiguity. The warning is enabled by default. But heads up bestie: the warning for ambiguous virtual bases is enabled by the-Wextraoption instead.
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ suppresses warnings about using C++11 inheriting constructors when the base class being inherited from has a C variadic constructor. This warning is on by default because โ plot twist โ the ellipsis is not inherited.-Wno-invalid-offsetof(C++ and Objective-C++ only) โ suppresses warnings from applying theoffsetofmacro to a non-POD type. Per the 2014 ISO C++ standard, applyingoffsetofto a non-standard-layout type is undefined. But in existing C++ implementations,offsetofusually gives you something meaningful anyway. So this flag is for the girlies who know they're writing nonportable code and have deliberately chosen to ignore the warning about it. The restrictions onoffsetofmay get relaxed in a future version of the C++ standard, so stay tuned ig.-Wsized-deallocation(C++ and Objective-C++ only) โ warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
without a definition of the corresponding sized deallocation function
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
or vice versa. Enabled by -Wextra along with -fsized-deallocation.
-Wsuggest-final-typesโ warns about types with virtual methods where your code quality would be better if the type were declared with the C++11finalspecifier, or, if possible, declared in an anonymous namespace. Why do we care? Because it lets GCC more aggressively devirtualize the polymorphic calls, and that's the dream ๐. This warning hits harder with link-time optimization, where the info about the class hierarchy graph is more complete.-Wsuggest-final-methodsโ warns about virtual methods where code quality would improve if the method were declared with the C++11finalspecifier, or, if possible, its type were declared in an anonymous namespace or with thefinalspecifier. Same deal: more effective with link-time optimization, where the class-hierarchy-graph tea is more complete. And the rec is to first consider the suggestions from-Wsuggest-final-typesand then rebuild with the new annotations. Order matters, bestie.-Wsuggest-overrideโ warns about overriding virtual functions that aren't marked with theoverridekeyword. Just sayoverride, it's free.-Wuse-after-free-Wuse-after-free=nโ warns about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. This warning is enabled at all optimization levels, but ngl it may give you different results with optimization than without.-Wuse-after-free=1โ at level 1 the warning tries to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call torealloc, regardless of whether the call actually reallocated the memory or not. This includes double-freecalls plus uses in arithmetic and relational expressions. And even though it's undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.-Wuse-after-free=2โ at level 2, on top of the unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, that secondfreecall in the function below gets diagnosed at this level:
struct A { int refcount; void *data; };
void release (struct A *p)
{
int refcount = --p->refcount;
free (p);
if (refcount == 0)
free (p->data); // warning: p may be used after free
}
-Wuse-after-free=3โ at level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. Like, all uses of indeterminate pointers are undefined, full stop, but equality tests sometimes show up after calls toreallocas an attempt to figure out whether the call relocated the object to a different address. They get diagnosed at a separate level so legacy code can gradually transition to safe alternatives. For example, the equality test in this function below is diagnosed at level 3:
void adjust_pointers (int**, int);
void grow (int **p, int n)
{
int **q = (int**)realloc (p, n *= 2);
if (q == p)
return;
adjust_pointers ((int**)q, n);
}
To dodge the warning at this level, store offsets into allocated memory instead of pointers. That way you don't need to adjust the stored pointers after reallocation at all. Iconic workaround, honestly.
-Wuse-after-free=2 is included in -Wall.
-Wuseless-cast(C++ and Objective-C++ only) โ warns when an expression is cast to its own type. But it does not fire when a class object is converted to a non-reference type, because that's a legit way to create a temporary:
struct S { };
void g (S&&);
void f (S&& arg)
{
g (S(arg)); // make arg prvalue so that it can bind to S&&
}
-Wno-conversion-null(C++ and Objective-C++ only) โ do not warn for conversions betweenNULLand non-pointer types.-Wconversion-nullis enabled by default, so this is your off switch.
๐ Options Controlling Objective-C and Objective-C++ Dialects ๐
(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves. Just so we're clear bestie, that's not what this is.)
This section is all about the command-line options that are only meaningful for Objective-C and Objective-C++ programs. You can also use most of the language-independent GNU compiler options, so you're not stuck with just these. For example, you might compile a file some_class.m like this:
gcc -g -fgnu-runtime -O -c some_class.m
In this example, -fgnu-runtime is an option meant only for Objective-C and Objective-C++ programs; you can use the other options with any language supported by GCC.
Also note: since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Same energy โ Objective-C++ compilations may use C++-specific options (e.g., -Wabi).
Okay so here's the list of options that are only for compiling Objective-C and Objective-C++ programs:
-fconstant-string-class=class-nameโ uses class-name as the name of the class to instantiate for each literal string specified with the syntax@"...". The default class name isNXConstantStringif the GNU runtime is being used, andNSConstantStringif the NeXT runtime is being used (see below, iykyk). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption, if it's also present, overrides the-fconstant-string-classsetting and causes@"..."literals to be laid out as constant CoreFoundation strings. And note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent.-fgnu-runtimeโ generates object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems.-fnext-runtimeโ generates output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro__NEXT_RUNTIME__is predefined if (and only if) this option is used. No cap.-fno-nil-receiversโ assumes that all Objective-C message dispatches ([receiver message:arg]) in this translation unit make sure the receiver is notnil. That assumption lets the runtime use more efficient entry points. Heads up though: this option is only available in conjunction with the NeXT runtime and ABI version 0 or 1.-fobjc-abi-version=nโ bestie, this one picks version n of the Objective-C ABI for whichever runtime you're on. Lowkey only the NeXT runtime supports it rn. So for NeXT: Version 0 = the traditional (32-bit) ABI, no properties, no other Objective-C 2.0 extras. Version 1 = traditional (32-bit) ABI, but with properties and the other Objective-C 2.0 additions. Version 2 = the modern (64-bit) ABI. And if you just don't say anything? Default is Version 0 on 32-bit target machines, Version 2 on 64-bit target machines. โจ-fobjc-call-cxx-cdtorsโ okay so for every Objective-C class, it checks whether any of its instance variables is a C++ object with a non-trivial default constructor. If yeah, it synthesizes a special- (id) .cxx_constructinstance method that runs those non-trivial default constructors on those instance variables, in order, and then returnsself. Same vibe check for destructors: if any instance variable is a C++ object with a non-trivial destructor, it synthesizes a special- (void) .cxx_destructmethod that runs all those default destructors, in reverse order.
The - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class, not ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods across an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime immediately after a new object instance is allocated; the - (void) .cxx_destruct methods get invoked immediately before the runtime deallocates an object instance. ๐ซถ
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the - (id) .cxx_construct and - (void) .cxx_destruct methods.
-fobjc-direct-dispatchโ allows fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. ๐ฆ-fobjc-exceptionsโ turns on syntactic support for structured exception handling in Objective-C, kinda like what C++ offers. You need this option to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. Available with both the GNU runtime and the NeXT runtime โ but not available together with the NeXT runtime on Mac OS X 10.2 and earlier. ๐-fobjc-gcโ enables garbage collection (GC) in Objective-C and Objective-C++ programs. This option is only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that doesn't need special compiler flags. ๐-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, it checks for a nil receiver in method invocations before doing the actual method call. This is the default, and you can turn it off with-fno-objc-nilcheck. Class methods and super calls are never checked for nil this way no matter what this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used.-fobjc-std=objc1โ conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When you use this with the Objective-C or Objective-C++ compiler, any Objective-C syntax not recognized by GCC 4.0 gets rejected. Super useful if you need to make sure your Objective-C code can be compiled with older versions of GCC. ๐-freplace-objc-classesโ emits a special marker instructingld(1)not to statically link in the resulting object file, and letsdyld(1)load it in at run time instead. This is used together with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded while the program is executing, without needing to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later. ๐ฅ-fzero-linkโ when compiling for the NeXT runtime, the compiler ordinarily replaces calls toobjc_getClass("...")(when the class name is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the-fzero-linkflag suppresses this behavior and causes calls toobjc_getClass("...")to be retained. This is useful in Zero-Link debugging mode, since it lets individual class implementations be modified during program execution. The GNU runtime currently always retains calls toobjc_get_class("...")regardless of command-line options.-fno-local-ivarsโ by default, instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. That can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the-fno-local-ivarsflag disables this behavior, thus avoiding variable shadowing issues. ๐-fivar-visibility=[public|protected|private|package]โ sets the default instance variable visibility to the option you pick, so that instance variables declared outside the scope of any access modifier directives default to that specified visibility.-gen-declsโ dumps interface declarations for all classes seen in the source file to a file namedsourcename.decl. โจ-Wassign-intercept(Objective-C and Objective-C++ only) โ warns whenever an Objective-C assignment is being intercepted by the garbage collector.-Wno-property-assign-default(Objective-C and Objective-C++ only) โ don't warn if a property for an Objective-C object has no assign semantics specified.-Wno-protocol(Objective-C and Objective-C++ only) โ if a class is declared to implement a protocol, a warning is issued for every method in the protocol that isn't implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the-Wno-protocoloption, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.-Wobjc-root-class(Objective-C and Objective-C++ only) โ warns if a class interface lacks a superclass. Most classes will inherit fromNSObject(orObject) for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with__attribute__((objc_root_class)).-Wselector(Objective-C and Objective-C++ only) โ warns if multiple methods of different types for the same selector are found during compilation. The check happens on the list of methods in the final stage of compilation. Also, a check is performed for each selector appearing in a@selector(...)expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation isn't reached โ for example because an error is found during compilation, or because the-fsyntax-onlyoption is being used.-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warns if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of typeidorClass. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.-Wundeclared-selector(Objective-C and Objective-C++ only) โ warns if a@selector(...)expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the@selector(...)expression, either explicitly in an@interfaceor@protocoldeclaration, or implicitly in an@implementationsection. This option always performs its checks as soon as a@selector(...)expression is found, while-Wselectoronly performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. ๐-print-objc-runtime-infoโ generates a C header describing the largest structure that is passed by value, if any.
๐ Options to Control Diagnostic Messages Formatting ๐
Okay so traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (like its width, and so on). You can use the options below to control the formatting algorithm for diagnostic messages โ like how many characters per line, how often source location info should be reported. Ngl, some language front ends may not honor these options. ๐ญ
-fmessage-length=nโ try to format error messages so they fit on lines of about n characters. If n is zero, then no line-wrapping is done; each error message appears on a single line. This is the default for all front ends.
Heads up โ this option also affects the display of the #error and #warning pre-processor directives, and the deprecated function/type/variable attribute. It does not however affect the pragma GCC warning and pragma GCC error pragmas.
-fdiagnostics-plain-outputโ this option requests that diagnostic output look as plain as possible, which may be useful when runningdejagnuor other utilities that need to parse diagnostics output and prefer that it remain more stable over time.-fdiagnostics-plain-outputis currently equivalent to the following options:
-fno-diagnostics-show-caret -fno-diagnostics-show-line-numbers
-fdiagnostics-color=never -fdiagnostics-urls=never
-fdiagnostics-path-format=separate-events
In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list. ๐ธ
-fdiagnostics-show-location=onceโ only meaningful when you're in line-wrapping mode, bestie. It tells the diagnostic messages reporter to emit source location info once: when a message is too long to fit on a single physical line and has to get wrapped, the source location won't get emitted (as prefix) again and again on the subsequent continuation lines. This is the default behavior. ๐-fdiagnostics-show-location=every-lineโ also only meaningful in line-wrapping mode. It tells the diagnostic messages reporter to emit the same source location info (as prefix) for the physical lines that result from the process of breaking a message that was too long to fit on a single line. every line gets the full vibe check.-fdiagnostics-color[=WHEN],-fno-diagnostics-colorโ use color in diagnostics! ๐ WHEN isnever,always, orauto. The default depends on how the compiler has been configured โ it can be any of those WHEN options, or alsoneverif theGCC_COLORSenvironment variable isn't present in the environment, andautootherwise.automakes GCC use color only when the standard error is a terminal, and when not executing in an emacs shell. The forms-fdiagnostics-colorand-fno-diagnostics-colorare aliases for-fdiagnostics-color=alwaysand-fdiagnostics-color=never, respectively.
The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator. (See the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) These substring values are integers in decimal representation and can be concatenated with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors.
The default GCC_COLORS is
error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\
quote=01:path=01;36:fixit-insert=32:fixit-delete=31:\
diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
type-diff=01;32:fnname=01;32:targs=35
where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. ๐ซ๐ Supported capabilities are as follows:
error=โ SGR substring forerror:markers.warning=โ SGR substring forwarning:markers.note=โ SGR substring fornote:markers.path=โ SGR substring for colorizing paths of control-flow events as printed via-fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns.range1=โ SGR substring for first additional range.range2=โ SGR substring for second additional range.locus=โ SGR substring for location information,file:lineorfile:line:columnetc.quote=โ SGR substring for information printed within quotes.fnname=โ SGR substring for names of C++ functions.targs=โ SGR substring for C++ function template parameter bindings.fixit-insert=โ SGR substring for fix-it hints suggesting text to be inserted or replaced.fixit-delete=โ SGR substring for fix-it hints suggesting text to be deleted.diff-filename=โ SGR substring for filename headers within generated patches.diff-hunk=โ SGR substring for the starts of hunks within generated patches.diff-delete=โ SGR substring for deleted lines within generated patches.diff-insert=โ SGR substring for inserted lines within generated patches.type-diff=โ SGR substring for highlighting mismatching types within template arguments in the C++ frontend.
-fdiagnostics-urls[=WHEN]โ use escape sequences to embed URLs in diagnostics โจ๐ฆ For example, when-fdiagnostics-show-optionemits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option.
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when the standard error is a terminal, and when not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature, see below.
The default depends on how the compiler has been configured โ it can be any of the above WHEN options.
GCC can also be configured (via the --with-diagnostics-urls=auto-if-env configure-time option) so that the default is affected by environment variables. Under such a configuration, GCC defaults to using auto if either GCC_URLS or TERM_URLS environment variables are present and non-empty in the environment of the compiler, or never if neither are.
However, even with -fdiagnostics-urls=always, the behavior is still dependent on those environment variables: if GCC_URLS is set to empty or no, do not embed URLs in diagnostics. If set to st, URLs use ST escape sequences. If set to bel, the default, URLs use BEL escape sequences. Any other non-empty value enables the feature. If GCC_URLS is not set, use TERM_URLS as a fallback.
Note: ST is an ANSI escape sequence, string terminator ESC \, BEL is an ASCII character, CTRL+G that usually sounds like a beep. ๐
At this time GCC tries to detect also a few terminals that are known to not implement the URL feature, and have bugs or at least had bugs in some versions that are still in use, where the URL escapes are likely to misbehave, i.e. print garbage on the screen. ๐ That list is currently xfce4-terminal, certain known to be buggy gnome-terminal versions, the linux console, and mingw. This check can be skipped with -fdiagnostics-urls=always.
-fno-diagnostics-show-optionโ by default, each diagnostic emitted includes text indicating the command-line option that directly controls the diagnostic (if such an option is known to the diagnostic machinery). Specifying the-fno-diagnostics-show-optionflag suppresses that behavior. ๐-fno-diagnostics-show-caretโ by default, each diagnostic emitted includes the original source line and a caret^indicating the column. This option suppresses this information. The source line is truncated to n characters, if the-fmessage-length=noption is given. When the output is done to the terminal, the width is limited to the width given by theCOLUMNSenvironment variable or, if not set, to the terminal width.-fno-diagnostics-show-labelsโ by default, when printing source code (via-fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions:
printf ("foo %s bar", long_i + long_j);
~^ ~~~~~~~~~~~~~~~
| |
char * long int
This option suppresses the printing of these labels (in the example above, the vertical bars and the char * and long int text). ๐
-fno-diagnostics-show-cweโ diagnostic messages can optionally have an associated CWE (https://cwe.mitre.org/index.html) identifier. GCC itself only provides such metadata for some of the-fanalyzerdiagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata. ๐-fno-diagnostics-show-rulesโ diagnostic messages can optionally have rules associated with them, such as from a coding standard, or a specification. GCC itself does not do this for any of its diagnostics, but plugins may do so. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata.-fno-diagnostics-show-line-numbersโ by default, when printing source code (via-fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin. ๐-fdiagnostics-minimum-margin-width=widthโ this option controls the minimum width of the left margin printed by-fdiagnostics-show-line-numbers. It defaults to6. ๐-fdiagnostics-parseable-fixitsโ emit fix-it hints in a machine-parseable format, suitable for consumption by IDEs. ๐ฅ๏ธโจ For each fix-it, a line will be printed after the relevant diagnostic, starting with the stringfix-it:. For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013").
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position.
-fdiagnostics-generate-patchโ print fix-it hints to stderr in unified diff format, after any diagnostics are printed. ๐ For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
void show_cb(GtkDialog *dlg)
{
- gtk_widget_showall(dlg);
+ gtk_widget_show_all(dlg);
}
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color). ๐จ
-fdiagnostics-show-template-treeโ bestie, when the C++ frontend is out here printing diagnostics about mismatching template types, like this mess:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
this flag turns on a tree-like structure showing which bits of the types are common and which bits are lowkey fighting each other, like:
map<
[...],
vector<
[double != float]>>
and the parts that differ get highlighted with color โ "double" and "float" in this case. slay.
-fno-elide-typeโ so by default, when the C++ frontend prints diagnostics about mismatching template types, it prints the common parts as[...]to keep the error message cute and short. example:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
but if you specify -fno-elide-type, that behavior gets suppressed, no cap. this flag also affects the output of the -fdiagnostics-show-template-tree flag, so keep that in mind bestie.
-fdiagnostics-path-format=KINDโ picks how paths of control-flow events get printed for diagnostics that have such a path attached.KINDisnone,separate-events, orinline-events, andinline-eventsis the default.
none means, literally, don't print diagnostic paths at all. nothing. silence. ๐
separate-events means print a separate "note" diagnostic for each event within the diagnostic. for example:
test.c:29:5: error: passing NULL as argument 1 to 'PyList_Append' which requires a non-NULL parameter
test.c:25:10: note: (1) when 'PyList_New' fails, returning NULL
test.c:27:3: note: (2) when 'i < count'
test.c:29:5: note: (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
inline-events means print the events "inline" within the source code. this view tries to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges inside the source.
for example, those same events as above might come out like:
'test': events 1-3
|
| 25 | list = PyList_New(0);
| | ^~~~~~~~~~~~~
| | |
| | (1) when 'PyList_New' fails, returning NULL
| 26 |
| 27 | for (i = 0; i < count; i++) {
| | ~~~
| | |
| | (2) when 'i < count'
| 28 | item = PyLong_FromLong(random());
| 29 | PyList_Append(list, item);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
|
interprocedural control flow gets shown by grouping the events by stack frame and using indentation to show how the stack frames are nested, pushed, and popped. iconique honestly.
for example:
'test': events 1-2
|
| 133 | {
| | ^
| | |
| | (1) entering 'test'
| 134 | boxed_int *obj = make_boxed_int (i);
| | ~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling 'make_boxed_int'
|
+--> 'make_boxed_int': events 3-4
|
| 120 | {
| | ^
| | |
| | (3) entering 'make_boxed_int'
| 121 | boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling 'wrapped_malloc'
|
+--> 'wrapped_malloc': events 5-6
|
| 7 | {
| | ^
| | |
| | (5) entering 'wrapped_malloc'
| 8 | return malloc (size);
| | ~~~~~~~~~~~~~
| | |
| | (6) calling 'malloc'
|
<-------------+
|
'test': event 7
|
| 138 | free_boxed_int (obj);
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (7) calling 'free_boxed_int'
|
(etc)
-fdiagnostics-show-path-depthsโ this one hands you extra info when printing control-flow paths tied to a diagnostic. โจ
if this option is provided, then the stack depth gets printed for each run of events within -fdiagnostics-path-format=inline-events. and if you provide it with -fdiagnostics-path-format=separate-events, then the stack depth and the function declaration get appended when printing each event.
heads up: this is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. so it's giving maintainer energy, not everyday-user energy, iykyk.
-fno-show-columnโ don't print column numbers in diagnostics. periodt. this might be necessary if your diagnostics are getting scanned by a program that doesn't understand the column numbers, likedejagnu. ๐ฆ-fdiagnostics-column-unit=UNITโ picks the units for the column number. this affects traditional diagnostics (when there's no-fno-show-column), and also JSON format diagnostics if you requested those.
the default UNIT, display, counts the number of display columns each character takes up. this can be bigger than the number of bytes needed to encode the character, in the case of tab characters, or it can be smaller, in the case of multibyte characters. for example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding needs two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding needs four bytes. the math is mathing. ๐
setting UNIT to byte changes the column number to the raw byte count in all cases, exactly as was traditionally output by GCC prior to version 11.1.0.
-fdiagnostics-column-origin=ORIGINโ picks the origin for column numbers, aka the column number assigned to the first column. the default value of1matches traditional GCC behavior and the GNU style guide. some utilities might perform better with an origin of0, and honestly any non-negative value may be specified. you do you bestie. ๐-fdiagnostics-escape-format=FORMATโ when GCC prints the pertinent source lines for a diagnostic, it normally tries to print the source bytes directly. but some diagnostics are about encoding issues in the source file โ malformed UTF-8, Unicode normalization drama, that whole vibe โ and those diagnostics are flagged so GCC escapes bytes that aren't printable ASCII when printing their pertinent source lines.
this option controls how those bytes get escaped.
the default FORMAT, unicode, displays Unicode characters that aren't printable ASCII in the form <U+XXXX>, and bytes that don't correspond to a Unicode character validly-encoded in UTF-8-encoded get displayed as hexadecimal in the form <XX>.
for example, a source line containing the string before, followed by the Unicode character U+03C0 ("GREEK SMALL LETTER PI", with UTF-8 encoding 0xCF 0x80), followed by the byte 0xBF (a stray UTF-8 trailing byte), followed by the string after, will be printed for such a diagnostic as:
before<U+03C0><BF>after
setting FORMAT to bytes displays all non-printable-ASCII bytes in the form <XX>, which shows off the underlying encoding of non-ASCII Unicode characters. for that same example above, you'd get:
before<CF><80><BF>after
-fdiagnostics-format=FORMATโ pick a different format for printing diagnostics.FORMATistext,sarif-stderr,sarif-file,json,json-stderr, orjson-file.
the default is text.
the sarif-stderr and sarif-file formats both emit diagnostics in SARIF Version 2.1.0 format โ either to stderr, or to a file named source.sarif, respectively.
the json format is a synonym for json-stderr. the json-stderr and json-file formats are identical apart from where the JSON is emitted to โ with the former, the JSON goes to stderr, whereas with json-file it gets written to source.gcc.json. ๐
the emitted JSON consists of a top-level JSON array containing JSON objects representing the diagnostics. the JSON is emitted as one line, with no formatting; the examples below have been formatted for clarity, so don't come for them.
diagnostics can have child diagnostics. for example, this error and note:
misleading-indentation.c:15:3: warning: this 'if' clause does not
guard... [-Wmisleading-indentation]
15 | if (flag)
| ^~
misleading-indentation.c:17:5: note: ...this statement, but the latter
is misleadingly indented as if it were guarded by the 'if'
17 | y = 2;
| ^
might be printed in JSON form (after formatting) like this:
where the "note" is a child of the "warning" ๐ like, literally a nested child, the diagnostics have a whole family-tree thing going on and we respect it.
A diagnostic has a "kind". If this is "warning", then there is an "option" key describing the command-line option controlling the warning. slay, it tells you which flag to blame โจ
A diagnostic can contain zero or more locations. Each location has an optional "label" string and up to three positions within it: a "caret" position and optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers indicating a column position:
"display-column"counts display columns, accounting for tabs and multibyte characters. ๐ฆ"byte-column"counts raw bytes. ๐ข"column"is equal to one of the previous two, as dictated by the-fdiagnostics-column-unitoption.
All three columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but may be set, for instance, to 0 for compatibility with other utilities that number columns from 0 ๐
. The column origin is recorded in the JSON output in the "column-origin" tag. In the remaining examples below, the extra column number outputs have been omitted for brevity, bestie โ we're keeping it cute and short.
For example, this error:
bad-binary-ops.c:64:23: error: invalid operands to binary + (have 'S' {aka
'struct s'} and 'T' {aka 'struct t'})
64 | return callee_4a () + callee_4b ();
| ~~~~~~~~~~~~ ^ ~~~~~~~~~~~~
| | |
| | T {aka struct t}
| S {aka struct s}
has three locations. Its primary location is at the "+" token at column 23. It has two secondary locations, describing the left and right-hand sides of the expression, which have labels. It might be printed in JSON form as:
{
"children": [],
"kind": "error",
"locations": [
{
"caret": {
"column": 23, "file": "bad-binary-ops.c", "line": 64
}
},
{
"caret": {
"column": 10, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 21, "file": "bad-binary-ops.c", "line": 64
},
"label": "S {aka struct s}"
},
{
"caret": {
"column": 25, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 36, "file": "bad-binary-ops.c", "line": 64
},
"label": "T {aka struct t}"
}
],
"escape-source": false,
"message": "invalid operands to binary + ..."
}
If a diagnostic contains fix-it hints, it has a "fixits" array, consisting of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits ๐. For example, this diagnostic with a replacement fix-it hint:
demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
mean 'color'?
8 | return ptr->colour;
| ^~~~~~
| color
might be printed in JSON form as:
{
"children": [],
"fixits": [
{
"next": {
"column": 21,
"file": "demo.c",
"line": 8
},
"start": {
"column": 15,
"file": "demo.c",
"line": 8
},
"string": "color"
}
],
"kind": "error",
"locations": [
{
"caret": {
"column": 15,
"file": "demo.c",
"line": 8
},
"finish": {
"column": 20,
"file": "demo.c",
"line": 8
}
}
],
"escape-source": false,
"message": "\u2018struct s\u2019 has no member named ..."
}
where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value ๐ซ. Deletions are expressed via an empty value for "string", insertions by having "start" equal "next". so simple, so elegant, we love to see it โจ
If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing the events. Each event object has a "description" string, a "location" object, along with a "function" string and a "depth" number for representing interprocedural paths. The "function" represents the current function at that event, and the "depth" represents the stack depth relative to some baseline: the higher, the more frames are within the stack ๐.
For example, the intraprocedural example shown for -fdiagnostics-path-format= might have this JSON for its path:
"path": [
{
"depth": 0,
"description": "when 'PyList_New' fails, returning NULL",
"function": "test",
"location": {
"column": 10,
"file": "test.c",
"line": 25
}
},
{
"depth": 0,
"description": "when 'i < count'",
"function": "test",
"location": {
"column": 3,
"file": "test.c",
"line": 27
}
},
{
"depth": 0,
"description": "when calling 'PyList_Append', passing NULL from (1) as argument 1",
"function": "test",
"location": {
"column": 5,
"file": "test.c",
"line": 29
}
}
]
Diagnostics have a boolean attribute "escape-source", hinting whether non-ASCII bytes should be escaped when printing the pertinent lines of source code ("true" for diagnostics involving source encoding issues) ๐.
โจ Options to Request or Suppress Warnings โจ
Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error ๐. Like, the code works, but bestieโฆ are we sure?
The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC ๐ซถ:
-fsyntax-onlyโ Check the code for syntax errors, but don't do anything beyond that. Just the vibe check, no compiling ๐ธ.-fmax-errors=nโ Limits the maximum number of error messages to n, at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is no limit on the number of error messages produced. If-Wfatal-errorsis also specified, then-Wfatal-errorstakes precedence over this option ๐.-wโ Inhibit all warning messages. all of them. gone. silenced. ๐-Werrorโ Make all warnings into errors ๐ฅ. Every little warning gets main character energy and becomes a full-on error.-Werror=โ bestie, this turns a specific warning into a full-on error. You append the specifier for the warning you're mad at; like-Werror=switchmakes the warnings controlled by-Wswitchinto errors. And there's a negative form too, for when you want to un--Werrorjust ONE little warning:-Wno-error=switchmakes-Wswitchwarnings not be errors, even when-Werroris fully in effect. ๐
Every controllable warning's message includes the option that controls it. So you can take that exact option and pair it with -Werror= or -Wno-error=. (If you want that option text to stop showing up in the message, hit it with the -fno-diagnostics-show-option flag.)
Note that specifying-Werror=fooautomatically implies-Wfoo. However,-Wno-error=foodoes not imply anything. Not a thing. Nothing. ๐ซถ
-Wfatal-errorsโ this one makes the compiler just abort compilation on the first error instead of trying to keep going and printing further error messages. It's giving "I've seen enough." ๐ญ
okay so you can request a whole bunch of specific warnings with options that start with -W, for example -Wimplicit to request warnings on implicit declarations. Every one of these specific warning options also has a negative form starting with -Wno- that turns the warnings off, like -Wno-implicit. This manual only lists one of the two forms โ whichever one is not the default. For more language-specific options, go look at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. Additional warnings can be produced by enabling the static analyzer;
Some options, like -Wall and -Wextra, turn on other options, like -Wunused, which may turn on further options, like -Wunused-value. And the combined effect of positive and negative forms? More specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. โจ
When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. But if the -Wno- form is used, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This lets you use new -Wno- options with old compilers โ but if something goes wrong, the compiler warns that an unrecognized option is present. ๐
The effectiveness of some warnings depends on optimizations also being enabled, ngl. For example -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings may not be issued at all unless optimization is enabled. While optimization in general improves the efficacy of control and data flow sensitive warnings, in some cases it may also cause false positives. ๐
-Wpedantic-pedanticโ this issues all the warnings demanded by strict ISO C and ISO C++; it rejects all programs that use forbidden extensions, plus some other programs that don't follow ISO C and ISO C++. For ISO C, it follows the version of the ISO C standard specified by any-stdoption you used.
Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are rejected. periodt.
-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. This alternate format can also be used to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". But like โ only system header files should use these escape routes; application programs should avoid them. ๐ซ
Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added. ๐ญ
A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -Wpedantic. We don't have plans to support such a feature in the near future.
Where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there is a corresponding base standard โ the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.) ๐ฆ
-pedantic-errorsโ gives an error whenever the base standard (see-Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time, and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to-Werror=pedantic, since there are errors enabled by this option and not enabled by the latter, and vice versa. no cap.-Wallโ this enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. ๐
-Wall turns on the following warning flags:
-Waddress -Warray-bounds=1 (only with -O2) -Warray-compare
-Warray-parameter=2 (C and Objective-C only) -Wbool-compare
-Wbool-operation -Wc++11-compat -Wc++14-compat -Wcatch-value (C++
and Objective-C++ only) -Wchar-subscripts -Wcomment
-Wdangling-pointer=2 -Wduplicate-decl-specifier (C and Objective-C
only) -Wenum-compare (in C/ObjC; this is on by default in C++)
-Wenum-int-mismatch (C and Objective-C only) -Wformat
-Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and
Objective-C only) -Wimplicit-function-declaration (C and Objective-C
only) -Winit-self (only for C++) -Wlogical-not-parentheses -Wmain
(only for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wself-move (only for C++)
-Wsequence-point -Wsign-compare (only in C++) -Wsizeof-array-div
-Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstrict-aliasing
-Wstrict-overflow=1 -Wswitch -Wtautological-compare -Wtrigraphs
-Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label
-Wunused-value -Wunused-variable -Wuse-after-free=2 -Wvla-parameter
(C and Objective-C only) -Wvolatile-register-var
-Wzero-length-bounds
Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually. ๐
-Wextraโ this enables some extra warning flags that are not enabled by-Wall. (This option used to be called-W. The older name is still supported, but the newer name is more descriptive.) ๐
-Wclobbered -Wcast-function-type -Wdangling-reference (C++ only)
-Wdeprecated-copy (C++ only) -Wempty-body -Wenum-conversion (C only)
-Wignored-qualifiers -Wimplicit-fallthrough=3
-Wmissing-field-initializers -Wmissing-parameter-type (C only)
-Wold-style-declaration (C only) -Woverride-init -Wsign-compare (C
only) -Wstring-compare -Wredundant-move (only for C++) -Wtype-limits
-Wuninitialized -Wshift-negative-value (in C++11 to C++17 and in C99
and newer) -Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for the following cases:
- A pointer is compared against integer zero with
"<","<=",">", or">=". - (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
- (C++ only) Ambiguous virtual bases.
- (C++ only) Subscripting an array that has been declared
"register". - (C++ only) Taking the address of a variable that has been declared
"register". - (C++ only) A base class is not initialized in the copy constructor of a derived class.
-Wabi(C, Objective-C, C++ and Objective-C++ only) โ warns about code affected by ABI changes. This includes code that may not be compatible with the vendor-neutral C++ ABI as well as the psABI for the particular target. ๐
Since G++ now defaults to updating the ABI with each major release, normally -Wabi warns only about C++ ABI compatibility problems if there is a check added later in a release series for an ABI issue discovered since the initial release. -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).
-Wabi can also be used with an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2.
If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for C++ ABI warnings. ๐
okay so โ they genuinely tried to warn you about every single one of these cases, but bestie, realistically? there are probably some cases nobody warns you about, even while G++ is out here generating code that's just... not compatible. ๐ And also sometimes you get a warning even though the code is totally compatible. it's giving chaos.
If the whole "G++ code might not be binary compatible with code from other compilers" thing is keeping you up at night, you should rewrite your code to dodge these warnings. periodt.
Here's the tea on known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9):
- A template with a non-type template parameter of reference type was mangled incorrectly:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}
This was fixed in -fabi-version=3. โจ
- SIMD vector types declared using
__attribute ((vector_size))were mangled in a non-standard way that does not allow for overloading of functions taking vectors of different sizes.
The mangling was changed in -fabi-version=4.
__attribute ((const))andnoreturnwere mangled as type qualifiers, anddecltypeof a plain declaration was folded away.
These mangling issues were fixed in -fabi-version=5.
- Scoped enumerators passed as arguments to a variadic function are promoted like unscoped enumerators, causing
va_argto complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller thanint.
Also, the ABI changed the mangling of template argument packs, const_cast, static_cast, prefix increment/decrement, and a class scope function used as a template argument.
These issues were corrected in -fabi-version=6.
- Lambdas in default argument scope were mangled incorrectly, and the ABI changed the mangling of
nullptr_t.
These issues were corrected in -fabi-version=7.
- When mangling a function type with function-cv-qualifiers, the un-qualified function type was incorrectly treated as a substitution candidate.
This was fixed in -fabi-version=8, the default for GCC 5.1.
decltype(nullptr)incorrectly had an alignment of 1, leading to unaligned accesses. Note that this did not affect the ABI of a function with anullptr_tparameter, as parameters have a minimum alignment.
This was fixed in -fabi-version=9, the default for GCC 5.2.
- Target-specific attributes that affect the identity of a type, such as ia32 calling conventions on a function type (stdcall, regparm, etc.), did not affect the mangled name, leading to name collisions when function pointers were used as template arguments.
This was fixed in -fabi-version=10, the default for GCC 6.1.
This option also enables warnings about psABI-related changes. The known psABI changes at this point include:
- For SysV/x86-64, unions with
long doublemembers are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. For example:
union U {
long double ld;
int i;
};
union U is now always passed in memory.
-Wno-changes-meaning(C++ and Objective-C++ only) โ so C++ has โจrulesโจ: unqualified uses of a name inside a class have to mean the same thing across the entire scope of the class, which means declaring the name after you use it is ill-formed:
struct A;
struct B1 { A a; typedef A A; }; // warning, 'A' changes meaning
struct B2 { A a; struct A { }; }; // error, 'A' changes meaning
By default, the B1 case is only a warning because the two declarations have the same type, while the B2 case is an error. Both diagnostics can be disabled with -Wno-changes-meaning. Alternately, the error case can be reduced to a warning with -Wno-error=changes-meaning or -fpermissive.
Both diagnostics are also suppressed by -fms-extensions. ๐ซถ
-Wchar-subscriptsโ warns if an array subscript has typechar. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by-Wall. ๐-Wno-coverage-mismatchโ warns if feedback profiles do not match when using the-fprofile-useoption. If a source file is changed between compiling with-fprofile-generateand with-fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error.-Wno-coverage-mismatchcan be used to disable the warning or-Wno-error=coverage-mismatchcan be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended. ๐ญ-Wno-coverage-invalid-line-numberโ warns in case a function ends earlier than it begins due to an invalid linenum macros. The warning is emitted only with--coverageenabled.
By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error.
-Wno-cpp(C, Objective-C, C++, Objective-C++ and Fortran only) โ suppresses warning messages emitted by#warningdirectives. shhh ๐คซ-Wdouble-promotion(C, C++, Objective-C and Objective-C++ only) โ gives you a warning when a value of typefloatis implicitly promoted todouble. CPUs with a 32-bit "single-precision" floating-point unit implementfloatin hardware, but emulatedoublein software. On such a machine, doing computations usingdoublevalues is much more expensive because of the overhead required for software emulation. ๐
It is easy to accidentally do computations with double because floating-point literals are implicitly of type double. For example, in:
float area(float radius)
{
return 3.14159 * radius * radius;
}
the compiler performs the entire computation with double because the floating-point literal is a double. caught in 4k ๐ซฃ
-Wduplicate-decl-specifier(C and Objective-C only) โ warns if a declaration has duplicateconst,volatile,restrictor_Atomicspecifier. This warning is enabled by-Wall. โจ-Wformat-Wformat=nโ checks calls toprintfandscanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes, in theprintf,scanf,strftimeandstrfmon(an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by-ffreestandingor-fno-builtin.
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for strfmon formats, since those are not in any version of the C standard).
-Wformat=1-Wformatโ option-Wformatis equivalent to-Wformat=1, and-Wno-formatis equivalent to-Wformat=0. Since-Wformatalso checks for null format arguments for several functions,-Wformatalso implies-Wnonnull. Some aspects of this level of format checking can be disabled by the options:-Wno-format-contains-nul,-Wno-format-extra-args, and-Wno-format-zero-length.-Wformatis enabled by-Wall.-Wformat=2โ enable-Wformatplus additional format checks. Currently equivalent to-Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
-Wno-format-contains-nulโ if-Wformatis specified, do not warn about format strings that contain NUL bytes. ๐ซ-Wno-format-extra-argsโ if-Wformatis specified, do not warn about excess arguments to aprintforscanfformat function. The C standard specifies that such arguments are ignored.
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.
-Wformat-overflow-Wformat-overflow=levelโ warns about calls to formatted input/output functions such assprintfandvsprintfthat might overflow the destination buffer. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. ๐
๐ธ -Wformat-overflow / -Wformat-overflow=1 ๐ธ
okay bestie, picture this: GCC reads your little sprintf call and just knows that buffer is not gonna fit the vibe. ๐ Level 1 is what you get from -Wformat-overflow=1, and it's also what -Wformat switches on for you. It's the conservative, low-drama setting โ it only comes for the calls that are most likely to overflow the buffer. No false accusations, we're respectful here.
The assumptions at this level, bestie, write them down:
- numeric arguments to format directives whose values are unknown? assumed to have the value of
1โจ - strings of unknown length? assumed to be empty ๐ซถ
- numeric arguments that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive's precision or by a finite set of string literals? they take on the value within that range that gives the most bytes on output. worst case, always. icon behavior.
So like, the sprintf call below gets diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') that the function appends to the destination buffer is gonna be written past its end. ๐ญ Bumping the buffer size by a single byte is enough to make the warning go away โ though ngl it may not be enough to actually stop the overflow. ๐
void f (int a, int b)
{
char buf [13];
sprintf (buf, "a = %i, b = %i\n", a, b);
}
๐
-Wformat-overflow=2 ๐
Level 2 is level 1 but with main character energy โ it also drags calls that might overflow the destination buffer given an argument of sufficient length or magnitude. She's not waiting for proof, she's asking "what if?"
At level 2 the guessing rules change, so pay attention:
- unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise.
- unknown string arguments whose length can't be assumed to be bounded โ either by the directive's precision, or by a finite set of string literals they may evaluate to, or by the character array they may point to โ are assumed to be
1character long.
At level 2, that example up there gets flagged again, but this time because with a equal to a 32-bit INT_MIN, the first %i directive will write some of its digits beyond the end of the destination buffer. ๐ต To make the call safe no matter what values those two variables hold, the destination buffer has to be at least 34 bytes. GCC is nice enough to drop the minimum buffer size into an informational note right after the warning. ๐ซถ
Now โ instead of just making the buffer bigger, you can also constrain the range of formatted values. The max length of string arguments can be bounded by specifying the precision in the format directive. And when numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, picking an appropriate length modifier for the format specifier shrinks the buffer you need. For example: if a and b up there can be assumed to be within the precision of the short int type, then using either the %hi format directive or casting the argument to short drops the maximum required buffer size down to 24 bytes. slay.
void f (int a, int b)
{
char buf [23];
sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
-Wno-format-zero-lengthโ if-Wformatis specified, then do not warn about zero-length formats, okay? the C standard literally specifies that zero-length formats are allowed. let them live. โจ-Wformat-nonliteralโ if-Wformatis specified, also warn when the format string isn't a string literal, because then it can't be checked. the one exception: unless the format function takes its format arguments as ava_list. ๐ซก-Wformat-securityโ if-Wformatis specified, also warn about uses of format functions that represent possible security problems. rn it warns about calls toprintfandscanffunctions where the format string isn't a string literal and there are no format arguments, likeprintf (foo);. This can be a whole security hole if that format string came from untrusted input and it contains%n. ๐ญ (right now this is a subset of what-Wformat-nonliteralwarns about, but future warnings may be added to-Wformat-securitythat aren't included in-Wformat-nonliteralโ so watch this space.)-Wformat-signednessโ if-Wformatis specified, also warn when the format string wants an unsigned argument and the argument is signed, and vice versa. mismatch behavior, we don't do that here. ๐
๐ฆ -Wformat-truncation / -Wformat-truncation=level ๐ฆ
Warn about calls to formatted input/output functions like snprintf and vsnprintf that might result in output truncation. When the exact number of bytes written by a format directive can't be figured out at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. Turning optimizations on will in most cases make the warning more accurate โ but it can also produce false positives, so like, be aware. ๐ Except as noted otherwise, this option uses the same logic as -Wformat-overflow.
Level 1, which you get from plain -Wformat-truncation and from -Wformat-truncation=1, is turned on by -Wformat and uses a conservative approach: it only warns about calls to bounded functions whose return value is unused and that will most likely result in output truncation.
-Wformat-truncation=2 โ level 2 also warns about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude. ๐ฅ
-Wformat-y2kโ if-Wformatis specified, also warn aboutstrftimeformats that may yield only a two-digit year. y2k said "I lived, bitch" and honestly we should all be so lucky. ๐-Wnonnullโ warn about passing a null pointer for arguments that are marked as requiring a non-null value by thenonnullfunction attribute.-Wnonnullis included in-Walland-Wformat, and it can be disabled with the-Wno-nonnulloption. ๐ซถ-Wnonnull-compareโ warn when you compare an argument marked with thenonnullfunction attribute against null inside the function. like bestie it literally cannot be null, what are we doing. ๐ญ-Wnonnull-compareis included in-Walland it can be disabled with the-Wno-nonnull-compareoption.-Wnull-dereferenceโ warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. this one's only active when-fdelete-null-pointer-checksis active, which gets enabled by optimizations in most targets. The precision of these warnings depends on the optimization options you used. โ ๏ธ-Winfinite-recursionโ warn about infinitely recursive calls. It's effective at all optimization levels, but it needs optimization to detect infinite recursion in calls between two or more functions.-Winfinite-recursionis included in-Wall. Compare it with-Wanalyzer-infinite-recursion, which gives a similar diagnostic but is implemented in a totally different way โ as part of-fanalyzer. ๐-Winit-self(C, C++, Objective-C and Objective-C++ only) โ warn about uninitialized variables that are initialized with themselves. note that this option can only be used together with the-Wuninitializedoption. For example, GCC warns aboutibeing uninitialized in the snippet below only when-Winit-selfhas been specified:
int f()
{
int i = i;
return i;
}
This warning is enabled by -Wall in C++. โจ
-Wno-implicit-int(C and Objective-C only) โ this option controls warnings when a declaration doesn't specify a type. That warning is enabled by default in C99 and later dialects of C, and also by-Wall.-Wno-implicit-function-declaration(C and Objective-C only) โ this option controls warnings when a function is used before being declared. That warning is enabled by default in C99 and later dialects of C, and also by-Wall. The warning gets turned into an error by-pedantic-errors. ๐ค-Wimplicit(C and Objective-C only) โ same as-Wimplicit-intand-Wimplicit-function-declaration. This warning is enabled by-Wall.-Wimplicit-fallthroughโ-Wimplicit-fallthroughis the same as-Wimplicit-fallthrough=3, and-Wno-implicit-fallthroughis the same as-Wimplicit-fallthrough=0. easy math, love that for us. ๐
๐ -Wimplicit-fallthrough=n ๐
Warn when a switch case falls through. For example:
switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;
case 3:
a = 3;
break;
}
She does not warn when the last statement of a case can't fall through โ like when there's a return statement, or a call to a function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes control flow statements such as ifs into account, and only warns when appropriate. E.g.
switch (cond)
{
case 1:
if (i > 3) {
bar (5);
break;
} else if (i < 1) {
bar (0);
} else
return;
default:
...
}
Now, sometimes a switch case fall through is exactly what you want, so GCC gives you an attribute โ __attribute__ ((fallthrough)) โ that you use alongside a null statement to suppress the warning that would normally pop up: ๐
switch (cond)
{
case 1:
bar (0);
__attribute__ ((fallthrough));
default:
...
}
C++17 comes through with a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. And if you're on C++11 or C++14, you can use [[gnu::fallthrough]];, which is a GNU extension. ๐ซถ Instead of those attributes, you can also just add a fallthrough comment to silence the warning โ the whole body of the C or C++ style comment has to match the regular expressions listed below. The option argument n specifies what kind of comments get accepted:
-Wimplicit-fallthrough=0disables the warning altogether.-Wimplicit-fallthrough=1matches the.*regular expression โ any comment at all counts as a fallthrough comment.-Wimplicit-fallthrough=2โ case insensitively matches the".*falls?[ \t-]*thr(ough|u).*"regular expression. ๐-Wimplicit-fallthrough=3โ case sensitively matches one of the following regular expressions, bestie:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
-Wimplicit-fallthrough=4โ case sensitively matches one of these regular expressions, slay:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5โ this one doesn't recognize any comments as fallthrough comments. Only attributes disable the warning. periodt. ๐
The comment needs to be followed after optional whitespace and other comments by "case" or "default" keywords, or by a user label that precedes some "case" or "default" label. iykyk ๐ธ
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra. โจ
-Wno-if-not-aligned(C, C++, Objective-C and Objective-C++ only) โ controls whether warnings triggered by the"warn_if_not_aligned"attribute should be issued. These warnings are enabled by default. ๐ซถ-Wignored-qualifiers(C and C++ only) โ warns you if the return type of a function has a type qualifier like"const". For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning only pops off for scalar types or"void". And heads up: ISO C prohibits qualified"void"return types on function definitions, so those return types always get a warning even without this option.
This warning is also enabled by -Wextra. ๐
-Wno-ignored-attributes(C and C++ only) โ this option controls warnings when an attribute is ignored. The way it's different from the-Wattributesoption?? It warns whenever the compiler decides to drop an attribute, not that the attribute is unknown or used in a wrong place or whatever. This warning is enabled by default. ๐-Wmainโ warns you if the type of"main"is suspicious."main"should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either-Wallor-Wpedantic. ๐-Wmisleading-indentation(C and C++ only) โ warns when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for"if","else","while", and"for"clauses with a guarded statement that doesn't use braces, followed by an unguarded statement with the same indentation. not me getting tricked by whitespace ๐ญ
In the following example, the call to "bar" is misleadingly indented as if it were guarded by the "if" conditional:
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic such as the following example:
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
And it's not issued after a "#line" directive, since that typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references. ๐ง
This warning is enabled by -Wall in C and C++. โจ
-Wmissing-attributesโ warns when a declaration of a function is missing one or more attributes that a related function is declared with, where that absence may adversely affect the correctness or efficiency of generated code. For example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the-Wattribute-alias=2option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. ๐
Attributes considered include "alloc_align", "alloc_size", "cold", "const", "hot", "leaf", "malloc", "nonnull", "noreturn", "nothrow", "pure", "returns_nonnull", and "returns_twice".
In C++, the warning is issued when an explicit specialization of a primary template declared with attribute "alloc_align", "alloc_size", "assume_aligned", "format", "format_arg", "malloc", or "nonnull" is declared without it. Attributes "deprecated", "error", and "warning" suppress the warning.. (yes bestie, that double period is fr fr in the source, iconic)
You can use the "copy" attribute to apply the same set of attributes to a declaration as that on another declaration, without explicitly enumerating the attributes. This attribute can be applied to declarations of functions, variables, or types.
-Wmissing-attributes is enabled by -Wall. ๐
For example, since the declaration of the primary function template below makes use of both attribute "malloc" and "alloc_size", the declaration of the explicit specialization of the template is diagnosed because it's missing one of the attributes:
template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);
template <>
void* __attribute__ ((malloc)) // missing alloc_size
allocate<void> (size_t);
-Wmissing-bracesโ warns if an aggregate or union initializer isn't fully bracketed. In the following example, the initializer for"a"is not fully bracketed, but that for"b"is fully bracketed:
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall. ๐ธ
-Wmissing-include-dirs(C, C++, Objective-C, Objective-C++ and Fortran only) โ warns if a user-supplied include directory does not exist. This option is disabled by default for C, C++, Objective-C and Objective-C++. For Fortran, it's partially enabled by default by warning for-Iand-J, only. ๐ฆ-Wno-missing-profileโ this option controls warnings if feedback profiles are missing when using the-fprofile-useoption. It diagnoses those cases where a new function or a new file is added between compiling with-fprofile-generateand with-fprofile-use, without regenerating the profiles. In these cases, the profile feedback data files don't contain any profile feedback information for the newly added function or file respectively. Also, in the case when profile count data (.gcda) files are removed, GCC can't use any profile feedback information. In all these cases, warnings are issued to inform you that a profile generation step is due. ๐ญ
Ignoring the warning can result in poorly optimized code. You can use -Wno-missing-profile to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified. bestie pls don't. ๐
-Wmismatched-deallocโ warns for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn't a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of attribute"malloc". Unless disabled by the-fno-builtinoption, the standard functions"calloc","malloc","realloc", and"free", as well as the corresponding forms of C++"operator new"and"operator delete", are implicitly associated as matching allocators and deallocators. In the following example"mydealloc"is the deallocator for pointers returned from"myalloc":
void mydealloc (void*);
__attribute__ ((malloc (mydealloc, 1))) void*
myalloc (size_t);
void f (void)
{
void *p = myalloc (32);
// ...use p...
free (p); // warning: not a matching deallocator for myalloc
mydealloc (p); // ok
}
In C++, the related option -Wmismatched-new-delete diagnoses mismatches involving either "operator new" or "operator delete". ๐
Option -Wmismatched-dealloc is included in -Wall. โจ
-Wmultistatement-macrosโ warns about unsafe multiple statement macros that appear to be guarded by a clause such as"if","else","for","switch", or"while", in which only the first statement is actually guarded after the macro is expanded. the betrayal ๐ญ
For example:
#define DOIT x++; y++
if (c)
DOIT;
will increment "y" unconditionally, not just when "c" holds. The can usually be fixed by wrapping the macro in a do-while loop:
#define DOIT do { x++; y++; } while (0)
if (c)
DOIT;
This warning is enabled by -Wall in C and C++. ๐
-Wparenthesesโ warns if parentheses are omitted in certain contexts, like when there's an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about. the way we've all been there ๐
Also warns if a comparison like "x<=y<=z" appears; this is equivalent to "(x<=y ? 1 : 0) <= z", which is a different interpretation from that of ordinary mathematical notation. sneaky!!
Also warns for dangerous uses of the GNU extension to "?:" with omitted middle operand. When the condition in the "?": operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead. ๐
For C++ this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:
{
// Declares a local variable called mymutex.
std::unique_lock<std::mutex> (mymutex);
// User meant std::unique_lock<std::mutex> lock (mymutex);
}
๐ bestie that one is on by -Wall, so enjoy.
-Wno-self-move (C++ and Objective-C++ only)
Yells at you when a value gets moved to itself via std::move. And honestly? A std::move like that usually does absolutely nothing. ๐
struct T {
...
};
void fn()
{
T t;
...
t = std::move (t);
}
Enabled by -Wall. โจ
-Wsequence-point
Warns about code that might have undefined semantics because it breaks the sequence point rules from the C and C++ standards. Not being dramatic โ this is the real deal. ๐ญ
So, the C and C++ standards define the order that expressions get evaluated in terms of sequence points. A sequence point is basically a partial ordering between chunks of execution: the stuff evaluated before it, and the stuff evaluated after it. These happen:
- after a full expression gets evaluated (a full expression = one that isn't part of a bigger expression)
- after the first operand of
&&,||,? :or,(the comma operator) is evaluated - before a function gets called (but after its arguments and the expression naming the called function are evaluated)
- and in certain other places โจ
Other than what the sequence point rules say, the order of evaluation of subexpressions is not specified. And all these rules only describe a partial order, not a total order โ because like, if two functions get called inside one expression with no sequence point between them, the order they get called in isn't specified either. However, the standards committee has ruled that function calls do not overlap.
It's also not specified when modifications to object values actually take effect in between sequence points. Programs that depend on that have undefined behavior, because the C and C++ standards say this, word for word:
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored."
And if your program breaks those rules, the results on any particular implementation are entirely unpredictable. So likeโฆ good luck bestie ๐
Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it's been found pretty effective at catching this sort of problem in programs. ๐
Heads up: the C++17 standard will define the order of evaluation of operands in more cases โ specifically it requires the right-hand side of an assignment to be evaluated before the left-hand side, so those examples above are no longer undefined there. But this option will still warn about them, to help people avoid writing code that's undefined in C and earlier revisions of C++. ๐
The standard is worded confusingly, so ngl there's some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at https://gcc.gnu.org/readings.html. ๐
This warning is enabled by -Wall for C and C++. ๐
-Wno-return-local-addr
Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (Iconic footgun behavior, honestly. ๐ซถ)
-Wreturn-type
Warns whenever a function is defined with a return type that defaults to int. It also warns about any return statement with no return value in a function whose return type isn't void (and fyi, falling off the end of the function body counts as returning without a value). โจ
For C only: it warns about a return statement with an expression in a function whose return type is void, unless the expression's type is also void. As a GNU extension, that latter case is accepted without a warning unless -Wpedantic is used. And attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function? That's undefined. ๐ญ
Unlike in C, in C++ flowing off the end of a non-void function other than main results in undefined behavior even when the value of the function is not used. no cap.
This warning is enabled by default in C++ and by -Wall otherwise.
-Wno-shift-count-negative
Controls warnings if a shift count is negative. This warning is enabled by default. โญ
-Wno-shift-count-overflow
Controls warnings if a shift count is greater than or equal to the bit width of the type. This warning is enabled by default. โญ
-Wshift-negative-value
Warns if you left shift a negative value. This warning is enabled by -Wextra in C99 (and newer) and C++11 to C++17 modes. ๐
-Wno-shift-overflow / -Wshift-overflow=n
These options control warnings about left shift overflows. ๐
-Wshift-overflow=1โ This is the warning level of-Wshift-overflowand is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), as signed left shifts always wrap.-Wshift-overflow=2โ This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
-Wswitch
Warns whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning. ๐) case labels outside the enumeration range also provoke warnings when this option is used โ even if there is a default label. This warning is enabled by -Wall. โจ
-Wswitch-default
Warns whenever a switch statement does not have a default case. simple as that ๐
-Wswitch-enum
Warns whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label. ๐
-Wno-switch-bool
Do not warn when a switch statement has an index of boolean type and the case values are outside the range of a boolean type. It's possible to suppress this warning by casting the controlling expression to a type other than bool. Like:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs. ๐
-Wno-switch-outside-range
This option controls warnings when a switch case has a value that is outside of its respective type range. This warning is enabled by default for C and C++ programs. โญ
-Wno-switch-unreachable
Do not warn when a switch statement contains statements between the controlling expression and the first case label, which will never be executed. For example:
switch (cond)
{
i = 15;
...
case 5:
...
}
Hot tip: -Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:
switch (cond)
{
int i;
...
case 5:
i = 5;
...
}
This warning is enabled by default for C and C++ programs. ๐
-Wsync-nand (C and C++ only)
Warns when the __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4. ๐ญ
-Wtrivial-auto-var-init
Warns when -ftrivial-auto-var-init cannot initialize the automatic variable. A common situation is an automatic variable that's declared between the controlling expression and the first case label of a switch statement. ๐ซถ
-Wunused-but-set-parameter
Warns whenever a function parameter is assigned to, but otherwise unused (aside from its declaration). ๐ด
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused together with -Wextra.
-Wunused-but-set-variable
Warns whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by -Wall. โจ
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-function
Warns whenever a static function is declared but not defined, or a non-inline static function is unused. This warning is enabled by -Wall. ๐
-Wunused-label
Warns whenever a label is declared but not used. This warning is enabled by -Wall. โจ
To suppress this warning use the unused attribute.
-Wunused-local-typedefs (C, Objective-C, C++ and Objective-C++ only)
Warns when a typedef locally defined in a function is not used. This warning is enabled by -Wall. ๐
-Wunused-parameter
Warns whenever a function parameter is unused aside from its declaration. ๐
To suppress this warning use the unused attribute.
-Wno-unused-result
Do not warn if a caller of a function marked with attribute warn_unused_result does not use its return value. The default is -Wunused-result. โญ
-Wunused-variable
Warns whenever a local or static variable is unused aside from its declaration. This option implies -Wunused-const-variable=1 for C, but not for C++. This warning is enabled by -Wall. ๐ฅ
To suppress this warning use the unused attribute.
-Wunused-const-variable-Wunused-const-variable=nโ bestie, this one yells at you whenever a constant static variable is justโฆ sitting there unused, aside from its declaration. Like it's in the group chat but never says anything. ๐ญ
-Wunused-const-variable=1 is turned on by -Wunused-variable for C, but not for C++. Why? Because in C that declares variable storage, but in C++ it's not an error at all โ const variables literally take the place of #defines there. โจ
Wanna make it shut up? Use the unused attribute. ๐
-Wunused-const-variable=1โ this is the warning level that-Wunused-variableenables for C. It only warns about unusedstatic constvariables defined in the main compilation unit โ not the static const ones declared in any header you included. ๐-Wunused-const-variable=2โ this level also warns about unused constant static variables in headers (system headers excluded, don't worry ๐ซถ). This is the warning level of plain-Wunused-const-variable, and you have to explicitly ask for it, because in C++ it isn't an error and in C it might be way harder to clean up every single header you pulled in. ๐
-Wunused-valueโ warns whenever a statement computes a result that's explicitly not used. To silence it, cast the unused expression tovoid. โ
This covers an expression-statement, or the left-hand side of a comma expression that has no side effects. Example time: an expression like x[i,j] triggers a warning, while x[(void)i,j] does not. Slay. ๐
This warning is enabled by -Wall.
-Wunusedโ all the above-Wunusedoptions combined. ๐
Okay so, to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (heads up: -Wall implies -Wunused), or separately specify -Wunused-parameter. Pick your fighter. ๐
-Wuninitializedโ warns if an object with automatic or allocated storage duration gets used without having been initialized. In C++, it also warns if a non-static reference or a non-staticconstmember shows up in a class with no constructors. ๐จ
Bonus: passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified argument of a built-in function known to read that object is also diagnosed by this warning. (-Wmaybe-uninitialized is what gets issued for ordinary functions.)
Wanna also get warned about code that uses the uninitialized value of the variable in its own initializer? That's a whole different vibe โ use the -Winit-self option. ๐
These warnings happen for individual uninitialized elements of structure, union or array variables, and for variables that are uninitialized as a whole. They do not happen for variables or elements declared volatile. And because these warnings depend on optimization, the exact variables or elements you get warned about depend on the precise optimization options and the version of GCC you're running. Not me being vague, that's just how it is. ๐คท
Also note: there may be no warning about a variable that's only used to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed. Gone. Poof. ๐จ
In C++, this warning also calls out using uninitialized objects in member-initializer-lists. For example, GCC warns about b being uninitialized in this snippet:
struct A {
int a;
int b;
A() : a(b) { }
};
-Wno-invalid-memory-modelโ this option controls warnings for invocations of__atomicBuiltins,__syncBuiltins, and the C11 atomic generic functions when the memory consistency argument is either invalid for the operation or outside the range of values of thememory_orderenumeration. ๐ง
For example, since the __atomic_store and __atomic_store_n built-ins are only defined for the relaxed, release, and sequentially consistent memory orders, the following code is diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default. โญ
-Wmaybe-uninitializedโ for an object with automatic or allocated storage duration: if there exists a path from function entry to a use of the object where it is initialized, but there also exist other paths where the object is not initialized, the compiler warns if it can't prove those uninitialized paths never get executed at run time. ๐ซฃ
Also, passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified function argument is diagnosed by this warning too. (-Wuninitialized is what gets issued for built-in functions known to read the object.) Annotate the function with the attribute access (none) to say "hey, this argument isn't used to access the object" and dodge the warning. ๐ธ
These warnings are only even possible in optimizing compilation, because otherwise GCC just isn't keeping track of the state of your variables. No tracking, no warning.
They're optional because GCC may not be able to tell when the code is actually correct even though it looks like it has an error. Here's one example of how that goes down:
{
int x;
switch (y)
{
case 1: x = 1;
break;
case 2: x = 4;
break;
case 3: x = 5;
}
foo (x);
}
If the value of y is always 1, 2 or 3, then x is always initialized โ but GCC doesn't know that. ๐ To suppress the warning you need to provide a default case with assert(0) or similar code.
This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler only sees the calls to setjmp. It cannot know where longjmp will be called โ in fact, a signal handler could call it at any point in the code. So you may get a warning even when there's genuinely no problem, because longjmp can't actually be called at the place that would cause the problem. iconic but annoying, honestly. ๐ญ
Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. ๐ฅ
This warning is enabled by -Wall or -Wextra.
-Wunknown-pragmasโ warns when a#pragmadirective shows up that GCC doesn't understand. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. That is not the case if the warnings are only enabled by the-Wallcommand-line option. ๐-Wno-pragmasโ do not warn about misuses of pragmas, like incorrect parameters, invalid syntax, or conflicts between pragmas. See also-Wunknown-pragmas. ๐-Wno-prio-ctor-dtorโ do not warn if a priority from 0 to 100 is used for a constructor or destructor. Here's the tea: the constructor and destructor attributes let you assign a priority to control the order of execution beforemainis called or after it returns. The priority values must be greater than 100, because the compiler reserves priority values between 0--100 for the implementation. ๐ซ-Wstrict-aliasingโ only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules the compiler is using for optimization. It does not catch all cases, but it does try to catch the more common pitfalls. It's included in-Wall. It is equivalent to-Wstrict-aliasing=3. โจ-Wstrict-aliasing=nโ same deal, only active when-fstrict-aliasingis active, and it warns about code that might break the strict aliasing rules the compiler uses for optimization. Higher levels = higher accuracy (fewer false positives). Higher levels also = more effort, similar to the way-Oworks. And again:-Wstrict-aliasingis equivalent to-Wstrict-aliasing=3.- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels don't warn but
-fstrict-aliasingstill breaks the code, since it has very few false negatives. However, it has many false positives. It warns for all pointer conversions between possibly incompatible types, even if they're never dereferenced. Runs in the front end only. ๐ต - Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. It warns about incomplete types. Runs in the front end only. ๐
- Level 3 (default for
-Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end:*(int*)&some_float. If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types. ๐
- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels don't warn but
-Wstrict-overflow-Wstrict-overflow=nโ only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Important caveat bestie: it does not warn about all cases where the code might overflow โ it only warns about cases where the compiler implements some optimization. So this warning depends on the optimization level. ๐
An optimization that assumes signed overflow doesn't occur is perfectly safe if the values of the variables involved are such that overflow never actually happens. So this warning can easily give a false positive: a warning about code that isn't actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires โ in particular, when determining whether a loop will be executed at all. ๐
-Wstrict-overflow=1โ warns about cases that are both questionable and easy to avoid. For example, the compiler simplifiesx + 1 > xto 1. This level of-Wstrict-overflowis enabled by-Wall; higher levels are not, and must be explicitly requested. โญ
-Wstrict-overflow=2โ also clocks the other cases where a comparison gets simplified into a constant. Likeabs (x) >= 0bestie. And the tea here is that this one can only be simplified when signed integer overflow is undefined, bcabs (INT_MIN)overflows toINT_MIN, which is literally less than zero. And psst:-Wstrict-overflowwith no level at all? Same as-Wstrict-overflow=2. Slay.-Wstrict-overflow=3โ okay so on top of everything above, this one also warns about other cases where a comparison is simplified. Example era:x + 1 > 1gets simplified tox > 0.-Wstrict-overflow=4โ and now we're warning about other simplifications that the cases above didn't cover. Example:(x * 10) / 5simplifies tox * 2.-Wstrict-overflow=5โ the final boss level. This also warns when the compiler shrinks the magnitude of a constant involved in a comparison. Likex + 2 > ygets simplified tox + 1 >= y. Fair warning though: this is ONLY reported at the highest warning level, because this simplification applies to a ton of comparisons, so this level hands you a very large number of false positives. It's giving spam. ๐ฅ
-Wstring-compareโ warns on calls tostrcmpandstrncmpwhose result is determined to be either zero or non-zero in tests for that equality, because one argument's length is greater than the size of the array the other argument lives in (or, forstrncmp, the bound). Basically these calls might be mistakes bestie. Like, check the glow-up on this:
extern char a[4];
void f (char *d)
{
strcpy (d, "string");
...
if (0 == strcmp (a, d)) // cannot be true
puts ("a and d are the same");
}
The strcmp call above is diagnosed bc its result is necessarily non-zero no matter what's chilling in the array a.
-Wstring-compare is enabled by -Wextra. ๐
-Wno-stringop-overflow-Wstringop-overflow-Wstringop-overflow=typeโ these warn for calls to string manipulation functions likememcpyandstrcpythat are determined to overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking used to figure out the size of the destination. Heads up: that argument only means something for functions that operate on character arrays, NOT for raw memory functions likememcpy, which always use Object Size type-0. This option also warns for calls that specify a size way beyond the largest possible object, or at mostSIZE_MAX / 2bytes. It produces the best results with optimization on, but can still catch a small subset of simple buffer overflows even without optimization, in calls to GCC built-ins like__builtin_memcpythat correspond to the standard functions. Either way, it only warns about a subset of buffer overflows that the corresponding overflow-checking built-ins detect. For example, it drops a warning on thestrcpycall below because it copies at least 5 characters (that's the stringblueincluding the terminatingNUL) into a buffer of size 4. ๐ญ
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
static char buf [4];
const char *str;
switch (clr)
{
case blue: str = "blue"; break;
case purple: str = "purple"; break;
case yellow: str = "yellow"; break;
}
return strcpy (buf, str); // warning here
}
Also, -Wstringop-overflow=2 is enabled by default. ๐
-Wstringop-overflow-Wstringop-overflow=1โ this one uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting it does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is actually known. When the destination might be one of several objects, it assumes it's the largest one of them. And on Linux systems, when optimization is enabled at this setting, it warns for the same code as when the_FORTIFY_SOURCEmacro is defined to a non-zero value.-Wstringop-overflow=2โ this one uses type-one Object Size Checking to determine the sizes of destination objects. Here it warns about overflows when writing to members of the largest complete objects whose exact size is known. But ngl, it does not warn about excessive writes to those same members of unknown objects referenced by pointers, since they might point to arrays with an unknown number of elements. This is the default setting of the option. โจ-Wstringop-overflow=3โ uses type-two Object Size Checking to figure out the sizes of destination objects. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option, and yes it may result in warnings for safe code. ๐-Wstringop-overflow=4โ uses type-three Object Size Checking to figure out the sizes of destination objects. Here it warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Just like-Wstringop-overflow=3, this setting of the option may result in warnings for benign code.
-Wno-stringop-overreadโ warns for calls to string manipulation functions likememchr, orstrcpy, that are determined to read past the end of the source sequence. Lowkey chaotic.
Also: -Wstringop-overread is enabled by default.
-Wno-stringop-truncationโ do not warn for calls to bounded string manipulation functions likestrncat,strncpy, andstpncpythat may either truncate the copied string or leave the destination unchanged.
So in this next example, the call to strncat specifies a bound that's less than the length of the source string. As a result the copy of the source gets truncated and therefore the call is diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound.
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
And here's another one: the strncpy call below copies to d just the characters before the terminating NUL, without appending the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call is diagnosed. To avoid the warning when the result isn't expected to be NUL-terminated, call memcpy instead, bestie.
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
And in this example, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than that size, the result of the copy won't be NUL-terminated. So yep, this call is diagnosed too. To avoid the warning, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL.
void copy (const char *s)
{
char buf[80];
strncpy (buf, s, sizeof buf);
...
}
Now, in situations where a character array is intended to store a sequence of bytes with no terminating NUL, you can annotate that array with the nonstring attribute to avoid this warning. But real talk: such arrays are NOT suitable arguments to functions that expect NUL-terminated strings. To help catch accidental misuses of these arrays, GCC issues warnings unless it can prove the use is safe.
-Wstrict-flex-arraysโ warns about improper usages of flexible array members, according to the level of thestrict_flex_array (level)attribute attached to the trailing array field of a structure โ if that's available โ otherwise according to the level of the option-fstrict-flex-arrays=level.
This option is effective only when level is bigger than 0. Otherwise it gets ignored, with a warning. ๐
- when
level=1, warnings are issued for a trailing array reference of a structure that has 2 or more elements, if the trailing array is referenced as a flexible array member. - when
level=2, in addition tolevel=1, extra warnings are issued for a trailing one-element array reference of a structure, if the array is referenced as a flexible array member. - when
level=3, in addition tolevel=2, extra warnings are issued for a trailing zero-length array reference of a structure, if the array is referenced as a flexible array member.
-Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc]โ warns for cases where adding an attribute might be beneficial. The attributes we currently support are listed below. ๐ซถ-Wsuggest-attribute=pure-Wsuggest-attribute=const-Wsuggest-attribute=noreturn-Wmissing-noreturn-Wsuggest-attribute=mallocโ warns about functions that might be candidates for the attributespure,const,noreturn, ormalloc. The compiler only warns for functions visible in other compilation units, or (forpureandconst) when it can't prove the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, callingabort, or trapping. This analysis needs the option-fipa-pure-const, which is enabled by default at-Oand higher. And higher optimization levels improve the accuracy of the analysis. ๐
-Wsuggest-attribute=format,-Wmissing-format-attributeโ ok so this one ๐ซถ warns you about function pointers that might be candidates forformatattributes. And bestie, hear me: candidates, like, possible ones, not absolute ones. GCC is guessing here, not declaring. The guess is that function pointers carryingformatattributes which get used in assignment, initialization, parameter passing, or return statements should have a matchingformatattribute in the resulting type. Translation: the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have aformatattribute โ otherwise, warning. ๐
GCC also warns about function definitions that might be candidates for format attributes. Again โ only possible candidates, don't come for GCC. The guess is that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but that might not always be the case, and some functions where format attributes would be appropriate may just not get detected. It's giving โจvibes-based static analysisโจ and honestly? Relatable.
-Wsuggest-attribute=coldโ warns about functions that might be candidates for thecoldattribute. This is based on static detection and generally only warns about functions which always lead to a call to anothercoldfunction โ think wrappers of C++throw, or fatal error reporting functions leading toabort. So basically: "this function is doomsday-coded, mark it ๐".-Walloc-zeroโ warns about calls to allocation functions decorated with attributealloc_sizethat specify zero bytes, including calls to the built-in forms ofaligned_alloc,alloca,calloc,malloc, andrealloc. Because the behavior of these functions when called with a zero size differs among implementations (and in the case ofreallocit's been deprecated ๐ญ), relying on it may result in subtle portability bugs and should be avoided. Fr fr, don't do it.-Walloc-size-larger-than=byte-sizeโ warns about calls to functions decorated with attributealloc_sizethat try to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value ofPTRDIFF_MAXon the target.-Walloc-size-larger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size ofSIZE_MAXor more, or by-Wno-alloc-size-larger-than. ๐-Wno-alloc-size-larger-thanโ disables the-Walloc-size-larger-than=warnings. The option is equivalent to-Walloc-size-larger-than=SIZE_MAXor larger.-Wallocaโ this option warns on all uses ofallocain the source. All of them. Every single one. Periodt.-Walloca-larger-than=byte-sizeโ warns on calls toallocawith an integer argument whose value is either zero, or that isn't bounded by a controlling predicate limiting its value to at most byte-size. It also warns for calls toallocawhere the bound value is unknown. And arguments of non-integer types are considered unbounded even if they appear to be constrained to the expected range. ๐
For example, a bounded case of alloca could be:
void func (size_t n)
{
void *p;
if (n <= 1000)
p = alloca (n);
else
p = malloc (n);
f (p);
}
In the above example, passing -Walloca-larger-than=1000 would not issue a warning, because the call to alloca is known to be at most 1000 bytes. But if -Walloca-larger-than=500 were passed, the compiler would emit a warning. Caught in 4K. ๐ฅ
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. For example:
void func ()
{
void *p = alloca (n);
f (p);
}
If -Walloca-larger-than=500 were passed, the above would trigger a warning โ but this time because of the lack of bounds checking, not because of the bound itself.
Note that even seemingly correct code involving signed integers could cause a warning:
void func (signed int n)
{
if (n < 500)
{
p = alloca (n);
f (p);
}
}
In the above example, n could be negative, which causes a larger-than-expected argument to be implicitly cast into the alloca call. Not the plot twist anyone wanted. ๐ญ
This option also warns when alloca is used in a loop. Yeah.
-Walloca-larger-than=PTRDIFF_MAX is enabled by default, but is usually only effective when -ftree-vrp is active (default for -O2 and above).
See also -Wvla-larger-than=byte-size.
-Wno-alloca-larger-thanโ disables the-Walloca-larger-than=warnings. The option is equivalent to-Walloca-larger-than=SIZE_MAXor larger.-Warith-conversionโ do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from-Wconversion,-Wfloat-conversion, and-Wsign-conversion.
void f (char c, int i)
{
c = c + i; // warns with -Wconversion
c = c + 1; // only warns with -Warith-conversion
}
See that second line? Only this option catches it. iykyk. ๐
-Warray-bounds,-Warray-bounds=nโ warns about out of bounds subscripts or offsets into arrays. This warning is enabled by-Wall. It's more effective when-ftree-vrpis active (the default for-O2and above) but a subset of instances are issued even without optimization.
By default, the trailing array of a structure will be treated as a flexible array member by -Warray-bounds or -Warray-bounds=n if it is declared as either a flexible array member per C99 standard onwards ([]), a GCC zero-length array extension ([0]), or a one-element array ([1]). As a result, out of bounds subscripts or offsets into zero-length arrays or one-element arrays are not warned by default.
You can add the option -fstrict-flex-arrays or -fstrict-flex-arrays=level to control how this option treats the trailing array of a structure as a flexible array member:
- when
level<=1, no change to the default behavior. - when
level=2, additional warnings will be issued for out of bounds subscripts or offsets into one-element arrays; - when
level=3, in addition tolevel=2, additional warnings will be issued for out of bounds subscripts or offsets into zero-length arrays. -Warray-bounds=1โ this is the default warning level of-Warray-boundsand is enabled by-Wall; higher levels are not, and must be explicitly requested. ๐-Warray-bounds=2โ this warning level also warns about the intermediate results of pointer arithmetic that may yield out of bounds values. Heads up though: this warning level may give a larger number of false positives and is deactivated by default. ๐
-Warray-compareโ warns about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;
-Warray-compare is enabled by -Wall. Not you comparing arrays like that bestie ๐ญ
-Warray-parameter,-Warray-parameter=nโ warns about redeclarations of functions involving arguments of array or pointer types of inconsistent kinds or forms, and enables the detection of out-of-bounds accesses to such parameters by warnings such as-Warray-bounds.
If the first function declaration uses the array form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size, or accessing more than the maximum number of elements, may be diagnosed by warnings such as -Warray-bounds. At level 1 the warning diagnoses inconsistencies involving array parameters declared using the T[static N] form.
For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one with the keyword static specifies that the array argument must have at least four elements:
void f (int[static 4]);
void f (int[]); // warning (inconsistent array form)
void g (void)
{
int *p = (int *)malloc (4);
f (p); // warning (array too small)
...
}
At level 2 the warning also triggers for redeclarations involving any other inconsistency in array or pointer argument forms denoting array sizes. Pointers and arrays of unspecified bound are considered equivalent and do not trigger a warning.
void g (int*);
void g (int[]); // no warning
void g (int[8]); // warning (inconsistent array bound)
-Warray-parameter=2 is included in -Wall. And the -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments.
-Wattribute-alias=n,-Wno-attribute-aliasโ warns about declarations using thealiasand similar attributes whose target is incompatible with the type of the alias. ๐ซถ-Wattribute-alias=1โ the default warning level of the-Wattribute-aliasoption diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs.-Wattribute-alias=2โ at this level-Wattribute-aliasalso diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the-Wmissing-attributesoption, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.
Attributes on the guest list for that one include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice.
-Wattribute-alias is literally just -Wattribute-alias=1 in a trench coat, and that's the default, bestie. Wanna yeet these warnings? Either -Wno-attribute-alias or -Wattribute-alias=0. Both work. Pick your fighter. ๐
-Wbidi-chars=[none|unpaired|any|ucn]โ Okay so this one is genuinely kinda scary ๐ญ. It warns you about UTF-8 bidirectional control characters hanging out in your comments, string literals, character constants, and identifiers where they could be misleading. Why do we care? Because these little guys can flip left-to-right writing into right-to-left (and back again), and then the logical order and the visual order in your editor are not the same thing anymore. That's a whole situation. It can be straight-up dangerous โ like, a chunk of code might look commented out when it's actually, no cap, live code. ๐
GCC gives you three levels of warning here:
- Default is
-Wbidi-chars=unpaired, which flags improperly terminated bidi contexts. -Wbidi-chars=nonesays nope, off, don't wanna hear it.-Wbidi-chars=anyflags any use of bidirectional control characters at all.
By default this warning does not check UCNs. But you can turn that on with -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. And heads up โ -Wbidi-chars=ucn on its own is valid, and it means the same thing as -Wbidi-chars=unpaired,ucn, but only if no earlier -Wbidi-chars=any got specified. Options have memory, apparently. ๐ง โจ
-Wbool-compareโ Warns when you compare a boolean expression against an integer value that isn'ttrue/false. Like, bestie, this comparison is always false:
int n = 5;
...
if ((n > 1) == 2) { ... }
This warning is enabled by -Wall. ๐
-Wbool-operationโ Warns about suspicious operations on boolean-typed expressions. Friendly reminder that bitwise negation of a boolean is very likely a bug in your program, not a personality trait. ๐ For C, this one also yells about incrementing or decrementing a boolean, which rarely makes sense. (In C++, decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++17, and deprecated otherwise.)
This warning is enabled by -Wall.
-Wduplicated-branchesโ Warns when an if-else has two literally identical branches. It catches situations like:
if (p != NULL)
return 0;
else
return 0;
It does not warn when both branches contain just a null statement. And it also catches conditional operators, like:
int i = x ? *p : *p;
Same thing twice, girl. We see it. ๐
-Wduplicated-condโ Warns about duplicated conditions in an if-else-if chain. Example, yes it warns for this:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
You already asked that question. It answered. Move on. ๐ญ
-Wframe-addressโ Warns when__builtin_frame_addressor__builtin_return_addressgets called with an argument greater than0. Those calls may return indeterminate values or straight-up crash your program. This warning is included in-Wall. โ ๏ธ-Wno-discarded-qualifiers(C and Objective-C only) โ Do not warn when type qualifiers on pointers are being discarded. Normally the compiler yells if aconst char *variable gets passed to a function expecting achar *parameter. This option is your "shhh, I know what I'm doing" card for that warning.-Wno-discarded-array-qualifiers(C and Objective-C only) โ Do not warn when type qualifiers on arrays that are pointer targets are being discarded. Typically the compiler warns if aconst int (*)[]variable is passed to a function taking aint (*)[]parameter. Use this to mute it.-Wno-incompatible-pointer-types(C and Objective-C only) โ Do not warn when a conversion happens between pointers with incompatible types. Note this is for cases not covered by-Wno-pointer-sign, which handles pointer argument passing or assignment with different signedness. Two different jobs, two different flags, don't mix them up. ๐-Wno-int-conversion(C and Objective-C only) โ Do not warn about incompatible integer-to-pointer and pointer-to-integer conversions. This one is all about implicit conversions. For explicit conversions you'd want-Wno-int-to-pointer-castand-Wno-pointer-to-int-castinstead.-Wzero-length-boundsโ Warns about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged, because accesses to them are undefined. ๐จ
For example, the first two stores in function bad get diagnosed because the array elements overlap the subsequent members b and c. The third store is diagnosed by -Warray-bounds because it's beyond the bounds of the enclosing object.
struct X { int a[0]; int b, c; };
struct X x;
void bad (void)
{
x.a[0] = 0; // -Wzero-length-bounds
x.a[1] = 1; // -Wzero-length-bounds
x.a[2] = 2; // -Warray-bounds
}
Option -Wzero-length-bounds is enabled by -Warray-bounds. Iconic chain reaction. ๐ฅ
-Wno-div-by-zeroโ Do not warn about compile-time integer division by zero. Note that floating-point division by zero is not warned about at all, because that can be a legitimate way of obtaining infinities and NaNs. So like, integer zero division = sus, float zero division = valid technique. Math stays weird. ๐ฆ-Wsystem-headersโ Prints warning messages for constructs found in system header files. Normally warnings from system headers are suppressed, on the assumption that they usually don't indicate real problems and would just make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. โจ
Careful though: using-Wallin conjunction with this option does not warn about unknown pragmas in system headers. For that, you need-Wunknown-pragmastoo. Two flags, one job. That's just how it is. ๐
-Wtautological-compareโ Warns if a self-comparison always evaluates to true or false. It catches a bunch of classics like:
int i = 1;
...
if (i > i) { ... }
It also warns about bitwise comparisons that always evaluate to true or false, for instance:
if ((a & 16) == 10) { ... }
...will always be false.
This warning is enabled by -Wall. ๐ญ
-Wtrampolinesโ Warns about trampolines generated for pointers to nested functions. So what's a trampoline? It's a small piece of data or code created at run time on the stack when the address of a nested function is taken, and it's used to call the nested function indirectly. For some targets it's made up of data only, so it needs no special treatment. But for most targets it's made up of code, which means the stack has to be made executable for the program to work properly. Yeah. That. ๐-Wfloat-equalโ Warns if floating-point values are used in equality comparisons.
The whole idea here: sometimes it's convenient (for the programmer) to think of floating-point values as approximations to infinitely precise real numbers. If that's your vibe, then you need to compute โ by analyzing the code, or some other way โ the maximum or likely maximum error that the computation introduces, and allow for it when you do comparisons (and when producing output, but that's a different problem entirely, bestie). In particular, instead of testing for equality, you should check whether the two values have ranges that overlap. That's what the relational operators are for. So those equality comparisons? Probably a mistake. ๐
-Wtraditional(C and Objective-C only) โ Warns about certain constructs that behave differently in traditional C versus ISO C. It also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs you should just avoid. The list, because of course there's a list:- Macro parameters that appear within string literals in the macro body. In traditional C, macro replacement takes place within string literals, but in ISO C it does not.
- In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the
#appeared in column 1 on the line. So-Wtraditionalwarns about directives that traditional C understands but ignores because the#isn't the first character on the line. It also suggests you hide directives like#pragmathat traditional C doesn't understand by indenting them. And some traditional implementations don't recognize#elif, so this option suggests avoiding it altogether. ๐ - A function-like macro that appears without arguments.
- The unary plus operator.
- The
Uinteger constant suffix, or theForLfloating-point constant suffixes. (Traditional C does support theLsuffix on integer constants.) Note that these suffixes show up in macros defined in system headers on most modern systems, e.g. the_MIN/_MAXmacros in<limits.h>. Using these macros in user code might normally lead to spurious warnings, however GCC's integrated preprocessor has enough context to avoid warning in these cases. Smart girl behavior. ๐ - A function declared external in one block and then used after the end of the block.
- A
switchstatement has an operand of typelong. - A non-
staticfunction declaration follows astaticone. This construct is not accepted by some traditional C compilers. - The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
- Usage of ISO string concatenation is detected.
- Initialization of automatic aggregates.
- Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
- Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g.
__STDC__to avoid missing initializer warnings, and relies on default initialization to zero in the traditional C case.
- Conversions via prototypes between fixed/floating-point values and vice versa. Bestie, when you're compiling with traditional C and those prototypes just aren't there, it causes serious problems ๐ญ. And heads up โ this is only a subset of the possible conversion warnings; for the full set you want
-Wtraditional-conversion.- ISO C style function definitions. Okay so this warning is intentionally not issued for prototype declarations or variadic functions, because those ISO C features show up in your code when you're using libiberty's traditional C compatibility macros,
PARAMSandVPARAMS๐ซถ. It's also bypassed for nested functions, because that feature is already a GCC extension and so it's just not relevant to traditional C compatibility.
- ISO C style function definitions. Okay so this warning is intentionally not issued for prototype declarations or variadic functions, because those ISO C features show up in your code when you're using libiberty's traditional C compatibility macros,
-Wtraditional-conversion(C and Objective-C only) โ warns you when a prototype forces a type conversion that would be different from what would happen to the same argument with no prototype around ๐ . That covers conversions of fixed point to floating and vice versa, plus conversions that change the width or signedness of a fixed-point argument โ except when it's the same as the default promotion.-Wdeclaration-after-statement(C and Objective-C only) โ warns when a declaration shows up after a statement inside a block ๐. This construct, which you know from C++, got introduced with ISO C99 and is by default allowed in GCC. ISO C90 does not support it, periodt.-Wshadowโ warns whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C), or whenever a built-in function is shadowed โจ. Ngl, in C++ the compiler warns if a local variable shadows an explicit typedef, but not if it shadows astruct/class/enum. If this warning is enabled, it also includes all instances of local shadowing โ which means-Wno-shadow=localand-Wno-shadow=compatible-localget ignored when-Wshadowis used. Same as-Wshadow=global.-Wno-shadow-ivar(Objective-C only) โ do not warn whenever a local variable shadows an instance variable in an Objective-C method ๐.-Wshadow=globalโ warns for any shadowing. Same as-Wshadow.-Wshadow=localโ warns when a local variable shadows another local variable or a parameter ๐.-Wshadow=compatible-localโ warns when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The whole idea behind creating this flag (on top of-Wshadow=local) is that when a local variable shadows another one of an incompatible type, it's most likely intentional โ not a bug, not a typo โ like in this iconic little example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
for (int i = 0; i < N; ++i)
{
...
}
...
}
Since the two variable i in the example above have incompatible types, enabling only -Wshadow=compatible-local does not emit a warning ๐. And because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking is expected to catch that and emit an error or warning. Using this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means shadowing const char *i by char *i does not emit a warning.
This warning is also enabled by -Wshadow=local โจ.
-Wlarger-than=byte-sizeโ warns whenever an object is defined whose size exceeds byte-size.-Wlarger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size ofSIZE_MAXor more, or by-Wno-larger-than.
Also warns for calls to bounded functions like memchr or strnlen that specify a bound greater than the largest possible object, which is PTRDIFF_MAX bytes by default. Those warnings can only be disabled by -Wno-larger-than.
-Wno-larger-thanโ disables-Wlarger-than=warnings ๐ . This option is equivalent to-Wlarger-than=SIZE_MAXor larger.-Wframe-larger-than=byte-sizeโ warns if the size of a function frame exceeds byte-size ๐ธ. Fair warning: the computation done to figure out the stack frame size is approximate and not conservative โ the actual requirements may be somewhat greater than byte-size even if you never get a warning ๐ญ. On top of that, any space allocated viaalloca, variable-length arrays, or related constructs is not included by the compiler when it decides whether or not to issue a warning.-Wframe-larger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size ofSIZE_MAXor more, or by-Wno-frame-larger-than.-Wno-frame-larger-thanโ disables-Wframe-larger-than=warnings ๐ซถ. Equivalent to-Wframe-larger-than=SIZE_MAXor larger.-Wfree-nonheap-objectโ warns when you attempt to deallocate an object that was either not allocated on the heap, or via a pointer that was not returned from a prior call to the corresponding allocation function ๐. For example, because the call tostpcpyreturns a pointer to the terminating nul character and not to the beginning of the object, the call tofreebelow gets diagnosed:
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is included in -Wall โญ.
-Wstack-usage=byte-sizeโ warns if the stack usage of a function might exceed byte-size ๐. The computation done to determine the stack usage is conservative. And unlike frame-larger-than, any space allocated viaalloca, variable-length arrays, or related constructs is included by the compiler when it's deciding whether or not to issue a warning.
The message keeps in step with the output of -fstack-usage ๐ฆ:
- If the stack usage is fully static but exceeds the specified amount, it's:
warning: stack usage is 1120 bytes
- If the stack usage is (partly) dynamic but bounded, it's:
warning: stack usage might be 1648 bytes
- If the stack usage is (partly) dynamic and not bounded, it's:
warning: stack usage might be unbounded
-Wstack-usage=PTRDIFF_MAX is enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-stack-usage โจ.
-Wno-stack-usageโ disables-Wstack-usage=warnings ๐. This option is equivalent to-Wstack-usage=SIZE_MAXor larger.-Wunsafe-loop-optimizationsโ warns if the loop cannot be optimized because the compiler can't assume anything about the bounds of the loop indices ๐. With-funsafe-loop-optimizations, warn if the compiler makes such assumptions. Lowkey a whole different vibe.-Wno-pedantic-ms-format(MinGW targets only) โ when used together with-Wformatand-pedanticand without GNU extensions, this option disables the warnings about the non-ISOprintf/scanfformat width specifiersI32,I64, andIused on Windows targets, which depend on the MS runtime ๐.-Wpointer-arithโ warns about anything that depends on the "size of" a function type or ofvoid๐. GNU C assigns these types a size of1, for convenience in calculations withvoid *pointers and pointers to functions. In C++, it also warns when an arithmetic operation involvesNULL. This warning is also enabled by-Wpedantic.-Wno-pointer-compareโ do not warn if a pointer is compared with a zero character constant ๐ซถ. That comparison usually means the pointer was meant to be dereferenced. Like:
const char *p = foo ();
if (p == '\0')
return 42;
Note that the code above is invalid in C++11 ๐.
This warning is enabled by default.
-Wtsanโ warns about unsupported features in ThreadSanitizer ๐ธ.
ThreadSanitizer does not support std::atomic_thread_fence and can report false positives ๐ญ.
This warning is enabled by default.
-Wtype-limitsโ warns if a comparison is always true or always false because of the limited range of the data type โ but it does not warn for constant expressions ๐ . For example, warn if an unsigned variable is compared against zero with<or>=. This warning is also enabled by-Wextra.-Wabsolute-value(C and Objective-C only) โ warns for calls to standard functions that compute the absolute value of an argument when a more appropriate standard function is available โจ. For example, callingabs(3.14)triggers the warning, because the appropriate function to call to compute the absolute value of a double argument isfabs. The option also triggers warnings when the argument in a call to such a function has an unsigned type. This warning can be suppressed with an explicit type cast, and it's also enabled by-Wextra.-Wcomment-Wcommentsโ warns whenever a comment-start sequence/*appears in a/*comment, or whenever a backslash-newline appears in a//comment ๐ฆ. This warning is enabled by-Wall.-Wtrigraphsโ warns if any trigraphs are encountered that might change the meaning of the program ๐. Trigraphs within comments are not warned about, except those that would form escaped newlines.
This option is implied by -Wall. If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but still get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs ๐
.
-Wundefโ warns if an undefined identifier is evaluated in an#ifdirective ๐. Such identifiers get replaced with zero.-Wexpansion-to-definedโ warns wheneverdefinedis encountered in the expansion of a macro (including the case where the macro is expanded by an#ifdirective) ๐ญ. Such usage is not portable. This warning is also enabled by-Wpedanticand-Wextra.-Wunused-macrosโ warns about macros defined in the main file that are unused ๐ค. A macro counts as used if it's expanded or tested for existence at least once. The preprocessor also warns if the macro has not been used at the time it is redefined or undefined.- (heads up, continuing) Macros that are built-in, macros you
#defineon the command line, and macros defined in include files โ those do not get warned about. Only user macros in the actual source. โจ
ok bestie, little gotcha: if a macro is actually used, but only used inside skipped conditional blocks, the preprocessor still reports it as unused. ๐ญ To dodge the warning in that case, you might improve the scope of the macro's definition โ for example, tuck it into the first skipped block. Or alternatively, just feed it a lil dummy use like this:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsโ do not warn whenever an#elseor an#endifis followed by text. Ngl, this sometimes happens in older programs with code shaped like:
#if FOO
...
#else FOO
...
#endif FOO
That second and third FOO should be in comments. This warning is on by default, so yeah, it'll show up unless you silence it. ๐ซถ
-Wbad-function-cast(C and Objective-C only) โ warns when a function call gets cast to a non-matching type. Like if you call a function returning an integer type and cast it to a pointer type. It's giving "bestie why". ๐-Wc90-c99-compat(C and Objective-C only) โ warns about features that aren't in ISO C90 but are in ISO C99. For instance: variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows__extension__. ๐-Wc99-c11-compat(C and Objective-C only) โ warns about features not present in ISO C99 but present in ISO C11. For instance: anonymous structures and unions, the_Atomictype qualifier, the_Thread_localstorage-class specifier, the_Alignasspecifier, theAlignofoperator, the_Generickeyword, and so on. Also independent of the standards mode. Warnings are disabled in the expression that follows__extension__. ๐ธ-Wc11-c2x-compat(C and Objective-C only) โ warns about features not present in ISO C11 but present in ISO C2X. For instance: omitting the string in_Static_assert, use of[[]]syntax for attributes, use of decimal floating-point types, and so on. Yep, independent of the standards mode again. Warnings are disabled in the expression that follows__extension__. โจ-Wc++-compat(C and Objective-C only) โ warns about ISO C constructs that live outside the common subset of ISO C and ISO C++, e.g. a request for implicit conversion fromvoid *to a pointer to non-voidtype. ๐ฆ-Wc++11-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g. identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011. This warning turns on-Wnarrowingand is enabled by-Wall. ๐ฅ-Wc++14-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. Enabled by-Wall. ๐-Wc++17-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. Enabled by-Wall. ๐-Wc++20-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. Enabled by-Wall. โญ-Wno-c++11-extensions(C++ and Objective-C++ only) โ do not warn about C++11 constructs in code being compiled with an older C++ standard. Even without this option, some C++11 constructs will only be diagnosed if-Wpedanticis used. ๐ง-Wno-c++14-extensions(C++ and Objective-C++ only) โ do not warn about C++14 constructs in code being compiled with an older C++ standard. Even without this option, some C++14 constructs will only be diagnosed if-Wpedanticis used. ๐-Wno-c++17-extensions(C++ and Objective-C++ only) โ do not warn about C++17 constructs in code being compiled with an older C++ standard. Even without this option, some C++17 constructs will only be diagnosed if-Wpedanticis used. ๐-Wno-c++20-extensions(C++ and Objective-C++ only) โ do not warn about C++20 constructs in code being compiled with an older C++ standard. Even without this option, some C++20 constructs will only be diagnosed if-Wpedanticis used. ๐-Wno-c++23-extensions(C++ and Objective-C++ only) โ do not warn about C++23 constructs in code being compiled with an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if-Wpedanticis used. ๐-Wcast-qualโ warns whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if aconst char *is cast to an ordinarychar *.
It also warns when you make a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, like in this example:
/* p is char ** value. */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK. */
*q = "string";
/* Now char** pointer points to read-only memory. */
**p = 'b';
Likeโฆ that last line is a whole crime scene. ๐จ
-Wcast-alignโ warns whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if achar *is cast to anint *on machines where integers can only be accessed at two- or four-byte boundaries. ๐ตโ๐ซ-Wcast-align=strictโ warns whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if achar *is cast to anint *regardless of the target machine. No hiding behind your architecture, bestie. ๐-Wcast-function-typeโ warns when a function pointer is cast to an incompatible function pointer. In a cast involving function types with a variable argument list, only the types of initial arguments that are provided are considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are ignored, likeintvs.longon ILP32 targets. Likewise, type qualifiers are ignored. The function typevoid (*) (void)is special and matches everything, which can be used to suppress this warning. In a cast involving pointer to member types, this warning warns whenever the type cast is changing the pointer to member type. This warning is enabled by-Wextra. ๐ฅ-Wwrite-stringsโ when compiling C, give string constants the typeconst char[length]so that copying the address of one into a non-constchar *pointer produces a warning. These warnings help you find, at compile time, code that can try to write into a string constant โ but only if you've been very careful about usingconstin declarations and prototypes. Otherwise it's just a nuisance. This is why-Walldoes not request these warnings.
When compiling C++, warn about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs. ๐
-Wclobberedโ warns for variables that might be changed bylongjmporvfork. This warning is also enabled by-Wextra. ๐ญ-Wno-complain-wrong-langโ by default, language front ends complain when a command-line option is valid, but not applicable to that front end. This may be disabled with-Wno-complain-wrong-lang, which is mostly useful when invoking a single compiler driver for multiple source files written in different languages, for example:
$ g++ -fno-rtti a.cc b.f90
The driver g++ invokes the C++ front end to compile a.cc and the Fortran front end to compile b.f90. The latter front end diagnoses
f951: Warning: command-line option '-fno-rtti' is valid for C++/D/ObjC++ but not for Fortran
which may be disabled with -Wno-complain-wrong-lang. So iconic of you to compile two languages at once tho. ๐ซถ
-Wconversionโ warns for implicit conversions that may alter a value. This includes conversions between real and integer, likeabs (x)whenxisdouble; conversions between signed and unsigned, likeunsigned ui = -1; and conversions to smaller types, likesqrtf (M_PI). Do not warn for explicit casts likeabs ((int) x)andui = (unsigned) -1, or if the value is not changed by the conversion like inabs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using-Wno-sign-conversion.
For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to void, the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.
Warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion. โจ
-Wdangling-elseโ warns about constructions where there may be confusion as to whichifstatement anelsebranch belongs to. Here's an example of such a case:
{
if (a)
if (b)
foo ();
else
bar ();
}
In C/C++, every else branch belongs to the innermost possible if statement, which in this example is if (b). This is often not what the programmer expected, as illustrated in the above example by the indentation the programmer chose. When there's the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. The resulting code looks like this:
{
if (a)
{
if (b)
foo ();
else
bar ();
}
}
This warning is enabled by -Wparentheses. Not the vibes getting ambiguous ๐ โ braces are your bestie fr fr. ๐
-Wdangling-pointer,-Wdangling-pointer=nโ okay bestie, this one is literally the "your pointer is SO expired" warning ๐ it yells at you for using pointers (or C++ references) that point at objects with automatic storage duration after those objects' lifetime has already ended. And it's not just plain local vars โ nested-block locals, compound literals, unnamed temporary objects, all of them. It also side-eyes you for stashing the address of one of those expired objects into an escaped pointer. ๐ซถ The warning is enabled at all optimization levels, but heads up: it may yield different results with optimization than without.-Wdangling-pointer=1โ level 1 only diagnoses unconditional uses of dangling pointers. Iconic. For example:
int f (int c1, int c2, x)
{
char *p = strchr ((char[]){ c1, c2 }, c3);
// warning: dangling pointer to a compound literal
return p ? *p : 'x';
}
And in this next function, the store of the address of the local variable x into the escaped pointer *p also triggers the warning:
void g (int **p)
{
int x = 7;
// warning: storing the address of a local variable in *p
*p = &x;
}
-Wdangling-pointer=2โ level 2 goes further, and honestly it's giving detective energy ๐ because on top of unconditional uses, it also diagnoses conditional uses of dangling pointers.
For example, because the array a in the following function is out of scope by the time the pointer s (which was set to point at it) gets used, the warning triggers at this level:
void f (char *s)
{
if (!s)
{
char a[12] = "tmpname";
s = a;
}
// warning: dangling pointer to a may be used
strcat (s, ".tmp");
...
}
Quick glow-up note:-Wdangling-pointer=2is included in-Wall. โจ
-Wdate-timeโ warns you when the macros"__TIME__","__DATE__"or"__TIMESTAMP__"show up, because they might prevent bit-wise-identical reproducible compilations. ๐ธ Reproducibility girlies stay winning, no cap.-Wempty-bodyโ warns if there's an empty body in anif,elseordo whilestatement. Yeah bestie,{ }with nothing in it is suspicious ๐ This warning is also enabled by-Wextra.-Wno-endif-labelsโ do not warn about stray tokens after"#else"and"#endif". That's it. That's the whole thing. ๐-Wenum-compareโ warns about a comparison between values of different enumerated types. In C++ this warning is enabled by default and enumerated type mismatches in conditional expressions are also diagnosed. In C, it's enabled by-Wall.-Wenum-conversionโ warns when a value of an enumerated type gets implicitly converted to a different enumerated type. Sneaky little glow-down, honestly. In C this warning is enabled by-Wextra.-Wenum-int-mismatch(C and Objective-C only) โ warns about mismatches between an enumerated type and an integer type in declarations. Like, for example:
enum E { l = -1, z = 0, g = 1 };
int foo(void);
enum E foo(void);
In C, an enumerated type is compatible with char, a signed integer type, or an unsigned integer type. BUT since the choice of the underlying type of an enumerated type is implementation-defined, these mismatches may cause portability issues. ๐ญ In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat.
-Wjump-misses-init(C, Objective-C only) โ warns if agotostatement or aswitchstatement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. It only warns about variables that are initialized when they are declared, and it's only supported for C and Objective-C โ in C++ this sort of branch is an error in any case, so there's nothing to warn about. ๐คทโโ๏ธ
Fun fact: -Wjump-misses-init is included in -Wc++-compat. And you can turn it off with the -Wno-jump-misses-init option.
-Wsign-compareโ warns when a comparison between signed and unsigned values could produce an incorrect result when the signed value gets converted to unsigned. Classic signedness betrayal ๐ In C++, this warning is also enabled by-Wall. In C, it is also enabled by-Wextra.-Wsign-conversionโ warns for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning (clock it, bestie โจ). In C, this option is enabled also by-Wconversion.-Wfloat-conversionโ warns for implicit conversions that reduce the precision of a real value. That includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by-Wconversion. ๐ Precision loss is not the vibe.-Wno-scalar-storage-orderโ do not warn on suspicious constructs involving reverse scalar storage order.-Wsizeof-array-divโ warns about divisions of twosizeofoperators when the first one is applied to an array and the divisor does not equal the size of the array element. In that case, the computation will not yield the number of elements in the array, which is likely what you actually meant. ๐ญ This warning warns e.g. about:
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall.
-Wsizeof-pointer-divโ warns for suspicious divisions of twosizeofexpressions that divide the pointer size by the element size. That's the usual way to compute the array size, but it will not work out correctly with pointers. ๐ซ This warning warns e.g. aboutsizeof (ptr) / sizeof (ptr[0])ifptris not an array, but a pointer. This warning is enabled by-Wall.-Wsizeof-pointer-memaccessโ warns for suspicious length parameters to certain string and memory built-in functions if the argument usessizeof. This warning triggers for example formemset (ptr, 0, sizeof (ptr));ifptris not an array, but a pointer โ and it suggests a possible fix โ or aboutmemcpy (&foo, ptr, sizeof (&foo));.
-Wsizeof-pointer-memaccess also warns about calls to bounded string copy functions like strncat or strncpy that specify as the bound a sizeof expression of the source array. For example, in the following function the call to strncat specifies the size of the source string as the bound. That is almost certainly a mistake, and so the call is diagnosed:
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
The -Wsizeof-pointer-memaccess option is enabled by -Wall.
-Wno-sizeof-array-argumentโ do not warn when thesizeofoperator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs. ๐-Wmemset-elt-sizeโ warns for suspicious calls to thememsetbuilt-in function, if the first argument references an array, and the third argument is a number equal to the number of elements, but not equal to the size of the array in memory. That right there indicates the user has omitted a multiplication by the element size. ๐ This warning is enabled by-Wall.-Wmemset-transposed-argsโ warns for suspicious calls to thememsetbuilt-in function where the second argument is not zero and the third argument is zero. For example, the callmemset (buf, sizeof buf, 0)is diagnosed becausememset (buf, 0, sizeof buf)was meant instead. ๐ The diagnostic is only emitted if the third argument is a literal zero โ otherwise, if it's an expression that folds to zero, or a cast of zero to some type, it's far less likely that the arguments were mistakenly transposed, and no warning is emitted. This warning is enabled by-Wall.-Waddressโ warns about suspicious uses of address expressions. These include comparing the address of a function or a declared object to the null pointer constant, such as in:
void f (void);
void g (void)
{
if (!f) // warning: expression evaluates to false
abort ();
}
comparisons of a pointer to a string literal, such as in:
void f (const char *x)
{
if (x == "abc") // warning: expression evaluates to false
puts ("equal");
}
and tests of the results of pointer addition or subtraction for equality to null, such as in:
void f (const int *p, int i)
{
return p + i == NULL;
}
Such uses typically indicate a programmer error: the address of most functions and objects necessarily evaluates to true (the exception are weak symbols), so their use in a conditional might indicate missing parentheses in a function call or a missing dereference in an array expression. The subset of the warning for object pointers can be suppressed by casting the pointer operand to an integer type such as intptr_t or uintptr_t. Comparisons against string literals result in unspecified behavior and are not portable, and suggest the intent was to call strcmp. The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress warning is enabled by -Wall.
-Wno-address-of-packed-memberโ do not warn when the address of a packed member of a struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default.-Wlogical-opโ warns about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected. It also warns when the operands of a logical operator are the same:
extern int a;
if (a < 0 && a < 0) { ... }
Like bestieโฆ a < 0 && a < 0?? Twice?? ๐ซ
-Wlogical-not-parenthesesโ warns about logical not used on the left hand side operand of a comparison. This option does not warn if the right operand is considered to be a boolean expression. Its purpose is to detect suspicious code like the following:
int a;
...
if (!a > 1) { ... }
okay bestie so if you ever need to suppress that warning, you can literally wrap the LHS in parentheses like this:
if ((!a) > 1) { ... }
and boom, the warning is gone. Also this warning is enabled by -Wall.
-Waggregate-returnโ warns if any functions that return structures or unions are defined or called. (And if you're in a language where you can return an array, that also gets a warning. ๐ )-Wno-aggressive-loop-optimizationsโ warns if, in a loop with a constant number of iterations, the compiler detects undefined behavior in some statement during one or more of the iterations. ๐ซ-Wno-attributesโ do not warn if an unexpected"__attribute__"is used, like unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes.
Additionally, using -Wno-attributes=, it is possible to suppress warnings about unknown scoped attributes (in C++11 and C2X). For example, -Wno-attributes=vendor::attr disables warning about the following declaration:
[[vendor::attr]] void f();
It is also possible to disable warning about all attributes in a namespace using -Wno-attributes=vendor::, which prevents warning about both of these declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Note that -Wno-attributes= does not imply -Wno-attributes. ๐
-Wno-builtin-declaration-mismatchโ warns if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that does not include a prototype is called with arguments whose promoted types do not match those expected by the function. When-Wextrais specified, also warn when a built-in function that takes arguments is declared without a prototype. The-Wbuiltin-declaration-mismatchwarning is enabled by default. To avoid the warning, include the appropriate header to bring the prototypes of built-in functions into scope. โจ
For example, the call to memset below is diagnosed by the warning because the function expects a value of type size_t as its argument but the type of 32 is int. With -Wextra, the declaration of the function is diagnosed as well.
extern void* memset ();
void f (void *d)
{
memset (d, '\0', 32);
}
-Wno-builtin-macro-redefinedโ do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of__TIMESTAMP__,__TIME__,__DATE__,__FILE__, and__BASE_FILE__. ๐-Wstrict-prototypes(C and Objective-C only) โ warns if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration that specifies the argument types.) ๐-Wold-style-declaration(C and Objective-C only) โ warns for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers likestaticare not the first things in a declaration. This warning is also enabled by-Wextra. ๐ญ-Wold-style-definition(C and Objective-C only) โ warns if an old-style function definition is used. A warning is given even if there is a previous prototype. A definition using()is not considered an old-style definition in C2X mode, because it is equivalent to(void)in that case, but is considered an old-style definition for older standards. ๐-Wmissing-parameter-type(C and Objective-C only) โ a function parameter is declared without a type specifier in K&R-style functions:
void foo(bar) { }
This warning is also enabled by -Wextra. ๐ซถ
-Wmissing-prototypes(C and Objective-C only) โ warns if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. This option is not valid for C++ because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. Use-Wmissing-declarationsto detect missing declarations in C++. ๐-Wmissing-declarationsโ warns if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations; use-Wmissing-prototypesto detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces. ๐ธ-Wmissing-field-initializersโ warns if a structure's initializer has some fields missing. For example, the following code causes such a warning, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so the following modification does not trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
In C this option does not warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
Likewise, in C++ this option does not warn about the empty { } initializer, for example:
struct s { int f, g, h; };
s x = { };
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers. โจ
-Wno-missing-requiresโ by default, the compiler warns about a concept-id appearing as a C++20 simple-requirement:
bool satisfied = requires { C<T> };
Here satisfied will be true if C<T> is a valid expression, which it is for all T. Presumably the user meant to write:
bool satisfied = requires { requires C<T> };
so satisfied is only true if concept C is satisfied for type T.
This warning can be disabled with -Wno-missing-requires. ๐ฅ
-Wno-missing-template-keywordโ the member access tokens.,->and::must be followed by the"template"keyword if the parent object is dependent and the member being named is a template.
template <class X>
void DoStuff (X x)
{
x.template DoSomeOtherStuff<X>(); // Good.
x.DoMoreStuff<X>(); // Warning, x is dependent.
}
In rare cases it is possible to get false positives. To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:
void NotATemplate (my_class t)
{
int N = 5;
bool test = t.m < N > (0); // Treated as a template.
test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}
This warning can be disabled with -Wno-missing-template-keyword. ๐ฆ
-Wno-multicharโ do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code. ๐-Wnormalized=[none|id|nfc|nfkc]โ in ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. To avoid confusion, the ISO 10646 standard sets out some normalization rules which, when applied, ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized; this option controls that warning. ๐
There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized. โญ
Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default. ๐ญ
You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. ๐
Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly. ๐
-Wno-attribute-warningโ do not warn about usage of functions declared with"warning"attribute. By default, this warning is enabled.-Wno-attribute-warningcan be used to disable the warning or-Wno-error=attribute-warningcan be used to disable the error when compiled with-Werrorflag. ๐-Wno-deprecatedโ do not warn about usage of deprecated features. ๐-Wno-deprecated-declarationsโ do not warn about uses of functions, variables, and types marked as deprecated by using the"deprecated"attribute. ๐ฆ-Wno-overflowโ do not warn about compile-time overflow in constant expressions. ๐-Wno-odrโ bestie, this one snitches on One Definition Rule violations during link-time optimization. It's on by default, so it's already doing its lil surveillance job. ๐-Wopenacc-parallelismโ yells at you when your OpenACC parallelism choices are potentially suboptimal. Not illegal, justโฆ not the serve it could've been. ๐-Wopenmp-simdโ fires when the vectorizer cost model overrides the OpenMP simd directive you set. Rude, honestly. If you wanna relax that cost model, reach for-fsimd-cost-model=unlimited. โจ-Woverride-init(C and Objective-C only) โ warns when an initialized field without side effects gets overridden while you're using designated initializers.
This one is part of -Wextra, so if you want the other -Wextra warnings but not this one, hit it with -Wextra -Wno-override-init. ๐
-Wno-override-init-side-effects(C and Objective-C only) โ turns off the warning for when an initialized field with side effects gets overridden in designated initializers. This warning is enabled by default.-Wpackedโ warns when a struct is given thepackedattribute but that attribute literally does nothing to its layout or size. Which means the struct might be mis-aligned for basically zero benefit. Not the slay, it's the ๐ซ .
Like, look at this โ f.x inside struct bar ends up misaligned even though struct bar itself has no packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compatโ okay history lesson ๐: GCC 4.1, 4.2 and 4.3 straight-up ignored thepackedattribute on bit-fields of typechar. It got fixed in GCC 4.4, but that fix can change your struct layout, which is the kind of chaos that ruins your whole week.
So GCC tells you when the offset of such a field changed in GCC 4.4. For exaaaample, there's no longer a 4-bit padding between field a and b in this:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable it.
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warns when a struct field with explicitly specified alignment inside a packed struct or union ends up misaligned. Ngl it's giving "you asked for alignment and the universe said no".
So a warning gets issued on struct S like warning: alignment 1 of 'struct S' is less than 8, in this code right here:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
struct S8 s8;
};
This warning is enabled by -Wall.
-Wpaddedโ warns if padding sneaks into a structure, whether it's to align an element or to align the whole thing. Sometimes you can rearrange the fields, shrink the padding, and make the whole struct smaller. Free diet, no gym. ๐ช-Wredundant-declsโ warns if literally anything gets declared more than once in the same scope, even in the cases where the double declaration is valid and changes absolutely nothing. It's the "why are you like this" of warnings. ๐-Wrestrictโ warns when an object referenced by arestrict-qualified parameter (or in C++, a__restrict-qualified parameter) is aliased by another argument, or when copies between such objects overlap.
For instance, the call to strcpy below is trying to truncate the string by replacing its first chars with the last four. But since the call writes the terminating NUL into a[4], the copies overlap and the call gets diagnosed. Caught in 4K. ๐ธ
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
-Wrestrict catches some instances of simple overlap even without optimization, but it works best at -O2 and above. It's included in -Wall.
-Wnested-externs(C and Objective-C only) โ warns if anexterndeclaration shows up inside a function. Putting your externs inside a function? In this economy? ๐ญ-Winlineโ warns if a function declared asinlinecannot be inlined. But even with this option on, the compiler won't warn about failures to inline functions declared in system headers. It's got selective hearing, and honestly? Same.
The compiler uses a whole bunch of heuristics to decide whether to inline something or not. For example, it considers the size of the function being inlined and how much inlining has already happened in the current function.
Which means seemingly tiny, insignificant changes in your source can make -Winline warnings appear or vanish. So if you're chasing them like a detective ๐, know that the vibes are unstable.
-Winterference-sizeโ warns about using C++17std::hardware_destructive_interference_sizewithout specifying its value with--param destructive-interference-size. Also warns about questionable values for that option.
This variable exists to control class layout and avoid false sharing in concurrent code:
struct independent_fields {
alignas(std::hardware_destructive_interference_size)
std::atomic<int> one;
alignas(std::hardware_destructive_interference_size)
std::atomic<int> two;
};
Here one and two are meant to be far enough apart that stores to one won't force the other to reload the cache line. Space, boundaries, healthy relationships. ๐ฆ
By default, --param destructive-interference-size and --param constructive-interference-size are set based on the current -mtune option โ typically the L1 cache line size for that particular target CPU, sometimes a range if you're tuning for a generic target.
So every translation unit that depends on ABI compatibility for these variables has to be compiled with the same-mtune(or-mcpu). No mixing, no matching. ๐ซ
If ABI stability is important โ like, say, the use is in a header for a library โ you should probably not use the hardware interference size variables at all. Alternatively, you can force a particular value with --param.
And if you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can turn the warning off with -Wno-interference-size. Live your truth. ๐
-Wint-in-bool-contextโ warns about suspicious use of integer values where boolean values are expected. Like conditional expressions (?:) using non-boolean integer constants in a boolean context, such asif (a <= b ? 2 : 3). Sussy. ๐คจ
Or left shifting signed integers in a boolean context, like for (a = 0; 1 << a; a++);. Same energy, also flagged.
And likewise for all kinds of multiplications regardless of data type. This warning is enabled by -Wall.
-Wno-int-to-pointer-castโ suppresses warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error, not a warning.Wint-to-pointer-castis enabled by default.-Wno-pointer-to-int-cast(C and Objective-C only) โ suppresses warnings from casts from a pointer to an integer type of a different size. Round trip, but make it cursed. ๐-Winvalid-pchโ warns if a precompiled header is found in the search path but cannot be used. It's right there!! And yet. ๐ค-Winvalid-utf8โ warns if an invalid UTF-8 character is found. This warning is on by default for C++23 if-finput-charset=UTF-8is used, and it gets turned into an error with-pedantic-errors. So behave. ๐-Wno-unicodeโ don't diagnose invalid forms of delimited or named escape sequences that are treated as separate tokens.Wunicodeis enabled by default.-Wlong-longโ warns if thelong longtype is used. This gets enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. To shut the warnings up, use-Wno-long-long.-Wvariadic-macrosโ warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. Enabled by either-Wpedanticor-Wtraditional. To silence the messages, use-Wno-variadic-macros. ๐คซ-Wno-varargsโ don't warn on questionable usage of the macros used to handle variable arguments, likeva_start. These warnings are enabled by default.-Wvector-operation-performanceโ warns if a vector operation isn't implemented via the SIMD capabilities of the architecture. Mainly useful for performance tuning, aka for the number girlies ๐.
A vector operation can be implemented a few ways:
- "piecewise" โ the scalar operation is performed on every vector element.
- "in parallel" โ the vector operation is implemented using scalars of a wider type, which normally is more performance efficient. โจ
- "as a single scalar" โ the vector fits into a scalar type.
-Wvlaโ warns if a variable-length array is used in the code. And-Wno-vlaprevents the-Wpedanticwarning about the variable-length array. Two warnings, one vibe check.-Wvla-larger-than=byte-sizeโ with this option in play, the compiler warns about declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that lets the array size exceed byte-size bytes.
This is similar to how -Walloca-larger-than=byte-size works, but with variable-length arrays instead. ๐
Heads up bestie: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning might not even trigger for those. Sneaky.
-Wvla-larger-than=PTRDIFF_MAX is enabled by default but is typically only effective when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=byte-size. ๐
-Wno-vla-larger-thanโ disables the-Wvla-larger-than=warnings. The option is equivalent to-Wvla-larger-than=SIZE_MAXor larger.-Wvla-parameterโ warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and it enables detection of out-of-bounds accesses to such parameters by warnings like-Warray-bounds.
If the first function declaration uses the VLA form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function, and the maximum number of elements accessed by it.
So failing to provide arguments of sufficient size, or accessing more than the maximum number of elements, may get diagnosed. The bounds are the bounds, periodt. ๐
-Wvolatile-register-varโ ok so this one yells at you if you declared aregistervariable asvolatile๐ and like, here's the thing bestie: thatvolatilemodifier does not stop all the optimizations that could kill off reads and/or writes to register variables. Nope. So don't think it's gonna save you. This warning is switched on by-Wall.-Wxor-used-as-pow(C, C++, Objective-C and Objective-C++ only) โ warns you about uses of^, the exclusive-or operator, in cases where it looks like the user meant exponentiation. Specifically, it fires when the left-hand side is the decimal constant2or10and the right-hand side is also a decimal constant.
In C and C++, ^ means exclusive or โ but in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. So the vibe check gets confused ๐ญ
This warning is enabled by default. Wanna silence it? Just convert one of the operands to hexadecimal. Boom, gone โจ
-Wdisabled-optimizationโ warns if a requested optimization pass is disabled. Ngl this usually does not mean something's wrong with your code; it just means GCC's optimizers couldn't handle it effectively. Often it's because your code is too big or too complex โ and GCC flat-out refuses to optimize programs when the optimization itself is probably gonna take an inordinate amount of time. Respect for the boundaries honestly ๐ซถ-Wpointer-sign(C and Objective-C only) โ warns when you pass or assign a pointer argument with different signedness. This option is only supported for C and Objective-C. It's implied by-Walland by-Wpedantic, and you can turn it off with-Wno-pointer-sign.-Wstack-protectorโ this one is only active when-fstack-protectoris active. It warns about functions that are not protected against stack smashing ๐ก๏ธ-Woverlength-stringsโ warns about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally let you have string constants way longer than the standard's minimum limit, but very portable programs should avoid using longer strings.
The limit applies after string constant concatenation and does not count the trailing NUL. In C90 the limit was 509 characters; in C99 it was raised to 4095. C++98 doesn't specify a normative minimum maximum, so we don't diagnose overlength strings in C++.
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.
-Wunsuffixed-float-constants(C and Objective-C only) โ issues a warning for any floating constant that doesn't have a suffix. When you use it together with-Wsystem-headers, it warns about such constants in system header files too. This can be useful when preparing code to use with theFLOAT_CONST_DECIMAL64pragma from the decimal floating-point extension to C99.-Wno-lto-type-mismatchโ during link-time optimization, don't warn about type mismatches in global declarations from different compilation units. Requires-fltoto be enabled. Enabled by default.-Wno-designated-init(C and Objective-C only) โ suppresses warnings when a positional initializer is used to initialize a structure that has been marked with thedesignated_initattribute.
โจ Options That Control Static Analysis โจ
-fanalyzerโ bestie this option enables a static analysis of program flow that hunts for "interesting" interprocedural paths through the code, and issues warnings for the problems it finds on them ๐
Heads up: this analysis is much more expensive than other GCC warnings.
In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It's a bug-finding tool, not a tool for proving program correctness โ so don't ask it for a notarized certificate, okay?
In this release, the analyzer is only suitable for use on C code.
Turning this option on effectively enables the following warnings:
-Wanalyzer-allocation-size -Wanalyzer-deref-before-check
-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file
-Wanalyzer-exposure-through-uninit-copy
-Wanalyzer-fd-access-mode-mismatch -Wanalyzer-fd-double-close
-Wanalyzer-fd-leak -Wanalyzer-fd-phase-mismatch
-Wanalyzer-fd-type-mismatch -Wanalyzer-fd-use-after-close
-Wanalyzer-fd-use-without-check -Wanalyzer-file-leak
-Wanalyzer-free-of-non-heap -Wanalyzer-imprecise-fp-arithmetic
-Wanalyzer-infinite-recursion -Wanalyzer-jump-through-null
-Wanalyzer-malloc-leak -Wanalyzer-mismatching-deallocation
-Wanalyzer-null-argument -Wanalyzer-null-dereference
-Wanalyzer-out-of-bounds -Wanalyzer-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-putenv-of-auto-var
-Wanalyzer-shift-count-negative -Wanalyzer-shift-count-overflow
-Wanalyzer-stale-setjmp-buffer
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-use-of-uninitialized-value
-Wanalyzer-va-arg-type-mismatch -Wanalyzer-va-list-exhausted
-Wanalyzer-va-list-leak -Wanalyzer-va-list-use-after-va-end
-Wanalyzer-write-to-const -Wanalyzer-write-to-string-literal
This option is only available if GCC was configured with analyzer support enabled. No support, no analysis, periodt.
-Wanalyzer-too-complexโ if-fanalyzeris enabled, the analyzer uses various heuristics to try to explore the control flow and data flow in the program, but sufficiently complicated code can defeat all of that ๐ต
By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it hits an internal limit. The -Wanalyzer-too-complex option warns you if that happens.
-Wno-analyzer-allocation-sizeโ this warning requires-fanalyzer, which enables it; to disable it, use-Wno-analyzer-allocation-size.
This diagnostic warns for paths through the code in which a pointer to a buffer is assigned to point at a buffer with a size that is not a multiple of sizeof (*pointer).
See CWE-131: Incorrect Calculation of Buffer Size (https://cwe.mitre.org/data/definitions/131.html).
-Wno-analyzer-deref-before-checkโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-deref-before-checkto disable it.
This diagnostic warns for paths through the code in which a pointer is checked for NULL after it has already been dereferenced, which suggests the pointer could have been NULL. Cases like this suggest that the check for NULL is either redundant, or that it needs to be moved to before the pointer is dereferenced.
It also considers values passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value, and thus will complain if such values are checked for NULL after returning from such a function call.
Ngl this diagnostic is unlikely to be reported when any level of optimization is enabled, because GCC's optimization logic will typically consider such checks for NULL as redundant and optimize them away before the analyzer ever "sees" them. So if you wanna trigger it, disable optimization. ๐
-Wno-analyzer-double-fcloseโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-fcloseto disable it.
This diagnostic warns for paths through the code in which a FILE * can have fclose called on it more than once.
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-double-freeโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-freeto disable it.
This diagnostic warns for paths through the code in which a pointer can have a deallocator called on it more than once โ either free, or a deallocator referenced by attribute malloc.
See CWE-415: Double Free (https://cwe.mitre.org/data/definitions/415.html).
-Wno-analyzer-exposure-through-output-fileโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-exposure-through-output-fileto disable it.
This diagnostic warns for paths through the code in which a security-sensitive value is written to an output file (like writing a password to a log file ๐ฌ).
See CWE-532: Information Exposure Through Log Files (https://cwe.mitre.org/data/definitions/532.html).
-Wanalyzer-exposure-through-uninit-copyโ this warning requires both-fanalyzerand the use of a plugin to specify a function that copies across a "trust boundary". Use-Wno-analyzer-exposure-through-uninit-copyto disable it.
This diagnostic warns for "infoleaks" โ paths through the code in which uninitialized values are copied across a security boundary (like code within an OS kernel that copies a partially-initialized struct on the stack to user space ๐).
See CWE-200: Exposure of Sensitive Information to an Unauthorized Actor (https://cwe.mitre.org/data/definitions/200.html).
-Wno-analyzer-fd-access-mode-mismatchโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-fd-access-mode-mismatchto disable it.
This diagnostic warns for paths through code in which a read on a write-only file descriptor is attempted, or vice versa.
...and it also yells at you when a function tagged with fd_arg_read (N) gets called with a file descriptor that was opened with O_WRONLY at referenced argument N, or when a function tagged with fd_arg_write (N) gets a file descriptor opened with O_RDONLY at referenced argument N. Like bestie the analyzer read your intent and your actual open call and they are NOT texting back. ๐
-Wno-analyzer-fd-double-closeโ okay so this warning only exists if-fanalyzeris on (that's what enables it), so you'd use-Wno-analyzer-fd-double-closeto turn it off.
This diagnostic warns you about code paths where a file descriptor can be closed more than once. Closing it once: fine. Closing it twice: chaos. ๐
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-fd-leakโ requires-fanalyzer(it's the thing enabling it, bestie); use-Wno-analyzer-fd-leakto disable it.
This diagnostic warns for paths through your code where an open file descriptor just... gets leaked. Nobody closes it. It's still out here holding a slot. ๐ญ
See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).
-Wno-analyzer-fd-phase-mismatchโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-phase-mismatchto disable it.
This diagnostic warns for paths through code where you attempt an operation in the wrong phase of a file descriptor's lifetime. The classic: trying to call accept on a stream socket that hasn't had listen successfully called on it yet. Ma'am, the socket isn't even listening. ๐
See CWE-666: Operation on Resource in Wrong Phase of Lifetime (https://cwe.mitre.org/data/definitions/666.html).
-Wno-analyzer-fd-type-mismatchโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-type-mismatchto disable it.
This diagnostic warns for paths through code where you attempt an operation on the wrong type of file descriptor. For example it'll warn when you try socket operations on a file descriptor you got from open, or when you try to use a stream socket operation on a datagram socket. Different species, bestie. ๐ฆ
-Wno-analyzer-fd-use-after-closeโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-use-after-closeto disable it.
This diagnostic warns for paths through code where a read or write is called on a closed file descriptor. It's giving "texting your ex after the breakup," ngl.
It also warns for paths through code where a function tagged with fd_arg (N), fd_arg_read (N) or fd_arg_write (N) is called with a closed file descriptor at referenced argument N.
-Wno-analyzer-fd-use-without-checkโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-use-without-checkto disable it.
This diagnostic warns for paths through code where a file descriptor is used without ever being checked for validity. Do we even know this fd is valid? No. And yet we're using it. Bold. ๐
It also warns for paths through code where a function tagged with fd_arg (N), fd_arg_read (N) or fd_arg_write (N) is called with a file descriptor at referenced argument N without being checked for validity.
-Wno-analyzer-file-leakโ requires-fanalyzer, which enables it; use-Wno-analyzer-file-leakto disable it.
This diagnostic warns for paths through the code where a <stdio.h> FILE * stream object gets leaked. That FILE * is just out there, un-fclosed, living its life. โจ
See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).
-Wno-analyzer-free-of-non-heapโ requires-fanalyzer, which enables it; use-Wno-analyzer-free-of-non-heapto disable it.
This diagnostic warns for paths through the code where free is called on a non-heap pointer โ like an on-stack buffer, or a global. free only takes heap pointers, bestie, please don't hand it a stack address. ๐ญ
See CWE-590: Free of Memory not on the Heap (https://cwe.mitre.org/data/definitions/590.html).
-Wno-analyzer-imprecise-fp-arithmeticโ requires-fanalyzer, which enables it; use-Wno-analyzer-imprecise-fp-arithmeticto disable it.
This diagnostic warns for paths through the code where floating-point arithmetic is used in places where precise computation is needed. Heads up: at the moment this diagnostic only warns on floating-point operands used inside the calculation of an allocation size. That's the whole scope rn.
-Wno-analyzer-infinite-recursionโ requires-fanalyzer, which enables it; use-Wno-analyzer-infinite-recursionto disable it.
This diagnostics warns for paths through the code which appear to lead to infinite recursion. ๐
Specifically, when the analyzer "sees" a recursive call, it compares the state of memory at the entry to the new frame with the state at the entry to the previous frame of that function on the stack. The warning fires if nothing in memory appears to be changing. Any changes it observes to parameters or globals are assumed to lead to termination of the recursion, and that suppresses the warning.
Fr fr, this diagnostic is likely to miss cases of infinite recursion that got converted to iteration by the optimizer before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic.
Compare with -Winfinite-recursion, which gives a similar diagnostic but is implemented in a different way.
-Wno-analyzer-jump-through-nullโ requires-fanalyzer, which enables it; use-Wno-analyzer-jump-through-nullto disable it.
This diagnostic warns for paths through the code where a NULL function pointer is called. A NULL pointer at the call site is giving "calling an empty contact," and it never ends well. ๐
-Wno-analyzer-malloc-leakโ requires-fanalyzer, which enables it; use-Wno-analyzer-malloc-leakto disable it.
This diagnostic warns for paths through the code where a pointer allocated via an allocator is leaked: either malloc, or a function marked with attribute malloc.
See CWE-401: Missing Release of Memory after Effective Lifetime (https://cwe.mitre.org/data/definitions/401.html).
-Wno-analyzer-mismatching-deallocationโ requires-fanalyzer, which enables it; use-Wno-analyzer-mismatching-deallocationto disable it.
This diagnostic warns for paths through the code where the wrong deallocation function is called on a pointer value, based on which function was used to allocate that pointer value. It'll warn about mismatches between free, scalar delete and vector delete[], and those marked as allocator/deallocator pairs using attribute malloc. You cannot malloc and then delete[], babes. The analyzer WILL notice. ๐
See CWE-762: Mismatched Memory Management Routines (https://cwe.mitre.org/data/definitions/762.html).
-Wno-analyzer-out-of-boundsโ requires-fanalyzer, which enables it; use-Wno-analyzer-out-of-boundsto disable it.
This diagnostic warns for paths through the code where a buffer is definitely read or written out-of-bounds. It applies to cases where the analyzer can determine a constant offset, and for accesses past the end of a buffer that also has a constant capacity. And further, it does limited checking for accesses past the end when the offset as well as the capacity is symbolic.
See CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer (https://cwe.mitre.org/data/definitions/119.html).
-Wno-analyzer-possible-null-argumentโ requires-fanalyzer, which enables it; use-Wno-analyzer-possible-null-argumentto disable it.
This diagnostic warns for paths through the code where a possibly-NULL value is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. The attribute said no NULLs and you said "maybe NULL tho." Rude, honestly. ๐ซถ
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-possible-null-dereferenceโ requires-fanalyzer, which enables it; use-Wno-analyzer-possible-null-dereferenceto disable it.
This diagnostic warns for paths through the code where a possibly-NULL value is dereferenced. Possible is enough to make the analyzer nervous, and honestly, same.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-null-argumentโ requires-fanalyzer, which enables it; use-Wno-analyzer-null-argumentto disable it.
This diagnostic warns for paths through the code where a value known to be NULL is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. No "maybe" here โ the analyzer literally knows. Caught in 4K. ๐ธ
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-null-dereferenceโ requires-fanalyzer, which enables it; use-Wno-analyzer-null-dereferenceto disable it.
This diagnostic warns for paths through the code where a value known to be NULL is dereferenced. Straight to NULL at address zero, no cap. ๐
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-putenv-of-auto-varโ requires-fanalyzer, which enables it; use-Wno-analyzer-putenv-of-auto-varto disable it.
This diagnostic warns for paths through the code where a call to putenv is passed a pointer to an automatic variable or an on-stack buffer. That stack memory's gonna vanish the second the function returns, and the environment will be left holding a stale pointer. Iconic in the worst way. ๐ญ
See POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument (https://wiki.sei.cmu.edu/confluence/x/6NYxBQ).
-Wno-analyzer-shift-count-negativeโ requires-fanalyzer, which enables it; use-Wno-analyzer-shift-count-negativeto disable it.
This diagnostic warns for paths through the code where a shift is attempted with a negative count. It's analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but this one is implemented by analyzing interprocedural paths instead of merely parsing the syntax tree. However โ and this is the tea โ the analyzer does not prioritize detection of such paths, so false negatives are more likely here relative to other warnings. ๐
-Wno-analyzer-shift-count-overflowโ requires-fanalyzer, which enables it; use-Wno-analyzer-shift-count-overflowto disable it.
Okay bestie, quick PSA before we dive in: this one is about shift counts! ๐
This diagnostic yells at you for paths through your code where a shift gets attempted with a count that's greater than or equal to the precision of the operand's type. It's like the cousin of the -Wshift-count-overflow diagnostic that lives in the C/C++ front ends โ except this one is built from analyzing interprocedural paths instead of just vibing with the syntax tree. ๐ But here's the tea: the analyzer does not prioritize spotting these paths, so false negatives are more likely here compared to other warnings. F in the chat. ๐ญ
-Wno-analyzer-stale-setjmp-bufferโ this one needs-fanalyzerto even exist (that flag turns it on); hit it with-Wno-analyzer-stale-setjmp-bufferto switch it off. ๐
It warns about paths through the code where longjmp gets called to rewind back to a jmp_buf that belongs to a setjmp call inside a function that has already returned. ๐
When setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. And that stack frame becomes invalid the moment the function containing the setjmp call returns. So trying to rewind to it via longjmp would reference a stack frame that literally does not exist anymore, and that's probably gonna crash (or do something even worse ๐).
-Wno-analyzer-tainted-allocation-sizeโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-allocation-sizeto disable it.
Warns about paths where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized first โ so an attacker could inject a comically large allocation and potentially cause a denial of service attack. Not it. ๐ค
See CWE-789: Memory Allocation with Excessive Size Value (https://cwe.mitre.org/data/definitions/789.html).
-Wno-analyzer-tainted-assertionโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-assertionto disable it.
Warns about paths where a value that could be under an attacker's control gets used as part of a condition without being sanitized first, and that condition guards a call to a function marked with the noreturn attribute (like __builtin_unreachable). Those functions usually mean the program is terminating abnormally, like an assertion failure handler. For example:
assert (some_tainted_value < SOME_LIMIT);
In such cases:
- when assertion-checking is enabled: an attacker could trigger a denial of service by injecting an assertion failure ๐ต
- when assertion-checking is disabled, like by defining
NDEBUG: an attacker could inject data that subverts the process, since it presumably violates a precondition the code is assuming. spooky fr fr ๐ป
Heads up ๐ซถ: when assertion-checking is disabled, the assertions usually get removed by the preprocessor before the analyzer even has a chance to "see" them โ so this diagnostic can only generate warnings on builds where assertion-checking is enabled.
For this warning's purposes, any function marked with the noreturn attribute counts as a possible assertion failure handler, including __builtin_unreachable. And ngl, those functions are sometimes removed by the optimizer before the analyzer "sees" them either โ so you should disable optimization when you're trying to trigger this diagnostic. ๐
See CWE-617: Reachable Assertion (https://cwe.mitre.org/data/definitions/617.html).
It can also flag constructions like this:
switch (some_tainted_value) {
case 0:
/* [...etc; various valid cases omitted...] */
break;
default:
__builtin_unreachable (); /* BUG: attacker can trigger this */
}
...even though, strictly speaking, that's technically not an assertion failure. ๐โโ๏ธ
-Wno-analyzer-tainted-array-indexโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-array-indexto disable it.
Warns about paths where a value that could be under an attacker's control gets used as the index of an array access without being sanitized, so an attacker could inject an out-of-bounds access. ๐จ
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).
-Wno-analyzer-tainted-divisorโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-divisorto disable it.
Warns about paths where a value that could be under an attacker's control gets used as the divisor in a division or modulus operation without being sanitized โ so an attacker could inject a division-by-zero. โ๐ฅ
See CWE-369: Divide By Zero (https://cwe.mitre.org/data/definitions/369.html).
-Wno-analyzer-tainted-offsetโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-offsetto disable it.
Warns about paths where a value that could be under an attacker's control gets used as a pointer offset without being sanitized, so an attacker could inject an out-of-bounds access. ๐ฏ
See CWE-823: Use of Out-of-range Pointer Offset (https://cwe.mitre.org/data/definitions/823.html).
-Wno-analyzer-tainted-sizeโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-sizeto disable it.
Warns about paths where a value that could be under an attacker's control gets used as the size of an operation like memset without being sanitized, so an attacker could inject an out-of-bounds access. ๐ซ
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).
-Wno-analyzer-unsafe-call-within-signal-handlerโ this one needs-fanalyzerto even exist (that flag enables it); use-Wno-analyzer-unsafe-call-within-signal-handlerto disable it.
Warns about paths where a function that's known to be async-signal-unsafe (like fprintf) gets called from a signal handler. โก๐
โโ๏ธ
See CWE-479: Signal Handler Use of a Non-reentrant Function (https://cwe.mitre.org/data/definitions/479.html).
-Wno-analyzer-use-after-freeโ needs-fanalyzerto enable it; use-Wno-analyzer-use-after-freeto disable it.
Warns about paths where a pointer gets used after a deallocator was called on it โ either free, or a deallocator referenced by the malloc attribute. ๐๏ธ๐
See CWE-416: Use After Free (https://cwe.mitre.org/data/definitions/416.html).
-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ needs-fanalyzerto enable it; use-Wno-analyzer-use-of-pointer-in-stale-stack-frameto disable it.
Warns about paths where a pointer gets dereferenced that points to a variable sitting in a stale stack frame. ๐ฅ
-Wno-analyzer-va-arg-type-mismatchโ needs-fanalyzerto enable it; use-Wno-analyzer-va-arg-type-mismatchto disable it.
Warns about interprocedural paths where the analyzer catches an attempt to use va_arg to extract a value passed to a variadic call, but with a type that does not match the type of the expression that was passed to the call. ๐
See CWE-686: Function Call With Incorrect Argument Type (https://cwe.mitre.org/data/definitions/686.html).
-Wno-analyzer-va-list-exhaustedโ needs-fanalyzerto enable it; use-Wno-analyzer-va-list-exhaustedto disable it.
Warns about interprocedural paths where the analyzer catches an attempt to use va_arg to access the next value passed to a variadic call โ except all the values in the va_list have already been consumed. ๐ฝ๏ธโ
See CWE-685: Function Call With Incorrect Number of Arguments (https://cwe.mitre.org/data/definitions/685.html).
-Wno-analyzer-va-list-leakโ needs-fanalyzerto enable it; use-Wno-analyzer-va-list-leakto disable it.
Warns about interprocedural paths where the analyzer catches that va_start or va_copy got called on a va_list with no matching call to va_end. ๐ฐ๐ง
-Wno-analyzer-va-list-use-after-va-endโ needs-fanalyzerto enable it; use-Wno-analyzer-va-list-use-after-va-endto disable it.
Warns about interprocedural paths where the analyzer catches an attempt to use a va_list after va_end has been called on it. va_list. ๐
-Wno-analyzer-write-to-constโ needs-fanalyzerto enable it; use-Wno-analyzer-write-to-constto disable it.
Warns about paths where the analyzer catches an attempt to write through a pointer to a const object. But again, the analyzer does not prioritize detecting these paths, so false negatives are more likely compared to other warnings. ๐ซฃ
-Wno-analyzer-write-to-string-literalโ needs-fanalyzerto enable it; use-Wno-analyzer-write-to-string-literalto disable it.
Warns about paths where the analyzer catches an attempt to write through a pointer to a string literal. And same deal โ no prioritization, so false negatives are more likely relative to other warnings. โ๏ธ๐ซ
-Wno-analyzer-use-of-uninitialized-valueโ needs-fanalyzerto enable it; use-Wno-analyzer-use-of-uninitialized-valueto disable it.
Warns about paths where an uninitialized value is used. ๐ฌ
See CWE-457: Use of Uninitialized Variable (https://cwe.mitre.org/data/definitions/457.html).
So yeah, the analyzer has hardcoded knowledge about the behavior of the following memory-management functions: โจ to be continued โจ ๐
Continuing the analyzer's little black book of functions it already knows the tea on, because it's nosy like that ๐ :
allocaโ yeah bestie, it knows this one intimately- the built-in functions
__builtin_alloc,__builtin_alloc_with_align,__builtin_calloc,__builtin_free,__builtin_malloc,__builtin_memcpy,__builtin_memcpy_chk,__builtin_memset,__builtin_memset_chk,__builtin_realloc,__builtin_stack_restore, and__builtin_stack_save callocfreemallocmemsetoperator deleteoperator delete []operator newoperator new []reallocstrdupstrndup
...and it's equally obsessed with these file-descriptor besties:
openclosecreatdup,dup2anddup3isattypipe, andpipe2readwritesocket,bind,listen,accept, andconnect
...and it keeps receipts on these <stdio.h> stream functions too ๐:
- the built-in functions
__builtin_fprintf,__builtin_fprintf_unlocked,__builtin_fputc,__builtin_fputc_unlocked,__builtin_fputs,__builtin_fputs_unlocked,__builtin_fwrite,__builtin_fwrite_unlocked,__builtin_printf,__builtin_printf_unlocked,__builtin_putc,__builtin_putchar,__builtin_putchar_unlocked,__builtin_putc_unlocked,__builtin_puts,__builtin_puts_unlocked,__builtin_vfprintf, and__builtin_vprintf fopenfcloseferrorfgetsfgets_unlockedfilenofreadgetcgetcharfprintfprintffwrite
...and also, respectfully, these ones ๐:
- the built-in functions
__builtin_expect,__builtin_expect_with_probability,__builtin_strchr,__builtin_strcpy,__builtin_strcpy_chk,__builtin_strlen,__builtin_va_copy, and__builtin_va_start - the GNU extensions
erroranderror_at_line getpasslongjmpputenvsetjmpsiglongjmpsignalsigsetjmpstrchrstrlen
Bonus lore: a whole bunch of functions with an __analyzer_ prefix have special meaning to the analyzer too, and the deets on those live in the GCC Internals manual. iykyk โจ
The pertinent parameters for controlling the exploration (aka how far it's willing to wander off) are:
--param analyzer-bb-explosion-factor=value--param analyzer-max-enodes-per-program-point=value--param analyzer-max-recursion-depth=value--param analyzer-min-snodes-for-call-summary=value
The following options control the analyzer. Strap in ๐
-fanalyzer-call-summariesโ simplifies interprocedural analysis by computing the effect of certain calls, instead of going on a whole side quest through every single path from callsite to each possible return. If it's enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per--param analyzer-min-snodes-for-call-summary=value). Basically it only summarises the messy ones fr fr.-fanalyzer-checker=nameโ restricts the analyzer to run just the named checker, and enables it. Some checkers are off by default (even with-fanalyzer), like thetaintchecker that implements-Wanalyzer-tainted-array-index, and you need this option to wake them up.
Note: currently,-fanalyzer-checker=taintdisables the following warnings from-fanalyzer:
-Wanalyzer-deref-before-check-Wanalyzer-double-fclose-Wanalyzer-double-free-Wanalyzer-exposure-through-output-file-Wanalyzer-fd-access-mode-mismatch-Wanalyzer-fd-double-close-Wanalyzer-fd-leak-Wanalyzer-fd-use-after-close-Wanalyzer-fd-use-without-check-Wanalyzer-file-leak-Wanalyzer-free-of-non-heap-Wanalyzer-malloc-leak-Wanalyzer-mismatching-deallocation-Wanalyzer-null-argument-Wanalyzer-null-dereference-Wanalyzer-possible-null-argument-Wanalyzer-possible-null-dereference-Wanalyzer-unsafe-call-within-signal-handler-Wanalyzer-use-after-free-Wanalyzer-va-list-leak-Wanalyzer-va-list-use-after-va-end
-fno-analyzer-feasibilityโ this one is for analyzer developers, bestie, not for the rest of us. By default the analyzer checks that there's actually a feasible control flow path for each diagnostic it emits: that the conditions holding are not mutually exclusive. Any diagnostic with no feasible path found gets rejected. You can suppress that filtering with-fno-analyzer-feasibility, for debugging issues in this code.-fanalyzer-fine-grainedโ also for analyzer developers ๐ง. Internally the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. By default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. With-fanalyzer-fine-grained, every single statement gets its own edge. No sharing.-fanalyzer-show-duplicate-countโ analyzer developers only: if multiple diagnostics were detected as duplicates of each other, it emits a note when reporting the best diagnostic, telling you the number of additional diagnostics that got suppressed by the deduplication logic. It's like "and 12 others ๐".-fno-analyzer-state-mergeโ analyzer developers only. By default the analyzer tries to keep things cute and simple by merging sufficiently similar states at each program point as it builds its "exploded graph". With-fno-analyzer-state-mergethat merging can be suppressed, for debugging state-handling issues.-fno-analyzer-state-purgeโ analyzer developers only. By default the analyzer simplifies analysis by purging aspects of state at a program point that look like they don't matter anymore, e.g. the values of locals that aren't accessed later in the function and aren't relevant to leak analysis. With-fno-analyzer-state-purgethat purging can be suppressed, for debugging state-handling issues.-fno-analyzer-suppress-followupsโ analyzer developers only. By default the analyzer stops exploring an execution path after it hits certain diagnostics, so it doesn't spiral into a whole cascade of follow-up diagnostics. The diagnostics that terminate analysis along a path are:-Wanalyzer-null-argument-Wanalyzer-null-dereference-Wanalyzer-use-after-free-Wanalyzer-use-of-pointer-in-stale-stack-frame-Wanalyzer-use-of-uninitialized-value
With -fno-analyzer-suppress-followups the analyzer keeps exploring those paths even after such diagnostics, which can help for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior. Chaotic but valid.
-fanalyzer-transitivityโ this option enables transitivity of constraints within the analyzer. Math girlies rise ๐ธ-fno-analyzer-undo-inliningโ analyzer developers only.-fanalyzerruns relatively late compared to other code analysis tools, and some optimizations have already been applied to the code. In particular function inlining may have occurred, which means the interprocedural execution paths the analyzer emits can contain function frames that don't correspond to the ones in the original source code ๐ญ. By default the analyzer tries to reconstruct the original function frames, and to emit events showing the inlined calls. With-fno-analyzer-undo-inliningthat attempt at reconstructing the original frame info can be disabled, which may help when debugging issues in the analyzer.-fanalyzer-verbose-edgesโ analyzer developers only. Enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. It's giving unhinged levels of detail, respectfully.-fanalyzer-verbose-state-changesโ analyzer developers only. Enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.-fanalyzer-verbosity=levelโ this controls the complexity of the control flow paths that get emitted for analyzer diagnostics. The level can be one of:- 0 โ at this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
freediagnostic, both calls tofreewill be shown. - 1 โ as per the previous level, but also show events for the entry to each function.
- 2 โ as per the previous level, but also show events relating to control flow that are significant to triggering the issue (e.g. "true path taken" at a conditional). This level is the default.
- 3 โ as per the previous level, but show all control flow events, not just significant ones.
- 4 โ this level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
- 0 โ at this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
-fdump-analyzerโ dumps internal details about what the analyzer is doing tofile.analyzer.txt. Careful tho:-fdump-analyzer-stderroverrides this option.-fdump-analyzer-stderrโ dumps internal details about what the analyzer is doing to stderr. This option overrides-fdump-analyzer. It wins, periodt.-fdump-analyzer-callgraphโ dumps a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot. Pretty graphs, we love to see it ๐ฆ-fdump-analyzer-exploded-graphโ dumps a representation of the "exploded graph" suitable for viewing with GraphViz tofile.eg.dot. Nodes are color-coded based on state-machine states to emphasize state changes. Aesthetic and informative โจ-fdump-analyzer-exploded-nodesโ emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source.-fdump-analyzer-exploded-nodes-2โ dumps a textual representation of the "exploded graph" tofile.eg.txt.-fdump-analyzer-exploded-nodes-3โ dumps a textual representation of the "exploded graph" to one dump file per node, tofile.eg-id.txt. Heads up bestie: this is typically a large number of dump files ๐-fdump-analyzer-exploded-pathsโ dumps a textual representation of the "exploded path" for each diagnostic tofile.idx.kind.epath.txt.-fdump-analyzer-feasibilityโ dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the formfile.*.fg.dot,file.*.tg.dot, andfile.*.fpath.txt.-fdump-analyzer-jsonโ dumps a compressed JSON representation of the analyzer's internal organs intofile.analyzer.json.gz. ๐ heads up bestie: the precise format is subject to change, so don't you dare build a parser on it and then come crying to me.-fdump-analyzer-state-purgeโ same energy as-fdump-analyzer-supergraph, it dumps a representation of the "supergraph" that's suitable for viewing with GraphViz, except this one annotates the graph with info on what state will be purged at each node. ๐ง It gets written tofile.state-purge.dot.-fdump-analyzer-supergraphโ dumps representations of the "supergraph" so you can view them with GraphViz, going tofile.supergraph.dotand tofile.supergraph-eg.dot. โจ These show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" and the diagnostics associated with them. iconic.-fdump-analyzer-untrackedโ emits custom warnings with internal details, literally intended for analyzer developers. ๐ซถ if that's not you, enjoy the mystery.
๐ธ Options for Debugging Your Program ๐ธ
okay so to tell GCC to emit extra info for a debugger, in almost all cases you just add -g to your other options. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options. ๐
GCC lets you use -g with -O. The shortcuts taken by optimized code may occasionally be surprising, and I'm not gonna lie to you: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values are already at hand; some statements may execute in different places because they have been moved out of loops. ๐ญ Nevertheless it is possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs. no cap.
If you're not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so that -Og may result in a better debugging experience. ๐
-gโ produces debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF). GDB can work with this debugging information. ๐
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program. If you want to control for certain whether to generate the extra information, use -gvms (see below).
-ggdbโ produces debugging information for use by GDB. This means using the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible. ๐-gdwarf-gdwarf-versionโ produces debugging information in DWARF format (if that's supported). The value of version may be either2,3,4or5; the default version for most targets is5(with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version2, and AIX, which defaults to version4). ๐
Note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables. ๐ฆ
Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher.
GCC no longer supports DWARF Version 1, which is substantially different than Version 2 and later. For historical reasons, some other DWARF-related options such as -fno-dwarf2-cfi-asm retain a reference to DWARF Version 2 in their names, but apply to all currently-supported versions of DWARF. the way the names are just โจ legacy โจ, we love her.
-gbtfโ requests BTF debug information. BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options. ๐-gctf-gctflevelโ requests CTF debug information and uses level to specify how much CTF debug information should be produced. If-gctfis specified without a value for level, the default level of CTF debug information is2. ๐
CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.
Level 0 produces no CTF debug information at all. Thus, -gctf0 negates -gctf. ๐
Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information.
Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only. โญ
-gvmsโ produces debugging information in Alpha/VMS debug format (if that is supported). This is the format used by DEBUG on Alpha/VMS systems. ๐ง-glevel-ggdblevel-gvmslevelโ requests debugging information and also uses level to specify how much information. The default level is2. ๐ธ
Level 0 produces no debug information at all. Thus, -g0 negates -g. ๐ซถ
Level 1 produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no information about local variables.
Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3. ๐ฅ
If you use multiple -g options, with or without level numbers, the last such option is the one that is effective. periodt.
-gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. Instead use an additional -glevel option to change the debug level for DWARF. ๐
-fno-eliminate-unused-debug-symbolsโ by default, no debug information is produced for symbols that are not actually used. Use this option if you want debug information for all symbols. ๐-femit-class-debug-alwaysโ instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class. This option should be used only with debuggers that are unable to handle the way GCC normally emits debugging information for classes because using this option increases the size of debugging information by as much as a factor of two. ๐ญ so like, know what you're doing.-fno-merge-debug-stringsโ directs the linker to not merge together strings in the debugging information that are identical in different object files. Merging is not supported by all assemblers or linkers. Merging decreases the size of the debug information in the output file at the cost of increasing link processing time. Merging is enabled by default. โจ-fdebug-prefix-map=old=newโ when compiling files residing in directory old, record debugging information describing them as if the files resided in directory new instead. This can be used to replace a build-time path with an install-time path in the debug info. It can also be used to change an absolute path to a relative path by using.for new. This can give more reproducible builds, which are location independent, but may require an extra command to tell GDB where to find the source files. See also-ffile-prefix-mapand-fcanon-prefix-map. ๐ฆ-fvar-trackingโ runs the variable tracking pass. It computes where variables are stored at each position in code. Better debugging information is then generated (if the debugging information format supports this information). ๐
It is enabled by default when compiling with optimization (-Os, -O, -O2, ...), debugging information (-g) and the debug info format supports it.
-fvar-tracking-assignmentsโ annotates assignments to user variables early in the compilation and attempts to carry the annotations over throughout the compilation all the way to the end, in an attempt to improve debug information while optimizing. Use of-gdwarf-4is recommended along with it. โญ
It can be enabled even if var-tracking is disabled, in which case annotations are created and maintained, but discarded at the end. By default, this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled. ๐
-gsplit-dwarfโ if DWARF debugging information is enabled, separate as much debugging information as possible into a separate output file with the extension.dwo. This option allows the build system to avoid linking files with debug information. To be useful, this option requires a debugger capable of reading.dwofiles. ๐-gdwarf32-gdwarf64โ if DWARF debugging information is enabled,-gdwarf32selects the 32-bit DWARF format and-gdwarf64selects the 64-bit DWARF format. The default is target specific, on most targets it is-gdwarf32though. The 32-bit DWARF format is smaller, but can't support more than 2GiB of debug information in any of the DWARF debug information sections. The 64-bit DWARF format allows larger debug information and might not be well supported by all consumers yet. ๐-gdescribe-diesโ adds description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. ๐ง-gpubnamesโ generates DWARF.debug_pubnamesand.debug_pubtypessections. โจ-ggnu-pubnamesโ generates.debug_pubnamesand.debug_pubtypessections in a format suitable for conversion into a GDB index. This option is only useful with a linker that can produce GDB index version 7. ๐-fdebug-types-sectionโ when using DWARF Version 4 or higher, type DIEs can be put into their own.debug_typessection instead of making them part of the.debug_infosection. It is more efficient to put them in a separate comdat section since the linker can then remove duplicates. But not all DWARF consumers support.debug_typessections yet and on some objects.debug_typesproduces larger instead of smaller debugging information. ๐ญ the betrayal fr fr.-grecord-gcc-switches,-gno-record-gcc-switchesโ okay so bestie, this one shoves the command-line options you used to invoke the compiler (the ones that might affect code generation) straight into theDW_AT_producerattribute in your DWARF debugging info โจ. They get concatenated together, with spaces separating them from each other and from the compiler version. It's enabled by default, periodt. Also peep-frecord-gcc-switchesfor a whole other way of stashing compiler options into the object file ๐.-gstrict-dwarfโ nope, no extensions of a later DWARF standard version than whatever you picked with-gdwarf-version. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed, but not with this flag on. Strict queen ๐ .-gno-strict-dwarfโ allow using extensions of later DWARF standard versions than the one selected with-gdwarf-version. Live a little ๐ธ.-gas-loc-supportโ tells the compiler that your assembler supports".loc"directives ๐ซถ. Then it may use them so the assembler generates DWARF2+ line number tables for you.
This is generally desirable, because assembler-generated line-number tables are a lot more compact than the ones the compiler can generate itself. Lowkey iconic.
This option gets enabled by default if, at GCC configure time, the assembler was found to support such directives.
-gno-as-loc-supportโ forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are going to be generated at all. DIY energy ๐ฅ.-gas-locview-supportโ informs the compiler that the assembler supports "view" assignment and reset assertion checking in".loc"directives โจ.
Enabled by default if, at GCC configure time, the assembler was found to support them.
-gno-as-locview-supportโ forces GCC to assign view numbers internally, if-gvariable-location-viewsare explicitly requested.-gcolumn-info,-gno-column-infoโ emit location column info into DWARF debugging info, not just file and line ๐. Enabled by default, no cap.-gstatement-frontiers,-gno-statement-frontiersโ this makes GCC drop markers into the internal representation at the beginning of statements, and keep them roughly in place all through compilation, using them to guide the output of"is_stmt"markers in the line number table ๐. Enabled by default when compiling with optimization (-Os,-O1,-O2, ...), and outputting DWARF 2 debug information at the normal level.-gvariable-location-views,-gvariable-location-views=incompat5,-gno-variable-location-viewsโ augments variable location lists with progressive view numbers implied from the line number table ๐. This lets debug info consumers inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point. If the assembler lacks support for view numbers in line number tables, this makes the compiler emit the line number table, which generally makes them somewhat less compact. The augmented line number tables and location lists are fully backward-compatible, so debug info consumers that aren't aware of these augmentations can still consume them โ they just won't derive any benefit from them either ๐.
Enabled by default when outputting DWARF 2 debug information at the normal level, as long as there's assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is not. When assembler support isn't available, this may still be enabled, but it'll force GCC to output internal line number tables, and if -ginternal-reset-location-views isn't enabled, that will most certainly lead to silently mismatching location views ๐ญ.
There's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, which you can turn on with -gvariable-location-views=incompat5. This option may be removed in the future, and is only provided as a reference implementation of the proposed representation. Debug info consumers aren't expected to support this extended format, and they'd be rendered unable to decode location lists using it ๐.
-ginternal-reset-location-views,-gno-internal-reset-location-viewsโ attempts to determine location views that can be omitted from location view lists ๐ธ. This requires the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when you're using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a"view number mismatch". This is only enabled on ports that define a reliable estimation function.-ginline-points,-gno-inline-pointsโ generates extended debug info for inlined functions โจ. Location view tracking markers get inserted at inlined entry points, so address and view numbers can be computed and output in debug info. This can be enabled independently of location views, in which case the view numbers won't be output โ but it can only be enabled along with statement frontiers, and it's only enabled by default if location views are enabled ๐.-gz[=type]โ produces compressed debug sections in DWARF format, if that's supported ๐๏ธ. If type isn't given, the default type depends on the capabilities of the assembler and linker used. type may be one ofnone(don't compress debug sections), orzlib(use zlib compression in ELF gABI format). If the linker doesn't support writing compressed debug sections, the option is rejected โ full stop. Otherwise, if the assembler doesn't support them,-gzis silently ignored when producing object files ๐ถ.-femit-struct-debug-baseonlyโ emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the struct is defined.
This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger ๐ญ. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF debug output.
-femit-struct-debug-reducedโ emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the type is defined, unless the struct is a template or defined in a system header ๐.
This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF debug output.
-femit-struct-debug-detailed[=spec-list]โ specifies the struct-like types for which the compiler generates debug info. The intent? Reduce duplicate struct debug info between different object files within the same program ๐.
This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serve most needs.
A specification has the syntax [dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word limits the specification to structs that are used directly (dir:) or used indirectly (ind:). A struct type is used directly when it's the type of a variable, member. Indirect uses arise through pointers to structs. That is, when use of an incomplete struct is valid, the use is indirect. An example is struct one direct; struct two * indirect;.
The optional second word limits the specification to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain ๐. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed doesn't yet implement them.
The third word specifies the source files for those structs for which the compiler should emit debug info. The values none and any have the normal meaning. The value base means that the base of name of the file in which the type declaration appears must match the base of the name of the main compilation file. In practice, this means that when compiling foo.c, debug info is generated for types declared in that file and foo.h, but not other header files. The value sys means those types satisfying base or declared in system or compiler headers.
You may need to experiment to determine the best settings for your application ๐งช.
The default is -femit-struct-debug-detailed=all.
This option works only with DWARF debug output.
-fno-dwarf2-cfi-asmโ emit DWARF unwind info as a compiler-generated".eh_frame"section instead of using GAS".cfi_*"directives.-fno-eliminate-unused-debug-typesโ normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are nowhere used in the source file being compiled. Sometimes it's useful to have GCC emit debugging information for all types declared in a compilation unit, regardless of whether or not they're actually used in that compilation unit โ for example if, in the debugger, you want to cast a value to a type that isn't actually used in your program (but is declared) ๐ . More often, however, this results in a significant amount of wasted space ๐.
๐ Options That Control Optimization ๐
These options control various sorts of optimizations, bestie. Strap in.
Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results ๐. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code. Chef's kiss predictability.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program ๐ฅ. Trade-offs, babes.
Okay so GCC is out here optimizing based on what it knows about your program. Like, if you compile multiple files at once into a single output file, it can use all that info from every file when it's compiling each one. It's giving โจcross-file wisdomโจ.
But lowkey, not every optimization has its own flag, bestie. Only the ones with flags are getting listed in this section. The rest are just vibing in the background.
Most optimizations are fully off at -O0 or if you don't set an -O level at all โ even if you specify individual optimization flags. Yeah, it's like that. And -Og also suppresses a bunch of optimization passes. Not me being extra, it's just facts.
And depending on your target and how GCC was configured, the optimizations enabled at each -O level might be a lil different from what's listed here. If you wanna know exactly what's enabled at each level, run gcc -Q --help=optimizers. It's the receipts, periodt.
-O,-O1โ Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.
With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O turns on the following optimization flags:
-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
-O2โ Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to-O, this option increases both compilation time and the performance of the generated code.
-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp -fipa-cp -fipa-icf -fipa-ra -fipa-sra -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition -freorder-functions
-frerun-cse-after-loop -fschedule-insns -fschedule-insns2
-fsched-interblock -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
Please note the warning under-fgcseabout invoking-O2on programs that use computed gotos. ๐
NOTE: In Ubuntu 8.10 and later versions,-D_FORTIFY_SOURCE=2, in Ubuntu 24.04 and later versions,-D_FORTIFY_SOURCE=3, is set by default, and is activated when-Ois set to 2 or higher. This enables additional compile-time and run-time checks for several libc functions. To disable, specify either-U_FORTIFY_SOURCEor-D_FORTIFY_SOURCE=0.
NOTE: In Debian 13 and Ubuntu 24.04 and later versions,-D_TIME_BITS=64together with-D_FILE_OFFSET_BITS=64is set by default on the 32bit architecturesarmel,armhf,hppa,m68k,mips,mipsel,powerpcandsh4.
-O3โ Optimize yet more.-O3turns on all optimizations specified by-O2and also turns on the following optimization flags:
-fgcse-after-reload -fipa-cp-clone -floop-interchange
-floop-unroll-and-jam -fpeel-loops -fpredictive-commoning
-fsplit-loops -fsplit-paths -ftree-loop-distribution
-ftree-partial-pre -funswitch-loops -fvect-cost-model=dynamic
-fversion-loops-for-strides
-O0โ Reduce compilation time and make debugging produce the expected results. This is the default. ๐-Osโ Optimize for size.-Osenables all-O2optimizations except those that often increase code size:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size. It's giving minimalism, but make it fast. ๐
-Ofastโ Disregard strict standards compliance.-Ofastenables all-O3optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on-ffast-math,-fallow-store-data-racesand the Fortran-specific-fstack-arrays, unless-fmax-stack-var-sizeis specified, and-fno-protect-parens. It turns off-fsemantic-interposition. YOLO, but for math. ๐ฅ-Ogโ Optimize debugging experience.-Ogshould be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience. It is a better choice than-O0for producing debuggable code because some compiler passes that collect debug information are disabled at-O0.
Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect. Otherwise -Og enables all -O1 optimization flags except for those that may interfere with debugging:
-fbranch-count-reg -fdelayed-branch -fdse -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants -fmove-loop-stores -fssa-phiopt
-ftree-bit-ccp -ftree-dse -ftree-pta -ftree-sra
-Ozโ Optimize aggressively for size rather than speed. This may increase the number of instructions executed if those instructions require fewer bytes to encode.-Ozbehaves similarly to-Osincluding enabling most-O2optimizations. Tiny but mighty. โจ
If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. So the last one wins, bestie. No take-backs.
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed---the one you typically use. You can figure out the other form by either removing no- or adding it.
The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired.
-fno-defer-popโ For machines that must pop arguments after a function call, always pop the arguments as soon as each function returns. At levels-O1and higher,-fdefer-popis the default; this allows the compiler to let arguments accumulate on the stack for several function calls and pop them all at once.-fforward-propagateโ Perform a forward propagation pass on RTL. The pass tries to combine two instructions and checks if the result can be simplified. If loop unrolling is active, two passes are performed and the second is scheduled after loop unrolling.
This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.
-ffp-contract=styleโ-ffp-contract=offdisables floating-point expression contraction.-ffp-contract=fastenables floating-point expression contraction such as forming of fused multiply-add operations if the target has native support for them.-ffp-contract=onenables floating-point expression contraction if allowed by the language standard. This is currently not implemented and treated equal to-ffp-contract=off.
The default is -ffp-contract=fast.
-fomit-frame-pointerโ Omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available.
On some targets this flag has no effect because the standard calling sequence always uses a frame pointer, so it cannot be omitted.
Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions. Several targets always omit the frame pointer in leaf functions.
Enabled by default at -O1 and higher.
-foptimize-sibling-callsโ Optimize sibling and tail recursive calls.
Enabled at levels -O2, -O3, -Os.
-foptimize-strlenโ Optimize various standard C string functions (e.g.strlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives.
Enabled at levels -O2, -O3.
-fno-inlineโ Do not expand any functions inline apart from those marked with thealways_inlineattribute. This is the default when not optimizing.
Single functions can be exempted from inlining by marking them with the noinline attribute.
-finline-small-functionsโ Integrate functions into their callers when their body is smaller than expected function call code (so overall size of program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating in this way. This inlining applies to all functions, even those not declared inline.
Enabled at levels -O2, -O3, -Os.
-findirect-inliningโ Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has any effect only when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
Enabled at levels -O2, -O3, -Os.
-finline-functionsโ Consider all functions for inlining, even if they are not declared inline. The compiler heuristically decides which functions are worth integrating in this way.
If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.
Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.
-finline-functions-called-onceโ bestie, this one says: consider everystaticfunction that gets called exactly once for inlining into whoever called it, even if nobody bothered to mark itinline. And the way that works is, if a call to a given function actually gets integrated, then that function doesn't get output as assembler code in its own right anymore. Bye bye, standalone version. ๐
It's enabled at levels -O1, -O2, -O3 and -Os, but not -Og.
-fearly-inliningโ so this one inlines functions marked byalways_inline, plus functions whose body seems smaller than the function call overhead, and it does all that early โ before doing-fprofile-generateinstrumentation and the real inlining pass. Why do we care? Because doing it this way makes profiling significantly cheaper, and usually makes inlining faster on programs that have big chains of nested wrapper functions. We love an efficiency queen. โจ
Enabled by default.
-fipa-sraโ performs interprocedural scalar replacement of aggregates, removal of unused parameters, and replacement of parameters passed by reference with parameters passed by value. Glow up for your function signatures, fr fr.
Enabled at levels -O2, -O3 and -Os.
-finline-limit=nโ okay so by default GCC limits the size of functions that can be inlined, and this flag gives you coarse control of that limit.nhere is the size of functions that can be inlined, counted in number of pseudo instructions. ๐
Inlining is actually controlled by a whole bunch of parameters, which you can specify individually with --param name=value. The -finline-limit=n option sets some of those parameters like this:
max-inline-insns-singleโ is set ton/2.max-inline-insns-autoโ is set ton/2.
See below for documentation of the individual parameters that control inlining, and for the defaults of those parameters.
Note: there may be no value of -finline-limit that results in default behavior. Not me finding out the hard way ๐ญ
Note: pseudo instruction here means an abstract measurement of a function's size, in this particular context. It is in no way a count of assembly instructions, so its exact meaning might change from one release to another. It's giving vibes-based units, honestly.
-fno-keep-inline-dllexportโ this is a more fine-grained version of-fkeep-inline-functions, and it only applies to functions declared using thedllexportattribute or declspec. Very specific, very demure. ๐ฆ-fkeep-inline-functionsโ in C, this emitsstaticfunctions that are declaredinlineinto the object file, even if the function has already been inlined into all of its callers. This switch does not affect functions using theextern inlineextension in GNU C90. In C++, it emits any and all inline functions into the object file. Collect them all, I guess. ๐-fkeep-static-functionsโ emitstaticfunctions into the object file, even if the function is never used. That's right, we keep the unused ones too. Main character energy for functions nobody calls. ๐-fkeep-static-constsโ emit variables declaredstatic constwhen optimization isn't turned on, even if the variables aren't referenced.
GCC enables this option by default. If you want to force the compiler to check whether a variable is referenced โ regardless of whether optimization is turned on or not โ use the -fno-keep-static-consts option instead.
-fmerge-constantsโ attempts to merge identical constants (string constants and floating-point constants) across compilation units. Twin merge, but it's constants. ๐ธ
This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.
Enabled at levels -O1, -O2, -O3, -Os.
-fmerge-all-constantsโ attempts to merge identical constants and identical variables.
This option implies -fmerge-constants. On top of what -fmerge-constants does, it also considers e.g. even constant initialized arrays, or initialized constant variables with integral or floating-point types.
Okay so real talk, this one is non-conforming behavior territory. Languages like C or C++ require each variable โ including multiple instances of the same variable in recursive calls โ to have distinct locations. So using this option results in non-conforming behavior. It's giving "I know what I'm doing" and honestly? Sometimes you do. But you've been warned. ๐
-fmodulo-schedโ perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. Loops getting a little makeover. โจ-fmodulo-sched-allow-regmovesโ perform more aggressive SMS-based modulo scheduling, with register moves allowed. Setting this flag deletes certain anti-dependences edges, which triggers the generation of reg-moves based on the life-range analysis. Heads up though: this option is only effective when-fmodulo-schedis enabled. They're a package deal, bestie. ๐ซถ-fno-branch-count-regโ disables the optimization pass that scans for opportunities to usedecrement and branchinstructions on a count register, instead of instruction sequences that decrement a register, compare it against zero, and then branch based on the result.
This option is only meaningful on architectures that support such instructions โ which include x86, PowerPC, IA-64 and S/390. Also note that -fno-branch-count-reg does not remove the decrement and branch instructions from the generated instruction stream that were introduced by other optimization passes. It can't undo what's already been done, lowkey.
The default is -fbranch-count-reg at -O1 and higher, except for -Og.
-fno-function-cseโ do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly inside it.
This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used. Sometimes the chaos is the point.
The default is -ffunction-cse.
-fno-zero-initialized-in-bssโ if the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code. Space saving, we love her. ๐
This option turns that behavior off, because some programs explicitly rely on variables going to the data section โ e.g. so that the resulting executable can find the beginning of that section and/or make assumptions based on that. Respect the weird programs, they have their reasons.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ performs optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is redirected either to the destination of the second branch, or to a point immediately following it, depending on whether the condition is known to be true or false. Gymnastics, but for control flow. ๐คธ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-typesโ when you're using a type that occupies multiple registers, such aslong longon a 32-bit system, this splits the registers apart and allocates them independently. This normally generates better code for those types, but it may make debugging more difficult. Trade-offs, always trade-offs. ๐ญ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-types-earlyโ fully split wide types early, instead of very late. This option has no effect unless-fsplit-wide-typesis turned on. Package deal again, keep up bestie.
This is the default on some targets.
-fcse-follow-jumpsโ in common subexpression elimination (CSE), scan through jump instructions when the target of the jump is not reached by any other path. For example, when CSE encounters anifstatement with anelseclause, CSE follows the jump when the condition tested is false. She's nosy, but productively. ๐
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ similar to-fcse-follow-jumps, but this one causes CSE to follow jumps that conditionally skip over blocks. When CSE encounters a simpleifstatement with no else clause,-fcse-skip-blockscauses CSE to follow the jump around the body of theif. Sibling behavior, equally iconic. ๐
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-runs common subexpression elimination after loop optimizations are performed. Because sometimes you gotta do it twice. Once before the glow-up, once after. ๐
Enabled at levels -O2, -O3, -Os.
-fgcseโ performs a global common subexpression elimination pass. This pass also performs global constant and copy propagation. Multi-tasking queen. ๐
Note: when compiling a program that uses computed gotos โ a GCC extension โ you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line. Just a heads up, iykyk.
Enabled at levels -O2, -O3, -Os.
-fgcse-lmโ when-fgcse-lmis enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This allows a loop containing a load/store sequence to be changed into a load outside the loop, and a copy/store within the loop. Moved out of the loop like it's moving out of its hometown. ๐ง
Enabled by default when -fgcse is enabled.
-fgcse-smโ when-fgcse-smis enabled, a store motion pass is run after global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with-fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. Dynamic duo behavior. ๐ซถ
Not enabled at any optimization level.
-fgcse-lasโ when-fgcse-lasis enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location โ both partial and full redundancies, no cap.
Not enabled at any optimization level.
-fgcse-after-reloadโ when-fgcse-after-reloadis enabled, a redundant load elimination pass is performed after reload. The purpose of this pass is to clean up redundant spilling. Cleaning up after the party โจ
Enabled by -O3, -fprofile-use and -fauto-profile.
-faggressive-loop-optimizationsโ this option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. This assumes that loop code does not invoke undefined behavior, by for example causing signed integer overflows or out-of-bound array accesses. The bounds for the number of iterations of a loop are used to guide loop unrolling and peeling, and loop exit test optimizations.
It's enabled by default, which means it is assuming no UB is happening in your loops. If your loops are doing crimes, that's on you. ๐
-funconstrained-commonsโ this option tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. This prevents certain optimizations that depend on knowing the array bounds. Mystery-sized arrays get to stay mysterious. ๐-fcrossjumpingโ perform cross-jumping transformation. This transformation unifies equivalent code and saves code size. The resulting code may or may not perform better than without cross-jumping. Honestly? Could go either way, and that's the fun of it. ๐
Enabled at levels -O2, -O3, -Os.
-fauto-inc-decโ combine increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that do not have instructions to support this. Enabled by default at-O1and higher on architectures that support this. Two steps, one move. ๐ฅ-fdceโ bestie, this does dead code elimination (DCE) on RTL ๐งนโจ like... code that literally never runs? gone. deleted. not invited to the function ๐ It's enabled by default at-O1and higher.-fdseโ dead store elimination (DSE) on RTL ๐ You're gonna write to a variable and then immediately overwrite it before anyone reads it? girl what was the point. This removes the pointless one. Enabled by default at-O1and higher.-fif-conversionโ okay so this attempts to turn conditional jumps into branch-less equivalents ๐ฆ The glow-up includes conditional moves,min,max, set flags andabsinstructions, plus some little tricks doable by standard arithmetics. Whether it uses conditional execution on chips where that's available is controlled by-fif-conversion2.
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fif-conversion2โ uses conditional execution (where available) to transform conditional jumps into branch-less equivalents ๐ same vibe, different flavor.
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fdeclone-ctor-dtorโ so the C++ ABI requires multiple entry points for constructors and destructors, right? one for a base subobject, one for a complete object, and one for a virtual destructor that callsoperator deleteafterwards ๐ตโ๐ซ And for a hierarchy with virtual bases, the base and complete variants are clones โ meaning two whole copies of the function. NOT it.
With this option, the base and complete variants get changed into thunks that call a common implementation. Slay ๐
Enabled by -Os.
-fdelete-null-pointer-checksโ assumes programs cannot safely dereference null pointers, and that no code or data element lives at address zero ๐ซ0๏ธโฃ This enables simple constant folding optimizations at all optimization levels. Also, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers โ those assume a memory access to address zero always results in a trap, so if a pointer is checked after it's already been dereferenced, it cannot be null.
ngl bestie, in some environments this assumption is simply not true ๐ญ Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.
This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR and MSP430, this option is completely disabled.
Passes that use the dataflow information are enabled independently at different optimization levels.
-fdevirtualizeโ attempts to convert calls to virtual functions into direct calls โจ This happens both within a procedure and interprocedurally, as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels-O2,-O3,-Os.-fdevirtualize-speculativelyโ attempts to convert calls to virtual functions into speculative direct calls ๐ฎ Based on the analysis of the type inheritance graph, it determines for a given call the set of likely targets. If the set is small โ preferably of size 1 โ it changes the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, like inlining. And when they seem useless after further optimization, they're converted back into original form. so it's giving "we're just gonna try it, no pressure" ๐ฆ-fdevirtualize-at-ltransโ streams extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode ๐ก This option enables more devirtualization but significantly increases the size of streamed data. For this reason it's disabled by default.-fexpensive-optimizationsโ performs a number of minor optimizations that are relatively expensive ๐ธโจ
Enabled at levels -O2, -O3, -Os.
-freeโ attempts to remove redundant extension instructions ๐ง This is especially helpful for the x86-64 architecture, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. love that for them.
Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.
-fno-lifetime-dseโ so in C++ the value of an object is only affected by changes within its lifetime โณ when the constructor begins, the object has an indeterminate value, and any changes during the lifetime of the object are dead when the object is destroyed. Normally dead store elimination takes advantage of this. But if your code relies on the value of the object storage persisting beyond the lifetime of the object, you can use this flag to disable this optimization.
To preserve stores before the constructor starts (e.g. because your operator new clears the object storage) but still treat the object as dead after the destructor, you can use -flifetime-dse=1. The default behavior can be explicitly selected with -flifetime-dse=2. And -flifetime-dse=0 is equivalent to -fno-lifetime-dse. iykyk ๐ธ
-flive-range-shrinkageโ attempts to decrease register pressure through register live range shrinkage ๐ This is helpful for fast processors with small or moderate size register sets.-fira-algorithm=algorithmโ use the specified coloring algorithm for the integrated register allocator ๐จ The algorithm argument can bepriority, which specifies Chow's priority coloring, orCB, which specifies Chaitin-Briggs coloring. Chaitin-Briggs coloring is not implemented for all architectures, but for those targets that do support it, it's the default because it generates better code. periodt.-fira-region=regionโ use specified regions for the integrated register allocator ๐บ๏ธ The region argument should be one of the following:allโ use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set.mixedโ use all loops except for loops with small register pressure as the regions. This value usually gives the best results in most cases and for most architectures, and is enabled by default when compiling with optimization for speed (-O,-O2, ...).oneโ use all functions as a single region. This typically results in the smallest code size, and is enabled by default for-Osor-O0.
-fira-hoist-pressureโ use IRA to evaluate register pressure in the code hoisting pass for decisions to hoist expressions ๐๏ธ This option usually results in smaller code, but it can slow the compiler down. trade-offs, bestie ๐
This option is enabled at level -Os for all targets.
-fira-loop-pressureโ use IRA to evaluate register pressure in loops for decisions to move loop invariants ๐ This option usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down.
This option is enabled at level -O3 for some targets.
-fno-ira-share-save-slotsโ disables sharing of stack slots used for saving call-used hard registers living through a call ๐ Each hard register gets a separate stack slot, and as a result function stack frames are larger.-fno-ira-share-spill-slotsโ disables sharing of stack slots allocated for pseudo-registers ๐ฌ Each pseudo-register that does not get a hard register gets a separate stack slot, and as a result function stack frames are larger.-flra-rematโ enables CFG-sensitive rematerialization in LRA โป๏ธ Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it's profitable. iconic behavior honestly.
Enabled at levels -O2, -O3, -Os.
-fdelayed-branchโ if supported for the target machine, attempts to reorder instructions to exploit instruction slots available after delayed branch instructions ๐ฏ
Enabled at levels -O1, -O2, -O3, -Os, but not at -Og.
-fschedule-insnsโ if supported for the target machine, attempts to reorder instructions to eliminate execution stalls due to required data being unavailable ๐ฆ This helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating-point instruction is required. it's giving "keep everyone busy while we wait" ๐ซถ
Enabled at levels -O2, -O3.
-fschedule-insns2โ similar to-fschedule-insns, but requests an additional pass of instruction scheduling after register allocation has been done ๐ซ This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle.
Enabled at levels -O2, -O3, -Os.
-fno-sched-interblockโ disables instruction scheduling across basic blocks ๐ โโ๏ธ which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fno-sched-specโ disables speculative motion of non-load instructions ๐ which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-pressureโ enables register pressure sensitive insn scheduling before register allocation ๐ซง This only makes sense when scheduling before register allocation is enabled, i.e. with-fschedule-insnsor at-O2or higher. Using this option can improve the generated code and decrease its size by preventing register pressure increase above the number of available hard registers and the subsequent spills in register allocation.-fsched-spec-loadโ allows speculative motion of some load instructions ๐ฆ This only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-spec-load-dangerousโ allows speculative motion of more load instructions ๐ณ dangerous is literally in the name, bestie. This only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-stalled-insns-fsched-stalled-insns=nโ defines how many insns (if any) can be moved prematurely from the queue of stalled insns into the ready list during the second scheduling pass โฑ๏ธ-fno-sched-stalled-insnsmeans that no insns are moved prematurely,-fsched-stalled-insns=0means there is no limit on how many queued insns can be moved prematurely. And-fsched-stalled-insnswithout a value is equivalent to-fsched-stalled-insns=1. no cap ๐-fsched-stalled-insns-dep,-fsched-stalled-insns-dep=n โ bestie, this one decides how many insn groups (aka cycles) get examined looking for a dependency on a stalled insn that's a candidate for premature removal from the queue of stalled insns ๐ซถ. Plot twist: it only does anything during the second scheduling pass, and only if you've also got-fsched-stalled-insnson. And-fno-sched-stalled-insns-depis literally the same thing as-fsched-stalled-insns-dep=0, while-fsched-stalled-insns-depwith no value at all is the same as-fsched-stalled-insns-dep=1. slay โจ-fsched2-use-superblocksโ when we're scheduling after register allocation, use superblock scheduling ๐ . This lets stuff move across basic block boundaries, which means faster schedules โ cute! But ngl it's experimental, bc not every machine description GCC uses models the CPU closely enough to keep this algorithm from giving you unreliable results ๐ญ. Also it only makes sense when you're scheduling after register allocation, i.e. with-fschedule-insns2or at-O2or higher.-fsched-group-heuristicโ turns on the group heuristic in the scheduler, which favors the instruction that belongs to a schedule group ๐. It's enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-critical-path-heuristicโ enables the critical-path heuristic in the scheduler, which favors instructions on the critical path ๐ฅ. Enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-spec-insn-heuristicโ enables the speculative instruction heuristic in the scheduler, which favors speculative instructions with greater dependency weakness ๐ซ. Enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-rank-heuristicโ enables the rank heuristic in the scheduler, which favors the instruction belonging to a basic block with greater size or frequency ๐ธ. Enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-last-insn-heuristicโ enables the last-instruction heuristic in the scheduler, which favors the instruction that is less dependent on the last instruction scheduled ๐ฆ. Enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-dep-count-heuristicโ enables the dependent-count heuristic in the scheduler, which favors the instruction that has more instructions depending on it ๐. Enabled by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.
-freschedule-modulo-scheduled-loopsโ so modulo scheduling happens before traditional scheduling, right? And if a loop is modulo scheduled, the later scheduling passes might still go in and change its schedule ๐. Use this option to control that behavior.-fselective-schedulingโ schedule instructions using the selective scheduling algorithm. Selective scheduling runs instead of the first scheduler pass ๐ .-fselective-scheduling2โ schedule instructions using the selective scheduling algorithm โ but this time it runs instead of the second scheduler pass โจ.-fsel-sched-pipeliningโ enables software pipelining of innermost loops during selective scheduling ๐. Heads up: this has literally no effect unless one of-fselective-schedulingor-fselective-scheduling2is turned on.-fsel-sched-pipelining-outer-loopsโ when you're pipelining loops during selective scheduling, this also pipelines outer loops ๐ซถ. And same deal: no effect unless-fsel-sched-pipeliningis turned on.-fsemantic-interpositionโ some object formats, like ELF, let the dynamic linker interpose symbols ๐. Which means that for symbols exported from the DSO, the compiler cannot do interprocedural propagation, inlining and other optimizations, because it has to assume the function or variable in question might change. While this feature is useful โ like, say, to rewrite memory allocation functions with a debugging implementation โ it's expensive when it comes to code quality. With-fno-semantic-interposition, the compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Similarly, if interposition happens for variables, the constructor of the variable will be the same. And no cap: this flag has no effect for functions explicitly declared inline (where it is never allowed for interposition to change semantics) and for symbols explicitly declared weak.-fshrink-wrapโ emit function prologues only before the parts of the function that actually need them, instead of up at the top of the function ๐. This flag is enabled by default at-Oand higher.-fshrink-wrap-separateโ shrink-wrap separate parts of the prologue and epilogue separately, so those parts only get executed when they're needed ๐. It's on by default, but it has no effect unless-fshrink-wrapis also turned on and the target supports this.-fcaller-savesโ enables allocation of values to registers that are clobbered by function calls, by emitting extra instructions to save and restore those registers around such calls ๐พ. That allocation only happens when it looks like it'll result in better code. Also, this option is always enabled by default on certain machines, usually the ones with no call-preserved registers to use instead. Enabled at levels-O2,-O3,-Os.-fcombine-stack-adjustmentsโ tracks stack adjustments (pushes and pops) and stack memory references, then tries to find ways to combine them ๐ง. Enabled by default at-O1and higher.-fipa-raโ use caller save registers for allocation if those registers aren't used by any called function ๐ซถ. In that case you don't need to save and restore them around calls. This is only possible if the called functions are part of the same compilation unit as the current function and they're compiled before it. Enabled at levels-O2,-O3,-Osโ however, the option is disabled if the generated code will be instrumented for profiling (-p, or-pg) or if the callee's register usage can't be known exactly (this happens on targets that don't expose prologues and epilogues in RTL) ๐ญ.-fconserve-stackโ attempt to minimize stack usage. The compiler tries to use less stack space, even if that makes the program slower ๐. This option implies setting thelarge-stack-frameparameter to100and thelarge-stack-frame-growthparameter to400.-ftree-reassocโ perform reassociation on trees ๐ณ. This flag is enabled by default at-O1and higher.-fcode-hoistingโ perform code hoisting. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible โซ. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at-O2and higher.-ftree-preโ perform partial redundancy elimination (PRE) on trees ๐ณโจ. This flag is enabled by default at-O2and-O3.-ftree-partial-preโ makes partial redundancy elimination (PRE) more aggressive ๐ค. This flag is enabled by default at-O3.-ftree-forwpropโ perform forward propagation on trees ๐ฟ. This flag is enabled by default at-O1and higher.-ftree-freโ perform full redundancy elimination (FRE) on trees ๐ณ. The difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. This flag is enabled by default at-O1and higher.-ftree-phipropโ perform hoisting of loads from conditional pointers on trees โคด๏ธ. This pass is enabled by default at-O1and higher.-fhoist-adjacent-loadsโ speculatively hoist loads from both branches of an if-then-else, if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction ๐. This flag is enabled by default at-O2and higher.-ftree-copy-propโ perform copy propagation on trees ๐ฒ. This pass eliminates unnecessary copy operations. This flag is enabled by default at-O1and higher.-fipa-pure-constโ discover which functions are pure or constant ๐ง. Enabled by default at-O1and higher.-fipa-referenceโ discover which static variables do not escape the compilation unit ๐ซง. Enabled by default at-O1and higher.-fipa-reference-addressableโ discover read-only, write-only and non-addressable static variables ๐. Enabled by default at-O1and higher.-fipa-stack-alignmentโ reduce stack alignment on call sites if possible ๐. Enabled by default.-fipa-ptaโ perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐ง . Heads up bestie, this option can cause excessive memory and compile-time usage on large compilation units ๐ญ. It is not enabled by default at any optimization level.-fipa-profileโ perform interprocedural profile propagation. Functions called only from cold functions get marked as cold โ๏ธ. Also, functions executed once (such as"cold","noreturn", static constructors or destructors) are identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at-O1and higher.-fipa-modrefโ perform interprocedural mod/ref analysis ๐. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. This flag is enabled by default at-O1and higher.-fipa-cpโ perform interprocedural constant propagation ๐ข. This optimization analyzes the program to figure out when values passed to functions are constants, and then optimizes accordingly. It can substantially increase performance if the application has constants passed to functions ๐. This flag is enabled by default at-O2,-Osand-O3. It is also enabled by-fprofile-useand-fauto-profile.-fipa-cp-clone</p> โ okay so this one does function cloning so that interprocedural constant propagation hits harder. When it's on, the ICP pass clones a function whenever an externally visible function can be called with constant arguments. Slay, right? Except ๐ซ because cloning means multiple copies of functions, which can bump your code size up a LOT (peep--param ipa-cp-unit-growth=valueif that hurts). It's on by default at-O3, and it also gets switched on by-fprofile-useand-fauto-profile. ๐-fipa-bit-cpโ when enabled, it does interprocedural bitwise constant propagation. On by default at-O2, and also by-fprofile-useand-fauto-profile. Important: it needs-fipa-cpto be enabled first โ no-fipa-cp, no bit-cp bestie. โจ-fipa-vrpโ when enabled, it does interprocedural propagation of value ranges. On by default at-O2. And yeah, same deal: it requires-fipa-cpto be enabled. ๐ฆ-fipa-icfโ performs Identical Code Folding for functions and read-only variables. It shrinks code size, and heads up ๐ญ it may disturb unwind stacks by replacing a function with an equivalent one that has a different name. It works more effectively with link-time optimization enabled.
So even though the behaviour is similar to the Gold Linker's ICF optimization, GCC's ICF works on different levels, so the optimizations are not the same โ there are equivalences only GCC finds, and equivalences only Gold finds. Not the same girl, not the same job. ๐
This flag is enabled by default at -O2 and -Os.
-flive-patching=levelโ controls GCC's optimizations so the output is suitable for live-patching. ๐ฉน
Here's the whole situation: if the compiler's optimization uses a function's body (or info pulled out of its body) to optimize or change another function, that other one is called an impacted function of the former. So if a function gets patched, its impacted functions gotta be patched too. Periodt.
The impacted functions are decided by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, when cloning a function and changing its caller to call this new clone, or when extracting a function's pureness/constness info to optimize its direct or indirect callers, etc.
Usually the more IPA optimizations you turn on, the more impacted functions each function has. So to control how many impacted functions there are and to make computing the impacted-function list easier, the IPA optimizations can be partially enabled at two different levels.
The level argument should be one of the following:
inline-cloneโ only enable inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. Which means: when you patch a function, all its callers and its clones' callers are impacted, so they need patching too. ๐
-flive-patching=inline-clone disables these optimization flags:
-fwhole-program -fipa-pta -fipa-reference -fipa-ra
-fipa-icf -fipa-icf-functions -fipa-icf-variables -fipa-bit-cp
-fipa-vrp -fipa-pure-const -fipa-reference-addressable
-fipa-stack-alignment -fipa-modref
inline-only-staticโ only enable inlining of static functions. So when you patch a static function, all its callers are impacted and therefore need to be patched as well.
On top of all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables these additional optimization flags:
-fipa-cp-clone -fipa-sra -fpartial-inlining -fipa-cp
When -flive-patching is specified without any value, the default value is inline-clone.
This flag is disabled by default. ๐
โ ๏ธ Note that-flive-patchingis not supported with link-time optimization (-flto). Don't try it bestie, it's not giving.
-fisolate-erroneous-paths-dereferenceโ detects paths that trigger erroneous or undefined behavior by dereferencing a null pointer. It isolates those paths from the main control flow and turns the statement with the erroneous/undefined behavior into a trap. Enabled by default at-O2and higher, and it depends on-fdelete-null-pointer-checksalso being enabled. ๐-fisolate-erroneous-paths-attributeโ detects paths that trigger erroneous or undefined behavior because a null value is used in a way that's forbidden by a"returns_nonnull"or"nonnull"attribute. Same treatment: isolate those paths from the main control flow and turn the offending statement into a trap. This is not currently enabled, but it may be enabled by-O2in the future. ๐ฎ-ftree-sinkโ performs forward store motion on trees. On by default at-O1and higher. โจ-ftree-bit-ccpโ performs sparse conditional bit constant propagation on trees and propagates pointer alignment information. This pass only operates on local scalar variables, and it's enabled by default at-O1and higher โ except for-Og. It requires that-ftree-ccpis enabled. ๐ง-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees. Also only operates on local scalar variables, and on by default at-O1and higher. ๐-fssa-backpropโ propagates info about the uses of a value up the definition chain so the definitions can get simplified. For example, this pass strips sign operations if the sign of a value never matters. Enabled by default at-O1and higher. ๐-fssa-phioptโ does pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at-O1and higher, except for-Og. ๐ธ-ftree-switch-conversionโ converts simple initializations in aswitchinto initializations from a scalar array. Enabled by default at-O2and higher. ๐ฅ-ftree-tail-mergeโ looks for identical code sequences, and when it finds them it replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. On by default at-O2and higher. You can limit the compilation time this pass eats up with themax-tail-merge-comparisonsparameter and themax-tail-merge-iterationsparameter. โณ-ftree-dceโ performs dead code elimination (DCE) on trees. Enabled by default at-O1and higher. ๐-ftree-builtin-call-dceโ performs conditional dead code elimination (DCE) for calls to built-in functions that may set"errno"but are otherwise free of side effects. Enabled by default at-O2and higher, if-Osis not also specified. ๐-ffinite-loopsโ assumes that a loop with an exit will eventually take that exit and not loop forever. Which lets the compiler remove loops that otherwise have no side-effects, since it's not counting eventual endless looping as a side effect anymore. ๐
This option is enabled by default at -O2 for C++ with -std=c++11 or higher.
-ftree-dominator-optsโ performs a whole lil variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. It also does jump threading (to reduce jumps to jumps). Enabled by default at-O1and higher. โจ-ftree-dseโ performs dead store elimination (DSE) on trees. A dead store is a store into a memory location that later gets overwritten by another store with no intervening loads โ in that case the earlier store can be deleted. Enabled by default at-O1and higher. ๐-ftree-chโ performs loop header copying on trees. This is beneficial because it makes code motion optimizations more effective, and it also saves one jump. Enabled by default at-O1and higher. It's not enabled for-Os, since it usually increases code size. ๐ซถ-ftree-loop-optimizeโ performs loop optimizations on trees. Enabled by default at-O1and higher. ๐-ftree-loop-linear-floop-strip-mine-floop-blockโ perform loop nest optimizations. Same as-floop-nest-optimize. To use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure. ๐งฉ-fgraphite-identityโ enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using-fgraphite-identitywe can check the costs or benefits of theGIMPLE -> GRAPHITE -> GIMPLEtransformation. Some minimal optimizations are also performed by the code generatorisl, like index splitting and dead code elimination in loops. ๐ฆ-floop-nest-optimizeโ enables theislbased loop nest optimizer. This is a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental. ๐งช-floop-parallelize-allโ uses the Graphite data dependence analysis to find loops that can be parallelized, then parallelizes all the loops that can be analyzed to not contain loop carried dependences โ without checking whether parallelizing them is actually profitable. ๐ญ-ftree-coalesce-varsโ while transforming the program out of the SSA representation, it tries to reduce copying by coalescing versions of different user-defined variables instead of just compiler temporaries. Heads up โ ๏ธ this may severely limit your ability to debug an optimized program compiled with-fno-var-tracking-assignments. In the negated form, this flag prevents SSA coalescing of user variables. It's enabled by default if optimization is enabled, and it does very little otherwise. ๐-ftree-loop-if-convertโ tries to transform conditional jumps in the innermost loops into branch-less equivalents. The intent is to remove control-flow from the innermost loops so the vectorization pass has an easier time handling those loops. Enabled by default if vectorization is enabled. ๐ฅ-ftree-loop-distributionโ performs loop distribution. This flag can improve cache performance on big loop bodies and allows further loop optimizations, like parallelization or vectorization, to take place. For example, the loop
DO I = 1, N
A(I) = B(I) + C
D(I) = E(I) * F
ENDDO
is transformed to
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
okay and to close that one out: this flag is enabled by default at -O3. it's also enabled by -fprofile-use and -fauto-profile. slay. ๐
-ftree-loop-distribute-patternsโ bestie this one does loop distribution on patterns that can be code generated with calls to a library ๐โจ. this flag is enabled by default at-O2and higher, and by-fprofile-useand-fauto-profile.
what this pass actually does is distribute the initialization loops and generate a call to memset zero. like, watch โ for example, the loop
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
gets transformed to
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and then the initialization loop gets transformed into a call to memset zero ๐ซถ. this flag is enabled by default at -O3. it is also enabled by -fprofile-use and -fauto-profile.
-floop-interchangeโ performs loop interchange outside of graphite ๐ฅ. this one can improve cache performance on loop nest and let further loop optimizations โ like vectorization โ take place. the way that it works, okay: for example, the loop
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
is transformed to
for (int i = 0; i < N; i++)
for (int k = 0; k < N; k++)
for (int j = 0; j < N; j++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
this flag is enabled by default at -O3. it is also enabled by -fprofile-use and -fauto-profile. iconic behavior honestly ๐
-floop-unroll-and-jamโ applies unroll and jam transformations on feasible loops ๐. in a loop nest this unrolls the outer loop by some factor and fuses the resulting multiple inner loops. this flag is enabled by default at-O3. it is also enabled by-fprofile-useand-fauto-profile.-ftree-loop-imโ performs loop invariant motion on trees ๐ณ. okay important detail: this pass moves only invariants that are hard to handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). with-funswitch-loopsit also moves operands of conditions that are invariant out of the loop, so that we can use just trivial invariantness analysis in loop unswitching ๐ง. the pass also includes store motion.-ftree-loop-ivcanonโ creates a canonical counter for number of iterations in loops for which determining number of iterations requires complicated analysis ๐ตโ๐ซ. later optimizations then may determine the number easily. useful especially in connection with unrolling. no cap ๐ฏ-ftree-scev-cpropโ performs final value replacement. so here's the tea โ: if a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, replace uses of the final value by such a computation โ provided it is sufficiently cheap ๐ธ. this reduces data dependencies and may allow further simplifications. enabled by default at-O1and higher.-fivoptsโ performs induction variable optimizations on trees: strength reduction, induction variable merging and induction variable elimination ๐ฟ.-ftree-parallelize-loops=nโ parallelize loops!! โจ i.e., split their iteration space to run in n threads. this is only possible for loops whose iterations are independent and can be arbitrarily reordered ๐. also like, heads up: the optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive, rather than constrained e.g. by memory bandwidth ๐ซ . this option implies-pthread, and thus is only supported on targets that have support for-pthread.-ftree-ptaโ performs function-local points-to analysis on trees ๐. this flag is enabled by default at-O1and higher, except for-Og.-ftree-sraโ performs scalar replacement of aggregates ๐. this pass replaces structure references with scalars to prevent committing structures to memory too early. this flag is enabled by default at-O1and higher, except for-Og.-fstore-mergingโ performs merging of narrow stores to consecutive memory addresses ๐งฉ. this pass merges contiguous stores of immediate values narrower than a word into fewer wider stores to reduce the number of instructions. this is enabled by default at-O2and higher as well as-Os.-ftree-terโ performs temporary expression replacement during the SSA->normal phase ๐ฆ. single use/single def temporaries are replaced at their use location with their defining expression. this results in non-GIMPLE code, but gives the expanders much more complex trees to work on resulting in better RTL generation. this is enabled by default at-O1and higher.-ftree-slsrโ performs straight-line strength reduction on trees โจ. this recognizes related expressions involving multiplications and replaces them by less expensive calculations when possible. this is enabled by default at-O1and higher.-ftree-vectorizeโ performs vectorization on trees ๐ฆ. this flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif not explicitly specified.-ftree-loop-vectorizeโ performs loop vectorization on trees. this flag is enabled by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftree-slp-vectorizeโ performs basic block vectorization on trees. this flag is enabled by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftrivial-auto-var-init=choiceโ initializes automatic variables with either a pattern or with zeroes, to increase the security and predictability of a program by preventing uninitialized memory disclosure and use ๐โจ.
okay so this is the important part bestie: GCC still considers an automatic variable that doesn't have an explicit initializer as uninitialized.-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still report warning messages on such automatic variables, and the compiler will perform optimization as if the variable were uninitialized ๐ญ
with this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. however, the current implementation cannot initialize automatic variables that are declared between the controlling expression and the first case of a "switch" statement. use -Wtrivial-auto-var-init to report all such cases ๐.
the three values of choice are:
uninitializedโ doesn't initialize any automatic variables. this is C and C++'s default ๐patternโ initialize automatic variables with values which will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump and without being values that programmers can rely on for useful program semantics. the current value is byte-repeatable pattern with byte"0xFE". the values used for pattern initialization might be changed in the future ๐zeroโ initialize automatic variables with zeroes. clean, simple, iconic ๐ซถ
the default is uninitialized.
you can control this behavior for a specific variable by using the variable attribute "uninitialized".
-fvect-cost-model=modelโ alters the cost model used for vectorization ๐ธ. the model argument should be one ofunlimited,dynamic,cheaporvery-cheap. let's break it down:- with the
unlimitedmodel the vectorized code-path is assumed to be profitable ๐ - with the
dynamicmodel a runtime check guards the vectorized code-path to enable it only for iteration counts that will likely execute faster than when executing the original scalar loop ๐ - the
cheapmodel disables vectorization of loops where doing so would be cost prohibitive โ for example due to required runtime checks for data dependence or alignment โ but otherwise is equal to thedynamicmodel ๐ - the
very-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code that is being vectorized. for example, if each iteration of a vectorized loop would only be able to handle exactly four iterations of the scalar loop, thevery-cheapmodel would only allow vectorization if the scalar iteration count is known to be a multiple of four ๐ข
- with the
the default cost model depends on other optimization flags and is either dynamic or cheap.
-fsimd-cost-model=modelโ alters the cost model used for vectorization of loops marked with the OpenMP simd directive ๐. the model argument should be one ofunlimited,dynamic,cheap. all values of model have the same meaning as described in-fvect-cost-modeland by default a cost model defined with-fvect-cost-modelis used.-ftree-vrpโ performs Value Range Propagation on trees ๐ณ. this is similar to the constant propagation pass, but instead of values, ranges of values are propagated ๐๐. this allows the optimizers to remove unnecessary range checks like array bound checks and null pointer checks ๐ซ. this is enabled by default at-O2and higher. heads up tho: null pointer check elimination is only done if-fdelete-null-pointer-checksis enabled.-fsplit-pathsโ splits paths leading to loop backedges ๐. this can improve dead code elimination and common subexpression elimination. this is enabled by default at-O3and above.-fsplit-ivs-in-unrollerโ enables expression of values of induction variables in later iterations of the unrolled loop using the value in the first iteration ๐. this breaks long dependency chains, thus improving efficiency of the scheduling passes. slay โจ
a combination of -fweb and CSE is often sufficient to obtain the same effect. however, that is not reliable in cases where the loop body is more complicated than a single basic block ๐ฌ. it also does not work at all on some architectures due to restrictions in the CSE pass ๐
this optimization is enabled by default.
-fvariable-expansion-in-unrollerโ with this option, the compiler creates multiple copies of some local variables when unrolling a loop, which can result in superior code ๐โโ๏ธ
this optimization is enabled by default for PowerPC targets, but disabled by default otherwise ๐
-fpartial-inliningโ bestie, this one inlines parts of functions. Like not the whole function, just the juicy bits. But heads up: it literally does nothing unless inlining itself is already turned on by-finline-functionsor-finline-small-functions. ๐
It's enabled at levels -O2, -O3, -Os.
-fpredictive-commoningโ does the predictive commoning optimization, which is a fancy way of saying it reuses computations from previous iterations of loops โ especially memory loads and stores. it's giving "why recompute when you already know" energy. โจ
Enabled at level -O3. It's also enabled by -fprofile-use and -fauto-profile.
-fprefetch-loop-arraysโ if your target machine supports it, GCC generates instructions to prefetch memory, which makes loops that access big arrays go faster. ๐๏ธ
real talk: this option may generate better or worse code. results are highly dependent on the structure of the loops in your source. no cap.
Disabled at level -Os.
-fno-printf-return-valueโ do NOT substitute constants for the known return value of formatted output functions likesprintf,snprintf,vsprintf, andvsnprintf(but notprintfoffprintf). This transformation is what lets GCC optimize โ or literally eliminate โ branches based on the known return value of these functions when they're called with arguments that are either constant, or whose values are known to be in a range that makes figuring out the exact return value possible. ๐ธ
For example, when -fprintf-return-value is in effect, both the branch and the body of the if statement (but not the call to snprint) can be optimized away when i is a 32-bit or smaller integer, because the return value is guaranteed to be at most 8. ๐
char buf[9];
if (snprintf (buf, "%08x", i) >= sizeof buf)
...
The -fprintf-return-value option relies on other optimizations and yields best results with -O2 and above. It works in tandem with the -Wformat-overflow and -Wformat-truncation options. And the -fprintf-return-value option is enabled by default. ๐
-fno-peephole,-fno-peephole2โ disables any machine-specific peephole optimizations. The difference between-fno-peepholeand-fno-peephole2is how they're implemented in the compiler; some targets use one, some use the other, a few use both. it's giving sibling energy fr fr. ๐
-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.
-fno-guess-branch-probabilityโ don't guess branch probabilities using heuristics. periodt.
GCC uses heuristics to guess branch probabilities if nobody gives it profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by __builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can be... complex ๐ญ, and in some cases it may be useful to disable the heuristics so the effects of __builtin_expect are easier to understand.
It's also possible to specify the expected probability of the expression with the __builtin_expect_with_probability built-in function.
The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.
-freorder-blocksโ reorders basic blocks in the compiled function to reduce the number of taken branches and improve code locality. slay. โจ
Enabled at levels -O1, -O2, -O3, -Os.
-freorder-blocks-algorithm=algorithmโ use the specified algorithm for basic block reordering. The algorithm argument can besimple, which does not increase code size (except sometimes due to secondary effects like alignment), orstc, the "software trace cache" algorithm, which tries to put all often-executed code together, minimizing the number of branches executed by making extra copies of code. ๐
The default is simple at levels -O1, -Os, and stc at levels -O2, -O3.
-freorder-blocks-and-partitionโ on top of reordering basic blocks in the compiled function to reduce the number of taken branches, this partitions hot and cold basic blocks into separate sections of the assembly and.ofiles, to improve paging and cache locality performance. iconic behavior. ๐ฅ
This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or a target-specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that doesn't support named sections. When -fsplit-stack is used this option is not enabled by default (to avoid linker errors), but it may be enabled explicitly (if you're using a working linker).
Enabled for x86 at levels -O2, -O3, -Os.
-freorder-functionsโ reorders functions in the object file to improve code locality. It's implemented by using special subsections.text.hotfor the most frequently executed functions and.text.unlikelyfor the unlikely-executed ones. The reordering is done by the linker, so the object file format must support named sections and the linker must place them in a reasonable way.
ngl this option isn't effective unless you either provide profile feedback (see-fprofile-arcsfor the deets) or manually annotate functions withhotorcoldattributes.
Enabled at levels -O2, -O3, -Os.
-fstrict-aliasingโ lets the compiler assume the strictest aliasing rules that apply to the language being compiled. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed to never reside at the same address as an object of a different type, unless the types are almost the same. For example, anunsigned intcan alias anint, but not avoid*or adouble. A character type may alias any other type. ๐ฆ
Pay special attention to code like this, bestie:
union a_union {
int i;
double d;
};
int f() {
union a_union t;
t.d = 3.0;
return t.i;
}
The practice of reading from a different union member than the one most recently written to (called "type-punning") is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So the code above works as expected. However, this code might not:
int f() {
union a_union t;
int* ip;
t.d = 3.0;
ip = &t.i;
return *ip;
}
Similarly, access by taking the address, casting the resulting pointer, and dereferencing the result has undefined behavior, even if the cast uses a union type, e.g.:
int f() {
double d = 3.0;
return ((union a_union *) &d)->i;
}
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-fipa-strict-aliasingโ controls whether the rules of-fstrict-aliasingget applied across function boundaries. Note that if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary. ๐
The -fipa-strict-aliasing option is enabled by default and is effective only in combination with -fstrict-aliasing.
-falign-functions,-falign-functions=n,-falign-functions=n:m,-falign-functions=n:m:n2,-falign-functions=n:m:n2:m2โ aligns the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes. This ensures that at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. ๐
If m is not specified, it defaults to n.
Examples: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less.
The second pair of n2:m2 values lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 is not specified, it defaults to n2.
Some assemblers only support this flag when n is a power of two; in that case, it is rounded up.
-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-flimit-function-alignmentโ with this enabled, the compiler tries to avoid unnecessarily overaligning functions. It attempts to instruct the assembler to align by the amount specified by-falign-functions, but not to skip more bytes than the size of the function. ๐-falign-labels,-falign-labels=n,-falign-labels=n:m,-falign-labels=n:m:n2,-falign-labels=n:m:n2:m2โ aligns all branch targets to a power-of-two boundary. ๐ซถ
The parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.
If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.
If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-falign-loops,-falign-loops=n,-falign-loops=n:m,-falign-loops=n:m:n2,-falign-loops=n:m:n2:m2โ aligns loops to a power-of-two boundary. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. it pays for itself, bestie. ๐
If -falign-labels is greater than this value, then its value is used instead.
The parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536.
If n is not specified or is zero, use a machine-dependent default.
Enabled at levels -O2, -O3.
-falign-jumps,-falign-jumps=n,-falign-jumps=n:m,-falign-jumps=n:m:n2,-falign-jumps=n:m:n2:m2โ okay so this one lines up your branch targets on a power-of-two boundary โจ but ONLY for branch targets you can literally only reach by jumping to them. And the slay part? No dummy operations have to get executed. Zero. None. Iconic behavior honestly.
And if -falign-labels is bigger than this value? Then -falign-labels's value wins and gets used instead. Periodt.
The parameters work just like the -falign-functions option does, iykyk. Also fun fact: -fno-align-jumps and -falign-jumps=1 are genuinely the same thing โ both mean loops don't get aligned at all ๐ธ
If n isn't specified, or it's zero? Machine-dependent default, bestie, we don't decide that. And the max allowed n value is 65536.
Enabled at levels -O2, -O3. ๐
-fno-allocation-dceโ bestie do NOT remove unused C++ allocations during dead code elimination. Like, leave them alone. ๐-fallow-store-data-racesโ okay so this lets the compiler do optimizations that might introduce new data races on stores, without it having to first prove the variable can't be touched by other threads at the same time. It does not affect optimization of local data though. And it's safe to use if you KNOW global data won't be accessed by multiple threads ๐ซถ
So what optimizations does this actually unlock? Stuff like hoisting or if-conversions that might cause a value that was already chilling in memory to get re-written with that exact same value. In a single-threaded context that re-writing is totally fine and safe. In a multi-threaded context? Could be unsafe, no cap. Also heads up: on some processors, if-conversions might be required in order to enable vectorization. ๐
Enabled at level -Ofast.
-funit-at-a-timeโ this one's just left here for compatibility reasons, fr fr.-funit-at-a-timehas literally no effect, while-fno-unit-at-a-timeimplies-fno-toplevel-reorderand-fno-section-anchors.
Enabled by default. โจ
-fno-toplevel-reorderโ do NOT reorder top-level functions, variables, and"asm"statements. Output them in the exact same order they show up in the input file, periodt. When you use this option, unreferenced static variables don't get removed either.
This option exists to support existing code that depends on a particular ordering. For new code though? Better to use attributes when you can, bestie ๐ธ
-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Also: -fno-toplevel-reorder implies -fno-section-anchors.
-funreachable-trapsโ with this one, the compiler turns calls to"__builtin_unreachable"into traps instead of using them for optimization. This also affects any such calls that the compiler implicitly generated on its own ๐
It does the same thing as -fsanitize=unreachable -fsanitize-trap=unreachable, BUT it does not change the values of those options. And if -fsanitize=unreachable is enabled, that option takes priority over this one. Sorry bestie, priority is priority ๐
This option is enabled by default at -O0 and -Og.
-fwebโ constructs webs the way they're commonly used for register allocation purposes, and assigns each web its own individual pseudo register. This lets the register allocation pass work directly on pseudos, but it ALSO strengthens several other optimization passes โ think CSE, the loop optimizer, and the trivial dead code remover. Slay? Kinda. ๐ญ
BUT โ and this is a big but โ it can make debugging impossible, since variables no longer stay in a "home register". It's giving chaos.
Enabled by default with -funroll-loops.
-fwhole-programโ assume that the current compilation unit is the whole program being compiled. Every public function and variable โ except"main"and anything merged by the attribute"externally_visible"โ becomes a static function, and in effect they get optimized way more aggressively by the interprocedural optimizers ๐ฅ
With -flto this option has limited use. In most cases the precise list of symbols used or exported from the binary is known from the resolution info passed to the link-time optimizer by the linker plugin. It's still useful if no linker plugin is used, or during the incremental link step when final code is produced (with -flto -flinker-output=nolto-rel).
-flto[=n]โ okay this is the big one, bestie, gather round ๐ This option runs the standard link-time optimizer. When you invoke it with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. Then when the object files get linked together, all the function bodies are read from those ELF sections and instantiated as if they'd been part of the same translation unit the whole time. It's giving โจone single mindโจ.
To actually use the link-time optimizer, -flto AND your optimization options should be specified at compile time and during the final link. The recommendation is that you compile all the files participating in the same link with the same options, and also specify those options at link time. Like so:
gcc -c -O2 -flto foo.c
gcc -c -O2 -flto bar.c
gcc -o myprog -flto -O2 foo.o bar.o
The first two invocations to GCC save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, all the interprocedural analyses and optimizations in GCC work across the two files as if they were a single one ๐ฆ Which means, for example, that the inliner is able to inline functions in bar.o into functions in foo.o and vice-versa. Cross-file glow-up, we love to see it.
Another (and simpler!) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
The above generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation, and optimizes them as usual to produce myprog.
The important thing to keep in your head, bestie: to enable link-time optimizations you need to use the GCC driver to do the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. And you can always override that automatic decision by passing -fno-lto to the link command. You're the main character here, not the compiler ๐
To make whole program optimization actually effective, it's necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of the link-time optimized unit. When the linker supports it, the linker plugin (see -fuse-linker-plugin) passes info to the compiler about used and externally visible symbols. When the linker plugin isn't available, -fwhole-program should be used to let the compiler make these assumptions, which leads to more aggressive optimization decisions ๐ฅ
When a file is compiled with -flto without -fuse-linker-plugin, the generated object file is larger than a regular object file, because it contains GIMPLE bytecodes AND the usual final code (see -ffat-lto-objects). This means object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations get applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster, but you cannot do a regular, non-LTO link on them. Trade-offs, bestie, trade-offs. ๐ญ
When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. So you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically picks which files get optimized in LTO mode and which files get linked without further processing โจ
Generally, options specified at link time override those specified at compile time, although in some cases GCC tries to infer link-time options from the settings used to compile the input files ๐ฎ
If you don't specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files. Note that it's generally ineffective to specify an optimization level option only at link time and not at compile time, for two big reasons. First: compiling without optimization suppresses compiler passes that gather the info needed for effective optimization at link time. Second: some early optimization passes can only happen at compile time and not at link time. So like, don't do that. ๐
There are some code generation flags that GCC preserves when generating bytecodes, because they need to be used during the final link. Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags.
The following options -fPIC, -fpic, -fpie and -fPIE are combined based on this scheme:
-fPIC + -fpic = -fpic
-fPIC + -fno-pic = -fno-pic
-fpic/-fPIC + (no option) = (no option)
-fPIC + -fPIE = -fPIE
-fpic + -fPIE = -fpie
-fPIC/-fpic + -fpie = -fpie
Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is just... ignored. Nothing you can do, bestie. This includes options such as -freg-struct-return and -fpcc-struct-return. ๐
Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing get passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time though, so that's your escape hatch ๐
Diagnostic options such as -Wstringop-overflow get passed through to the link stage too, and their setting matches that of the compile-step at function granularity. Note that this only matters for diagnostics emitted during optimization. And note that code transforms like inlining can lead to warnings being enabled or disabled for regions of code that aren't consistent with the setting at compile time. Little chaos gremlin behavior, ngl ๐ง
When you need to pass options to the assembler via -Wa or -Xassembler, make sure to either compile such translation units with -fno-lto OR consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time. Pick your lane, bestie ๐
For debug info to actually get generated you need to hand over -g at compile time, bestie โ no -g, no debug info, that's the deal ๐. And here's the cute part: if any of the input files at link time were built with debug info generation turned on, then the link turns debug info generation on too โจ. But watch out ๐ โ the fancy elaborate debug info settings, like the dwarf level -gdwarf-5, have to be explicitly repeated at the linker command line, and mixing different settings across different translation units is discouraged. Periodt.
So LTO has a little warning for you: if it runs into objects with C linkage that are declared with incompatible types in separate translation units that are being linked together (which is undefined behavior according to ISO C99 6.2.7 ๐ญ), it may issue a non-fatal diagnostic. And the behavior is still undefined at run time, so likeโฆ it told you, but it can't save you ๐. Similar diagnostics can pop up for other languages too.
Another lil superpower of LTO? You can apply interprocedural optimizations across files written in different languages ๐:
gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran
Notice how the final link is done with g++ so you get the C++ runtime libraries, and -lgfortran is tacked on to grab the Fortran runtime libraries. In general, when you're mixing languages in LTO mode, use the same link command options you'd use when mixing languages in a regular (non-LTO) compilation. Iconic behavior honestly.
Now, if object files containing GIMPLE bytecode are sitting in a library archive โ say libfoo.a โ it's possible to extract them and use them in an LTO link, as long as you're using a linker with plugin support ๐ซถ. To build static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib. And to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. Then at link time, use the flag -fuse-linker-plugin to make sure the library actually participates in the LTO optimization process:
gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo
With the linker plugin enabled, the linker extracts the GIMPLE files it needs out of libfoo.a and passes them on to the running GCC so they can join the aggregated GIMPLE image that gets optimized โจ.
If you're not using a linker with plugin support, and/or you don't enable the linker plugin, then the objects inside libfoo.a get extracted and linked the usual way โ but they do not participate in the LTO optimization process, sadly ๐. And if you want a static library that's suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.
Link-time optimizations do not require the whole program to be present to operate โ no cap. If your program doesn't need any symbols exported, you can combine -flto and -fwhole-program to let the interprocedural optimizers use way more aggressive assumptions, which may lead to improved optimization opportunities ๐. But heads up: use of -fwhole-program is not needed when the linker plugin is active (peep -fuse-linker-plugin).
Real talk moment: the current implementation of LTO makes no attempt to generate bytecode that's portable between different types of hosts. The bytecode files are versioned and there's a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC. Fr fr, don't try it ๐.
Also lowkey important: link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF ๐.
If you specify the optional n, the optimization and code generation done at link time runs in parallel using n parallel jobs, by utilizing an installed make program. The environment variable MAKE can be used to override the program that's used ๐ ๏ธ.
You can also specify -flto=jobserver to use GNU make's job server mode to figure out the number of parallel jobs. This is so useful when the Makefile calling GCC is already executing in parallel ๐ธ. You must prepend a + to the command recipe in the parent Makefile for this to work โ no +, no party. This option likely only works if MAKE is GNU make. And even without the option value, GCC tries to automatically detect a running GNU make's job server ๐.
Then there's -flto=auto, which uses GNU make's job server if it's available, or otherwise falls back to autodetecting the number of CPU threads present in your system. Bestie just handles it for you ๐
.
-flto-partition=alg
Pick the partitioning algorithm the link-time optimizer uses, bestie โ you've got options ๐:
1to1โ a partitioning that mirrors the original source filesbalancedโ partitioning into equally sized chunks (whenever possible)maxโ creates a new partition for every symbol where possiblenoneโ disables partitioning and streaming completely. Also, when you specify the valuenone, it bypasses partitioning and executes the link-time optimization step directly from the WPA phase.oneโ specifies that exactly one partition should be used.
The default value is balanced. 1to1 can be used as a workaround for various code ordering issues, while the max partitioning is intended for internal testing only (so, not for you, sorry ๐ฅ).
-flto-compression-level=n
This one sets the level of compression used for the intermediate language written to LTO object files, and it's only meaningful in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms:
- zstd โ valid values are
0(no compression) up to19(maximum compression) - zlib โ supports values from
0to9
Values outside the supported range get clamped to either the minimum or the maximum of the supported values ๐ซถ. If you don't give the option, a default balanced compression setting is used.
-fuse-linker-plugin
Enables the use of a linker plugin during link-time optimization โจ. This option relies on plugin support in the linker, which is available in gold or in GNU ld 2.21 or newer.
This option enables the extraction of object files with GIMPLE bytecode out of library archives, which improves the quality of optimization by exposing more code to the link-time optimizer ๐. This info specifies what symbols can be accessed externally (by non-LTO objects or during dynamic linking). The resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. Peep -flto for a description of the effect of this flag and how to use it.
This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer, or gold).
-ffat-lto-objects
Fat LTO objects are object files that contain both the intermediate language and the object code ๐. That makes them usable for both LTO linking and normal linking. This option is only effective when compiling with -flto, and it's ignored at link time.
-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO ๐ญ. It requires a linker with linker plugin support for basic functionality. On top of that, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (one capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non-fat LTO, makefiles need to be modified to use them.
Note that modern binutils provide a plugin auto-load mechanism โ installing the linker plugin into $libdir/bfd-plugins has the same effect as using the command wrappers (gcc-ar, gcc-nm and gcc-ranlib) ๐
.
The default is -fno-fat-lto-objects on targets with linker plugin support.
-fcompare-elim
After register allocation and post-register allocation instruction splitting, this pass identifies arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic ๐. If possible, it eliminates the explicit comparison operation.
This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.
Enabled at levels -O1, -O2, -O3, -Os โจ.
-fcprop-registers
After register allocation and post-register allocation instruction splitting, this one performs a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. Lowkey elegant.
Enabled at levels -O1, -O2, -O3, -Os โจ.
-fprofile-correction
Profiles collected using an instrumented binary for multi-threaded programs may be inconsistent because of missed counter updates ๐ญ. When this option is specified, GCC uses heuristics to correct or smooth out those inconsistencies. By default, GCC just emits an error message when it detects an inconsistent profile (dramatic much).
This option is enabled by -fauto-profile.
-fprofile-partial-training
So with -fprofile-use, all portions of the program that weren't executed during the train run get optimized aggressively for size rather than speed ๐. But sometimes it's just not practical to train every possible hot path in a program โ like, the program might contain functions specific to a given hardware config, and the training might not cover all the hardware configurations the program gets run on, y'know?
With -fprofile-partial-training, profile feedback gets ignored for all functions not executed during the train run, leading them to be optimized as if they were compiled without profile feedback. This leads to better performance when the train run isn't representative โ but also leads to significantly bigger code, so it's a trade-off, bestie โ๏ธ.
-fprofile-use, -fprofile-use=path
Enables profile feedback-directed optimizations, plus the following optimizations โ a lot of which are generally profitable only when profile feedback is available:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-reorder-functions
Before you can use this option, you must first generate profiling information. No profile info, no -fprofile-use โ that's the rule ๐.
Okay so, quick heads-up bestie: by default GCC throws an error if the feedback profiles don't match the source code. ๐ญ You can downgrade that drama to a mere warning with -Wno-error=coverage-mismatch โ but heads up, that may result in poorly optimized code. Also, by default GCC emits a warning message if the feedback profiles don't exist at all (peep -Wmissing-profile). So like, it will absolutely tell on you. ๐
If path is specified, GCC looks at path to find the profile feedback data files. See -fprofile-dir. ๐
๐ sampling-based feedback, aka the AutoFDO corner ๐
-fauto-profile-fauto-profile=path
Turns on sampling-based feedback-directed optimizations, plus this whole squad of optimizations โ most of which are only really worth it when profile feedback is available:
-fbranch-probabilities-fprofile-values-funroll-loops-fpeel-loops-ftracer-fvpt-finline-functions-fipa-cp-fipa-cp-clone-fipa-bit-cp-fpredictive-commoning-fsplit-loops-funswitch-loops-fgcse-after-reload-ftree-loop-vectorize-ftree-slp-vectorize-fvect-cost-model=dynamic-ftree-loop-distribute-patterns-fprofile-correction
path is the name of a file containing AutoFDO profile information. If you just don't give one, it defaults to fbdata.afdo in the current directory. (It's giving "I'll find it myself bestie" energy. ๐)
Now listen โ producing an AutoFDO profile data file means running your program with the perf utility on a supported GNU/Linux target system. For more info, see <https://perf.wiki.kernel.org/>. ๐
E.g.
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then use the create_gcov tool to convert the raw profile data into a format GCC can actually use. You must also supply the unstripped binary for your program to this tool. See <https://github.com/google/autofdo> for the lore. ๐ฆ
E.g.
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
๐ floating-point vibe check ๐
The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled โ none of them are coming to save you by default, no cap. ๐ซถ
-ffloat-storeโ do not store floating-point variables in registers, and inhibit other options that might change whether a floating-point value is taken from a register or memory.
This option prevents undesirable excess precision on machines such as the 68000, where the floating registers (of the 68881) keep more precision than a "double" is supposed to have. Same situation on the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. โจ
-fexcess-precision=styleโ lets you have more control over excess precision on machines where floating-point operations happen in a format with more precision or range than the IEEE standard and interchange floating-point types.
By default, -fexcess-precision=fast is in effect โ meaning operations may be carried out in a wider precision than the types specified in the source, if that would result in faster code, and it's lowkey unpredictable when rounding to the types specified in the source code takes place. ๐ตโ๐ซ
When compiling C or C++, if -fexcess-precision=standard is specified, then excess precision follows the rules specified in ISO C99 or C++; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas -ffloat-store only affects assignments). This option is enabled by default for C or C++ if a strict conformance option such as -std=c99 or -std=c++17 is used. -ffast-math enables -fexcess-precision=fast by default regardless of whether a strict conformance option is used.
-fexcess-precision=standardis not implemented for languages other than C or C++. On the x86, it has no effect if-mfpmath=sseor-mfpmath=sse+387is specified; in the former case, IEEE semantics apply without excess precision, and in the latter, rounding is unpredictable. ๐
-ffast-mathโ sets the options-fno-math-errno,-funsafe-math-optimizations,-ffinite-math-only,-fno-rounding-math,-fno-signaling-nans,-fcx-limited-rangeand-fexcess-precision=fast. It's giving "turn off all the safety rails, we ball." ๐ฅ
This option causes the preprocessor macro "__FAST_MATH__" to be defined.
This option is not turned on by any -O option besides -Ofast, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of these specifications. So like, speed vs. correctness, pick your fighter. โ๏ธ
-fno-math-errnoโ do not set"errno"after calling math functions that are executed with a single instruction, e.g.,"sqrt". A program that relies on IEEE exceptions for math error handling may want to use this flag for speed while maintaining IEEE arithmetic compatibility.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of these specifications.
The default is -fmath-errno.
On Darwin systems, the math library never sets "errno". So there's genuinely no reason for the compiler to consider the possibility that it might, and -fno-math-errno is the default there. ๐
-funsafe-math-optimizationsโ allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link time, it may include libraries or startup files that change the default FPU control word or other similar optimizations. Yeah. Unsafe is literally in the name bestie. ๐
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of these specifications. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.
The default is -fno-unsafe-math-optimizations.
-fassociative-mathโ allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing the computation result. ๐จ
NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like "(x + 2**52) - 2**52"). May also reorder floating-point comparisons and thus may not be used when ordered comparisons are required.
This option requires that both -fno-signed-zeros and -fno-trapping-math be in effect. Moreover, it doesn't make much sense with -frounding-math. For Fortran the option is automatically enabled when both -fno-signed-zeros and -fno-trapping-math are in effect.
The default is -fno-associative-math.
-freciprocal-mathโ allow the reciprocal of a value to be used instead of dividing by the value, if this enables optimizations. For example"x / y"can be replaced with"x * (1/y)", which is useful if"(1/y)"is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value. ๐ฌ
The default is -fno-reciprocal-math.
-ffinite-math-onlyโ allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs. Like, imagine infinities just don't exist. Manifesting. โจ
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of these specifications.
The default is -fno-finite-math-only.
-fno-signed-zerosโ allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct+0.0and-0.0values, which then prohibits simplification of expressions such asx+0.0or0.0*x(even with-ffinite-math-only). This option implies that the sign of a zero result isn't significant. ๐
The default is -fsigned-zeros.
-fno-trapping-mathโ compile code assuming that floating-point operations cannot generate user-visible traps. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that-fno-signaling-nansbe in effect. Setting this option may allow faster code if one relies on "non-stop" IEEE arithmetic, for example.
This option should never be turned on by any -O option, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. Big yikes territory. ๐ญ
The default is -ftrapping-math.
Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used along with -frounding-math to specify the default state for "FENV_ACCESS". ๐ฎ
-frounding-mathโ disable transformations and optimizations that assume default floating-point rounding behavior. This is round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. This option should be specified for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. This option disables constant folding of floating-point expressions at compile time (which may be affected by rounding mode) and arithmetic transformations that are unsafe in the presence of sign-dependent rounding modes. ๐ง
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. ๐ณ
Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used along with -ftrapping-math to specify the default state for "FENV_ACCESS". ๐
-fsignaling-nansโ compile your code assuming that IEEE signaling NaNs are out here potentially generating user-visible traps during floating-point operations. Flipping this on disables the optimizations that could change how many exceptions you actually see with signaling NaNs, and it implies-ftrapping-math. โจ
It also makes the preprocessor macro __SUPPORT_SNAN__ get defined. ๐
Default? -fno-signaling-nans, bestie.
โ ๏ธ Heads up: this option is experimental, and it does not currently guarantee that it disables every single GCC optimization that messes with signaling NaN behavior. So likeโฆ proceed with awareness. ๐ญ
-fno-fp-int-builtin-inexactโ don't let the built-in functionsceil,floor,round, andtrunc(plus theirfloatandlong doublevariants) generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 do let these functions raise thatinexactexception, but ISO/IEC TS 18661-1:2014 โ the C bindings to IEEE 754-2008, as integrated into ISO C2X โ does not allow them to do so. ๐
The default is -ffp-int-builtin-inexact, which lets the exception be raised โ unless C2X or a later C standard is selected. And honestly? This option does absolutely nothing unless -ftrapping-math is in effect. ๐
Even if you use -fno-fp-int-builtin-inexact, if those functions generate a call to a library function then the inexact exception may still get raised, in the case where the library implementation doesn't follow TS 18661. ๐ธ
-fsingle-precision-constantโ treat floating-point constants as single precision instead of quietly converting them into double-precision constants. ๐ฆ-fcx-limited-rangeโ when enabled, this option states that a range reduction step is not needed when doing complex division. Also, there is no checking whether the result of a complex multiplication or division isNaN + I*NaNwith an attempt to rescue the situation in that case. ๐ฎโ๐จ The default is-fno-cx-limited-range, but it gets enabled by-ffast-math.
This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. Nevertheless, the option applies to all languages. iykyk. โจ
-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. ๐
The default is -fno-cx-fortran-rules.
The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code. ๐ (Yes, broken. That's not me being dramatic, that's the manpage.)
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilitiesto improve optimizations based on how many times each branch was taken. When a program compiled with-fprofile-arcsexits, it saves arc execution counts to a file calledsourcename.gcdafor each source file. ๐ The info in that data file is very dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations. See the details about file naming under-fprofile-arcs.
With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently they're only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often. ๐ฅ
Enabled by -fprofile-use and -fauto-profile.
-fprofile-valuesโ if you combine it with-fprofile-arcs, it adds code so that some data about values of expressions in the program gets gathered. ๐ซถ
With -fbranch-probabilities, it reads back the data gathered from profiling values of expressions, for usage in optimizations.
Enabled by -fprofile-generate, -fprofile-use, and -fauto-profile.
-fprofile-reorder-functionsโ function reordering based on profile instrumentation collects the first time of execution of a function and orders these functions in ascending order. โญ
Enabled with -fprofile-use.
-fvptโ if combined with-fprofile-arcs, this option tells the compiler to add code that gathers information about values of expressions.
With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator. ๐
Enabled with -fprofile-use and -fauto-profile.
-frename-registersโ try to avoid false dependencies in scheduled code by making use of registers left over after register allocation. This optimization most benefits processors with lots of registers. Depending on the debug information format adopted by the target, though, it can make debugging impossible, since variables no longer stay in a "home register". ๐
Enabled by default with -funroll-loops.
-fschedule-fusionโ performs a target dependent pass over the instruction stream to schedule instructions of the same type together, because the target machine can execute them more efficiently if they're adjacent to each other in the instruction flow. ๐
Enabled at levels -O2, -O3, -Os.
-ftracerโ perform tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, allowing other optimizations to do a better job. โจ
Enabled by -fprofile-use and -fauto-profile.
-funroll-loopsโ unroll loops whose number of iterations can be determined at compile time or upon entry to the loop.-funroll-loopsimplies-frerun-cse-after-loop,-fweband-frename-registers. It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). This option makes code larger, and may or may not make it run faster. ๐ข
Enabled by -fprofile-use and -fauto-profile.
-funroll-all-loopsโ unroll all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. ๐ฌ-funroll-all-loopsimplies the same options as-funroll-loops.-fpeel-loopsโ peels loops for which there's enough information that they don't roll much (from profile feedback or static analysis). It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). ๐
Enabled by -O3, -fprofile-use, and -fauto-profile.
-fmove-loop-invariantsโ enables the loop invariant motion pass in the RTL loop optimizer. Enabled at level-O1and higher, except for-Og. ๐-fmove-loop-storesโ enables the loop store motion pass in the GIMPLE loop optimizer. This moves invariant stores to after the end of the loop, in exchange for carrying the stored value in a register across the iteration. Note: for this option to have an effect,-ftree-loop-imhas to be enabled as well. Enabled at level-O1and higher, except for-Og.-fsplit-loopsโ split a loop into two if it contains a condition that's always true for one side of the iteration space and false for the other. โ๏ธ
Enabled by -fprofile-use and -fauto-profile.
-funswitch-loopsโ move branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (modified according to the result of the condition).
Enabled by -fprofile-use and -fauto-profile.
-fversion-loops-for-stridesโ if a loop iterates over an array with a variable stride, create another version of the loop that assumes the stride is always one. Like, for example:
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
becomes:
if (stride == 1)
for (int i = 0; i < n; ++i)
x[i] = ...;
else
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
This is especially useful for assumed-shape arrays in Fortran, where (for example) it allows better vectorization assuming contiguous accesses. ๐ฆ This flag is enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile.
-ffunction-sections,-fdata-sectionsโ place each function or data item into its own section in the output file, if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file. ๐ท๏ธ
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.
Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping). ๐๏ธ
On ELF/DWARF systems these options do not degenerate the quality of the debug information. There could be issues with other object files/debug info formats.
Only use these options when there are significant benefits from doing so! When you specify these options, the assembler and linker create larger object and executable files and are also slower. ๐ These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit, since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions.
-fstdarg-optโ optimize the prologue of variadic argument functions with respect to usage of those arguments. โจ-fsection-anchorsโ try to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to reduce the number of GOT entries and GOT accesses on some targets. โ
For example, the implementation of the following function foo:
static int a, b, c;
int foo (void) { return a + b + c; }
... usually works out the addresses of all three variables, but if you hit it with -fsection-anchors, it grabs them from one common anchor point instead โจ The effect is basically this lil pseudocode situation (and no, it is not valid C, don't come for me):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
Not all targets support this option, bestie. Some of them just said "no ๐ ".
-fzero-call-used-regs=choiceโ zeroes out call-used registers when a function returns, which levels up your program's security by either mitigating Return-Oriented Programming (ROP) attacks or stopping info from leaking out through the registers ๐ก๏ธ
The possible values of choice are the exact same ones as for the zero_call_used_regs attribute. The default is skip. ๐ซถ
You can control this behavior for one specific function by using the function attribute zero_call_used_regs.
--param name=valueโ okay so GCC be using a whole bunch of constants to control how much optimization happens. Like, GCC won't inline functions that have more than a certain number of instructions, that kind of thing. You can control some of these constants right from the command line with the--paramoption ๐ฅ
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases. So don't get too attached, girl ๐
To get the minimal, maximal and default values of a parameter, use the --help=param -Q options.
In each case, the value is an integer. The following choices of name are recognized for all targets:
predictable-branch-outcomeโ when a branch is predicted to be taken with a probability lower than this threshold (in percent), then it counts as well predictable.max-rtl-if-conversion-insnsโ RTL if-conversion tries to yeet the conditional branches around a block and replace them with conditionally executed instructions instead. This parameter gives the maximum number of instructions in a block that should even be considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable, so it's not the only factor bestie.max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove conditional branches around a block and swap in conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that if-conversion would generate, depending on whether the branch is statically determined to be predictable or not. The units for this parameter are the same as those for the GCC internalseq_costmetric. The compiler will try to provide a reasonable default for this parameter using theBRANCH_COSTtarget macro.max-crossjump-edgesโ the maximum number of incoming edges to consider for cross-jumping. The algorithm used by-fcrossjumpingis O(N^2) in the number of edges incoming to each block. Increasing values mean more aggressive optimization, so compilation time goes up with probably only a small improvement in executable size. It's giving "slightly slimmer, much slower" ngl.min-crossjump-insnsโ the minimum number of instructions that must be matched at the end of two blocks before cross-jumping gets performed on them. This value is ignored in the case where all instructions in the block being cross-jumped from are matched.max-grow-copy-bb-insnsโ the maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.max-goto-duplication-insnsโ the maximum number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behavior in a number of passes, GCC factors computed gotos early in the compilation process, and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more than max-goto-duplication-insns are unfactored. โจmax-delay-slot-insn-searchโ the maximum number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions get searched, the time savings from filling the delay slot are minimal, so stop searching. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in execution time.max-delay-slot-live-searchโ when trying to fill delay slots, the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, and it increases compilation time. This parameter should be removed when the delay slot code is rewritten to maintain the control-flow graph. (Not me โ โ that's just what the docs say, fr fr.)max-gcse-memoryโ the approximate maximum amount of memory inkBthat can be allocated in order to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization is just not done. Sorry babe ๐max-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream.max-pending-list-lengthโ the maximum number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources. Iconic waste honestly ๐max-modulo-backtrack-attemptsโ the maximum number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time. Exponentially!! bestie be careful ๐ญmax-inline-functions-called-once-loop-depthโ maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once.max-inline-functions-called-once-insnsโ maximal estimated size of functions produced while inlining functions called once.max-inline-insns-singleโ so several parameters control the tree inliner used in GCC, and this number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++).max-inline-insns-autoโ when you use-finline-functions(which is included in-O3), a lot of functions that would otherwise not be considered for inlining by the compiler get investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto).max-inline-insns-smallโ this is the bound applied to calls which are considered relevant with-finline-small-functions.max-inline-insns-sizeโ this is the bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization opportunities exposed by inlining.uninlined-function-insnsโ number of instructions accounted by the inliner for function overhead such as function prologue and epilogue.uninlined-function-timeโ extra time accounted by the inliner for function overhead such as the time needed to execute the function prologue and epilogue.inline-heuristics-hint-percentโ the scale (in percents) applied to inline-insns-single, inline-insns-single-O2, inline-insns-auto when inline heuristics hints that inlining is very profitable (aka it will enable later optimizations). Slay.uninlined-thunk-insnsuninlined-thunk-timeโ same as--param uninlined-function-insnsand--param uninlined-function-timebut applied to function thunks.inline-min-speedupโ when the estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on--param max-inline-insns-singleand--param max-inline-insns-auto. Rules were made to be broken ๐large-function-insnsโ the limit specifying really large functions. For functions larger than this limit after inlining, inlining is constrained by--param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by non-linear algorithms used by the back end.large-function-growthโ specifies maximal growth of a large function caused by inlining, in percents. For example, parameter value 100 limits large function growth to 2.0 times the original size.large-unit-insnsโ the limit specifying a large translation unit. Growth caused by inlining of units larger than this limit is limited by--param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of function A that is inline and B that just calls A three times. If B is small relative to A, the growth of the unit is 300% and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. Thus for smaller units, the size is increased to--param large-unit-insnsbefore applying--param inline-unit-growth.lazy-modulesโ maximum number of concurrently open C++ module files when lazy loading.inline-unit-growthโ specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value 20 limits unit growth to 1.2 times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size. Besties stay chilly ๐งipa-cp-unit-growthโ specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value 10 limits unit growth to 1.1 times the original size.
ipa-cp-large-unit-insnsโ the size of a translation unit that the IPA-CP pass is gonna look at and go "okay that one's large". ๐large-stack-frameโ the limit that defines what counts as a large stack frame. While it's inlining, the algorithm is literally trying its best not to blow past this limit too hard. ๐ซถlarge-stack-frame-growthโ the max growth of large stack frames that inlining is allowed to cause, in percent. Say you set it to1000โ that caps large stack frame growth at 11 times the original size. no cap. ๐ฅmax-inline-insns-recursive,max-inline-insns-recursive-autoโ the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by doing recursive inlining.
--param max-inline-insns-recursive applies to functions declared inline. For functions that are not declared inline, recursive inlining only happens when -finline-functions (which is included in -O3) is enabled โ and then --param max-inline-insns-recursive-auto applies instead. bestie it's a whole switch-up. ๐ฆ
max-inline-recursive-depth,max-inline-recursive-depth-autoโ the maximum recursion depth used for recursive inlining.
Same deal: --param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining only happens when -finline-functions (included in -O3) is enabled, and --param max-inline-recursive-depth-auto applies instead. ๐ซ
min-inline-recursive-probabilityโ recursive inlining is only profitable for functions with deep recursion on average, and it can actually hurt functions with shallow recursion depth โ it bloats the prologue size or makes the function body more complex for all the other optimizers. ๐ญ
When profile feedback is available (see -fprofile-generate), the actual recursion depth can be guessed from the probability that a function recurses through a given call expression. This parameter limits inlining to only those call expressions whose probability exceeds the given threshold (in percent).
early-inlining-insnsโ specify the growth the early inliner is allowed to make. Effectively, it increases how much inlining happens for code carrying a big abstraction penalty. โจmax-early-inliner-iterationsโ the iteration limit of the early inliner. Basically it bounds how many nested indirect calls the early inliner can resolve. Deeper chains still get handled by late inlining, so don't stress. ๐งcomdat-sharing-probabilityโ the probability (in percent) that a C++ inline function with comdat visibility gets shared across multiple compilation units. ๐modref-max-bases,modref-max-refs,modref-max-accessesโ the maximum number of base pointers, references and accesses that mod/ref analysis will store for a single function.modref-max-testsโ the maximum number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter should be bigger than--param modref-max-basesand--param modref-max-refs, periodt.modref-max-depthโ the maximum depth of the DFS walk used by modref escape analysis. Setting it to0disables the analysis completely. ๐modref-max-escape-pointsโ the maximum number of escape points that modref tracks per SSA-name.modref-max-adjustmentsโ the maximum number of times the access range gets enlarged during modref dataflow analysis.profile-func-internal-idโ a parameter controlling whether to use function internal id in profile database lookup. If the value is0, the compiler uses an id based on function assembler name and filename, which makes old profile data more tolerant to source changes like function reordering and such. ๐min-vect-loop-boundโ the minimum number of iterations below which loops are not vectorized when-ftree-vectorizeis used. The number of iterations after vectorization has to be greater than the value specified by this option to allow vectorization.gcse-cost-distance-ratioโ the scaling factor used when calculating the maximum distance an expression can be moved by GCSE optimizations. This is currently supported only in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting gets with simple expressions โ meaning the expressions whose cost is less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions. ๐gcse-unrestricted-costโ the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations stop constraining the distance an expression can travel. This is currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting gets. Specifying0lets all expressions travel unrestricted distances. โ๏ธmax-hoist-depthโ the depth of the search in the dominator tree for expressions to hoist. This exists to avoid quadratic behavior in the hoisting algorithm. A value of0doesn't limit the search at all, but heads up: it may slow down compilation of huge functions. ๐max-tail-merge-comparisonsโ the maximum number of similar bbs to compare a bb with. This is here to avoid quadratic behavior in tree tail merging.max-tail-merge-iterationsโ the maximum number of iterations of the pass over the function. This limits compilation time in tree tail merging. โณstore-merging-allow-unalignedโ allow the store merging pass to introduce unaligned stores, if it's legal to do so.max-stores-to-mergeโ the maximum number of stores to attempt to merge into wider stores in the store merging pass.max-store-chains-to-trackโ the maximum number of store chains to track at the same time while trying to merge them into wider stores in the store merging pass. ๐max-stores-to-trackโ the maximum number of stores to track at the same time while trying to merge them into wider stores in the store merging pass.max-unrolled-insnsโ the maximum number of instructions a loop may have for it to be unrolled. And if a loop does get unrolled, this parameter also decides how many times the loop code gets unrolled. ๐max-average-unrolled-insnsโ the maximum number of instructions, biased by the probabilities of their execution, that a loop may have for it to be unrolled. If a loop is unrolled, this parameter also decides how many times the loop code gets unrolled.max-unroll-timesโ the maximum number of unrollings of a single loop.max-peeled-insnsโ the maximum number of instructions a loop may have for it to be peeled. If a loop is peeled, this parameter also decides how many times the loop code gets peeled. ๐max-peel-timesโ the maximum number of peelings of a single loop.max-peel-branchesโ the maximum number of branches on the hot path through the peeled sequence.max-completely-peeled-insnsโ the maximum number of insns of a completely peeled loop.max-completely-peel-timesโ the maximum number of iterations of a loop for it to be suitable for complete peeling.max-completely-peel-loop-nest-depthโ the maximum depth of a loop nest suitable for complete peeling.max-unswitch-insnsโ the maximum number of insns of an unswitched loop.max-unswitch-depthโ the maximum depth of a loop nest to be unswitched.lim-expensiveโ the minimum cost of an expensive expression in loop invariant motion. ๐ธmin-loop-cond-split-probโ when FDO profile information is available,min-loop-cond-split-probspecifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split.iv-consider-all-candidates-boundโ the bound on the number of candidates for induction variables, below which all candidates are considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones get considered โ all to avoid quadratic time complexity. ๐iv-max-considered-usesโ the induction variable optimizations give up on loops that contain more induction variable uses than this.iv-always-prune-cand-set-boundโ if the number of candidates in the set is smaller than this value, always try to remove unnecessary ivs from the set when adding a new one. ๐งนavg-loop-niterโ the average number of iterations of a loop.dse-max-object-sizeโ the maximum size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times. โฐdse-max-alias-queries-per-storeโ the maximum number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores.scev-max-expr-sizeโ a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down. ๐ขscev-max-expr-complexityโ a bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down.max-tree-if-conversion-phi-argsโ the maximum number of arguments in a PHI that TREE if conversion will support, unless the loop is marked with thesimdpragma.vect-max-layout-candidatesโ the maximum number of possible vector layouts (think permutations) to consider when optimizing to-be-vectorized code.vect-max-version-for-alignment-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer.vect-max-version-for-alias-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer.vect-max-peeling-for-alignmentโ the maximum number of loop peels to enhance access alignment for the vectorizer. A value of-1means no limit. ๐max-iterations-to-trackโ bestie, this is the cap on how many iterations of a loop the brute-force algorithm (the one analyzing loop iteration counts) will actually sit there and try to evaluate. ๐ธhot-bb-count-fractionโ the denominator n of the fraction 1/n ๐ . A basic block only counts as "hot" if its execution count is at least 1/n of the biggest execution count any basic block in the whole program got. Default is10000, so a block is hot if its exec count beats 1/10000 of that max. Set it to0and nothing is ever considered hot. This one's for non-LTO mode.hot-bb-count-ws-permilleโ okay so, the number of most-executed permilles (0 to 1000, yes permille not percent, we're fancy) of the profiled execution of the entire program that a basic block's execution count has to fall inside to be called hot. Default990โ a block is hot if its count lands in the top 990 permilles, aka 99.0%, of the profiled execution of the whole program.0means never hot, periodt. This one's for LTO mode. โจhot-bb-frequency-fractionโ the denominator n of fraction 1/n of the entry block's execution frequency ๐. A basic block of a function needs to be executed at least 1/n as often as the function's entry block to be considered hot. Default is1000, so a block is hot in a function if it runs more frequently than 1/1000 of the entry block's frequency.0= never considered hot. No cap.unlikely-bb-count-fractionโ the denominator n of fraction 1/n of the number of profiled runs of the entire program, and a basic block's execution count has to be below that line to be considered "unlikely executed." Default is20, so a block is unlikely-executed if it runs in fewer than 1/20, or 5%, of the program's runs. And0? That means it's always considered unlikely executed. ๐max-predicted-iterationsโ the max number of loop iterations we predict statically. This slaps when a function has one loop with a known bound and another loop with an unknown bound: the known one gets predicted correctly, while the unknown one averages out to roughly10. Which means the loop without bounds ends up looking artificially cold next to its sibling. ๐ฅถbuiltin-expect-probabilityโ controls the probability of the expression having the specified value. Takes a percentage (i.e.0 ... 100) as input. ๐ฏbuiltin-string-cmp-inline-lengthโ the maximum length of a constant string for a builtin string cmp call to be eligible for inlining. ๐align-thresholdโ picks the fraction of the maximal execution frequency of a basic block in a function that's needed to align that basic block.align-loop-iterationsโ a loop that's expected to iterate at least the selected number of iterations gets aligned. โญtracer-dynamic-coverage,tracer-dynamic-coverage-feedbackโ this value limits superblock formation once the given percentage of executed instructions is covered. Basically it stops unnecessary code size expansion, thank u next. โ Thetracer-dynamic-coverage-feedbackparam is only used when profile feedback is available, because real profiles (as opposed to statically estimated ones) are way less balanced, which lets the threshold be a larger value. ๐tracer-max-code-growthโ stops tail duplication once code growth hits the given percentage. Kinda artificial as a limit ngl, since most of the duplicates get eliminated later during cross jumping, so you can set it way higher than the actual code growth you want. ๐tracer-min-branch-ratioโ stops reverse growth when the reverse probability of the best edge drops below this threshold (in percent).tracer-min-branch-probability,tracer-min-branch-probability-feedbackโ stops forward growth if the best edge's probability is lower than this threshold. Same deal astracer-dynamic-coverage: two params, one for each mode.tracer-min-branch-probability-feedbackis for compilation with profile feedback, andtracer-min-branch-probabilityis for compilation without. Heads up: for profile feedback compilation the value needs to be more conservative (higher) for the tracer to actually be effective. ๐stack-clash-protection-guard-sizeโ specifies the size of the operating system provided stack guard as 2 raised to num bytes. Higher values may reduce the number of explicit probes, BUT a value larger than the operating system provided guard will leave your code vulnerable to stack clash style attacks. So likeโฆ don't. ๐stack-clash-protection-probe-intervalโ stack clash protection means probing stack space as it gets allocated. This param controls the maximum distance between probes into the stack, as 2 raised to num bytes. Higher values may reduce the number of explicit probes, but again โ a value larger than the operating system provided guard leaves code vulnerable to stack clash style attacks. Same warning, same energy. ๐จmax-cse-path-lengthโ the maximum number of basic blocks on a path that CSE considers.max-cse-insnsโ the maximum number of instructions CSE processes before it flushes. ๐ฝggc-min-expandโ okay so GCC uses a garbage collector to manage its own memory allocation, and this parameter is the minimum percentage by which the GC's heap is allowed to expand between collections. Tuning it may improve compilation speed; it has no effect on code generation. The default is30% + 70% * (RAM/1GB)with an upper bound of100%whenRAM >= 1GB. Ifgetrlimitis available, the notion of "RAM" is the smallest of actual RAM andRLIMIT_DATAorRLIMIT_AS. If GCC can't calculate RAM on a particular platform, the lower bound of30%is used. And setting this parameter andggc-min-heapsizeto zero causes a full collection to occur at every opportunity โ extremely slow, but can be useful for debugging. ๐ggc-min-heapsizeโ minimum size of the garbage collector's heap before it starts bothering to collect garbage. The first collection happens after the heap expands byggc-min-expand%beyondggc-min-heapsize. Again, tuning this may improve compilation speed, and it has no effect on code generation. The default is the smaller ofRAM/8,RLIMIT_RSS, or a limit that tries to make sureRLIMIT_DATAorRLIMIT_ASaren't exceeded โ with a lower bound of4096(four megabytes) and an upper bound of131072(128 megabytes). If GCC can't calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection, and setting it plusggc-min-expandto zero causes a full collection to occur at every opportunity. Iconic debugging move. ๐max-reload-search-insnsโ the maximum number of instructions reload should look backward for an equivalent register. Increasing values mean more aggressive optimization, which pumps up compilation time, probably for slightly better performance. โจmax-cselib-memory-locationsโ the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making compilation time go up with probably slightly better performance.max-sched-ready-insnsโ the maximum number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass. Increasing values mean more thorough searches, making compilation time increase with probably little benefit. ๐ญmax-sched-region-blocksโ the maximum number of blocks in a region to be considered for interblock scheduling.max-pipeline-region-blocksโ the maximum number of blocks in a region to be considered for pipelining in the selective scheduler.max-sched-region-insnsโ the maximum number of insns in a region to be considered for interblock scheduling.max-pipeline-region-insnsโ the maximum number of insns in a region to be considered for pipelining in the selective scheduler.min-spec-probโ the minimum probability (in percents) of reaching a source block for interblock speculative scheduling.max-sched-extend-regions-itersโ the maximum number of iterations through CFG to extend regions. A value of0disables region extensions entirely. ๐max-sched-insn-conflict-delayโ the maximum conflict delay for an insn to be considered for speculative motion.sched-spec-prob-cutoffโ the minimal probability of speculation success (in percents) so that speculative insns get scheduled.sched-state-edge-prob-cutoffโ the minimum probability an edge must have for the scheduler to save its state across it.sched-mem-true-dep-costโ minimal distance (in CPU cycles) between a store and a load targeting the same memory locations.selsched-max-lookaheadโ the maximum size of the lookahead window of selective scheduling. It's a depth of search for available instructions. ๐selsched-max-sched-timesโ the maximum number of times an instruction is scheduled during selective scheduling. It's the limit on the number of iterations through which the instruction may be pipelined.selsched-insns-to-renameโ the maximum number of best instructions in the ready list that get considered for renaming in the selective scheduler. ๐sms-min-scโ the minimum value of stage count that swing modulo scheduler generates. ๐ฆ
๐ max-last-value-rtl
The biggest size โ measured as a count of RTLs โจ โ that can be stashed in an expression in the combiner for a pseudo register playing the role of that register's last known value. That's literally it bestie.
๐
max-combine-insns
The max number of instructions the RTL combiner will even attempt to combine. Like, it's got a limit and it respects it. Periodt.
๐ integer-share-limit
Small integer constants can share a data structure (so cute, so communal ๐), which cuts down the compiler's memory usage and makes it faster. This one sets the maximum value of a shared integer constant.
๐ฆ ssp-buffer-size
The minimum size of buffers (i.e. arrays) that get stack smashing protection when -fstack-protector is on.
Heads up: this default was"8"before Ubuntu 10.10. Right now it's"4", which bumps up the number of functions protected by the stack protector. ๐
๐ธ min-size-for-stack-sharing
The minimum size of variables that get to take part in stack slot sharing when you're not optimizing. No optimization, no big sharing energy.
โญ max-jump-thread-duplication-stmts
Max number of statements allowed in a block that needs to be duplicated when threading jumps. That's the ceiling, girlie.
๐ง max-jump-thread-paths
The max number of paths to consider when hunting for jump threading opportunities. Here's the tea โ: when you arrive at a block, incoming edges are only considered if the number of paths to be searched so far multiplied by the number of incoming edges does not exhaust the specified maximum number of paths to consider.
๐ max-fields-for-field-sensitive
Max number of fields in a structure that get treated in a field sensitive manner during pointer analysis. Structure said "I'm sensitive" and the analyzer said "okay noted."
๐ฅ prefetch-latency
An estimate of, on average, how many instructions get executed before the prefetch finishes. The distance prefetched ahead is proportional to this constant. Ramping this number up may also lead to fewer streams being prefetched (go peek at simultaneous-prefetches).
๐ simultaneous-prefetches
Max number of prefetches that can be running at the same time. Multitasking icon behavior.
๐ l1-cache-line-size
The size of a cache line in L1 data cache, in bytes.
โจ l1-cache-size
The size of L1 data cache, in kilobytes.
โจ l2-cache-size
The size of L2 data cache, in kilobytes. (Yes bestie, same unit energy as L1.)
๐ซถ prefetch-dynamic-strides
Should the loop array prefetch pass drop software prefetch hints for strides that are non-constant? Sometimes that's genuinely beneficial โ though the fact that the stride is non-constant may make it hard to predict when there's a clear benefit to issuing these hints. ๐ฅฒ
- Set it to
1if prefetch hints should be issued for non-constant strides. - Set it to
0if prefetch hints should be issued only for strides that are known to be constant and belowprefetch-minimum-stride.
๐ prefetch-minimum-stride
The minimum constant stride, in bytes, to start using prefetch hints for. If the stride is less than this threshold, prefetch hints will not be issued. Simple as that.
This setting slays for processors that have hardware prefetchers, because in that case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a max stride they can handle, you should use it here to improve how the software prefetchers get used.
A value of -1 means we don't have a threshold, and therefore prefetch hints can be issued for any constant stride.
Ngl, this setting is only useful for strides that are known and constant. No guessing games.
๐ destructive-interference-size / constructive-interference-size
These two are the values for the C++17 variables std::hardware_destructive_interference_size and std::hardware_constructive_interference_size. ๐ฏ
- The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects.
- The constructive interference size is the maximum recommended size of contiguous memory accessed together.
Typically both of them will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.
The destructive interference size is intended to be used for layout, and thus it has ABI impact. ๐ญ The default value is not expected to be stable, and on some targets it varies with -mtune โ so using this variable in a context where ABI stability is important, like the public interface of a library, is strongly discouraged. If you do use it in that context, users can stabilize the value using this option.
The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure that a type fits within a cache line. ๐
See also -Winterference-size.
๐ loop-interchange-max-num-stmts
The maximum number of stmts in a loop to be interchanged. Cap it, bestie.
๐ง loop-interchange-stride-ratio
The minimum ratio between the strides of two loops for an interchange to even be profitable. If it ain't worth it, we don't do it. โ
๐ min-insn-to-prefetch-ratio
The minimum ratio between the number of instructions and the number of prefetches needed to enable prefetching in a loop.
๐ prefetch-min-insn-to-mem-ratio
The minimum ratio between the number of instructions and the number of memory references needed to enable prefetching in a loop. Sibling energy with the one above.
๐ธ use-canonical-types
Should the compiler use the "canonical" type system? It should always be 1 โ that's the version that uses a more efficient internal mechanism for comparing types in C++ and Objective-C++.
But if bugs in the canonical type system are causing compilation failures, set this value to 0 to disable canonical types. Emergency mode activated. ๐จ
โญ switch-conversion-max-branch-ratio
Switch initialization conversion refuses to create arrays that are bigger than switch-conversion-max-branch-ratio times the number of branches in the switch. That's the rule and it's not negotiating.
๐ฅ max-partial-antic-length
Maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at -O3 and above.
Okay this one matters: for some sorts of source code, the enhanced partial redundancy elimination optimization can run away, consuming all of the memory available on the host machine. ๐ This parameter sets a limit on the length of the sets that are computed, which prevents that runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length โ so like, you've been warned.
๐ rpo-vn-max-loop-depth
Maximum loop depth that gets value-numbered optimistically. When the limit hits, the innermost rpo-vn-max-loop-depth loops and the outermost loop in the loop nest are value-numbered optimistically, and the remaining ones are not. Iconic selective behavior honestly.
๐ sccvn-max-alias-queries-per-access
Maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and that load or store is not considered redundant.
Fun fact: the number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry. โจ
๐ ira-max-loops-num
IRA uses regional register allocation by default. If a function contains more loops than the number given by this parameter, only at most the given number of the most frequently-executed loops form regions for regional register allocation. Only the popular loops get the spotlight. ๐
๐ซถ ira-max-conflict-table-size
Even though IRA uses a sophisticated algorithm to compress the conflict table, the table can still require excessive amounts of memory for huge functions. ๐ญ If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that does not require building a pseudo-register conflict table. Trade-offs, bestie!
๐ ira-loop-reserved-regs
IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (see -O3). The number of available registers reserved for some other purposes is given by this parameter. The default of the parameter is the best one found from numerous experiments. Science! ๐ฌ
โจ ira-consider-dup-in-all-alts
Makes IRA consider the matching constraint (duplicated operand number) heavily in all available alternatives for the preferred register class.
- If it's set as
zero, it means IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. - Otherwise, it means IRA will check all available alternatives for the preferred register class, even if it has already found some choice with an appropriate register class, and respect the found qualified matching constraint.
๐ ira-simple-lra-insn-threshold
Approximate function insn number in 1K units triggering simple local RA. Approximate is the key word here, she's estimating. ๐
๐ lra-inheritance-ebb-probability-cutoff
LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance (so cute, passing things down ๐ฅน). EBB is used as the region to do this optimization. The parameter defines a minimal fall-through edge probability, in percentage, used to add a BB to the inheritance EBB in LRA.
The default value was chosen from numerous runs of SPEC2000 on x86-64. Very researched, very slay.
๐ง loop-invariant-max-bbs-in-loop
Loop invariant motion can be very expensive โ both in compilation time and in the amount of needed compile-time memory โ with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them. Sorry girl, too big, no motion for you. ๐
๐ loop-max-datarefs-for-datadeps
Building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that are considered for data dependence analysis. These large loops are not handled by the optimizations that use loop data dependencies. Big loops, big feelings, no datadeps. ๐
max-vartrack-sizeโ okay bestie, this sets a maximum number of hash table slots to use during variable tracking dataflow analysis of any function. If this limit is exceeded with variable tracking at assignments enabled, analysis for that function is retried without it, after removing all debug insns from the function. If the limit is exceeded even without debug insns, var tracking analysis is completely disabled for the function. Setting the parameter to zero makes it unlimited. ๐max-vartrack-expr-depthโ this one sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. It's literally trading compilation time for more complete debug information. If you set it too low, value expressions that are available and could be represented in debug information may end up not being used; setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow. ๐max-debug-marker-countโ sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, such stmts will be dropped from the inlined copy of a function, and from its RTL expansion. ๐min-nondebug-insn-uidโ use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by-fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted. โจipa-sra-deref-prob-thresholdโ IPA-SRA replaces a pointer which is known not be NULL with one or more new parameters only when the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter. ๐ipa-sra-ptr-growth-factorโ IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter. ๐ธipa-sra-ptrwrap-growth-factorโ additional maximum allowed growth of total size of new parameters that ipa-sra replaces a pointer to an aggregate with, if it points to a local variable that the caller only writes to and passes it as an argument to other functions. ๐ipa-sra-max-replacementsโ maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it is also the maximum number of replacements of a formal parameter. ๐ฆsra-max-scalarization-size-Ospeed,sra-max-scalarization-size-Osizeโ the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively. โกsra-max-propagationsโ the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation. ๐tm-max-aggregate-sizeโ when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. This option only applies when using-fgnu-tm. ๐พgraphite-max-nb-scop-paramsโ to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. A variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP. ๐loop-block-tile-sizeโ loop blocking or strip mining transforms, enabled with-floop-blockor-floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using theloop-block-tile-sizeparameter. ๐งฑipa-jump-function-lookupsโ specifies number of statements visited during jump function offset discovery. ๐ต๏ธipa-cp-value-list-sizeโ IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization.ipa-cp-value-list-sizeis the maximum number of values and types it stores per one formal parameter of a function. ๐ipa-cp-eval-thresholdโ IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceedipa-cp-eval-threshold. ๐ฏipa-cp-max-recursive-depthโ maximum depth of recursive cloning for self-recursive function. ๐ipa-cp-min-recursive-probabilityโ recursive cloning only when the probability of call being executed exceeds the parameter. ๐ฒipa-cp-profile-count-baseโ when using-fprofile-useoption, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation. ๐ipa-cp-recursive-freq-factorโ the number of times interprocedural copy propagation expects recursive functions to call themselves. โป๏ธipa-cp-recursion-penaltyโ percentage penalty the recursive functions will receive when they are evaluated for cloning. ๐ipa-cp-single-call-penaltyโ percentage penalty functions containing a single call to another function will receive when they are evaluated for cloning. ๐ipa-max-agg-itemsโ IPA-CP is also capable to propagate a number of scalar values passed in an aggregate.ipa-max-agg-itemscontrols the maximum number of such values per one parameter. ๐ฆipa-cp-loop-hint-bonusโ when IPA-CP determines that a cloning candidate would make the number of iterations of a loop known, it adds a bonus ofipa-cp-loop-hint-bonusto the profitability score of the candidate. ๐ipa-max-loop-predicatesโ the maximum number of different predicates IPA will use to describe when loops in a function have known properties. ๐ipa-max-aa-stepsโ during its analysis of function bodies, IPA-CP employs alias analysis in order to track values pointed to by function parameters. In order not spend too much time analyzing huge functions, it gives up and consider all memory clobbered after examiningipa-max-aa-stepsstatements modifying memory. ๐ipa-max-switch-predicate-boundsโ maximal number of boundary endpoints of case ranges of switch statement. For switch exceeding this limit, IPA-CP will not construct cloning cost predicate, which is used to estimate cloning benefit, for default case of the switch statement. ๐ipa-max-param-expr-opsโ IPA-CP will analyze conditional statement that references some function parameter to estimate benefit for cloning upon certain constant value. But if number of operations in a parameter expression exceedsipa-max-param-expr-ops, the expression is treated as complicated one, and is not handled by IPA analysis. ๐คฏlto-partitionsโ specify desired number of partitions produced during WHOPR compilation. The number of partitions should exceed the number of CPUs used for compilation. ๐ฅ๏ธlto-min-partitionโ size of minimal partition for WHOPR (in estimated instructions). This prevents expenses of splitting very small programs into too many partitions. โ๏ธlto-max-partitionโ size of max partition for WHOPR (in estimated instructions). to provide an upper bound for individual size of partition. Meant to be used only with balanced partitioning. ๐lto-max-streaming-parallelismโ maximal number of parallel processes used for LTO streaming. ๐cxx-max-namespaces-for-diagnostic-helpโ the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. ๐งsink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block to allow statement sinking of a statement. Larger numbers result in more aggressive statement sinking. A small positive adjustment is applied for statements with memory operands as those are even more profitable so sink. โฌ๏ธmax-stores-to-sinkโ the maximum number of conditional store pairs that can be sunk. Set to0if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled. ๐case-values-thresholdโ the smallest number of different values for which it is best to use a jump-table instead of a tree of conditional branches. If the value is0, use the default for the machine. ๐ขjump-table-max-growth-ratio-for-sizeโ the maximum code size growth ratio when expanding into a jump table (in percent). The parameter is used when optimizing for size. ๐jump-table-max-growth-ratio-for-speedโ the maximum code size growth ratio when expanding into a jump table (in percent). The parameter is used when optimizing for speed. ๐๏ธtree-reassoc-widthโ set the maximum number of instructions executed in parallel in reassociated tree. This parameter overrides target dependent heuristics used by default if has non zero value. ๐ณsched-pressure-algorithmโ picks which of the two implementations of-fsched-pressureyou want, bestie. Algorithm 1 is the OG one and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was built as a compromise between algorithm 1's relatively conservative vibe and the honestly-kind-of-aggressive approach the default scheduler takes. It leans way harder on having a regular register file and accurate register pressure classes. Peephaifa-sched.ccin the GCC sources for the full lore. The default choice depends on the target. ๐max-slsr-cand-scanโ sets the max number of existing candidates we look at when hunting for a basis for a new straight-line strength reduction candidate.asan-globalsโ turns on buffer overflow detection for global objects. This kind of protection is on by default if you're using-fsanitize=address. To turn off global objects protection, use--param asan-globals=0.asan-stackโ turns on buffer overflow detection for stack objects. On by default when using-fsanitize=address. To turn off stack protection, use--param asan-stack=0.asan-instrument-readsโ turns on buffer overflow detection for memory reads. On by default when using-fsanitize=address. To turn off memory reads protection, use--param asan-instrument-reads=0.asan-instrument-writesโ turns on buffer overflow detection for memory writes. On by default when using-fsanitize=address. To turn off memory writes protection, use--param asan-instrument-writes=0.asan-memintrinโ turns on detection for built-in functions. On by default when using-fsanitize=address. To turn off built-in functions protection, use--param asan-memintrin=0.asan-use-after-returnโ turns on detection of use-after-return. On by default when using the-fsanitize=addressoption. To turn it off, use--param asan-use-after-return=0.
Note: by default this check is disabled at run time. To enable it, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS. ๐
asan-instrumentation-with-call-thresholdโ if the number of memory accesses in the function being instrumented is greater than or equal to this number, use callbacks instead of inline checks. Like, to disable inline code, use--param asan-instrumentation-with-call-threshold=0.asan-kernel-mem-intrinsic-prefixโ if nonzero, prefix calls to"memcpy","memset"and"memmove"with__asan_or__hwasan_for-fsanitize=kernel-addressor-fsanitize=kernel-hwaddress, respectively.hwasan-instrument-stackโ turns on hwasan instrumentation of statically sized stack-allocated variables. This is on by default when using-fsanitize=hwaddressand off by default when using-fsanitize=kernel-hwaddress. To disable stack instrumentation use--param hwasan-instrument-stack=0, and to enable it use--param hwasan-instrument-stack=1.hwasan-random-frame-tagโ when using stack instrumentation, decides tags for stack variables using a deterministic sequence that begins at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. Enabled by default for-fsanitize=hwaddressand unavailable for-fsanitize=kernel-hwaddress. To disable it use--param hwasan-random-frame-tag=0.hwasan-instrument-allocasโ turns on hwasan instrumentation of dynamically sized stack-allocated variables. On by default when using-fsanitize=hwaddress, off by default when using-fsanitize=kernel-hwaddress. To disable instrumentation of those variables use--param hwasan-instrument-allocas=0, and to enable it use--param hwasan-instrument-allocas=1.hwasan-instrument-readsโ turns on hwasan checks on memory reads. Instrumentation of reads is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable checking memory reads use--param hwasan-instrument-reads=0.hwasan-instrument-writesโ turns on hwasan checks on memory writes. Instrumentation of writes is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable checking memory writes use--param hwasan-instrument-writes=0.hwasan-instrument-mem-intrinsicsโ turns on hwasan instrumentation of builtin functions. Instrumentation of these builtin functions is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable instrumentation of builtin functions use--param hwasan-instrument-mem-intrinsics=0.use-after-scope-direct-emission-thresholdโ if the size of a local variable in bytes is smaller than or equal to this number, directly poison (or unpoison) shadow memory instead of using run-time callbacks.tsan-distinguish-volatileโ emits special instrumentation for accesses to volatiles.tsan-instrument-func-entry-exitโ emits instrumentation calls to__tsan_func_entry()and__tsan_func_exit().max-fsm-thread-path-insnsโ max number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.threader-debugโthreader-debug=[none|all]enables verbose dumping of the threader solver.parloops-chunk-sizeโ the chunk size of omp schedule for loops parallelized by parloops.parloops-scheduleโ the schedule type of omp schedule for loops parallelized by parloops (static,dynamic,guided,auto,runtime).parloops-min-per-threadโ the minimum number of iterations per thread of an innermost parallelized loop for which the parallelized variant is preferred over the single threaded one. Heads up though: for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two. ๐ซถmax-ssa-name-query-depthโ max depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion = following a use-def chain.max-speculative-devirt-maydefsโ the max number of may-defs we analyze when we're looking for a must-def that specifies the dynamic type of an object that invokes a virtual call we might be able to devirtualize speculatively.evrp-sparse-thresholdโ max number of basic blocks before EVRP uses a sparse cache.ranger-debugโ specifies the type of debug output to be issued for ranges.evrp-switch-limitโ specifies the max number of switch cases before EVRP ignores a switch.unroll-jam-min-percentโ the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable.unroll-jam-max-unrollโ the max number of times the outer loop should be unrolled by the unroll-and-jam transformation.max-rtl-if-conversion-unpredictable-costโ max permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that's considered unpredictable.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris used, the max number of times that an individual variable will be expanded during loop unrolling.partial-inlining-entry-probabilityโ max probability of the entry BB of a split region (in percent, relative to the entry BB of the function) to make partial inlining happen.max-tracked-strlensโ max number of strings for which the strlen optimization pass will track string lengths.gcse-after-reload-partial-fractionโ the threshold ratio for performing partial redundancy elimination after reload.gcse-after-reload-critical-fractionโ the threshold ratio of critical edges execution count that permits performing redundancy elimination after reload.max-loop-header-insnsโ the max number of insns in a loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enables loop epilogue vectorization using a smaller vector size.vect-partial-vector-usageโ controls when the loop vectorizer considers using partial vector loads and stores as an alternative to falling back to scalar code.0stops the vectorizer from ever using partial vector loads and stores.1allows partial vector loads and stores if vectorization removes the need for the code to iterate.2allows partial vector loads and stores in all loops. This parameter only has an effect on targets that support partial vector loads and stores.vect-inner-loop-cost-factorโ the max factor which the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the maximum of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is50.vect-induction-floatโ enables loop vectorization of floating point inductions.avoid-fma-max-bitsโ max number of bits for which we avoid creating FMAs.sms-loop-average-count-thresholdโ a threshold on the average loop count considered by the swing modulo scheduler.sms-dfa-historyโ the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.graphite-allow-codegen-errorsโ whether codegen errors should be ICEs when-fchecking.sms-max-ii-factorโ a factor for tuning the upper bound that the swing modulo scheduler uses for scheduling a loop.lra-max-considered-reload-pseudosโ the max number of reload pseudos we're willing to consider while spilling a non-reload pseudo. it's giving "how many backups can we juggle" energy ๐max-pow-sqrt-depthโ max depth of sqrt chains to use when synthesizing exponentiation by a real constant. nesting go brrr ๐ธmax-dse-active-local-storesโ the maximum number of active local stores in RTL dead store elimination. bye bye dead stores ๐asan-instrument-allocasโ turns on asan allocas/VLAs protection. safety girlies rise โจmax-iterations-computation-costโ a bound on the cost of an expression when we compute the number of iterations.max-isl-operationsโ maximum number of isl operations, and0means unlimited. no cap, fr fr ๐งgraphite-max-arrays-per-scopโ maximum number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of the loc list for which reverse ops should be added.fsm-scale-path-stmtsโ the scale factor to apply to the number of statements in a threading path crossing a loop backedge when comparing to--param=max-jump-thread-duplication-stmts.uninit-control-dep-attemptsโ maximum number of nested calls used to search for control dependencies during uninitialized variable analysis.uninit-max-chain-lenโ the maximum number of predicates anded for each predicate ored in the normalized predicate chain.uninit-max-num-chainsโ the maximum number of predicates ored in the normalized predicate chain.sched-autopref-queue-depthโ hardware autoprefetcher scheduler model control flag. it's the number of lookahead cycles the model looks into; at' 'it only enables the instruction sorting heuristic.loop-versioning-max-inner-insnsโ the maximum number of instructions an inner loop can have before the loop versioning pass decides it's too big to copy. no copying oversized loops, periodtloop-versioning-max-outer-insnsโ the maximum number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy, discounting any instructions in inner loops that directly benefit from versioning.ssa-name-def-chain-limitโ the maximum number ofSSA_NAMEassignments to follow in determining a property of a variable (like its value). this caps the number of iterations or recursive calls GCC does when optimizing certain statements, or when checking their validity before it drops diagnostics.store-merging-max-sizeโ maximum size of a single store merging region, in bytes.hash-table-verification-limitโ the number of elements for which hash table verification is done for each searched element.max-find-base-term-valuesโ maximum number of VALUEs handled during a singlefind_base_termcall.analyzer-max-enodes-per-program-pointโ the maximum number of exploded nodes per program point within the analyzer, before it stops analyzing that point.analyzer-max-constraintsโ the maximum number of constraints per state.analyzer-min-snodes-for-call-summaryโ the minimum number of supernodes within a function before the analyzer will even consider summarizing its effects at call sites.analyzer-max-enodes-for-full-dumpโ the maximum depth of exploded nodes that should show up in a dot dump before switching to a less verbose format.analyzer-max-recursion-depthโ the maximum number of times a callsite can appear in a call stack within the analyzer, before it stops analyzing a call that would recurse deeper.analyzer-max-svalue-depthโ the maximum depth of a symbolic value before the value gets approximated as unknown.analyzer-max-infeasible-edgesโ the maximum number of infeasible edges to reject before declaring a diagnostic as infeasible.gimple-fe-computed-hot-bb-thresholdโ the number of executions of a basic block which counts as hot. this parameter is used only in GIMPLE FE.analyzer-bb-explosion-factorโ the maximum number of 'after supernode' exploded nodes within the analyzer per supernode, before it stops analyzing.ranger-logical-depthโ maximum depth of logical expression evaluation the ranger will look through when evaluating outgoing edge ranges.ranger-recompute-depthโ maximum depth of instruction chains to consider for recomputation in the outgoing range calculator.relation-block-limitโ maximum number of relations the oracle will register in a basic block.min-pagesizeโ minimum page size, for warning purposes.openacc-kernelsโ specifies the mode of OpenACCkernelsconstructs handling. with--param=openacc-kernels=decompose, OpenACCkernelsconstructs get decomposed into parts โ a sequence of compute constructs, each then handled individually. this is work in progress, bestie, don't @ me. with--param=openacc-kernels=parloops, OpenACCkernelsconstructs are handled by the parloops pass, en bloc. this is the current default. ๐openacc-privatizationโ controls whether the-fopt-info-omp-noteand applicable-fdump-tree-*-detailsoptions emit OpenACC privatization diagnostics. with--param=openacc-privatization=quiet, don't diagnose โ this is the current default. with--param=openacc-privatization=noisy, do diagnose. pick your vibe ๐
the following choices of name are available on AArch64 targets:
aarch64-sve-compare-costsโ when vectorizing for SVE, consider using "unpacked" vectors for smaller elements and use the cost model to pick the cheapest approach. also use the cost model to choose between SVE and Advanced SIMD vectorization.
using unpacked vectors includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores.
aarch64-float-recp-precisionโ the number of Newton iterations for calculating the reciprocal for float type. the precision of division is proportional to this param when division approximation is enabled. the default value is1.aarch64-double-recp-precisionโ the number of Newton iterations for calculating the reciprocal for double type. the precision of division is propotional to this param when division approximation is enabled. the default value is2. (yes they wrote "propotional" and yes i'm keeping it, no i will not be fixing it ๐ )aarch64-autovec-preferenceโ forces an ISA selection strategy for auto-vectorization. accepts values from0to4, inclusive:0โ use the default heuristics.1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE. prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE. prefer SVE when the costs are deemed equal.
the default value is 0.
aarch64-loop-vect-issue-rate-nitersโ the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. if this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations.aarch64-vect-unroll-limitโ the vectorizer will use available tuning information to determine whether it would be beneficial to unroll the main vectorized loop, and by how much. this parameter sets the upper bound of how much the vectorizer will unroll the main loop. the default value isfour. slay โจ
the following choices of name are available on i386 and x86_64 targets:
x86-stlf-window-ninsnsโ instructions number above which STFL stall penalty can be compensated.x86-stv-max-visitsโ the maximum number of use and def visits when discovering a STV chain before the discovery is aborted.
๐ Program Instrumentation Options ๐
okay so GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates. for example, one purpose of instrumentation is to collect profiling statistics โ for finding program hot spots, code coverage analysis, or profile-guided optimizations. another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks like stack smashing or C++ vtable hijacking. and there's also a general hook you can use to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes. so many vibes, so many options ๐ฆ
-p<br>-pgโ generate extra code to write profile information suitable for the analysis programprof(for-p) orgprof(for-pg). you must use this option when compiling the source files you want data about, and you must also use it when linking. fr fr, both times ๐ฅ
you can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.
-fprofile-arcsโ add code so that program flow arcs get instrumented. during execution the program records how many times each branch and call is executed and how many times it is taken or returns. on targets that support constructors with priority support, profiling properly handles constructors, destructors and C++ constructors (and destructors) of classes which are used as a type of a global variable. chef's kiss ๐
when the compiled program exits it saves this data to a file called auxname.gcda for each source file. the data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). each object file's auxname is generated from the name of the output file, if explicitly specified and it is not the final executable, otherwise it is the basename of the source file. in both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o). ๐
Bestie quick lil heads-up before we go any further: when a command line links source files directly, the matching .gcda files get prefixed with the unsuffixed name of the output file. So like, "gcc a.c b.c -o binary" would pop out binary-a.gcda and binary-b.gcda. Noted. ๐
--coverageโ the glow-up option for compiling and linking code that's instrumented for coverage analysis. It's literally just a synonym for-fprofile-arcs -ftest-coverage(when you're compiling) and-lgcov(when you're linking). Go read those options' docs for the deets. โจ- Compile the source files with
-fprofile-arcsplus your optimization and code generation options. For test coverage analysis, also toss in-ftest-coverage. You do not need to profile every single source file in a program, ok? ๐ซถ - Compile the source files additionally with
-fprofile-abs-pathto create absolute path names in the.gcnofiles. This letsgcovfind the correct sources in projects where compilations happen with different working directories. iconic behavior. - Link your object files with
-lgcovor-fprofile-arcs(the latter implies the former, she's generous like that). - Run the program on a representative workload to generate the arc profile information. You can do this any number of times, no cap. Concurrent instances of your program? Totally fine โ provided the file system supports locking, the data files will be correctly updated. And unless a strict ISO C dialect option is in effect,
"fork"calls are detected and correctly handled without double counting. - Moreover (๐ fancy word), an object file can be recompiled multiple times and the corresponding
.gcdafile merges, as long as the source file and the compiler options are unchanged. - For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus
-fbranch-probabilities. - For test coverage analysis, use
gcovto produce human readable information from the.gcnoand.gcdafiles. Refer to thegcovdocumentation for further information.
- Compile the source files with
With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. ๐
-ftest-coverageโ produces a notes file that thegcovcode-coverage utility can use to show program coverage. Each source file's note file is calledauxname.gcno. Refer to the-fprofile-arcsoption above for a description ofauxnameand instructions on how to generate test coverage data. Heads up bestie: coverage data matches the source files more closely if you do not optimize. โจ-fprofile-abs-pathโ automatically converts relative source file names to absolute path names in the.gcnofiles. This allowsgcovto find the correct sources in projects where compilations occur with different working directories. She's organized like that. ๐-fprofile-dir=pathโ sets the directory to search for the profile data files in to path. This option affects only the profile data generated by-fprofile-generate,-ftest-coverage,-fprofile-arcsand used by-fprofile-useand-fbranch-probabilitiesand its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, so the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of thesourcename.gcdafile and use it as the file name of a.gcdafile. See details about the file naming in-fprofile-arcs. See similar option-fprofile-note. ๐ฆ
When an executable is run in a massive parallel environment, it is recommended to save profile to different folders. That can be done with variables in path that are exported during run-time:
%pโ process ID.%q{VAR}โ value of environment variable VAR
-fprofile-generate-fprofile-generate=pathโ enables options usually used for instrumenting an application to produce a profile useful for later recompilation with profile feedback based optimization. You must use-fprofile-generateboth when compiling and when linking your program. no skipping steps, ok? ๐
The following options are enabled: -fprofile-arcs, -fprofile-values, -finline-functions, and -fipa-bit-cp.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
To optimize the program based on the collected profile information, use -fprofile-use.
-fprofile-info-section-fprofile-info-section=nameโ registers the profile information in the specified section instead of using a constructor/destructor. The section name is name if it is specified, otherwise the section name defaults to".gcov_info". A pointer to the profile information generated by-fprofile-arcsis placed in the specified section for each translation unit. This option disables the profile information registration through a constructor and it disables the profile information processing through a destructor. This option is not intended to be used in hosted environments such as GNU/Linux. It targets freestanding environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. ๐
The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:
.gcov_info :
{
PROVIDE (__gcov_info_start = .);
KEEP (*(.gcov_info))
PROVIDE (__gcov_info_end = .);
}
The program could dump the profiling information registered in this linker set for example like this:
#include <gcov.h>
#include <stdio.h>
#include <stdlib.h>
extern const struct gcov_info *const __gcov_info_start[];
extern const struct gcov_info *const __gcov_info_end[];
static void
dump (const void *d, unsigned n, void *arg)
{
const unsigned char *c = d;
for (unsigned i = 0; i < n; ++i)
printf ("%02x", c[i]);
}
static void
filename (const char *f, void *arg)
{
__gcov_filename_to_gcfn (f, dump, arg );
}
static void *
allocate (unsigned length, void *arg)
{
return malloc (length);
}
static void
dump_gcov_info (void)
{
const struct gcov_info *const *info = __gcov_info_start;
const struct gcov_info *const *end = __gcov_info_end;
/* Obfuscate variable to prevent compiler optimizations. */
__asm__ ("" : "+r" (info));
while (info != end)
{
void *arg = NULL;
__gcov_info_to_gcda (*info, filename, dump, allocate, arg);
putchar ('\n');
++info;
}
}
int
main (void)
{
dump_gcov_info ();
return 0;
}
The merge-stream subcommand of gcov-tool may be used to deserialize the data stream generated by the "__gcov_filename_to_gcfn" and "__gcov_info_to_gcda" functions and merge the profile information into .gcda files on the host filesystem. ๐ง
-fprofile-note=pathโ if path is specified, GCC saves.gcnofile into path location. โ ๏ธ If you combine the option with multiple source files, the.gcnofile will be overwritten. be careful bestie.-fprofile-prefix-path=pathโ this option can be used in combination withprofile-generate=profile_dirandprofile-use=profile_dirto inform GCC where is the base directory of built source tree. By defaultprofile_dirwill contain files with mangled absolute paths of all object files in the built project. This is not desirable when the directory used to build the instrumented binary differs from the directory used to build the binary optimized with profile feedback, because the profile data will not be found during the optimized build. In such setups-fprofile-prefix-path=pathwith path pointing to the base directory of the build can be used to strip the irrelevant part of the path and keep all file names relative to the main build directory. ๐-fprofile-prefix-map=old=newโ when compiling files residing in directory old, record profiling information (with--coverage) describing them as if the files resided in directory new instead. See also-ffile-prefix-mapand-fcanon-prefix-map.-fprofile-update=methodโ alters the update method for an application instrumented for profile feedback based optimization. The method argument should be one ofsingle,atomicorprefer-atomic. The first one is useful for single-threaded applications, while the second one prevents profile corruption by emitting thread-safe code. ๐ฅ
Warning: when an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted.
Using prefer-atomic would be transformed either to atomic, when supported by a target, or to single otherwise. The GCC driver automatically selects prefer-atomic when -pthread is present in the command line. she's got main character energy fr fr.
-fprofile-filter-files=regexโ instrument only functions from files whose name matches any of the regular expressions (separated by semi-colons).
For example, -fprofile-filter-files=main\.c;module.*\.c will instrument only main.c and all C files starting with 'module'. ate. ๐
-fprofile-exclude-files=regexโ instrument only functions from files whose name does not match any of the regular expressions (separated by semi-colons). the inverse queen. ๐
For example, -fprofile-exclude-files=/usr/.* will prevent instrumentation of all files that are located in the /usr/ folder.
-fprofile-reproducible=[multithreaded|parallel-runs|serial]โ okay so this one is your โจreproducibility control knobโจ for profiles gathered by-fprofile-generate. The whole point: rebuild a program and get the same outcome every time, which is lowkey a big deal for distro packages. ๐
With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible โ as long as the trained program behaves the same every single time you run the train run, it's not multi-threaded, and profile data streaming always happens in the same order. Heads up bestie: profile streaming happens at the end of the program run and also before fork is invoked. ๐ซถ
Real talk though: it's pretty common that execution counts of some part of a program depend on stuff like the length of temporary file names or memory space randomization (which can affect hash-table collision rate ๐ญ). You can annotate that non-reproducible part of your program with the no_instrument_function function attribute. And gcov-dump with -l will dump the gathered data so you can verify it's actually reproducible. Periodt.
With -fprofile-reproducible=parallel-runs, the collected profile stays reproducible no matter what order the data streams into the gcda files. This is the one that lets you run multiple instances of the instrumented program in parallel (think make -j). Fair warning: it reduces the quality of the gathered data, especially for indirect call profiling. ๐
-fsanitize=addressโ turns on AddressSanitizer, a fast memory error detector. Memory access instructions get instrumented to catch out-of-bounds and use-after-free bugs. ๐
This option also enables -fsanitize-address-use-after-scope. More deets at https://github.com/google/sanitizers/wiki/AddressSanitizer.
The run-time behavior can be influenced using the ASAN_OPTIONS environment variable โ when you set it to help=1, all the available options get shown at startup of the instrumented program. List of supported options here: https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags.
โ ๏ธ This option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress.
Also ngl, the only targets -fsanitize=hwaddress is currently supported on are x86-64 (and only with the -mlam=u48 or -mlam=u57 options) and AArch64 โ and in both cases, only in ABIs with 64-bit pointers.
For more accurate stack traces, you can use options like -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which stops sibling and tail recursive calls from being optimized โ it's implicit for -O0, -O1, or -Og anyway), or -fno-ipa-icf (which disables Identical Code Folding for functions). And since multiple runs of a program may give backtraces with different addresses because of ASLR (Address Space Layout Randomization), you might want to turn ASLR off. On Linux you do that with:
setarch `uname -m` -R ./prog
-fsanitize=kernel-addressโ AddressSanitizer, but for the Linux kernel. ๐ธ More athttps://github.com/google/kernel-sanitizers.-fsanitize=hwaddressโ enables Hardware-assisted AddressSanitizer, which flexes a hardware ability to ignore the top byte of a pointer so it can detect memory errors with a low memory overhead. โจ Memory access instructions get instrumented to catch out-of-bounds and use-after-free bugs, and the option enables-fsanitize-address-use-after-scope. More athttps://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html.
Run-time behavior is influenced through the HWASAN_OPTIONS environment variable โ set it to help=1 and the available options show up at startup of the instrumented program.
โ ๏ธ Can't be combined with -fsanitize=thread or -fsanitize=address, and it's currently only available on AArch64.
-fsanitize=kernel-hwaddressโ Hardware-assisted AddressSanitizer, but for compiling the Linux kernel. ๐ฆ It's similar to-fsanitize=kernel-addressbut uses an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences that are necessary for compiling the Linux kernel. Those differences exist to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte.
Note: this option has different defaults from-fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but you can still get them by specifying the command-line options--param hwasan-instrument-stack=1and--param hwasan-instrument-allocas=1respectively. Using a random frame tag is not implemented for kernel instrumentation. ๐
-fsanitize=pointer-compareโ instruments comparison operations (<,<=,>,>=) that have pointer operands. This one must be combined with either-fsanitize=kernel-addressor-fsanitize=address, and it cannot be combined with-fsanitize=thread.
Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to theASAN_OPTIONSenvironment variable. Usingdetect_invalid_pointer_pairs=1detects the invalid operation only when both pointers are non-null. ๐
-fsanitize=pointer-subtractโ instruments subtraction with pointer operands. Same deal: must be combined with either-fsanitize=kernel-addressor-fsanitize=address, and cannot be combined with-fsanitize=thread.
Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to theASAN_OPTIONSenvironment variable. Usingdetect_invalid_pointer_pairs=1detects the invalid operation only when both pointers are non-null. ๐
-fsanitize=shadow-call-stackโ enables ShadowCallStack, a security enhancement mechanism that protects programs against return address overwrites (e.g. stack buffer overflows ๐). The way it works: it saves a function's return address to a separately allocated shadow call stack in the function prologue, then restores the return address from the shadow call stack in the function epilogue. Instrumentation only happens in functions that actually need to save the return address to the stack. ๐
Currently it only supports the aarch64 platform, and it's specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc โ if you want to use this in user space, you have to bring your own runtime support. ๐ซถ And fyi, this may cause the ABI rules to be broken.
On aarch64, the instrumentation makes use of the platform register x18. This generally means any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 โ otherwise functions compiled without -ffixed-x18 might clobber x18 and thereby corrupt the shadow stack pointer. ๐ญ
Also, because there is no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. Use -fno-exceptions to turn off exceptions.
More details at https://clang.llvm.org/docs/ShadowCallStack.html.
-fsanitize=threadโ enables ThreadSanitizer, a fast data race detector. ๐ฅ Memory access instructions get instrumented to detect data race bugs. More athttps://github.com/google/sanitizers/wiki#threadsanitizer.
Run-time behavior can be influenced using the TSAN_OPTIONS environment variable โ supported options are listed at https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags.
โ ๏ธ Cannot be combined with -fsanitize=address or -fsanitize=leak.
Note: sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
-fsanitize=leakโ enables LeakSanitizer, a memory leak detector. ๐ This one only matters for linking of executables: the executable gets linked against a library that overridesmallocand other allocator functions. More athttps://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer.
Run-time behavior can be influenced using the LSAN_OPTIONS environment variable. โ ๏ธ Cannot be combined with -fsanitize=thread.
-fsanitize=undefinedโ enables UndefinedBehaviorSanitizer, a fast undefined behavior detector. ๐ง Various computations get instrumented so undefined behavior is detected at runtime. More athttps://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html. Run-time behavior can be influenced using theUBSAN_OPTIONSenvironment variable.
Current suboptions are, in order:
๐ -fsanitize=shift
This option enables checking that the result of a shift operation is not undefined. Note that what exactly counts as undefined differs slightly between C and C++, and also between ISO C90 and C99, etc. This option has two suboptions: -fsanitize=shift-base and -fsanitize=shift-exponent.
๐ -fsanitize=shift-exponent
This option enables checking that the second argument of a shift operation is not negative and is smaller than the precision of the promoted first argument.
๐ -fsanitize=shift-base
If the second argument of a shift operation is within range, check that the result of the shift operation is not undefined. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc.
๐ -fsanitize=integer-divide-by-zero
Detect integer division by zero. ๐ซ
๐ -fsanitize=unreachable
With this option, the compiler turns the __builtin_unreachable call into a diagnostics message call instead. Heads up: when reaching the __builtin_unreachable call, the behavior is undefined. ๐
๐ -fsanitize=vla-bound
This option instructs the compiler to check that the size of a variable length array is positive.
๐ -fsanitize=null
This option enables pointer checking. Particularly, an application built with this option turned on will issue an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed to by a NULL pointer. ๐ฏ
-fsanitize=returnโ bestie, this one's checking yourreturnstatements, fr. Programs built with this on will throw an error message the second you hit the end of a non-void function without actually returning a value. ๐ Heads up: this works in C++ only.-fsanitize=signed-integer-overflowโ signed integer overflow checking, let's gooo. We verify that the result of+,*, and both unary and binary-does not overflow in signed arithmetics. It also catchesINT_MIN / -1signed division (sneaky one ๐). Ngl, the integer promotion rules gotta be taken into account here. Which means the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ this one instruments array bounds. Various out-of-bounds accesses get detected โจ. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented โ with the exception of flexible array member-like arrays for which-fstrict-flex-arraysor-fstrict-flex-arrays=options orstrict_flex_arrayattributes say they shouldn't be treated like flexible array member-like arrays. iykyk.-fsanitize=bounds-strictโ the โจstrictโจ sibling of array bounds instrumentation. Most out-of-bounds accesses get detected, including flexible array member-like arrays this time. Initializers of variables with static storage are still not instrumented.-fsanitize=alignmentโ checks the alignment of pointers when they're dereferenced ๐ซถ, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object.-fsanitize=object-sizeโ instrumentation of memory references using the__builtin_dynamic_object_sizefunction. Various out-of-bounds pointer accesses get detected, periodt.-fsanitize=float-divide-by-zeroโ detects floating-point division by zero. But lowkey important: unlike other similar options,-fsanitize=float-divide-by-zerois not enabled by-fsanitize=undefined, because floating-point division by zero can be a legitimate way of obtaining infinities and NaNs. So it's a vibe, not always a bug ๐ .-fsanitize=float-cast-overflowโ floating-point type to integer conversion checking. We check that the result of the conversion does not overflow. Same tea as above: unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Also, this option does not work well withFE_INVALIDexceptions enabled ๐.-fsanitize=nonnull-attributeโ instruments calls, checking whether null values are not passed to arguments marked as requiring a non-null value by thenonnullfunction attribute.-fsanitize=returns-nonnull-attributeโ instruments return statements in functions marked with thereturns_nonnullfunction attribute, to detect returning null values from such functions. Not the move ๐ญ.-fsanitize=boolโ instruments loads from bool. If a value other than 0/1 is loaded, a run-time error is issued. Simple as that ๐.-fsanitize=enumโ instruments loads from an enum type. If a value outside the range of values for the enum type is loaded, a run-time error is issued.-fsanitize=vptrโ instruments C++ member function calls, member accesses, and some conversions between pointers to base and derived classes, to verify the referenced object has the correct dynamic type. Main character energy tbh ๐.-fsanitize=pointer-overflowโ instruments pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued.-fsanitize=builtinโ instruments arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing 0 as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and is diagnosed by this option.
Ngl besties, note that sanitizers tend to increase the rate of false positive warnings โ most notably those around-Wmaybe-uninitialized. We recommend against combining-Werrorand [the use of] sanitizers. ๐ซ
Also while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message. This currently works only for the C family of languages.
-fno-sanitize=allโ this disables all previously enabled sanitizers. And no,-fsanitize=allis not allowed, because some sanitizers cannot be used together. It's giving "not a group project" ๐.-fasan-shadow-offset=numberโ forces GCC to use a custom shadow offset in AddressSanitizer checks. Super useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer ๐ง.-fsanitize-sections=s1,s2,...โ sanitize global variables in selected user-defined sections. Each si may contain wildcards. Slay.-fsanitize-recover[=opts]โ-fsanitize-recover=controls error recovery mode for sanitizers mentioned in the comma-separated list of opts. Enabling this option for a sanitizer component causes it to attempt to continue running the program as if no error happened ๐. Which means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors have been reported ๐. The-fno-sanitize-recover=option can be used to alter this behavior: only the first detected error is reported and the program then exits with a non-zero exit code.
Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all is also accepted โ the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.
Even if a recovery mode is turned on the compiler side, it needs to be also enabled on the runtime library side, otherwise the failures are still fatal ๐. The runtime library defaults to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. This can be overridden through setting the halt_on_error flag in the corresponding environment variable.
Syntax without an explicit opts parameter is deprecated. It is equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scopeโ enable sanitization of local variables to detect use-after-scope bugs. The option sets-fstack-reuseto none. Catch those sneaky ones ๐ฅ.-fsanitize-trap[=opts]โ the-fsanitize-trap=option instructs the compiler to report for sanitizers mentioned in the comma-separated list of opts undefined behavior using__builtin_traprather than alibubsanlibrary routine. If this option is enabled for a certain sanitizer, it takes precedence over the-fsanitizer-recover=for that sanitizer โ__builtin_trapwill be emitted and be fatal regardless of whether recovery is enabled or disabled using-fsanitize-recover=.
The advantage of this is that the libubsan library is not needed and is not linked in, so this is usable even in freestanding environments โจ.
Currently this feature works with -fsanitize=undefined (and its suboptions except for -fsanitize=vptr), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. -fsanitize-trap=all can be also specified, which enables it for undefined suboptions, -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. If -fsanitize-trap=undefined or -fsanitize-trap=all is used and -fsanitize=vptr is enabled on the command line, the instrumentation is silently ignored, as the instrumentation always needs libubsan support โ -fsanitize-trap=vptr is not allowed ๐ซ.
-fsanitize-undefined-trap-on-errorโ deprecated equivalent of-fsanitize-trap=all. Old news bestie, wrap it up ๐.-fsanitize-coverage=trace-pcโ enable coverage-guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_pcinto every basic block.-fsanitize-coverage=trace-cmpโ enable dataflow guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8for integral comparison with both operands variable, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8for integral comparison with one operand constant,__sanitizer_cov_trace_cmpfor__sanitizer_cov_trace_cmpdfor float or double comparisons, and__sanitizer_cov_trace_switchfor switch statements. So many of them, I know ๐ญ โ they each got a job.-fcf-protection=[full|branch|return|none|check]โ enable code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid. This prevents diverting the flow of control to an unexpected target ๐ก๏ธ. It's intended to protect against such threats as Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP).
The value branch tells the compiler to implement checking of validity of control-flow transfer at the point of indirect branch instructions, i.e. call/jmp instructions. The value return implements checking of validity at the point of returning from a function. The value full is an alias for specifying both branch and return. The value none turns off instrumentation.
Bestie, and then there's "check" ๐
โ that value is for the final link when you're doing link-time optimization (LTO). If your LTO object files got compiled with different -fcf-protection values, boom, error ๐. And at compile time? "check" is just straight-up ignored, no cap.
The macro __CET__ appears the second you use -fcf-protection. First bit of __CET__ gets set to 1 for the value "branch", and the second bit of __CET__ gets set to 1 for "return". So cute ๐
You can also use the "nocf_check" attribute to point at which functions and calls should get skipped from instrumentation. not invited, bye ๐
Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET) that works for i686 processors or newer. periodt โจ
NOTE: In Ubuntu 19.10 and later versions,-fcf-protectionis enabled by default for C, C++, ObjC, ObjC++, if none of-fno-cf-protectionnor-fcf-protection=*are found. ๐
-fharden-comparesโ for every logical test that survives gimple optimizations and isn't the condition in a conditional branch (think: conditions tested for conditional moves, or ones being stored in boolean variables), it emits extra code to compute and verify the reversed condition, and to call__builtin_trapif the results don't match ๐ค. Team it up with-fharden-conditional-branchesto cover all conditionals.-fharden-conditional-branchesโ same energy ๐ but for every non-vectorized conditional branch that survives gimple optimizations: extra code gets emitted to compute and verify the reversed condition, and to call__builtin_trapif the result is unexpected. Use it with-fharden-comparesto cover all conditionals.-fstack-protectorโ emits extra code that checks for buffer overflows, like stack smashing attacks ๐ก๏ธ. How though? It adds a guard variable to functions with vulnerable objects โ and that means functions that callalloca, plus functions with buffers larger than or equal to 8 bytes. The guards get initialized when a function is entered and then checked when the function exits. Guard check fails? An error message gets printed and the program exits, goodbye ๐. Also important: only variables that are actually allocated on the stack are considered โ optimized-away variables or variables allocated in registers do not count, sorry ๐ซถ-fstack-protector-allโ literally-fstack-protectorexcept that ALL functions are protected. every single one ๐-fstack-protector-strongโ like-fstack-protectorbut it also includes additional functions to be protected: the ones that have local array definitions, or that have references to local frame addresses ๐ฆ. And same rule as its siblings โ only variables actually allocated on the stack are considered; optimized-away variables or variables allocated in registers don't count.
NOTE: In Ubuntu 14.10 and later versions,-fstack-protector-strongis enabled by default for C, C++, ObjC, ObjC++, if none of-fno-stack-protector,-nostdlib, nor-ffreestandingare found. โจ
-fstack-protector-explicitโ like-fstack-protectorbut it only protects those functions which have thestack_protectattribute. so picky, so iconic ๐-fstack-checkโ generates code to verify that you don't go beyond the boundary of the stack. You should defo specify this flag if you're running in an environment with multiple threads ๐งต, but you only rarely need to specify it in a single-threaded environment, since stack overflow is automatically detected on nearly all systems if there's only one stack.
Okay real talk though โ this switch does not actually cause checking to be done. The operating system or the language runtime has to do that part, fr fr. What the switch does is generate code so that they see the stack being extended. ๐
You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, and specific means use the best checking method โ which is equivalent to bare -fstack-check.
Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie, it comes with the following drawbacks:
- Modified allocation strategy for large objects: they're always allocated dynamically if their size exceeds a fixed threshold. Heads up that this may change the semantics of some code ๐ญ
- Fixed limit on the size of the static frame of functions: when it is topped by a particular function, stack checking is not reliable and a warning is issued by the compiler.
- Inefficiency: because of both the modified allocation strategy and the generic implementation, code performance is hampered. sad but true ๐
Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.
-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code. But it is not generally sufficient to protect against stack-clash attacks. Wanna protect against those? You want -fstack-clash-protection.
-fstack-clash-protectionโ generates code to prevent stack clash style attacks ๐ฅ. When this option is enabled, the compiler will only allocate one page of stack space at a time, and each page gets accessed immediately after allocation. So yeah, it stops allocations from jumping over any stack guard page provided by the operating system. elite behaviour ๐
Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will still protect dynamic stack allocations. And it may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.
NOTE: In Ubuntu 19.10 and later versions,-fstack-clash-protectionis enabled by default for C, C++, ObjC, ObjC++, unless-fno-stack-clash-protectionis found. ๐
-fstack-limit-register=reg,-fstack-limit-symbol=sym,-fno-stack-limitโ generates code to make sure the stack doesn't grow beyond a certain value, either the value of a register or the address of a symbol. Need a bigger stack than that? A signal is raised at run time โ ๏ธ. For most targets, the signal is raised before the stack overruns the boundary, so it's possible to catch the signal without taking special precautions, which is lowkey a relief.
For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. Note that this may only work with the GNU linker.
You can locally override stack limit checking by using the "no_stack_limit" function attribute. ๐ฆ
-fsplit-stackโ generates code that automatically splits the stack before it overflows. The resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory ๐ณ. This is most useful when running threaded programs, since it's no longer necessary to calculate a good stack size to use for each thread. Right now it's only implemented for the x86 targets running GNU/Linux.
When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run. And if compiling all code โ including library code โ with -fsplit-stack isn't an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later. ๐
-fvtable-verify=[std|preinit|none]โ only available when you're compiling C++ code, iykyk. It turns on (or off, if you're using-fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and that it hasn't been corrupted or overwritten ๐. If an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted. ๐
This option causes run-time data structures to be built at program startup, and those get used for verifying the vtable pointers. The options std and preinit control the timing of when those data structures get built. In both cases the data structures are built before execution reaches main. Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized. ๐
If this option shows up multiple times on the command line with different values specified: none takes highest priority over both std and preinit; preinit takes priority over std. rules are rules โจ
-fvtv-debugโ when used together with-fvtable-verify=stdor-fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called ๐. This flag also makes the compiler log information about which vtable pointers it finds for each class. That info gets written to a file namedvtv_set_ptr_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise.
Note: this feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one first, bestie ๐๏ธ
-fvtv-countsโ this one's a debugging flag ๐. When used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, it makes the compiler keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts, and logs this information for each compilation unit. The compiler writes this info to a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class and writes that info tovtv_class_set_sizes.login the same directory. ๐ธ
Note: this feature appends data to the log files. To get fresh log files, be sure to delete any existing ones. ๐ซถ
-finstrument-functionsโจ โ bestie, this one sprinkles instrumentation calls for entry and exit to functions. Like, right after a function gets entered and right before it exits, these profiling functions get called with the address of the current function and its call site. (Heads up though ๐: on some platforms__builtin_return_addressdoes not work beyond the current function, so the call site info might just... not be available to the profiling functions otherwise.)
void __cyg_profile_func_enter (void *this_fn,
void *call_site);
void __cyg_profile_func_exit (void *this_fn,
void *call_site);
That first argument? It's the address of the start of the current function, which you can look up exactly in the symbol table. ๐
This instrumentation also happens for functions expanded inline in other functions. The profiling calls show, conceptually, where the inline function is entered and exited. Which means โ plot twist โ addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an extra code-size expansion, no cap. And if you use extern inline in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky ๐ and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)
A function can also be given the attribute no_instrument_function, and then this instrumentation just doesn't happen. Very much used for, say, the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (maybe signal handlers, if the profiling routines generate output or allocate memory). safety first bb ๐ซถ
-finstrument-functions-onceโ similar to-finstrument-functions, but the profiling functions get called only once per instrumented function. i.e. the first profiling function fires after the first entry into the instrumented function, and the second profiling function fires before the exit corresponding to this first entry. ๐ฆ
The definition of "once" here is a lil vague, ngl ๐ญ, because the implementation is not protected against data races. So the implementation only guarantees that the profiling functions are called at least once per process and at most once per thread โ but the calls are always paired. Which is to say: if a thread calls the first function, then it will call the second function, unless it never reaches the exit of the instrumented function. ๐
-finstrument-functions-exclude-file-list=file,file,...โ sets the list of functions that are excluded from instrumentation (see the description of-finstrument-functionsabove, bestie ๐). If the file that contains a function definition matches with one of file, then that function is not instrumented. The match is done on substrings: if the file parameter is a substring of the file name, it counts as a match. ๐
For example:
-finstrument-functions-exclude-file-list=/bits/stl,include/sys
...excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.
If, for some reason, you want to include letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option ๐).
-finstrument-functions-exclude-function-list=sym,sym,...โ this is similar to-finstrument-functions-exclude-file-list, but instead it sets the list of function names to be excluded from instrumentation. The function name being matched is its user-visible name, likevector<int> blah(const vector<int> &), not the internal mangled name (e.g.,_Z4blahRSt6vectorIiSaIiEE). Match is on substrings: if the sym parameter is a substring of the function name, it's a match. And for C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. ๐ธ-fpatchable-function-entry=N[,M]โ generates N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to0, so the function entry points to the address just at the first NOP. These NOP instructions reserve extra space โ which you can use to patch in any instrumentation you want at run time, provided that the code segment is writable. ๐ The amount of space is controllable indirectly via the number of NOPs; the NOP instruction used corresponds to the instruction emitted by the internal GCC back-end interfacegen_nop. This behavior is target-specific and may also depend on the architecture variant and/or other compilation options.
For run-time identification, the starting addresses of these areas โ which correspond to their respective function entries minus M โ are additionally collected in the __patchable_function_entries section of the resulting binary. ๐
Note that the value of __attribute__ ((patchable_function_entry (N,M))) takes precedence over the command-line option -fpatchable-function-entry=N,M. You can use this to increase the area size or to remove it completely on a single function. And if N=0, no pad location is recorded.
The NOP instructions are inserted at โ and maybe before, depending on M โ the function entry address, even before the prologue. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the local entry point is this function entry address. ๐
The maximum value of N and M is 65535. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the supported values for M are 0, 2, 6 and 14.
โจ Options Controlling the Preprocessor โจ
These options control the C preprocessor, which โ bestie, listen โ is run on each C source file before actual compilation. ๐ฆ
If you use the -E option, nothing is done except preprocessing. Some of these options make sense only together with -E because they cause the preprocessor output to be unsuitable for actual compilation. โ ๏ธ
In addition to the options listed here, there are a number of options to control search paths for include files, documented in Directory Options. And options to control preprocessor diagnostics are listed in Warning Options. ๐
-Dname โ predefine name as a macro, with definition1.-Dname=definition โ the contents of definition are tokenized and processed as if they appeared during translation phase three in a#definedirective. In particular, the definition is truncated by embedded newline characters. ๐ณ
If you're invoking the preprocessor from a shell or shell-like program, you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. iykyk
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args...)=definition' works. ๐ซถ
-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. โญ
-Uname โ cancel any previous definition of name, either built in or provided with a-Doption. ๐-includefile โ process file as if#include "file"appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If it's not found there, it's searched for in the remainder of the#include "..."search chain as normal. ๐
If multiple -include options are given, the files are included in the order they appear on the command line.
-imacrosfile โ exactly like-include, except that any output produced by scanning file is thrown away. ๐๏ธ Macros it defines remain defined. This lets you acquire all the macros from a header without also processing its declarations. Iconic, honestly.
All files specified by -imacros are processed before all files specified by -include.
-undefโ do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined. โจ-pthreadโ define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. ๐งต๐ฅ-Mโ instead of outputting the result of preprocessing, output a rule suitable formakedescribing the dependencies of the main source file. The preprocessor outputs onemakerule containing the object file name for that source file, a colon, and the names of all the included files โ including those coming from-includeor-imacroscommand-line options. ๐
Unless specified explicitly (with -MT or -MQ), the object file name consists of the name of the source file with any suffix replaced with object file suffix and with any leading directory parts removed. If there are many included files, then the rule is split into several lines using \-newline. The rule has no commands.
This option does not suppress the preprocessor's debug output, such as -dM. ๐ To avoid mixing such debug output with the dependency rules, you should explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal.
Passing -M to the driver implies -E, and suppresses warnings with an implicit -w. ๐คซ
-MMโ like-Mbut do not mention header files that are found in system header directories, nor header files that are included, directly or indirectly, from such a header.
This implies that the choice of angle brackets or double quotes in an #include directive does not in itself determine whether that header appears in -MM dependency output. ๐ค
-MFfile โ when used with-Mor-MM, specifies a file to write the dependencies to. If no-MFswitch is given, the preprocessor sends the rules to the same place it would send preprocessed output. ๐
okay so this bit is the continuation of the -MF saga, no re-intro needed, we're just sliding right in ๐
When you use it alongside the driver options -MD or -MMD, -MF overrides whatever the default dependency output file would've been.
If file is -, then the dependencies get written to stdout. yes, straight to your terminal, iconic behaviour honestly.
-MGโ When you're using this together with an option like-Mthat's asking for dependency generation,-MGjustโฆ assumes any missing header files are generated files, and adds them to the dependency list without throwing an error at you. The dependency filename is taken directly from the#includedirective, no path prepended, none of that.-MGalso suppresses preprocessed output, because bestie, a missing header file makes that output useless anyway.
This feature gets used for automatic updating of makefiles. slay.
-Mno-modulesโ Disable dependency generation for compiled module interfaces. that's it, that's the whole vibe.-MPโ This one tells CPP to add a phony target for each dependency other than the main file, so each one depends on nothing. These dummy rules work around the errorsmakethrows at you when you delete header files without updating the Makefile to match. classic.
This is the typical output you get:
test.o: test.c test.h
test.h:
-MT targetโ Changes the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix like.c, and appends the platform's usual object suffix. boom, that's your target.
An -MT option sets the target to be exactly the string you specify. Want multiple targets? You can pass them as a single argument to -MT, or just use multiple -MT options. your call, queen.
For example, -MT '$(objpfx)foo.o' might give you
$(objpfx)foo.o: foo.c
-MQ targetโ Same as-MT, except it quotes any characters that are special to Make. So-MQ '$(objpfx)foo.o'gives
$$(objpfx)foo.o: foo.c
The default target gets automatically quoted, as if you'd given it with -MQ. the compiler did it for you, no notes.
-MDโ-MDis equivalent to-M -MF file, except that-Eis not implied. The driver figures out file based on whether an-ooption was given. If it was, the driver uses its argument but with a suffix of.d. Otherwise it takes the name of the input file, strips any directory components and suffix, and slaps a.dsuffix on there.
If -MD is used with -E, any -o switch is understood to specify the dependency output file โ but if it's used without -E, each -o is understood to specify a target object file. subtle but important, iykyk.
Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process. multitasking queen.
-MMDโ Like-MDexcept it only mentions user header files, not system header files. we're keeping it selective ๐-fpreprocessedโ Indicate to the preprocessor that the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments, so you can pass a file preprocessed with-Cto the compiler without problems. In this mode the integrated preprocessor is little more than a tokenizer for the front ends. glorified tokenizer era.
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions that GCC uses for preprocessed files created by -save-temps.
-fdirectives-onlyโ When preprocessing, handle directives, but do not expand macros.
The behaviour of this option depends on the -E and -fpreprocessed options. it's giving conditional energy.
With -E, preprocessing is limited to the handling of directives such as #define, #ifdef, and #error. Other preprocessor operations, like macro expansion and trigraph conversion, are not performed. On top of that, the -dD option is implicitly enabled.
With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as __LINE__, which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with -E -fdirectives-only.
With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with -E -fdirectives-only.
-fdollars-in-identifiersโ Accept$in identifiers. just letting the dollar sign in, we love inclusivity โจ-fextended-identifiersโ Accept universal character names and extended characters in identifiers. This option is enabled by default for C99 (and later C standard versions) and C++. default behaviour, no extra work needed.-fno-canonical-system-headersโ When preprocessing, do not shorten system header paths with canonicalization. leave those paths long, bestie.-fmax-include-depth=depthโ Set the maximum depth of the nested#include. The default is200.-ftabstop=widthโ Set the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. If the value is less than1or greater than100, the option is ignored. The default is8.-ftrack-macro-expansion[=level]โ Track locations of tokens across macro expansions. This lets the compiler emit diagnostics about the current macro expansion stack when a compilation error happens inside a macro expansion. Heads up though: using this option makes the preprocessor and the compiler consume more memory. The level parameter can be used to choose the level of precision of token location tracking, so you can dial down the memory consumption if you need to. Value0of level de-activates this option. Value1tracks token locations in a degraded mode for the sake of minimal memory overhead โ in this mode, all tokens resulting from the expansion of an argument of a function-like macro have the same location. Value2tracks token locations completely, and this value is the most memory hungry. When this option is given no argument, the default parameter value is2.
Note that -ftrack-macro-expansion=2 is activated by default.
-fmacro-prefix-map=old=newโ When preprocessing files residing in directory old, expand the__FILE__and__BASE_FILE__macros as if the files resided in directory new instead. This can be used to change an absolute path to a relative path by using.for new, which can result in more reproducible builds that are location independent. This option also affects__builtin_FILE()during compilation. See also-ffile-prefix-mapand-fcanon-prefix-map.-fexec-charset=charsetโ Set the execution character set, used for string and character constants. The default isUTF-8. charset can be any encoding supported by the system'siconvlibrary routine. so many options, so little time.-fwide-exec-charset=charsetโ Set the wide execution character set, used for wide string and character constants. The default is one ofUTF-32BE,UTF-32LE,UTF-16BE, orUTF-16LE, whichever corresponds to the width ofwchar_tand the big-endian or little-endian byte order being used for code generation. As with-fexec-charset, charset can be any encoding supported by the system'siconvlibrary routine; however, you will have problems with encodings that do not fit exactly inwchar_t. consider yourself warned ๐ญ-finput-charset=charsetโ Set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default isUTF-8. This can be overridden by either the locale or this command-line option. Currently the command-line option takes precedence if there's a conflict. charset can be any encoding supported by the system'siconvlibrary routine.-fpch-depsโ When using precompiled headers, this flag causes the dependency-output flags to also list the files from the precompiled header's dependencies. If it's not specified, only the precompiled header gets listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used. mystery files, we don't talk about them ๐ซถ-fpch-preprocessโ This option allows use of a precompiled header together with-E. It inserts a special#pragma, specifically#pragma GCC pch_preprocess "filename", in the output to mark the place where the precompiled header was found, plus its filename. When-fpreprocessedis in use, GCC recognizes this#pragmaand loads the PCH.
This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.
You should not write this #pragma in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC's current directory. don't do the first thing, the second thing is fine, ok?
-fworking-directoryโ Enable generation of linemarkers in the preprocessor output that let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory, when it's present in the preprocessed input, as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debugging information is enabled, but this can be inhibited with the negated form-fno-working-directory. If the-Pflag is present in the command line, this option has no effect, since no#linedirectives are emitted whatsoever. conflicting flags era ๐-A predicate=answerโ Make an assertion with the predicate predicate and answer answer. This form is preferred to the older form-A predicate(answer), which is still supported, because it does not use shell special characters. newer form ate, periodt.-A -predicate=answerโ Cancel an assertion with the predicate predicate and answer answer. undoing the thing, we love a reversible queen.-Cโ Do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which get deleted along with the directive.
You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #. yeah. that's a whole thing. be ready for it.
-CCโ Do not discard comments, including during macro expansion. This is like-C, except that comments contained within macros are also passed through to the output file where the macro is expanded. the extra-C really said "and I'll go further" ๐ฅ
okay that's the end of this chunk bestie, more incoming, don't go anywhere ๐ธ
So basically -CC rolls up to -C and does everything it does, PLUS it takes every C++-style comment (you know, the // ones) that's chillin' inside a macro and turns it into a C-style comment instead. Why tho? Because otherwise later on, when that macro gets used, it would accidentally comment out the whole rest of the source line and everything would fall apart ๐. It's a whole trap, bestie.
So like, -CC is mainly there to support lint comments. That's its whole job. Periodt.
-Pโ ok so this one stops linemarkers from showing up in the preprocessor output. When's that useful? When you're running the preprocessor on something that is NOT C code, and it's getting piped to a program that would be all confused by linemarkers. So you just... kill them. Simple ๐-traditional,-traditional-cppโ these try to imitate how pre-standard C preprocessors behaved, instead of the ISO C preprocessors we have now. The GNU CPP manual has all the tea if you want details.
Heads up tho fr: GCC does NOT otherwise try to emulate a pre-standard C compiler, and these options only work with the -E switch, or when you're invoking CPP directly. Nowhere else. So don't come for me.
-trigraphsโ turn on ISO C trigraphs. A trigraph is a three-character sequence, all starting with??, that ISO C says stands for one single character. Example:??/means\, so'??/n'is a character constant for a newline. Cute right? ๐ฆ
The nine trigraphs and what they turn into:
Trigraph: ??( ??) ??< ??> ??= ??/ ??' ??! ??-
Replacement: [ ] { } # \ ^ | ~
By default GCC ignores trigraphs (it's giving "I don't see them"), but in standard-conforming modes it converts them. Peep the -std and -ansi options for that.
-remapโ turns on special code to work around file systems that only allow super short file names, like MS-DOS. Throwback energy fr ๐-Hโ prints the name of every header file used, on top of the normal stuff it's already doing. Each name gets indented so you can see how deep in the#includestack it is (nesting visualisation, iconic). Precompiled header files get printed too, even if they turn out to be invalid! And the way it tells you: an invalid precompiled header file is printed with...xand a valid one with...!. Noted ๐-dlettersโ tells GCC to make debugging dumps during compilation, specified byletters. The flags documented right here are the ones relevant to the preprocessor. Other letters get interpreted by the compiler proper, or they're being saved for future versions of GCC, so they're just silently ignored (they said "not my problem"). And if you specify letters whose behaviours conflict? The result is undefined. That's the danger zone, bestie ๐จ-dMโ instead of the normal output, it generates a list of#definedirectives for ALL the macros defined during the preprocessor's run, including predefined ones. This is literally how you find out what's predefined in your version of the preprocessor. Say you have no filefoo.h, then this command:
touch foo.h; cpp -dM foo.h
...shows you all the predefined macros. Chef's kiss.
But wait โ if you use -dM WITHOUT the -E option, then -dM gets interpreted as a synonym for -fdump-rtl-mach. Yeah. Sneaky.
-dDโ like-dMexcept in two ways: it does NOT include the predefined macros, and it outputs BOTH the#definedirectives AND the result of preprocessing. Both kinds of output go to the standard output file.-dNโ like-dD, but it emits only the macro names, not what they expand to. Names only, no spoilers ๐-dIโ outputs#includedirectives in addition to the result of preprocessing.-dUโ like-dDexcept only macros that get expanded, or whose definedness is tested in preprocessor directives, are output. The output is delayed until the use or test of the macro happens, and#undefdirectives are also output for macros that got tested but were undefined at the time.
-fdebug-cppโ this one is ONLY useful for debugging GCC itself. When you use it from CPP or with-E, it dumps debugging info about location maps. Every token in the output gets preceded by the dump of the map its location belongs to.
When it's used from GCC without -E, it does absolutely nothing. Nada. Zero effect. ๐ญ
-Wp,optionโ you can use-Wp,optionto bypass the compiler driver entirely and passoptionstraight through to the preprocessor. Ifoptionhas commas in it, it gets split into multiple options at the commas. BUT โ and this is a big but โ lots of options get modified, translated, or interpreted by the compiler driver before they ever reach the preprocessor, and-Wpforcibly skips that whole phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid-Wpand just let the driver handle the options instead. It's giving "risky shortcut" ngl.-Xpreprocessoroption โ passesoptionas an option to the preprocessor. Use this to supply system-specific preprocessor options that GCC doesn't recognise. And if you want to pass an option that takes an argument, you have to use-XpreprocessorTWICE โ once for the option and once for the argument. Two times. Not one. โจ-no-integrated-cppโ performs preprocessing as a separate pass before compilation. By default GCC does preprocessing as an integrated part of input tokenization and parsing. But if you provide this option, the appropriate language front end โcc1,cc1plus, orcc1objfor C, C++, and Objective-C respectively โ gets invoked twice instead: once for preprocessing only, and once for the actual compilation of the preprocessed input. This may be useful alongside the-Bor-wrapperoptions, to specify an alternate preprocessor or do extra processing of the program source between normal preprocessing and compilation. Fancy ๐-flarge-source-filesโ adjusts GCC to expect large source files, at the cost of slower compilation and higher memory usage. Trade-offs, always trade-offs.
Here's the detail: GCC normally tracks both column numbers and line numbers inside source files, and normally prints both of them in diagnostics. But once it's processed a certain number of source lines, it STOPS tracking column numbers and only tracks line numbers. Which means diagnostics for later lines won't include column numbers. It also means options like -Wmisleading-indentation just stop working at that point โ although the compiler does print a note if this happens, so at least it tells you. Passing -flarge-source-files significantly increases the number of source lines GCC can process before it stops tracking columns. Big files, big brain ๐ง
โจ Passing Options to the Assembler โจ
So you can also pass options to the assembler. Yes, really.
-Wa,optionโ passesoptionas an option to the assembler. Ifoptioncontains commas, it gets split into multiple options at the commas. Same comma logic, different destination.-Xassembleroption โ passesoptionas an option to the assembler. Use this to supply system-specific assembler options that GCC doesn't recognise. And again, if you want to pass an option that takes an argument, you must use-Xassemblertwice โ once for the option, once for the argument. Twice. Always twice. ๐ซถ
๐ Options for Linking ๐
These options come into play when the compiler links object files into an executable output file. And heads up โ they are meaningless if the compiler isn't doing a link step. Like, they just sit there. So know when they matter, bestie.
- object-file-name โ a file name that doesn't end in a special recognised suffix is considered to name an object file or a library. (The linker tells object files apart from libraries by looking at the file contents, iykyk.) If linking is happening, these object files are used as input to the linker.
-c,-S,-Eโ if ANY of these options is used, then the linker does NOT run, and object file names should not be used as arguments. Simple as that.-flinker-output=typeโ this option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. But for debugging the compiler, or if you want incremental linking with a non-LTO object file, it might be useful to control the type manually.
If type is exec, code generation produces a static binary. In this case -fpic and -fpie are both disabled.
If type is dyn, code generation produces a shared library. In this case -fpic or -fPIC is preserved, but NOT enabled automatically. This lets you build shared libraries without position-independent code on architectures where that's possible, i.e. on x86.
If type is pie, code generation produces an -fpie executable. This results in similar optimizations as exec, except that -fpie is not disabled if it's specified at compilation time.
If type is rel, the compiler assumes incremental linking is being done. The sections containing intermediate code for link-time optimization get merged, pre-optimized, and output to the resulting object file. Plus, if -ffat-lto-objects is specified, binary code is produced for future non-LTO linking. The object file produced by incremental linking is smaller than a static library produced from the same object files. And at link time, the result of incremental linking also loads faster than a static library โ assuming the majority of objects in the library are actually used. Slay โจ
Finally, nolto-rel configures the compiler for incremental linking where code generation is forced, a final binary is produced, and the intermediate code for later link-time optimization is stripped. When multiple object files get linked together, the resulting code is better optimized than with link-time optimizations disabled (cross-module inlining happens, for example), but most of the benefits of whole program optimizations are lost. RIP to those benefits ๐
During the incremental link (via -r), the linker plugin defaults to rel. With current interfaces to GNU Binutils though, it's NOT possible to incrementally link LTO objects and non-LTO objects into a single mixed object file. If any of the object files in an incremental link can't be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it's recommended to link such objects into a static library instead. Alternatively, you can use H.J. Lu's binutils, which has support for mixed objects. Options, options ๐
-fuse-ld=bfdโ use thebfdlinker instead of the default linker.-fuse-ld=goldโ use thegoldlinker instead of the default linker.-fuse-ld=lldโ use the LLVMlldlinker instead of the default linker.-fuse-ld=moldโ use the Modern Linker (mold) instead of the default linker. Modern, as the name suggests ๐-llibrary,-llibrary โ search the library named library when linking. (The second form, with the library as a separate argument, is only there for POSIX compliance and is not recommended.) The-loption is passed directly to the linker by GCC, so go read your linker documentation for the exact details. The general description below applies to the GNU linker.
and that's where this part wraps, but we are SO not done โ more coming ๐ซถ
The linker goes sniffing through a standard list of directories looking for the library, and that list is like several standard system directories plus whatever extra ones you told it about with -L.
Static libraries are basically archives of object files, and their names look like liblibrary.a. Some targets are also out here supporting shared libraries, which usually have names like liblibrary.so. If the linker finds both, bestie, it gives preference to the shared one โ unless you used -static. That's just how it is. ๐
And okay, the position where you write this option in the command matters, no cap. The linker searches and processes libraries and object files in the order they're specified. So foo.o -lz bar.o searches library z after foo.o but before bar.o. And if bar.o refers to functions in z... those functions may not be loaded. ๐ซ Order is the whole plot.
-lobjcโ this is the special-case edition of-l, and you need it to link an Objective-C or Objective-C++ program. Very specific, very necessary. โจ-nostartfilesโ do not use the standard system startup files when linking. The standard system libraries still get used normally, unless-nostdlib,-nolibc, or-nodefaultlibsis also in the mix.-nodefaultlibsโ do not use the standard system libraries when linking. Only the libraries you specify get passed to the linker, and any options that specify linkage of the system libraries โ think-static-libgccor-shared-libgccโ get ignored. The standard startup files are used normally, unless-nostartfilesis used.
Heads up though: the compiler may generate calls to memcmp, memset, memcpy and memmove. Those entries are usually resolved by entries in libc. When you use this option, you've gotta supply those entry points through some other mechanism. ๐
-nolibcโ do not use the C library or the system libraries tightly coupled with it when linking. You'll still link with the startup files, libgcc, or toolchain-provided language support libraries like libgnat, libgfortran or libstdc++ โ unless other options preventing their inclusion are used as well. This typically removes-lcfrom the link command line, plus the system libraries that normally tag along with it and become meaningless once you're assuming there's no C library โ for example-lpthreador-lmin some configurations. The whole point is bare-board targets where there is indeed no C library available. ๐ฆ-nostdlibโ do not use the standard system startup files or libraries when linking. No startup files, and only the libraries you specify get passed to the linker, and options specifying linkage of the system libraries, such as-static-libgccor-shared-libgcc, are ignored.
Same warning as before, bestie: the compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.
Now, one of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a โ a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages. ๐
In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, used to ensure C++ constructors are called.) ๐ซถ
-nostdlib++โ do not implicitly link with standard C++ libraries. That's it, that's the whole vibe.-eentry<br> *--entry=entry* โ specify that the program entry point is entry. The argument gets interpreted by the linker, and the GNU linker accepts either a symbol name or an address. Your call. ๐ธ-pieโ produce a dynamically linked position independent executable on targets that support it. For predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option. Matchy matchy, or chaos. ๐-no-pieโ don't produce a dynamically linked position independent executable. Simple as.-static-pieโ produce a static position independent executable on targets that support it. A static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. For predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option. ๐ฅ-pthreadโ link with the POSIX threads library. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. On some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking. Don't do half the vibe, do the whole vibe. ๐-rโ produce a relocatable object as output. This is also known as partial linking.-rdynamicโ pass the flag-export-dynamicto the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. You need this for some uses ofdlopen, or to allow obtaining backtraces from within a program. Very main character of it. โจ-sโ remove all symbol table and relocation information from the executable. Poof. Gone. ๐-staticโ on systems that support dynamic linking, this overrides-pieand prevents linking with the shared libraries. On other systems, this option has no effect. Literally nothing. ๐-sharedโ produce a shared object which can then be linked with other objects to form an executable. Not all systems support this option. For predictable results, you must also specify the same set of options used for compilation (-fpic,-fPIC, or model suboptions) when you specify this linker option.[1]-shared-libgcc<br> *-static-libgccโ on systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively. If no shared version of libgcc was built when the compiler was configured, these options have no effect.
There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.
Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do. Slay. ๐
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.
However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc. No shortcuts on that one. ๐ซถ
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links against libasan. If libasan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libasan. The-static-libasanoption directs the GCC driver to link libasan statically, without necessarily linking other libraries statically. Just libasan, being special. โญ-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links against libtsan. If libtsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libtsan. The-static-libtsanoption directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically.-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links against liblsan. If liblsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of liblsan. The-static-liblsanoption directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically. ๐ฆ-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links against libubsan. If libubsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libubsan. The-static-libubsanoption directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically.-static-libstdc++โ when the g++ program is used to link a C++ program, it normally automatically links against libstdc++. If libstdc++ is available as a shared library, and the-staticoption is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. The-static-libstdc++option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically. Commitment issues? Solved. ๐-symbolicโ bind references to global symbols when building a shared object. Warn about any unresolved references (unless overridden by the link editor option-Xlinker -z -Xlinker defs). Only a few systems support this option. Fancy, niche, iconic. ๐-Tscript โ use script as the linker script. This option is supported by most systems using the GNU linker. On some targets, such as bare-board targets without an operating system, the-Toption may be required when linking to avoid references to undefined symbols. Required, bestie. Not optional. ๐ญ-Xlinkeroption โ pass option as an option to the linker. You can use this to supply system-specific linker options that GCC does not recognize. Sneaking stuff past GCC's vibe check. ๐
If you wanna pass an option that takes its own separate argument, bestie, you have to use -Xlinker twice โ once for the option itself and once for the argument. Like fr, to pass -assert definitions you write -Xlinker -assert -Xlinker definitions. And it does NOT work to write -Xlinker "-assert definitions" because that shoves the whole string through as one single argument and the linker is just sitting there like ??? that's not what I asked for ๐
When you're using the GNU linker it's usually way comfier to pass arguments to linker options using the option=value syntax instead of as separate arguments. For example you can specify -Xlinker -Map=output.map rather than -Xlinker -Map -Xlinker output.map. Other linkers might not support this syntax for command-line options though, so iykyk ๐
-Wl,optionโ passesoptionas an option to the linker. Ifoptioncontains commas, it gets split into multiple options at the commas. You can use this syntax to hand an argument to the option. For example,-Wl,-Map,output.mappasses-Map output.mapto the linker. When you're using the GNU linker, you can also get the exact same effect with-Wl,-Map=output.map.
NOTE: In Ubuntu 8.10 and later versions, forLDFLAGS, the option-Wl,-z,relrois used. To disable, use-Wl,-z,norelro. โจ
-usymbol โ pretend the symbol symbol is undefined, so it forces linking of library modules to define it. You can use-umultiple times with different symbols to force loading of additional library modules. no cap ๐ซถ-zkeyword โ-zgets passed directly on to the linker along with the keyword keyword. Go check the section in your linker's documentation for the permitted values and what they actually mean ๐
๐ Options for Directory Search ๐
These options tell GCC which directories to go rummaging through for header files, for libraries, and for parts of the compiler itself. the way she searches, obsessed ๐ธ
- *
-I*dir` - *
-iquote*dir` - *
-isystem*dir` -idirafterdir โ add the directory dir to the list of directories to be searched for header files during preprocessing. If dir begins with=or$SYSROOT, then the=or$SYSROOTgets swapped out for the sysroot prefix; see--sysrootand-isysroot.
Directories specified with -iquote apply only to the quote form of the directive, #include "file". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the #include "file" and #include <file> directives. periodt ๐
You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order is:
- For the quote form of the include directive, the directory of the current file is searched first.
- For the quote form of the include directive, the directories specified by
-iquoteoptions are searched in left-to-right order, as they appear on the command line. - Directories specified with
-Ioptions are scanned in left-to-right order. - Directories specified with
-isystemoptions are scanned in left-to-right order. - Standard system directories are scanned.
- Directories specified with
-idirafteroptions are scanned in left-to-right order.
You can use -I to override a system header file, substituting your own version, since these directories get searched before the standard system header file directories. But bestie, please don't use this option to add directories that contain vendor-supplied system header files โ use -isystem for that, okay? ๐
The -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment that's applied to the standard system directories. main character treatment fr ๐
If a standard system include directory, or a directory specified with -isystem, is also specified with -I, then the -I option is ignored. The directory is still searched but as a system directory at its normal position in the system include chain. This is all to make sure that GCC's procedure to fix buggy system headers and the ordering for the #include_next directive don't get inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options. ๐
-I-โ split the include path. This option has been deprecated. Please use-iquoteinstead for-Idirectories before the-I-and then just remove the-I-option entirely. she's over, retired, no more ๐
Any directories specified with -I options before -I- are searched only for headers requested with #include "file"; they are not searched for #include <file>. If additional directories are specified with -I options after the -I-, those directories get searched for all #include directives.
On top of that, -I- inhibits the use of the directory of the current file directory as the first search directory for #include "file". And there is no way to override this effect of -I-. sorry not sorry ๐ญ
-iprefixprefix โ specify prefix as the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final/in there, don't forget it ๐- *
-iwithprefix*dir` -iwithprefixbeforedir โ append dir to the prefix specified previously with-iprefix, and add the resulting directory to the include search path.-iwithprefixbeforeputs it in the same place-Iwould;-iwithprefixputs it where-idirafterwould. cute little placement rules, we love a system โจ-isysrootdir โ this one is like the--sysrootoption, but it applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the--sysrootoption for more info ๐ฆ-imultilibdir โ use dir as a subdirectory of the directory containing target-specific C++ headers.-nostdincโ do not search the standard system directories for header files. Only the directories explicitly specified with-I,-iquote,-isystem, and/or-idirafteroptions (and the directory of the current file, if appropriate) get searched.-nostdinc++โ do not search for header files in the C++-specific standard directories, but still search the other standard directories. (This option is used when building the C++ library.) ๐ค-iplugindir=dir โ set the directory to search for plugins that are passed by-fplugin=nameinstead of-fplugin=path/name.so. This option is not meant to be used by the user โ it's only passed by the driver. lowkey internal business, mind yours ๐-Ldir โ add directory dir to the list of directories to be searched for-l.-Bprefix โ this option specifies where to find the executables, libraries, include files, and data files of the compiler itself. iconic housekeeping ๐
The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.
For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name isn't found, or if -B isn't specified, the driver tries two standard prefixes: /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that's found, the unmodified program name is searched for using the directories specified in your PATH environment variable. the search order is so thorough, she does not skip steps ๐
The compiler checks to see if the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.
-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.
The runtime support file libgcc.a can also be searched for using the -B prefix, if needed. If it's not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it's not found by those means. so like, keep that in mind ๐
Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.
As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it's replaced by [dir/]include. This is to help with boot-strapping the compiler. a lil niche hack, we stan ๐
-no-canonical-prefixesโ don't expand any symbolic links, don't resolve references to/../or/./, and don't make the path absolute when generating a relative prefix. leave it as is, bestie โจ--sysroot=dir โ use dir as the logical root directory for headers and libraries. For example, if the compiler normally searches for headers in/usr/includeand libraries in/usr/lib, it instead searchesdir/usr/includeanddir/usr/lib. everything shifts under the new root, slay ๐
If you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files. splitting duties, very organized ๐
The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker doesn't support this option, the header file aspect of --sysroot still works, but the library aspect does not. half a win is still a win ๐ซถ
--no-sysroot-suffixโ for some targets, a suffix gets added to the root directory specified with--sysroot, depending on the other options used, so that headers may for example be found indir/suffix/usr/includeinstead ofdir/usr/include. This option disables the addition of such a suffix. bye suffix, not today ๐
๐ ๏ธ Options for Code Generation Conventions ๐ ๏ธ
These machine-independent options control the interface conventions used in code generation. the ~vibes~ of the generated code, essentially ๐ธ
Most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed โ the one that is not the default. You can figure out the other form by either removing no- or adding it. it's giving mirror energy, you got this ๐
- *
-fstack-reuse=reuse-level*** โ okay so this one is literally the boss of how GCC reuses stack space, both for the local/auto variables *you* declared and for the temporaries the compiler made behind the scenes ๐ *reuse-level* can beall,named_vars, ornone`. Let me break it down bestie:allโ stack reuse is ON for everything: all local variables and all temporaries. โจnamed_varsโ reuse only happens for user-defined local variables that actually have names. ๐noneโ stack reuse is completely off, periodt. ๐ซ
The default value is all. You need this option when your program extends the lifetime of a scoped local variable, or of a compiler-generated temporary, past the end point defined by the language โ like, going beyond what the language said was allowed ๐ญ. Here's the tea: when a variable's lifetime ends, and that variable lives in memory, the optimizing compiler is free to reuse its stack space with other temporaries or scoped locals whose live range doesn't overlap with it. So legacy code that extends local lifetime is likely to break with the stack reuse optimization. It's giving "living on borrowed time" fr fr.
For example:
int *p;
{
int local1;
p = &local1;
local1 = 10;
....
}
{
int local2;
local2 = 20;
...
}
if (*p == 10) // out of scope use of local1
{
}
Another example:
struct A
{
A(int k) : i(k), j(k) { }
int i;
int j;
};
A *ap;
void foo(const A& ar)
{
ap = &ar;
}
void bar()
{
foo(A(10)); // temp object's lifetime ends when foo returns
{
A a(20);
....
}
ap->i+= 10; // ap references out of scope temp whose space
// is reused with a. What is the value of ap->i?
}
The lifetime of a compiler-generated temporary is well defined by the C++ standard ๐ธ. When a temporary's lifetime ends, and if that temporary lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range doesn't overlap with it. But some legacy code lowkey relies on the behavior of older compilers where temporaries' stack space is not reused, and the aggressive stack reuse can lead to runtime errors ๐. So this option is your little control knob for the temporary stack reuse optimization. iykyk.
-ftrapvโ this option generates traps for signed overflow on addition, subtraction, and multiplication operations ๐ชค. And here's the messy part:-ftrapvand-fwrapvoverride each other, so using-ftrapv -fwrapvon the command line results in-fwrapvbeing effective. Note that only active options override, so using-ftrapv -fwrapv -fno-wrapvon the command line results in-ftrapvbeing effective. Not me having to read that twice ๐ญ โ the order and the negations matter, bestie.-fwrapvโ this one tells the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation ๐. This flag enables some optimizations and disables others. Same drama as above:-ftrapvand-fwrapvoverride each other, so-ftrapv -fwrapvon the command line results in-fwrapvbeing effective. And again, only active options override โ so-ftrapv -fwrapv -fno-wrapvon the command line results in-ftrapvbeing effective. โจ-fwrapv-pointerโ instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation ๐. This flag disables some optimizations which assume pointer overflow is invalid. Yes, pointers get their own little wrap rule. Slay.-fstrict-overflowโ this option implies-fno-wrapv -fno-wrapv-pointer, and when negated implies-fwrapv -fwrapv-pointer. That's it, that's the whole vibe. Short and iconic ๐.-fexceptionsโ Enable exception handling ๐จ. It generates the extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you don't specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that don't normally require it. However, you may need to turn it on when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you're compiling older C++ programs that don't use exception handling. Basically: know your language's default, don't get caught lacking ๐.-fnon-call-exceptionsโ generates code that allows trapping instructions to throw exceptions. Heads up though: this requires platform-specific runtime support that does not exist everywhere ๐๐ซ. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as"SIGALRM". This enables-fexceptions.-fdelete-dead-exceptionsโ considers that instructions which may throw exceptions but don't otherwise contribute to the program's execution can be optimized away ๐๏ธ. This does not affect calls to functions except those with the"pure"or"const"attributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels.-funwind-tablesโ similar to-fexceptions, except that it just generates any needed static data, but does not affect the generated code in any other way โจ. You normally do not need to enable this option; instead, a language processor that needs this handling enables it on your behalf. So like, not your job bestie, let the language processor handle it ๐ซถ.-fasynchronous-unwind-tablesโ generate unwind table in DWARF format, if supported by the target machine ๐. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as debugger or garbage collector). Chef's kiss for debugging ๐ .-fno-gnu-uniqueโ okay on systems with a recent GNU assembler and C library, the C++ compiler uses the"STB_GNU_UNIQUE"binding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence of"RTLD_LOCAL". Why tho? Because it's necessary to avoid problems with a library used by two different"RTLD_LOCAL"plugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. But โ and this is the plot twist โ this causes"dlclose"to be ignored for affected DSOs ๐ญ. So if your program relies on reinitialization of a DSO via"dlclose"and"dlopen", you can use-fno-gnu-unique. Fix the vibe, break the other vibe, you know how it is.-fpcc-struct-returnโ return"short""struct"and"union"values in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers, particularly the Portable C Compiler (pcc) ๐ค.
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the-fpcc-struct-returnswitch is not binary compatible with code compiled with the-freg-struct-returnswitch โ ๏ธ. Use it to conform to a non-default application binary interface.
-freg-struct-returnโ return"struct"and"union"values in registers when possible โก. This is more efficient for small structures than-fpcc-struct-return.
If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there is no standard convention, GCC defaults to -fpcc-struct-return, except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative. Main character choice fr ๐
.
Warning: code compiled with the-freg-struct-returnswitch is not binary compatible with code compiled with the-fpcc-struct-returnswitch โ ๏ธ. Use it to conform to a non-default application binary interface.
-fshort-enumsโ allocate to an"enum"type only as many bytes as it needs for the declared range of possible values ๐. Specifically, the"enum"type is equivalent to the smallest integer type that has enough room. Tiny enum, tiny footprint, obsessed.
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch โ ๏ธ. Use it to conform to a non-default application binary interface.
-fshort-wcharโ override the underlying type for"wchar_t"to be"short unsigned int"instead of the default for the target ๐. This option is useful for building programs to run under WINE.
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch โ ๏ธ. Use it to conform to a non-default application binary interface.
-fcommonโ in C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard ๐. Tentative definitions are distinct from declarations of a variable with the"extern"keyword, which do not allocate storage.
The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit. Rude but fair ๐ญ.
The -fcommon places uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This behavior is inconsistent with C++, and on many targets implies a speed and code size penalty on global variable references ๐. It is mainly useful to enable legacy code to link without errors.
-fno-identโ Ignore the"#ident"directive ๐. That's it. Short queen behavior.-finhibit-size-directiveโ bestie, this one tells GCC not to spit out a.sizeassembler directive, or literally anything else that would cause chaos if the function gets split down the middle and the two halves end up placed super far apart in memory ๐. It's used when compilingcrtstuff.c, and that's it โ you should not need it for anything else, fr fr.-fverbose-asmโ this drops extra commentary into the generated assembly so it's actually readable ๐ . Ngl it's generally only useful for the people who genuinely need to read the generated assembly (like, maybe while debugging the compiler itself, iykyk).
-fno-verbose-asm, which is the default, omits that extra info and is handy when you're comparing two assembler files side by side ๐.
The added comments include:
- info on the compiler version and the command-line options,
- the source code lines tied to the assembly instructions, in the form
FILENAME:LINENUMBER:CONTENT OF LINE, - hints about which high-level expressions correspond to the various assembly instruction operands.
For example, given this C source file:
int test (int n)
{
int i;
int total = 0;
for (i = 0; i < n; i++)
total += i * i;
return total;
}
compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -
gcc -S test.c -fverbose-asm -Os -o -
gives output similar to this:
.file "test.c"
# GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu)
[...snip...]
# options passed:
[...snip...]
.text
.globl test
.type test, @function
test:
.LFB0:
.cfi_startproc
# test.c:4: int total = 0;
xorl %eax, %eax # <retval>
# test.c:6: for (i = 0; i < n; i++)
xorl %edx, %edx # i
.L2:
# test.c:6: for (i = 0; i < n; i++)
cmpl %edi, %edx # n, i
jge .L5 #,
# test.c:7: total += i * i;
movl %edx, %ecx # i, tmp92
imull %edx, %ecx # i, tmp92
# test.c:6: for (i = 0; i < n; i++)
incl %edx # i
# test.c:7: total += i * i;
addl %ecx, %eax # tmp92, <retval>
jmp .L2 #
.L5:
# test.c:10: }
ret
.cfi_endproc
.LFE0:
.size test, .-test
.ident "GCC: (GNU) 7.0.0 20160809 (experimental)"
.section .note.GNU-stack,"",@progbits
Heads up bestie: these comments are meant for humans, not machines, so the precise format of the comments is subject to change ๐.
-frecord-gcc-switchesโ this switch makes the command line you used to invoke the compiler get recorded straight into the object file being created ๐ธ. It's only implemented on some targets, and the exact format of the recording depends on the target and binary file format, but it usually looks like a section containing ASCII text. This switch is related to the-fverbose-asmswitch, except that one only records info in the assembler output file as comments, so it never reaches the object file ๐. See also-grecord-gcc-switchesfor another way of storing compiler options into the object file.-fpicโ generates position-independent code (PIC) suitable for use in a shared library, if it's supported for the target machine โจ. Code like this accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (and btw, the dynamic loader is not part of GCC โ it's part of the operating system). If the GOT size for the linked executable blows past a machine-specific maximum size, you get an error message from the linker saying-fpicdoes not work; in that case, recompile with-fPICinstead ๐. (These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit, iconic.)
Position-independent code requires special support, so it only works on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent, periodt.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.
-fPICโ if supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table ๐ฅ. This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Position-independent code requires special support, and therefore works only on certain machines.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 2.
-fpieand-fPIEโ these are similar to-fpicand-fPIC, but the generated position-independent code can be only linked into executables ๐ซถ. Usually these options are used to compile code that will be linked using the-pieGCC option.
-fpie and -fPIE both define the macros "__pie__" and "__PIE__". The macros have the value 1 for -fpie and 2 for -fPIE.
-fno-pltโ do not use the PLT for external function calls in position-independent code ๐. Instead, load the callee address at call sites from the GOT and branch to it. This leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures such as 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives more register allocation freedom to the compiler โจ. Lazy binding requires use of the PLT; with-fno-pltall external symbols are resolved at load time.
Alternatively, the function attribute "noplt" can be used to avoid calls through the PLT for specific external functions.
In position-dependent code, a few targets also convert calls to functions that are marked to not use the PLT to use the GOT instead ๐.
-fno-jump-tablesโ do not use jump tables for switch statements even where it would be more efficient than other code generation strategies ๐. This option is of use in conjunction with-fpicor-fPICfor building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables do not require a GOT and this option is not needed, so don't stress ๐.-fno-bit-testsโ do not use bit tests for switch statements even where it would be more efficient than other code generation strategies ๐ .- *
-ffixed-reg* โ treat the register namedregas a fixed register; generated code should never refer to it (except perhaps as a stack pointer, frame pointer or in some other fixed role) ๐.
reg must be the name of a register. The register names accepted are machine-specific and are defined in the "REGISTER_NAMES" macro in the machine description macro file.
This flag does not have a negative form, because it specifies a three-way choice, fr fr.
- *
-fcall-used-reg* โ treat the register namedregas an allocable register that is clobbered by function calls ๐. It may be allocated for temporaries or variables that do not live across a call. Functions compiled this way do not save and restore the registerreg.
It is an error to use this flag with the frame pointer or stack pointer ๐ญ. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results, no cap.
This flag does not have a negative form, because it specifies a three-way choice.
- *
-fcall-saved-reg* โ treat the register namedregas an allocable register saved by functions ๐ฆ. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the registerregif they use it.
It is an error to use this flag with the frame pointer or stack pointer ๐. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
And a different sort of disaster results from the use of this flag for a register in which function values may be returned ๐ญ.
This flag does not have a negative form, because it specifies a three-way choice.
-fpack-struct[=n]โ without a value specified, pack all structure members together without holes ๐. When a value is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location).
Warning bestie: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch ๐ณ. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.
-fleading-underscoreโ this option and its counterpart,-fno-leading-underscore, forcibly change the way C symbols are represented in the object file ๐ธ. One use is to help link with legacy assembly code.
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch, just so you know ๐ซถ.
- *
-ftls-model=model* โ alter the thread-local storage model to be used โจ. Themodelargument should be one ofglobal-dynamic,local-dynamic,initial-execorlocal-exec. Note that the choice is subject to optimization: the compiler may use a more efficient model for symbols not visible outside of the translation unit, or if-fpicis not given on the command line ๐.
The default without -fpic is initial-exec; with -fpic the default is global-dynamic.
-ftrampolinesโ okay so, for targets that normally need trampolines for nested functions, this makes them always generate them instead of using descriptors. And for targets that don't need them at all (hi HP-PA, hi IA-64 ๐ซถ)? It literally does nothing. Nothing. Zero. ๐
So what even is a trampoline, bestie? It's a tiny lil piece of code that gets created at run time on the stack when the address of a nested function is taken, and it's what lets you call that nested function indirectly. Which means โ and this is the part that matters โ it requires the stack to be made executable for the program to work properly. ๐ Executable stack. Yeah. That's the vibe.
-fno-trampolines is enabled by default on a language-by-language basis, so the compiler can dodge generating them when it computes that it's safe, and swap in descriptors instead. Descriptors are made up of data only, but the generated code has to be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.
๐จ Also, huge heads-up: code compiled with-ftrampolinesand code compiled with-fno-trampolinesare not binary compatible if nested functions are present. So this option must be used on a program-wide basis and be manipulated with extreme care. Not a lil oopsie. A real one. ๐ญ
And for languages other than Ada, the -ftrampolines and -fno-trampolines options currently have no effect, and trampolines are always generated on platforms that need them for nested functions. Periodt.
-fvisibility=[default|internal|hidden|protected]โ this one sets the default ELF image symbol visibility to whatever you picked, meaning all symbols get marked with it unless something overrides it inside the code. Using this can massively improve linking and load times of shared object libraries, produce more optimized code, give you near-perfect API export, and prevent symbol clashes. Use it in every shared object you distribute. That's not a suggestion, that's a whole recommendation. โจ
Despite the fancy nomenclature, default always means public โ i.e. available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage, so the only other commonly used option is hidden. The default if -fvisibility isn't specified is default, i.e. make every symbol public.
Ulrich Drepper's "How To Write Shared Libraries" has a good explanation of the benefits of making sure your ELF symbols have the correct visibility (you can find it at https://www.akkadia.org/drepper/) โ but there's a superior solution this option unlocks: instead of marking things hidden when the default is public, you make the default hidden and mark things public. That's the norm with DLLs on Windows, and with -fvisibility=hidden and __attribute__ ((visibility("default"))) instead of __declspec(dllexport) you get almost identical semantics with identical syntax. Literally a great boon to those working with cross-platform projects. ๐ฆ
If you're adding visibility support to existing code, #pragma GCC visibility may be of use. It works by you enclosing the declarations you want to set visibility for with (for example) #pragma GCC visibility push(hidden) and #pragma GCC visibility pop. Bear in mind that symbol visibility should be viewed as part of the API interface contract, so all new code should always specify visibility when it isn't the default. Like, declarations only for use within the local DSO should always be marked explicitly as hidden, so you avoid PLT indirection overheads โ and making it abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, operator new and operator delete must always be of default visibility. No exceptions, no cap.
Be aware that headers from outside your project โ in particular system headers and headers from any other library you use โ may not be expecting to be compiled with visibility other than the default. You might need to explicitly say #pragma GCC visibility push(default) before including any such headers.
extern declarations are not affected by -fvisibility, so a whole lot of code can be recompiled with -fvisibility=hidden with no modifications. But โ and you knew there was a but โ this means that calls to extern functions with no explicit visibility use the PLT, so it's more effective to use __attribute ((visibility)) and/or #pragma GCC visibility to tell the compiler which extern declarations should be treated as hidden.
Also note that -fvisibility does affect C++ vague linkage entities. So for instance, an exception class thrown between DSOs must be explicitly marked with default visibility so the type_info nodes get unified between the DSOs.
There's an overview of these techniques, their benefits, and how to use them at https://gcc.gnu.org/wiki/Visibility. Go read it, it slaps. ๐
-fstrict-volatile-bitfieldsโ reach for this one if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. Example time: targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide. With this flag you can declare all peripheral bit-fields asunsigned short(assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access. ๐
If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction โ even though that accesses bytes that don't contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. ๐
In some cases, such as when the packed attribute is applied to a structure field, it may not be possible to access the field with a single read or write that's correctly aligned for the target machine. In that case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time. Ate.
Note: due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. So it's recommended to define all bits of the field's type as bit-field members. ๐
The default value of this option is determined by the application binary interface for the target processor.
-fsync-libcallsโ this option controls whether any out-of-line instance of the__syncfamily of functions may be used to implement the C++11__atomicfamily of functions.
The default value is enabled, which means the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library.
GCC Developer Options ๐ปโจ
Okay bestie, this section is for the devs โ the GCC developers themselves. It covers command-line options that are primarily of interest to them, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That includes options that produce debug dumps at various points in the compilation; options that print statistics like memory use and execution time; and options that print information about GCC's configuration, like where it searches for libraries. For ordinary compilation and linking tasks you should rarely need any of these. It's giving backstage pass energy only. ๐๏ธ
Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error.
If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, a phase letter, and a pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it's the source file name. The pass number is determined by the order passes are registered with the compiler's pass manager โ generally the same as the order of execution, but passes registered by plugins, target-specific passes, or passes that are otherwise registered late are numbered higher than the pass named final, even if they're executed earlier. The phase letter is one of i (inter-procedural analysis), l (language-specific), r (RTL), or t (tree). The files are created in the directory of the output file. ๐๏ธ
-fcallgraph-info-fcallgraph-info=MARKERSโ makes the compiler output callgraph information for the program, on a per-object-file basis. The info is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information if you additionally specify a list of comma-separated markers. When thesumarker is specified, the callgraph is decorated with stack usage information โ that's equivalent to-fstack-usage. When thedamarker is specified, the callgraph is decorated with information about dynamically allocated objects. ๐ธ๏ธ
When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files.
-dletters-fdump-rtl-pass-fdump-rtl-pass=filenameโ says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.
Some -dletters switches have different meaning when -E is used for preprocessing.
Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings:
-fdump-rtl-alignmentsโ dump after branch alignments have been computed.-fdump-rtl-asmconsโ dump after fixing rtl statements that have unsatisfied in/out constraints.-fdump-rtl-auto_inc_decโ dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.-fdump-rtl-barriersโ dump after cleaning up the barrier instructions.-fdump-rtl-bbpartโ dump after partitioning hot and cold basic blocks.-fdump-rtl-bbroโ dump after block reordering.-fdump-rtl-btl1-fdump-rtl-btl2โ-fdump-rtl-btl1and-fdump-rtl-btl2enable dumping after the two branch target load optimization passes.-fdump-rtl-bypassโ dump after jump bypassing and control flow optimizations.
-fdump-rtl-combineโ dump after the RTL instruction combination pass ๐-fdump-rtl-compgotosโ dump after duplicating the computed gotos โจ-fdump-rtl-ce1,-fdump-rtl-ce2,-fdump-rtl-ce3โ these three turn on dumping after the three if conversion passes ๐ฆ-fdump-rtl-cprop_hardregโ dump after hard register copy propagation ๐-fdump-rtl-csaโ dump after combining stack adjustments ๐ธ-fdump-rtl-cse1,-fdump-rtl-cse2โ these two turn on dumping after the two common subexpression elimination passes ๐-fdump-rtl-dceโ dump after the standalone dead code elimination passes ๐-fdump-rtl-dbrโ dump after delayed branch scheduling ๐ฅ-fdump-rtl-dce1,-fdump-rtl-dce2โ these two turn on dumping after the two dead store elimination passes ๐-fdump-rtl-ehโ dump after finalization of EH handling code ๐-fdump-rtl-eh_rangesโ dump after conversion of EH handling range regions โญ-fdump-rtl-expandโ dump after RTL generation ๐ง-fdump-rtl-fwprop1,-fdump-rtl-fwprop2โ these two turn on dumping after the two forward propagation passes ๐-fdump-rtl-gcse1,-fdump-rtl-gcse2โ these two turn on dumping after global common subexpression elimination ๐ซถ-fdump-rtl-init-regsโ dump after the initialization of the registers ๐-fdump-rtl-initvalsโ dump after the computation of the initial value sets โจ-fdump-rtl-into_cfglayoutโ dump after converting to cfglayout mode ๐-fdump-rtl-iraโ dump after iterated register allocation ๐-fdump-rtl-jumpโ dump after the second jump optimization ๐ฅ-fdump-rtl-loop2โ this one turns on dumping after the rtl loop optimization passes ๐-fdump-rtl-machโ dump after performing the machine dependent reorganization pass, if that pass exists ๐-fdump-rtl-mode_swโ dump after removing redundant mode switches ๐ธ-fdump-rtl-rnregโ dump after register renumbering ๐-fdump-rtl-outof_cfglayoutโ dump after converting from cfglayout mode ๐ฆ-fdump-rtl-peephole2โ dump after the peephole pass ๐-fdump-rtl-postreloadโ dump after post-reload optimizations ๐-fdump-rtl-pro_and_epilogueโ dump after generating the function prologues and epilogues ๐-fdump-rtl-sched1,-fdump-rtl-sched2โ these two turn on dumping after the basic block scheduling passes โญ-fdump-rtl-reeโ dump after sign/zero extension elimination ๐ง-fdump-rtl-seqabstrโ dump after common sequence discovery ๐-fdump-rtl-shortenโ dump after shortening branches โ๏ธ-fdump-rtl-siblingโ dump after sibling call optimizations ๐ซถ-fdump-rtl-split1,-fdump-rtl-split2,-fdump-rtl-split3,-fdump-rtl-split4,-fdump-rtl-split5โ these options enable dumping after five rounds of instruction splitting ๐-fdump-rtl-smsโ dump after modulo scheduling. This pass is only run on some architectures ๐-fdump-rtl-stackโ dump after conversion from GCC's "flat register file" registers to the x87's stack-like registers. This pass is only run on x86 variants ๐-fdump-rtl-subreg1,-fdump-rtl-subreg2โ these two turn on dumping after the two subreg expansion passes โจ-fdump-rtl-unshareโ dump after all rtl has been unshared ๐ฅ-fdump-rtl-vartrackโ dump after variable tracking ๐ธ-fdump-rtl-vregsโ dump after converting virtual registers to hard registers ๐-fdump-rtl-webโ dump after live range splitting ๐ฆ-fdump-rtl-regclass,-fdump-rtl-subregs_of_mode_init,-fdump-rtl-subregs_of_mode_finish,-fdump-rtl-dfinit,-fdump-rtl-dfinishโ bestie, these dumps are defined but they always produce empty files ๐ญ like they show up to the party and contribute nothing, no cap ๐-da,-fdump-rtl-allโ produce all the dumps listed above. Every single one. Go off ๐-dAโ annotate the assembler output with miscellaneous debugging information ๐-dDโ dump all macro definitions at the end of preprocessing, in addition to normal output ๐-dHโ produce a core dump whenever an error occurs ๐ฅ-dpโ annotate the assembler output with a comment indicating which pattern and alternative is used. The length and cost of each instruction are also printed ๐-dPโ dump the RTL in the assembler output as a comment before each instruction. Also turns on-dpannotation โจ-dxโ just generate RTL for a function instead of compiling it. Usually used with-fdump-rtl-expand๐ง
-fdump-debugโ dump debugging information generated during the debug generation phase ๐-fdump-earlydebugโ dump debugging information generated during the early debug generation phase ๐โจ-fdump-noaddrโ when doing debugging dumps, suppress address output. This makes it more feasible to usediffon debugging dumps for compiler invocations with different compiler binaries and/or different text / bss / data / heap / stack / dso start locations ๐ซถ-freport-bugโ collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs ๐ง๐-fdump-unnumberedโ when doing debugging dumps, suppress instruction numbers and address output. This makes it more feasible to usediffon debugging dumps for compiler invocations with different options, in particular with and without-g๐-fdump-unnumbered-linksโ when doing debugging dumps (see the-doption above), suppress instruction numbers for the links to the previous and next instructions in a sequence ๐-fdump-ipa-switch,-fdump-ipa-switch-optionsโ control the dumping at various stages of inter-procedural analysis language tree to a file. The file name is generated by appending a switch specific suffix to the source file name, and the file is created in the same directory as the output file. The following dumps are possible:allโ enables all inter-procedural analysis dumps ๐cgraphโ dumps information about call-graph optimization, unused function removal, and inlining decisions ๐inlineโ dump after function inlining ๐ซถ
Additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized โจ
For example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined ๐
By default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis ๐
-fdump-ipa-clonesโ create a dump file containing information about creation of call graph node clones and removals of call graph nodes during inter-procedural optimizations and transformations. Its main intended use is that tools that create live-patches can determine the set of functions that need to be live-patched to completely replace a particular function (see-flive-patching). The file name is generated by appending suffix"ipa-clones"to the source file name, and the file is created in the same directory as the output file. Each entry in the file is on a separate line containing semicolon separated fields ๐
In the case of call graph clone creation, the individual fields are:
- String
"Callgraph clone". - Name of the function being cloned as it is presented to the assembler.
- A number that uniquely represents the function being cloned in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
- The file name of the source file where the function is defined.
- The line on which the function definition is located.
- The column where the function definition is located.
- Name of the new function clone as it is presented to the assembler.
- A number that uniquely represents the new function clone in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
- The file name of the source file where the source code location of the new clone points to.
- The line to which the source code location of the new clone points to.
- The column to which the source code location of the new clone points to.
- A string that determines the reason for cloning.
In the case of call graph clone removal, the individual fields are:
- String
"Callgraph removal". - Name of the function being removed as it would be presented to the assembler.
- A number that uniquely represents the function being cloned in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
- The file name of the source file where the function is defined.
- The line on which the function definition is located.
- The column where the function definition is located.
-fdump-langโ dump language-specific information. The file name is made by appending.langto the source file name ๐-fdump-lang-all,-fdump-lang-switch,-fdump-lang-switch-options,-fdump-lang-switch-options=filenameโ control the dumping of language-specific information. The options and filename portions behave as described in the-fdump-treeoption. The following switch values are accepted:allโ enable all language-specific dumps โจclassโ dump class hierarchy information. Virtual table information is emitted unless'slim'is specified. This option is applicable to C++ only ๐
moduleโ dump the module info. Bestie, the extra optionslineno(for locations),graph(reachability),blocks(clusters),uid(serialization),alias(mergeable),asmname(Elrond),eh(mapper) andvops(macros) can give you even more deets. C++ only, so don't come crying if you're on C. ๐rawโ dumps the raw internal tree data. Also C++ only. It's giving "behind the scenes" energy.
-fdump-passesโ prints the list of optimization passes that are getting turned on and off by your current command-line options, straight tostderr. Like a lil receipt of your vibe check. โจ-fdump-statistics-optionโ enables and controls dumping of pass statistics into a separate file. The file name is made by appending a suffix that ends in.statisticsto the source file name, and it lives in the same directory as your output file. If you use the-optionform, then:-statsโ counters get summed over the whole compilation unit-detailsโ dumps every event as the passes generate them
The default with no option at all? Sum counters for each function compiled. Periodt. ๐ซถ
-fdump-tree-all-fdump-tree-switch-fdump-tree-switch-options-fdump-tree-switch-options=filename
Controls the dumping at various stages of processing the intermediate language tree into a file. If you go with the -options form, options is a list of --separated options that control the dump details. Lowkey, not every option works for every dump โ the ones that don't mean anything just get ignored. No hard feelings. ๐
The following options are available:
addressโ print the address of each node. Usually this isn't super meaningful because it changes depending on the environment and source file. Its main character use is tying up a dump file with a debug environment. ๐asmnameโ ifDECL_ASSEMBLER_NAMEhas been set for a given decl, use that in the dump instead ofDECL_NAME. Main use case: making it easier to work backwards from mangled names in the assembly file.slimโ when dumping front-end intermediate representations, this inhibits dumping of members of a scope or the body of a function just because that scope was reached. Only dump those items when they're directly reachable by some other path.
When dumping pretty-printed trees, this option inhibits dumping the bodies of control structures.
When dumping RTL, print the RTL in slim (condensed) form instead of the default LISP-like representation.
rawโ print a raw representation of the tree. By default, trees are pretty-printed into a C-like representation.detailsโ enable more detailed dumps (not honored by every dump option). Also includes info from the optimization passes. ๐statsโ enable dumping of various statistics about the pass (again, not honored by every dump option).blocksโ enable showing basic block boundaries (disabled in raw dumps).graphโ for each of the other indicated dump files (-fdump-rtl-pass), dump a representation of the control flow graph that's suitable for viewing with GraphViz tofile.passid.pass.dot. Every function in the file gets pretty-printed as a subgraph, so GraphViz can render them all in one single plot. Iconic behavior, honestly.
This option currently only works for RTL dumps, and the RTL is always dumped in slim form. No cap.
vopsโ enable showing virtual operands for every statement.linenoโ enable showing line numbers for statements.uidโ enable showing the unique ID (DECL_UID) for each variable.verboseโ enable showing the tree dump for each statement.ehโ enable showing the EH region number holding each statement.scevโ enable showing scalar evolution analysis details.optimizedโ enable showing optimization information (only available in certain passes).missedโ enable showing missed optimization information (only available in certain passes).noteโ enable other detailed optimization information (only available in certain passes).allโ turns on all options, exceptraw,slim,verboseandlineno.optallโ turns on all optimization options, i.e.,optimized,missed, andnote.
To figure out what tree dumps are available or to find the dump for a pass you actually care about, follow these steps, bestie:
- Invoke GCC with
-fdump-passesand in thestderroutput look for a code that corresponds to the pass you're interested in. For example, the codestree-evrp,tree-vrp1, andtree-vrp2correspond to the three Value Range Propagation passes. The number at the end distinguishes distinct invocations of the same pass. ๐ฅ - To enable the creation of the dump file, append the pass code to the
-fdump-option prefix and invoke GCC with it. So for example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the-fdump-tree-evrpoption. Optionally you can specify the name of the dump file. If you don't specify one, GCC creates it as described below. - Find the pass dump in a file whose name is composed of three components separated by a period:
- the name of the source file GCC was invoked to compile,
- a numeric suffix indicating the pass number followed by the letter
tfor tree passes (and the letterrfor RTL passes), - and finally the pass code.
For example, the Early VRP pass dump might be in a file named myfile.c.038t.evrp in the current working directory. Heads up though: the numeric codes are not stable and may change from one version of GCC to another. ๐ญ
-fopt-info-fopt-info-options-fopt-info-options=filename
Controls optimization dumps from various optimization passes. If you use the -options form, options is a list of --separated option keywords used to select the dump details and optimizations.
These options split into three groups:
- options describing what kinds of messages should be emitted,
- options describing the verbosity of the dump, and
- options describing which optimizations should be included.
You can freely mix options from each group since they're non-overlapping. But bestie, if there's any conflict, the later options override the earlier ones on the command line. Them's the rules. ๐
The following options control which kinds of messages get emitted:
optimizedโ print information when an optimization is successfully applied. It's up to a pass to decide which info is relevant. For example, the vectorizer passes print the source location of loops that get successfully vectorized. โจmissedโ print information about missed optimizations. Individual passes control what info goes into the output.noteโ print verbose information about optimizations, like certain transformations, more detailed messages about decisions, etc.allโ print detailed optimization information. This includesoptimized,missed, andnote.
The following option controls the dump verbosity:
internalsโ by default only "high-level" messages are emitted. This option enables additional, more detailed messages that are likely only of interest to GCC developers.
One or more of the following option keywords can be used to describe a group of optimizations:
ipaโ enable dumps from all interprocedural optimizations.loopโ enable dumps from all loop optimizations.inlineโ enable dumps from all inlining optimizations.ompโ enable dumps from all OMP (Offloading and Multi Processing) optimizations.vecโ enable dumps from all vectorization optimizations.optallโ enable dumps from all optimizations. This is a superset of the optimization groups listed above.
If options is omitted, it defaults to optimized-optall, which means: dump messages about successful optimizations from all the passes, omitting messages that are treated as "internals".
If filename is provided, then the dumps from all the applicable optimizations get concatenated into filename. Otherwise the dump is output onto stderr. And yeah, though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided, everything except the first such option is ignored. ๐
Watch out: the output filename gets overwritten if there are multiple translation units. If you want a combined output from multiple translation units, use stderr instead.
In the following example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs the missed optimization report from all the passes into missed.all. And this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints info about missed optimization opportunities from vectorization passes on stderr. Ngl, note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter. ๐ฆ
As another example:
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs info about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
And finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. So only vec.miss is produced, which contains dumps from the vectorizer about missed opportunities. ๐
-fsave-optimization-recordโ writes aSRCFILE.opt-record.json.gzfile detailing what optimizations were performed, for those optimizations that support-fopt-info.
This option is experimental and the format of the data inside the compressed JSON file is subject to change. Don't get too attached, bestie. ๐ญ
It's roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, plus the following additional data for each message:
- the execution count of the code getting optimized, plus the lil metadata about whether that count came from actual profile data or was just a vibe-based estimate โ so whoever's reading can sort messages by code hotness ๐ฅ
- the function name of the code being optimized, where applicable ๐
- the "inlining chain" for the code being optimized โ so when a function gets inlined into a bunch of different spots (which might themselves be inlined, it's giving nesting dolls fr), the reader can tell all the copies apart ๐
- objects that identify which parts of the message refer to expressions, statements or symbol-table nodes, which of those categories they are, and โ when it's available โ their source code location ๐
- the GCC pass that emitted the message โจ
- and the location in GCC's own code from which the message got emitted ๐ซถ
On top of all that, some messages are logically nested inside other messages, reflecting implementation details of the optimization passes. iykyk ๐
๐ฆ -fsched-verbose=n
On targets that actually use instruction scheduling, this one controls how much debugging output the scheduler prints into the dump files.
- For
ngreater than zero,-fsched-verbosespits out the same info as-fdump-rtl-sched1and-fdump-rtl-sched2. - For
ngreater than one, it also gives you basic block probabilities, detailed ready list info, and unit/insn info. - For
ngreater than two, it adds RTL at abort point, plus control-flow and regions info. - And for
nover four,-fsched-verbosealso includes dependence info.
โจ -fenable-kind-pass / -fdisable-kind-pass=range-list
Okay bestie, this is a whole set of options used to explicitly disable/enable optimization passes. These are meant for debugging GCC itself, k? Regular compiler users should just use the normal options for enabling/disabling passes instead โ no cap.
-fdisable-ipa-passโ Disable IPA pass pass. pass is the pass name. If that same pass gets statically invoked in the compiler more than once, you append the pass name with a sequential number starting from1.-fdisable-rtl-pass,-fdisable-rtl-pass=range-listโ Disable RTL pass pass. pass is the pass name. If the same pass is statically invoked multiple times, append the pass name with a sequential number starting from1. The range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair split by a colon, and the range is inclusive on both ends. If the range is trivial, that number pair can be simplified down to a single number. If the function's call graph node's uid falls inside one of the specified ranges, the pass is disabled for that function. The uid shows up in the function header of a dump file, and you can dump the pass names with the option-fdump-passes.-fdisable-tree-pass,-fdisable-tree-pass=range-listโ Disable tree pass pass. Peep-fdisable-rtlfor the description of the option arguments.-fenable-ipa-passโ Enable IPA pass pass. pass is the pass name. If the same pass is statically invoked multiple times, append the pass name with a sequential number starting from1.-fenable-rtl-pass,-fenable-rtl-pass=range-listโ Enable RTL pass pass. Peep-fdisable-rtlfor the option argument description and examples.-fenable-tree-pass,-fenable-tree-pass=range-listโ Enable tree pass pass. Peep-fdisable-rtlfor the description of the option arguments.
Here are some examples showing uses of these options โ icons only, periodt:
# disable ccp1 for all functions
-fdisable-tree-ccp1
# disable complete unroll for function whose cgraph node uid is 1
-fenable-tree-cunroll=1
# disable gcse2 for functions at the following ranges [1,1],
# [300,400], and [400,1000]
# disable gcse2 for functions foo and foo2
-fdisable-rtl-gcse2=foo,foo2
# disable early inlining
-fdisable-tree-einline
# disable ipa inlining
-fdisable-ipa-inline
# enable tree full unroll
-fenable-tree-unroll
๐ -fchecking / -fchecking=n
Enable internal consistency checking. The default depends on how the compiler was configured. And -fchecking=2 turns on even further internal consistency checking that might actually affect code generation. slay but be careful ๐
๐ -frandom-seed=string
This option hands GCC a seed to use instead of random numbers when it's generating certain symbol names that gotta be different in every single compiled file. It's also used to drop unique stamps into coverage data files and the object files that produce them. So you can use -frandom-seed to produce reproducibly identical object files โ obsessed โจ
The string can either be a number (decimal, octal or hex) or an arbitrary string โ in which case it gets converted to a number by computing CRC32.
The string should be different for every file you compile, bestie. fr fr.
๐ธ -save-temps
Store the usual "temporary" intermediate files permanently; name them as auxiliary output files, exactly as described under -dumpbase and -dumpdir.
When you use it together with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file that has the same extension as an intermediate file. The corresponding intermediate file can be obtained by renaming the source file before using -save-temps.
-save-temps=cwdโ Equivalent to-save-temps -dumpdir ./.-save-temps=objโ Equivalent to-save-temps -dumpdir outdir/, whereoutdir/is the directory of the output file specified after the-ooption, including any directory separators. And if the-ooption isn't used, the-save-temps=objswitch behaves like-save-temps=cwd.
โฑ๏ธ -time[=file]
Report the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and the assembler (plus the linker if linking is done, bestie).
Without specifying an output file, the output looks like this:
# cc1 0.12 0.01
# as 0.00 0.01
The first number on each line is the "user time" โ that's time spent executing the program itself. The second number is "system time" โ time spent executing operating system routines on behalf of the program. Both numbers are in seconds. ๐
And with an output file specified, the output gets appended to that named file, and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
Here the "user time" and the "system time" move before the program name, and the options passed to the program get displayed too โ so you can later tell what file was being compiled, and with which options. icon behavior honestly ๐
๐
-fdump-final-insns[=file]
Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is .), the name of the dump file gets determined by appending .gkd to the dump base name โ see -dumpbase.
๐ฆ -fcompare-debug[=opts]
If no error happens during compilation, run the compiler a second time, adding opts and -fcompare-debug-second to the arguments passed to that second compilation. Dump the final internal representation in both compilations, and print an error if they differ. it's giving double-checking bestie ๐
If the equal sign is omitted, the default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if it's defined, non-empty and nonzero, implicitly enables -fcompare-debug. And if GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it's used for opts โ otherwise the default -gtoggle is used.
-fcompare-debug=, with the equal sign but without opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect.
To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning instead, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do.
๐ -fcompare-debug-second
This option gets implicitly passed to the compiler for the second compilation that -fcompare-debug requested, along with options to silence warnings, and it omits other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files get renamed so they contain the .gk additional extension during the second compilation, so nothing overwrites what the first one generated. ๐
When you pass this option to the compiler driver, it makes the first compilation get skipped โ which makes it useful for little other than debugging the compiler proper. ngl that's its whole personality ๐ญ
๐ฅ -gtoggle
Turn off generation of debug info, if leaving out this option generates it, or turn it on at level 2 otherwise. The position of this argument in the command line does not matter โ it takes effect after all other options are processed, and it does so only once, no matter how many times it's given. This is mainly intended to be used with -fcompare-debug. โจ
โญ -fvar-tracking-assignments-toggle
Toggle -fvar-tracking-assignments, in the same way that -gtoggle toggles -g. simple as that bestie ๐
๐ -Q
Makes the compiler print out each function name as it's compiled, and print some statistics about each pass when it finishes. satisfying fr ๐
๐ -ftime-report
Makes the compiler print some statistics about the time consumed by each pass when it finishes.
๐ -ftime-report-details
Record the time consumed by infrastructure parts separately for each pass.
๐ง -fira-verbose=n
Control the verbosity of the dump file for the integrated register allocator. The default value is 5. And if the value n is greater than or equal to 10, the dump output gets sent to stderr using the same format as n minus 10. slay ๐
-flto-reportโ bestie, this prints a lil report with the internal deets on how the link-time optimizer is doing its thing. Heads up tho: what's inside this report changes from version to version, so don't get attached. It's meant to be useful to GCC devs when they're processing object files in LTO mode (that's via-flto). ๐
Disabled by default. (sad but true ๐ซ )
-flto-report-wpaโ literally-flto-report's sibling, except it only prints for the WPA phase of link-time optimization. picky king behavior โจ-fmem-reportโ makes the compiler spill some statistics about permanent memory allocation when it finishes. it's giving receipts at the end of the party ๐-fmem-report-wpaโ same energy as-fmem-report, except it prints those permanent-memory-allocation stats for the WPA phase only. no notes ๐-fpre-ipa-mem-report,-fpost-ipa-mem-reportโ makes the compiler print some permanent memory allocation statistics before or after interprocedural optimization. before and after pics, but for memory ๐-fmultiflagsโ okay so this one enables multilib-aware"TFLAGS"to be used to build target libraries with options that are different from the ones the compiler is configured to use by default, and it does it through the use of specs. yes, specs. we love a technical queen ๐
So, like "TFLAGS", this lets the target libraries get built for portable baseline environments while the compiler itself defaults to more demanding ones. And that's actually useful because users can easily override the defaults the compiler is configured to use when building their own programs (say the defaults aren't ideal for their target environment), whereas rebuilding the runtime libraries is usually not as easy or desirable. no cap.
But unlike "TFLAGS", using specs lets different flags be selected for different multilibs. the way u do that: build with make TFLAGS=-fmultiflags, after configuring --with-specs=%{fmultiflags:...}.
This option is discarded by the driver once it's done processing driver self spec. bye felicia ๐
It's also useful for checking that "TFLAGS" are being used to build all target libraries, by configuring a non-bootstrap compiler --with-specs='%{!fmultiflags:%emissing TFLAGS}' and building the compiler and target libraries. chef's kiss ๐ฅ
-fprofile-reportโ makes the compiler print some statistics about how consistent the (estimated) profile is and the effect of individual passes. gossip about ur own code's behavior, honestly iconic ๐-fstack-usageโ makes the compiler output stack usage info for the program, per-function, bestie. the filename for the dump is made by appending.suto the auxname. and auxname? it's generated from the name of the output file (if it's explicitly specified and it's not an executable), otherwise it's the basename of the source file. okay so an entry is made up of three fields:- the name of the function.
- a number of bytes.
- one or more qualifiers:
"static","dynamic","bounded".
So the qualifier "static" means the function manipulates the stack statically: a fixed number of bytes get allocated for the frame on function entry and released on function exit, and no stack adjustments are otherwise made in the function. in that case the second field is this fixed number of bytes. cute and predictable ๐
The qualifier "dynamic" means the function manipulates the stack dynamically: in addition to the static allocation described above, stack adjustments get made in the body of the function, like to push/pop arguments around function calls. If the qualifier "bounded" is also present, then the amount of these adjustments is bounded at compile time, and the second field is an upper bound of the total amount of stack used by the function. If "bounded" is not present, then the amount of these adjustments is not bounded at compile time, and the second field only represents the bounded part. so like, partial info, don't be fooled ๐
-fstatsโ emit statistics about front-end processing at the end of the compilation. ngl this option is supported only by the C++ front end, and the info is generally only useful to the G++ development team. so it's giving internal-scoop-only ๐-fdbg-cnt-listโ print the name and the counter upper bound for all debug counters. the full roster, no crumbs left behind ๐- *
-fdbg-cnt=counter-value-list* โ set the internal debug counter lower and upper bound. so counter-value-list is a comma-separated list of name:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...] tuples, which sets the name of the counter and a list of closed intervals. The lower_bound is optional and is zero initialized if not set. for example, with-fdbg-cnt=dce:2-4:10-11,tail_call:10,dbg_cnt(dce)returns true only for the second, third, fourth, tenth and eleventh invocation. and fordbg_cnt(tail_call)true is returned for the first 10 invocations. math queen behavior fr fr โจ -print-file-name=library โ print the *full absolute name of the library file *library that would be used when linking---and don't do anything else. With this option, GCC does not compile or link anything; it just prints the file name. one job and it SLAYs at it ๐-print-multi-directoryโ print the directory name corresponding to the multilib selected by any other switches present in the command line. this directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ print the mapping from multilib directory names to compiler switches that enable them. the directory name is separated from the switches by;, and each switch starts with an@instead of the-, with no spaces between multiple switches. this is supposed to ease shell processing. very considerate of them actually ๐ซถ-print-multi-os-directoryโ print the path to OS libraries for the selected multilib, relative to somelibsubdirectory. If OS libraries are present in thelibsubdirectory and no multilibs are used, this is usually just., if OS libraries are present inlibsuffix sibling directories then this prints e.g.../lib64,../libor../lib32, or if OS libraries are present inlib/subdirsubdirectories it prints e.g.amd64,sparcv9orev6. it's giving choose-your-own-adventure with paths ๐-print-multiarchโ print the path to OS libraries for the selected multiarch, relative to somelibsubdirectory. short, sweet, iconic.- *
-print-prog-name=program* โ like-print-file-name, but it searches for a program such ascpp. different hunt, same energy ๐ -print-libgcc-file-nameโ same as-print-file-name=libgcc.a.
This is useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a. u can do:
gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
look at that backtick moment, we love a shell substitution โจ
-print-search-dirsโ print the name of the configured installation directory and a list of program and library directoriesgccsearches---and don't do anything else.
This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this, you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Don't forget the trailing /. like actually don't, bestie, it will not work ๐ญ
-print-sysrootโ print the target sysroot directory that's used during compilation. This is the target sysroot specified either at configure time or using the--sysrootoption, possibly with an extra suffix that depends on compilation options. If no target sysroot is specified, the option prints nothing. silence. crickets. ๐ฆ-print-sysroot-headers-suffixโ print the suffix added to the target sysroot when searching for headers, or give an error if the compiler is not configured with such a suffix---and don't do anything else. it's giving all-or-nothing ๐-dumpmachineโ print the compiler's target machine (for example,i686-pc-linux-gnu)---and don't do anything else. identity reveal moment ๐-dumpversionโ print the compiler version (for example,3.0,6.3.0or7)---and don't do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured, it can be just a single number (major version), two numbers separated by a dot (major and minor version) or three numbers separated by dots (major, minor and patchlevel version). so basically it might give u 1, 2, or 3 numbers, depends on the vibe check of the config ๐-dumpfullversionโ print the full compiler version---and don't do anything else. The output is always three numbers separated by dots, major, minor and patchlevel version. no ambiguity, no crumbs, we love consistency โจ-dumpspecsโ print the compiler's built-in specs---and don't do anything else. (This is used when GCC itself is being built.) behind-the-scenes tea โ
Machine-Dependent Options ๐ ๏ธ
Okay so here's the thing bestie: each target machine supported by GCC can have its own options---like, to let u compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m. iykyk ๐
Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform. friendly like that ๐ซถ
AArch64 Options ๐
These options are defined for AArch64 implementations:
- *
-mabi=name* โ generate code for the specified data model. Permissible values areilp32for a SysV-like data model whereint,long intand pointers are 32 bits, andlp64for a SysV-like data model whereintis 32 bits, butlong intand pointers are 64 bits.
The default depends on the specific target configuration. Note that the LP64 and ILP32 ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. no mixing, bestie, that's a crime fr ๐
-mbig-endianโ generate big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target. big endian bestie ๐-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. so the compiler chills but the assembler does whatever it wants ๐ญ-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for anaarch64-*-*but not anaarch64_be-*-*target. the lil endian icon ๐-mcmodel=tinyโ generate code for the tiny code model. The program and its statically defined symbols must be within 1MB of each other. Programs can be statically or dynamically linked. smol but mighty ๐ฃ-mcmodel=smallโ generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. the main character of code models ๐-mcmodel=largeโ generate code for the large code model. This makes no assumptions about addresses and sizes of sections. Programs can be statically linked only. The-mcmodel=largeoption is incompatible with-mabi=ilp32,-fpicand-fPIC. big model, big rules, and some of those combos? absolutely not bestie ๐ซ-mstrict-align-mno-strict-alignโ okay so this is the alignment vibe check ๐-mstrict-alignsays no ma'am to generating memory accesses that aren't lined up on a natural object boundary like the architecture spec describes, and-mno-strict-alignis like "eh, go off, do whatever." Pick your fighter.-momit-leaf-frame-pointer-mno-omit-leaf-frame-pointerโ do we keep the frame pointer in leaf functions or not? ๐ซถ-momit-leaf-frame-pointeryeets it,-mno-omit-leaf-frame-pointerkeeps it around. And the yeeting one? That's literally the default. periodt.- *
-mstack-protector-guard=guard* - *
-mstack-protector-guard-reg=reg* - *
-mstack-protector-guard-offset=offset* โ stack protection code time, bestie ๐ก๏ธ what this does is generate the stack protection using a canary atguard. The supported locations areglobalfor a global canary, orsysregfor a canary living in an appropriate system register.
If you pick that second one, then -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset come in and specify which system register to use as the base register for reading the canary, plus what offset from that base register to read from. Heads up tho: there's no default register or offset, because this is entirely for use inside the Linux kernel. ikyk. ๐ฅ
-mtls-dialect=descโ use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables โจ and yeah, this one's the default.-mtls-dialect=traditionalโ use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables. old school, still slays ๐-mtls-size=sizeโ set the bit size of immediate TLS offsets ๐ซ valid values are12,24,32,48. Oh and this option **requires binutils 2.26 or newer, no cap.-mfix-cortex-a53-835769-mno-fix-cortex-a53-835769โ turn the workaround for the ARM Cortex-A53 erratum number 835769 on or off ๐ what the workaround actually does is insert aNOPinstruction between memory instructions and 64-bit integer multiply-accumulate instructions. tiny little breather in the pipeline, iconic.-mfix-cortex-a53-843419-mno-fix-cortex-a53-843419โ turn the workaround for the ARM Cortex-A53 erratum number 843419 on or off ๐ธ this erratum workaround is made at link time, and this option will only pass the corresponding flag to the linker. so it's like, not even doing the thing itself, it's delegating. main character energy fr fr.-mlow-precision-recip-sqrt-mno-low-precision-recip-sqrtโ enable or disable the reciprocal square root approximation ๐งฎ honestly? this option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. enabling it reduces the precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. speed over accuracy, we love a tradeoff ๐-mlow-precision-sqrt-mno-low-precision-sqrtโ enable or disable the square root approximation ๐ same deal, it only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. enabling it drops the precision of square root results to about 16 bits for single precision and 32 bits for double precision. Oh and plot twist โ if you enable it, it implies-mlow-precision-recip-sqrt. package deal bestie ๐-mlow-precision-div-mno-low-precision-divโ enable or disable the division approximation ๐ yes this one is also only doing anything if-ffast-mathor-funsafe-math-optimizationsis used as well. enabling it reduces the precision of division results to about 16 bits for single precision and 32 bits for double precision.-mtrack-speculation-mno-track-speculationโ enable or disable generating extra code to track speculative execution through conditional branches ๐ that tracking state can then be used by the compiler when it's expanding calls to__builtin_speculation_safe_copy, which lets it generate a more efficient code sequence. smart girl behavior ngl.-moutline-atomics-mno-outline-atomicsโ enable or disable calls to out-of-line helpers that implement atomic operations โ๏ธ these helpers will, at runtime, figure out whether the LSE instructions from ARMv8.1-A can be used; and if they can't, they'll fall back to the load/store-exclusive instructions that are present in the base ARMv8.0 ISA. adaptive queen ๐
This option is only applicable when compiling for the base ARMv8.0 instruction set. If you're on a later revision โ like -march=armv8.1-a or -march=armv8-a+lse โ then the ARMv8.1-Atomics instructions get used directly. Same story when you're using -mcpu= and the selected cpu supports the lse feature. Oh, and it's on by default. ๐
- *
-march=name* โ specify the name of the target architecture, and optionally one or more feature modifiers โจ this option has the form-march=arch{+[no]feature}*.
Here's the rundown of what values for arch are allowed and what features they turn on by default:
arch value : Architecture : Includes by default
armv8-a : Armv8-A : +fp, +simd
armv8.1-a : Armv8.1-A : armv8-a, +crc, +lse, +rdma
armv8.2-a : Armv8.2-A : armv8.1-a
armv8.3-a : Armv8.3-A : armv8.2-a, +pauth
armv8.4-a : Armv8.4-A : armv8.3-a, +flagm, +fp16fml, +dotprod
armv8.5-a : Armv8.5-A : armv8.4-a, +sb, +ssbs, +predres
armv8.6-a : Armv8.6-A : armv8.5-a, +bf16, +i8mm
armv8.7-a : Armv8.7-A : armv8.6-a, +ls64
armv8.8-a : Armv8.8-a : armv8.7-a, +mops
armv9-a : Armv9-A : armv8.5-a, +sve, +sve2
armv9.1-a : Armv9.1-A : armv9-a, +bf16, +i8mm
armv9.2-a : Armv9.2-A : armv9.1-a, +ls64
armv9.3-a : Armv9.3-A : armv9.2-a, +mops
armv8-r : Armv8-R : armv8-r
The value native is available on native AArch64 GNU/Linux and it makes the compiler pick the architecture of the host system ๐ฅ๏ธ this option has no effect if the compiler can't recognize the architecture of the host system, tho.
The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers, -march and -mcpu Feature Modifiers. And if you specify conflicting feature modifiers? The right-most feature wins. always the right-most, periodt ๐
GCC uses name to decide what kind of instructions it can emit when generating assembly code ๐ฅ and if -march is specified without either -mtune or -mcpu also being specified, the code gets tuned to perform well across a range of target processors implementing the target architecture. broad appeal, honestly iconic.
- *
-mtune=name* โ specify the name of the target processor that GCC should tune the performance of the code for ๐ the permissible values for this option are:generic,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,cortex-a76,cortex-a76ae,cortex-a77,cortex-a65,cortex-a65ae,cortex-a34,cortex-a78,cortex-a78ae,cortex-a78c,ares,exynos-m1,emag,falkor,neoverse-512tvb,neoverse-e1,neoverse-n1,neoverse-n2,neoverse-v1,neoverse-v2,grace,qdf24xx,saphira,phecda,xgene1,vulcan,octeontx,octeontx81,octeontx83,octeontx2,octeontx2t98,octeontx2t96octeontx2t93,octeontx2f95,octeontx2f95n,octeontx2f95mm,a64fx,thunderx,thunderxt88,thunderxt88p1,thunderxt81,tsv110,thunderxt83,thunderx2t99,thunderx3t110,zeus,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53,cortex-a75.cortex-a55,cortex-a76.cortex-a55,cortex-r82,cortex-x1,cortex-x1c,cortex-x2,cortex-x3,cortex-a510,cortex-a710,cortex-a715,ampere1,ampere1a,cobalt-100andnative.
The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 specify that GCC should tune for a big.LITTLE system ๐ two moods, one chip.
The value neoverse-512tvb specifies that GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle โจ in other words, the option tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle and can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). This is more general than tuning for a specific core like Neoverse V1, but it's also more specific than the default tuning described below. she's in between, she contains multitudes ๐
Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system ๐ฅ๏ธ this option has no effect if the compiler can't recognize the processor of the host system.
If none of -mtune=, -mcpu= or -march= are specified, the code gets tuned to perform well across a range of target processors โจ
And important: this option cannot be suffixed by feature modifiers. don't even try it, bestie ๐
-mcpu=nameโ specify the name of the target processor, optionally suffixed by one or more feature modifiers ๐ซ this option has the form-mcpu=cpu{+[no]feature}*, where the permissible values forcpuare the same ones available for-mtune. The permissible values forfeatureare documented in the sub-section on aarch64-feature-modifiers, -march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the **right-most feature is used. (same rule as-march, consistency queen ๐)
GCC uses name to determine what kind of instructions it can emit when generating assembly code โ as if by -march โ and also to determine the target processor to tune performance for โ as if by -mtune ๐ but where this option is used alongside -march or -mtune, those options take precedence over the appropriate part of this option. so -mcpu is doing both jobs, but the specialists get to override. respect the hierarchy ๐
-mcpu=neoverse-512tvb is special ๐ because it doesn't refer to a specific core, but instead refers to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless it's overridden by -march, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with these properties. And unless it's overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb. ๐ค
-moverride=stringโ override tuning decisions made by the back-end in response to a-mtune=switch ๐ ๏ธ fair warning: the syntax, semantics, and accepted values forstringin this option are **not guaranteed to be consistent across releases. it's giving unstable API, ngl.
This option is only intended to be useful when developing GCC. iykyk โ if that's not you, walk away bestie ๐ถโโ๏ธ๐จ
-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files ๐ this option is provided for use in debugging the compiler. for the compiler girlies only ๐-mpc-relative-literal-loads-mno-pc-relative-literal-loadsโ enable or disable PC-relative literal loads โจ with this option, literal pools are accessed using a single instruction and emitted after each function. That limits the maximum size of functions to 1MB โ yeah, keep that in mind ๐ซ and this is enabled by default for-mcmodel=tiny.-msign-return-address=scopeโ ok so this picks which functions get return address signing, bestie. The allowed values arenone(signing off entirely, nada),non-leaf(pointer signing for the functions that are not leaf functions), andall(every single function gets signed, no exceptions, periodt). Default isnone. ๐ซถ Heads up though: this option has been deprecated by-mbranch-protection.-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ choose your branch protection features, bestie, it's giving security โจ.noneis the default and turns off every type of branch protection.standardturns on all types of branch protection features, and if a feature has extra tuning options,standardjust sets it to its standard level.pac-ret[+leaf]turns on return address signing at its standard level โ meaning it signs functions that save the return address to memory (non-leaf functions will practically always do this), using the a-key. The optional argumentleafextends the signing to include leaf functions too. The optional argumentb-keysigns the functions with the B-key instead of the A-key. Andbtiturns on the branch target identification mechanism. ๐-mharden-sls=optsโ this one enables compiler hardening against straight line speculation, aka SLS.optsis a comma-separated list of these:retbrblr
Also, -mharden-sls=all enables all SLS hardening, while -mharden-sls=none disables all of it. ๐ฅ
-msve-vector-bits=bitsโ sets how many bits live in an SVE vector register. Important: this only does anything when SVE is enabled. ๐
GCC supports two flavours of SVE code generation: "vector-length agnostic" output, which works with any size of vector register, and "vector-length specific" output, which lets GCC make assumptions about the vector length when that's useful for optimization reasons.
The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Specifying scalable selects vector-length agnostic output. At present -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. All other values generate vector-length specific code. The behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that is portable across different hardware SVE vector lengths. ๐ญ
The default is -msve-vector-bits=scalable, which produces vector-length agnostic code. ๐
โจ -march and -mcpu Feature Modifiers โจ
Feature modifiers used with -march and -mcpu can be any of the following, plus their inverses nofeature:
crcโ enable the CRC extension. This is on by default for-march=armv8.1-a. ๐ธcryptoโ enable the Crypto extension. This also enables Advanced SIMD and floating-point instructions.fpโ enable floating-point instructions. This is on by default for all possible values for options-marchand-mcpu.simdโ enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for options-marchand-mcpu.sveโ enable Scalable Vector Extension instructions. This also enables Advanced SIMD and floating-point instructions.lseโ enable Large System Extension instructions. This is on by default for-march=armv8.1-a.rdmaโ enable Round Double Multiply Accumulate instructions. This is on by default for-march=armv8.1-a.fp16โ enable the FP16 extension. This also enables floating-point instructions.fp16fmlโ enable the FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. This option is enabled by default for-march=armv8.4-a. Use of this option with architectures prior to Armv8.2-A is not supported. ๐rcpcโ enable the RCpc extension. This enables the use of the LDAPR instructions for load-acquire atomic semantics, and passes it on to the assembler, enabling inline asm statements to use instructions from the RCpc extension.dotprodโ enable the Dot Product extension. This also enables Advanced SIMD instructions.aesโ enable the Armv8-a aes and pmull crypto extension. This also enables Advanced SIMD instructions.sha2โ enable the Armv8-a sha2 crypto extension. This also enables Advanced SIMD instructions.sha3โ enable the sha512 and sha3 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.sm4โ enable the sm3 and sm4 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.profileโ enable the Statistical Profiling extension. This option is only to enable the extension at the assembler level and does not affect code generation.rngโ enable the Armv8.5-a Random Number instructions. This option is only to enable the extension at the assembler level and does not affect code generation.memtagโ enable the Armv8.5-a Memory Tagging Extensions. Use of this option with architectures prior to Armv8.5-A is not supported.sbโ enable the Armv8-a Speculation Barrier instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.ssbsโ enable the Armv8-a Speculative Store Bypass Safe instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.predresโ enable the Armv8-a Execution and Data Prediction Restriction instructions. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.sve2โ enable the Armv8-a Scalable Vector Extension 2. This also enables SVE instructions.sve2-bitpermโ enable SVE2 bitperm instructions. This also enables SVE2 instructions.sve2-sm4โ enable SVE2 sm4 instructions. This also enables SVE2 instructions.sve2-aesโ enable SVE2 aes instructions. This also enables SVE2 instructions.sve2-sha3โ enable SVE2 sha3 instructions. This also enables SVE2 instructions.tmeโ enable the Transactional Memory Extension.i8mmโ enable 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.f32mmโ enable 32-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.f64mmโ enable 64-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.bf16โ enable brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.ls64โ enable the 64-byte atomic load and store instructions for accelerators. This option is enabled by default for-march=armv8.7-a.mopsโ enable the instructions to accelerate memory operations like"memcpy","memmove","memset". This option is enabled by default for-march=armv8.8-aflagmโ enable the Flag Manipulation instructions Extension.pauthโ enable the Pointer Authentication Extension.csscโ enable the Common Short Sequence Compression instructions.
Okay so the vibe chain here: the feature crypto implies aes, sha2, and simd, which implies fp. And conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It's giving cascade ๐
๐ฆ Adapteva Epiphany Options ๐ฆ
These -m options are defined for Adapteva Epiphany:
-mhalf-reg-fileโ don't allocate any register in the range"r32"โฆ"r63". That lets code run on hardware variants that lack these registers. ๐-mprefer-short-insn-regsโ preferentially allocate registers that allow short instruction generation. Careful bestie, this can result in increased instruction count, so it may either reduce or increase overall code size. ๐ญ-mbranch-cost=numโ set the cost of branches to roughly num "simple" instructions. This cost is only a heuristic and is not guaranteed to produce consistent results across releases.-mcmoveโ enable the generation of conditional moves.-mnops=numโ emit num NOPs before every other generated instruction. (ma'am why ๐ญ)-mno-soft-cmpsfโ for single-precision floating-point comparisons, emit an"fsub"instruction and test the flags. This is faster than a software comparison, but it can get incorrect results in the presence of NaNs, or when two different small numbers are compared such that their difference is calculated as zero. The default is-msoft-cmpsf, which uses slower, but IEEE-compliant, software comparisons. โ ๏ธ-mstack-offset=numโ set the offset between the top of the stack and the stack pointer. E.g., a value of 8 means that the eight bytes in the range"sp+0...sp+7"can be used by leaf functions without stack allocation. Values other than 8 or 16 are untested and unlikely to work. Also note that this option changes the ABI โ compiling a program with a different stack offset than the libraries have been compiled with generally does not work. This option can be useful if you want to evaluate whether a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate--with-stack-offset=numoption. ๐ซถ-mno-round-nearestโ make the scheduler assume that the rounding mode has been set to truncating. The default is-mround-nearest.-mlong-callsโ if not otherwise specified by an attribute, assume all calls might be beyond the offset range of the"b"/"bl"instructions, and therefore load the function address into a register before performing an (otherwise direct) call. This is the default. ๐-mshort-callsโ unless some attribute says otherwise, just assume every direct call fits inside the range of theb/blinstructions, and use those for direct calls. default?-mlong-calls, bestie. it's giving "long haul." ๐-msmall16โ assume addresses can be loaded as 16-bit unsigned values. โ ๏ธ this does not apply to function addresses where-mlong-callssemantics are in effect. no cap.-mfp-mode=modeโ sets the prevailing mode of the floating-point unit. like, this decides the FP mode that gets provided and expected at function call and return time. if you match this mode to whatever mode you mostly need at function start, your programs get smaller and faster bc you're dodging unnecessary mode switches. slay. โจ
mode can be set to one of these:
callerโ any mode at function entry is valid, and it's retained or restored when the function returns, and when it calls other functions. this mode is useful for compiling libraries or other compilation units you might want to drop into different programs that have different prevailing FPU modes โ and the convenience of being able to use a single object file outweighs the size and speed overhead for any extra mode switching that might be needed, compared with what you'd need with a more specific choice of prevailing FPU mode. ๐ซถtruncateโ this is the mode used for floating-point calculations with truncating (i.e. round towards zero) rounding mode. that includes conversion from floating point to integer.round-nearestโ this is the mode used for floating-point calculations with round-to-nearest-or-even rounding mode.intโ this is the mode used to perform integer calculations in the FPU, e.g. integer multiply, or integer multiply-and-accumulate.
the default is -mfp-mode=caller ๐
-mno-split-lohi-mno-postinc-mno-postmodifyโ code generation tweaks that disable, respectively: splitting of 32-bit loads, generation of post-increment addresses, and generation of post-modify addresses. the defaults aremsplit-lohi,-mpost-inc, and-mpost-modify. ๐-mnovect-doubleโ change the preferred SIMD mode toSImode. the default is-mvect-double, which usesDImodeas preferred SIMD mode.-max-vect-align=numโ the maximum alignment for SIMD vector mode types. num may be4or8. the default is8. ๐ note that this is an ABI change, even though many library function interfaces are unaffected if they don't use SIMD vector modes in places that affect size and/or alignment of relevant types. so likeโฆ heads up.-msplit-vecmove-earlyโ split vector moves into single word moves before reload. in theory this can give better register allocation, but so far the reverse seems to be generally the case. ๐ญ theory said one thing, reality said another.-m1reg-regโ specify a register to hold the constant-1, which makes loading small negative constants and certain bitmasks faster. allowable values for reg arer43andr63, which specify use of that register as a fixed register, andnone, which means that no register is used for this purpose. the default is-m1reg-none.
๐ AMD GCN Options ๐
these options are defined specifically for the AMD GCN port. iconic. ๐ฅ
-march=gpu-mtune=gpuโ set architecture type or tuning for gpu. supported values for gpu are:fijiโ compile for GCN3 Fiji devices (gfx803).gfx900โ compile for GCN5 Vega 10 devices (gfx900).gfx906โ compile for GCN5 Vega 20 devices (gfx906).gfx908โ compile for CDNA1 Instinct MI100 series devices (gfx908).gfx90aโ compile for CDNA2 Instinct MI200 series devices (gfx90a).
-msram-ecc=on-msram-ecc=off-msram-ecc=anyโ compile binaries suitable for devices with the SRAM-ECC feature enabled, disabled, or either mode. this feature can be enabled per-process on some devices. the compiled code must match the device mode. ๐ค default isany, for devices that support it.-mstack-size=bytesโ specify how many bytes of stack space will be requested for each GPU thread (wave-front). ๐ซฃ beware that there may be many threads and only limited memory available. the size of the stack allocation may also have an impact on run-time performance. the default is32KBwhen using OpenACC or OpenMP, and1MBotherwise.-mxnackโ compile binaries suitable for devices with the XNACK feature enabled. some devices always require XNACK and some let the user configure XNACK. the compiled code must match the device mode. the default is-mno-xnack. ๐ข at present this option is a placeholder for support that is not yet implemented. (yes bestie, a placeholder. we're manifesting it. ๐)
๐ฆ ARC Options ๐ฆ
the following options control the architecture variant for which code is being compiled:
-mbarrel-shifterโ generate instructions supported by barrel shifter. this is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect.-mjli-alwaysโ force to call a function usingjli_sinstruction. this option is valid only for ARCv2 architecture.-mcpu=cpuโ set architecture type, register usage, and instruction scheduling parameters for cpu. there are also shortcut alias options available for backward compatibility and convenience. supported values for cpu are:arc600โ compile for ARC600. aliases:-mA6,-mARC600.arc601โ compile for ARC601. alias:-mARC601.arc700โ compile for ARC700. aliases:-mA7,-mARC700. this is the default when configured with--with-cpu=arc700.arcemโ compile for ARC EM.archsโ compile for ARC HS.emโ compile for ARC EM CPU with no hardware extensions.em4โ compile for ARC EM4 CPU.em4_dmipsโ compile for ARC EM4 DMIPS CPU.em4_fpusโ compile for ARC EM4 DMIPS CPU with the single-precision floating-point extension.em4_fpudaโ compile for ARC EM4 DMIPS CPU with single-precision floating-point and double assist instructions.hsโ compile for ARC HS CPU with no hardware extensions except the atomic instructions.hs34โ compile for ARC HS34 CPU.hs38โ compile for ARC HS38 CPU.hs38_linuxโ compile for ARC HS38 CPU with all hardware extensions on.hs4xโ compile for ARC HS4x CPU.hs4xdโ compile for ARC HS4xD CPU.hs4x_rel31โ compile for ARC HS4x CPU release 3.10a.arc600_normโ compile for ARC 600 CPU with "norm" instructions enabled.arc600_mul32x16โ compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.arc601_normโ compile for ARC 601 CPU with "norm" instructions enabled.arc601_mul32x16โ compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring reduced register set.
-mdpfp-mdpfp-compactโ generate double-precision FPX instructions, tuned for the compact implementation.-mdpfp-fastโ generate double-precision FPX instructions, tuned for the fast implementation. ๐ฅ-mno-dpfp-lrsrโ disable"lr"and"sr"instructions from using FPX extension aux registers.-meaโ generate extended arithmetic instructions. currently only"divaw","adds","subs", and"sat16"are supported. valid only for-mcpu=ARC700.-mno-mpyโ do not generate"mpy"-family instructions for ARC700. โ ๏ธ this option is deprecated.-mmul32x16โ generate 32x16-bit multiply and multiply-accumulate instructions.-mmul64โ generate"mul64"and"mulu64"instructions. valid only for-mcpu=ARC600.-mnormโ generate"norm"instructions. this is the default if-mcpu=ARC700is in effect.-mspfp-mspfp-compactโ generate single-precision FPX instructions, tuned for the compact implementation.-mspfp-fastโ generate single-precision FPX instructions, tuned for the fast implementation.-msimdโ enable generation of ARC SIMD instructions via target-specific builtins. valid only for-mcpu=ARC700.-msoft-floatโ ๐ต this option is ignored; it is provided for compatibility purposes only. software floating-point code is emitted by default, and this default can be overridden by FPX options:-mspfp,-mspfp-compact, or-mspfp-fastfor single precision, and-mdpfp,-mdpfp-compact, or-mdpfp-fastfor double precision. so like, it's here, but it's not doing anything. ๐-mswapโ generate"swap"instructions.-matomicโ this enables use of the locked load/store conditional extension to implement atomic memory built-in functions. not available for ARC 6xx or ARC EM cores.-mdiv-remโ enable"div"and"rem"instructions for ARCv2 cores.-mcode-densityโ enable code density instructions for ARC EM. this option is on by default for ARC HS.-mll64โ enable double load/store operations for ARC HS cores.-mtp-regno=regnoโ specify thread pointer register number.-mmpy-option=multoโ compile ARCv2 code with a multiplier design option. you can specify the option using either a string or numeric value for multo.wlh1is the default value. the recognized values are:0,noneโ no multiplier available.1,wโ 16x16 multiplier, fully pipelined. the following instructions are enabled:"mpyw"and"mpyuw".2,wlh1โ 32x32 multiplier, fully pipelined (1 stage). the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".3,wlh2โ 32x32 multiplier, fully pipelined (2 stages). the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".4,wlh3โ two 16x16 multipliers, blocking, sequential. the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".
okay we're deep in the ARC lore now bestie, and there is so much more coming ๐ stay with me โจ
5,wlh4โ one 16x16 multiplier, blocking, sequential ๐งฎ and the following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.6,wlh5โ one 32x4 multiplier, blocking, sequential ๐งฎ and the following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.7,plus_dmpyโ ARC HS SIMD support. โจ8,plus_macdโ ARC HS SIMD support. โจ9,plus_qmacwโ ARC HS SIMD support. โจ
Bestie, listen โ this option is only available for ARCv2 cores. No ARCv2, no vibes. ๐
-mfpu=fpuโ turns on support for specific floating-point hardware extensions for ARCv2 cores ๐งโโ๏ธ the supported values forfpuare giving:fpusโ enables support for single-precision floating-point hardware extensions.fpudโ enables support for double-precision floating-point hardware extensions. The single-precision floating-point extension is also enabled. ๐ซถ Not available for ARC EM.fpudaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point extension is also enabled. This option is only available for ARC EM.fpuda_divโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. Single-precision floating-point, square-root, and divide extensions are also enabled. This option is only available for ARC EM.fpuda_fmaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. Single-precision floating-point and fused multiply and add hardware extensions are also enabled. This option is only available for ARC EM.fpuda_allโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. All single-precision floating-point hardware extensions are also enabled. This option is only available for ARC EM.fpus_divโ enables support for single-precision floating-point, square-root and divide hardware extensions.fpud_divโ enables support for double-precision floating-point, square-root and divide hardware extensions. This option includes optionfpus_div. Not available for ARC EM.fpus_fmaโ enables support for single-precision floating-point and fused multiply and add hardware extensions.fpud_fmaโ enables support for double-precision floating-point and fused multiply and add hardware extensions. This option includes optionfpus_fma. Not available for ARC EM.fpus_allโ enables support for all single-precision floating-point hardware extensions.fpud_allโ enables support for all single- and double-precision floating-point hardware extensions. Not available for ARC EM.
-mirq-ctrl-saved=register-range, blink, lp_countโ this one spells out the general-purpose registers that the processor automatically saves and restores on interrupt entry and exit ๐ฎโ๐จregister-rangeis written as two registers with a dash between them, no cap. The register range always starts with"r0", and the upper limit is the"fp"register.blinkandlp_countare optional (so slay, so optional ๐ ). Heads up: this option is only valid for ARC EM and ARC HS cores.-mrgf-banked-regs=numberโ tells the compiler how many registers get replicated in the second register bank on entry to a fast interrupt โก Fast interrupts are the ones with the highest priority level P0. These interrupts save only thePCandSTATUS32registers, so they avoid memory transactions during interrupt entry and exit sequences โ icon behaviour tbh. Use this option when you're using fast interrupts in an ARC V2 family processor. The permitted values are4,8,16, and32.-mlpc-width=widthโ sets the width of the"lp_count"register ๐ valid values forwidthare8,16,20,24,28and32bits. The default width is fixed to 32 bits. If the width is less than 32, the compiler does not attempt to transform loops in your program to use the zero-delay loop mechanism unless it's known that the"lp_count"register can hold the required loop-counter value. Depending on the width you specify, the compiler and run-time library might keep using the loop mechanism for various needs. Oh and โ this option defines macro"__ARC_LPC_WIDTH__"with the value ofwidthโจ-mrf16โ instructs the compiler to generate code for a 16-entry register file ๐๏ธ and it defines the"__ARC_RF16__"preprocessor macro. Periodt.-mbranch-indexโ enables use of"bi"or"bih"instructions to implement jump tables ๐ฆ
The following options are passed through to the assembler, and also define preprocessor macro symbols. ๐
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol"__Xdsp_packa". โ ๏ธ This option is deprecated.-mdvbfโ passed down to the assembler to enable the dual Viterbi butterfly extension. Also sets the preprocessor symbol"__Xdvbf". โ ๏ธ This option is deprecated.-mlockโ passed down to the assembler to enable the locked load/store conditional extension. Also sets the preprocessor symbol"__Xlock".-mmac-d16โ passed down to the assembler. Also sets the preprocessor symbol"__Xxmac_d16". โ ๏ธ This option is deprecated.-mmac-24โ passed down to the assembler. Also sets the preprocessor symbol"__Xxmac_24". โ ๏ธ This option is deprecated.-mrtscโ passed down to the assembler to enable the 64-bit time-stamp counter extension instruction. Also sets the preprocessor symbol"__Xrtsc". โ ๏ธ This option is deprecated.-mswapeโ passed down to the assembler to enable the swap byte ordering extension instruction. Also sets the preprocessor symbol"__Xswape".-mtelephonyโ passed down to the assembler to enable dual- and single-operand instructions for telephony โ๏ธ Also sets the preprocessor symbol"__Xtelephony". โ ๏ธ This option is deprecated.-mxyโ passed down to the assembler to enable the XY memory extension. Also sets the preprocessor symbol"__Xxy".
The following options control how the assembly code is annotated: ๐๏ธ
-misizeโ annotate assembler instructions with estimated addresses.-mannotate-alignโ explains what alignment considerations led to the decision to make an instruction short or long.
The following options are passed through to the linker: ๐
-marclinuxโ passed through to the linker, to specify use of the"arclinux"emulation. This option is enabled by default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is not requested.-marclinux_profโ passed through to the linker, to specify use of the"arclinux_prof"emulation. This option is enabled by default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is requested.
The following options control the semantics of generated code: ๐ง
-mlong-callsโ generate calls as register indirect calls, which gives you access to the full 32-bit address range. ๐-mmedium-callsโ don't use less than a 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. Conditional execution of function calls is suppressed, so we can use the 25-bit range instead of the 21-bit range with conditional branch-and-link. This is the default for tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets.-G numโ put definitions of externally-visible data in a small data section if that data is no bigger thannumbytes ๐ฆ The default value ofnumis4for any ARC configuration, or8when we have double load/store operations.-mno-sdataโ do not generate sdata references ๐ โโ๏ธ This is the default for tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets.-mvolatile-cacheโ use ordinarily cached memory accesses for volatile references. This is the default.-mno-volatile-cacheโ enable cache bypass for volatile references.
The following options fine tune code generation: ๐๏ธ
-malign-callโ does nothing ๐ซ preserved for backward compatibility.-mauto-modify-regโ enable the use of pre/post modify with register displacement.-mbbit-peepholeโ enable bbit peephole2.-mno-brccโ this option disables a target-specific pass inarc_reorgto generate compare-and-branch ("brcc") instructions. It has no effect on generation of these instructions driven by the combiner pass.-mcase-vector-pcrelโ use PC-relative switch case tables to enable case table shortening. This is the default for-Os.-mcompact-casesiโ enable compact"casesi"pattern. This is the default for-Os, and only available for ARCv1 cores. โ ๏ธ This option is deprecated.-mno-cond-execโ disable the ARCompact-specific pass that generates conditional execution instructions.
Okay so here's the whole tea, bestie ๐ต due to delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass to generate conditional execution is often lacking, so the ARC port has kept a special pass around that tries to find more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have been done. This pass generally, but not always, improves performance and code size โ at the cost of extra compilation time, which is why there's an option to switch it off. If you have a problem with call instructions exceeding their allowable offset range because they are conditionalized, you should consider using -mmedium-calls instead.
-mearly-cbranchsiโ enable pre-reload use of the"cbranchsi"pattern.-mexpand-adddiโ expand"adddi3"and"subdi3"at RTL generation time into"add.f","adc"etc. โ ๏ธ This option is deprecated.-mindexed-loadsโ enable the use of indexed loads. ๐จ This can be problematic because some optimizers then assume that indexed stores exist, which is not the case.-mlraโ turns on Local Register Allocation, bestie. It's still experimental for ARC, so by default the compiler just uses standard reload (aka-mno-lra). ๐งช-mlra-priority-noneโ don't flag any priority for target registers.-mlra-priority-compactโ flag target register priority forr0..r3/r12..r15.-mlra-priority-noncompactโ dial down the target register priority forr0..r3/r12..r15.-mmillicodeโ ok so when you're optimizing for size (with-Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by calling a special function inlibgcc. That's a millicode call โจ. But these calls can pose performance issues, and/or cause linking issues when you link in a nonstandard way, so this option exists to turn millicode call generation on or off. ๐๏ธ-mcode-density-frameโ lets the compiler emit"enter"and"leave"instructions. Heads up though: those instructions are only valid for CPUs with the code-density feature. ๐-mcode-density-frameslay, but-mmixed-code? Nope.-mmixed-codeโ does nothing. Preserved for backward compatibility. ๐-mq-classโ this option is deprecated, friend. It enables q instruction alternatives, and it's the default for-Os. ๐-mRcqโ does nothing. Preserved for backward compatibility.-mRcwโ does nothing. Preserved for backward compatibility.-msize-level=levelโ fine-tune size optimization when it comes to instruction lengths and alignment. The recognized values for level are:0โ no size optimization. This level is deprecated and gets treated like1.1โ short instructions are used opportunistically.2โ on top of that, alignment of loops and of code after barriers are dropped.3โ on top of that, optional data alignment is dropped, and the optionOsis enabled.
This defaults to 3 when -Os is in effect. Otherwise, if this isn't set, the behavior is equivalent to level 1. ๐ธ
-mtune=cpuโ sets instruction scheduling parameters for cpu, overriding anything implied by-mcpu=. Supported values for cpu are:ARC600โ tune for ARC600 CPU.ARC601โ tune for ARC601 CPU.ARC700โ tune for ARC700 CPU with standard multiplier block.ARC700-xmacโ tune for ARC700 CPU with XMAC block.ARC725Dโ tune for ARC725D CPU.ARC750Dโ tune for ARC750D CPU.core3โ tune for ARCv2 core3 type CPU. This option enables usage of the"dbnz"instruction.release31aโ tune for ARC4x release 3.10a.
-mmultcost=numโ the cost to assume for a multiply instruction, where4is equal to a normal instruction.-munalign-prob-threshold=probabilityโ does nothing. Preserved for backward compatibility.
The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release ๐ญ:
-margonautโ obsolete FPX.-mbig-endian,-EBโ compile code for big-endian targets. Use of these options is now deprecated. Big-endian code is supported by configuring GCC to build"arceb-elf32"and"arceb-linux-uclibc"targets, for which big endian is the default.-mlittle-endian,-ELโ compile code for little-endian targets. Use of these options is now deprecated. Little-endian code is supported by configuring GCC to build"arc-elf32"and"arc-linux-uclibc"targets, for which little endian is the default.-mbarrel_shifterโ replaced by-mbarrel-shifter.-mdpfp_compactโ replaced by-mdpfp-compact.-mdpfp_fastโ replaced by-mdpfp-fast.-mdsp_packaโ replaced by-mdsp-packa.-mEAโ replaced by-mea.-mmac_24โ replaced by-mmac-24.-mmac_d16โ replaced by-mmac-d16.-mspfp_compactโ replaced by-mspfp-compact.-mspfp_fastโ replaced by-mspfp-fast.-mtune=cpuโ valuesarc600,arc601,arc700andarc700-xmacfor cpu are replaced byARC600,ARC601,ARC700andARC700-xmacrespectively.-multcost=numโ replaced by-mmultcost.
๐ ARM Options ๐
These -m options are defined for the ARM port, bestie:
-mabi=nameโ generate code for the specified ABI. Permissible values are:apcs-gnu,atpcs,aapcs,aapcs-linuxandiwmmxt.-mapcs-frameโ generate a stack frame that's compliant with the ARM Procedure Call Standard for all functions, even if it's not strictly necessary for correct execution of the code. Specifying-fomit-frame-pointerwith this option causes the stack frames not to be generated for leaf functions. The default is-mno-apcs-frame. This option is deprecated.-mapcsโ this is a synonym for-mapcs-frameand is deprecated.-mthumb-interworkโ generate code that supports calling between the ARM and Thumb instruction sets. Without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. The default is-mno-thumb-interwork, since slightly larger code is generated when-mthumb-interworkis specified. In AAPCS configurations this option is meaningless. ๐ฆ-mno-sched-prologโ prevent the reordering of instructions in the function prologue, or the merging of those instruction with the instructions in the function's body. What this gets you: all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this info can be used to locate the start of functions inside an executable piece of code. The default is-msched-prolog.-mfloat-abi=nameโ specifies which floating-point ABI to use. Permissible values are:soft,softfpandhard.- Specifying
softcauses GCC to generate output containing library calls for floating-point operations. softfpallows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions.hardallows generation of floating-point instructions and uses FPU-specific calling conventions.
- Specifying
The default depends on the specific target configuration. > Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. ๐ญ
-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler.-mlittle-endianโ generate code for a processor running in little-endian mode. This is the default for all standard configurations.-mbig-endianโ generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.-mbe8,-mbe32โ when linking a big-endian image, select between BE8 and BE32 formats. The option has no effect for little-endian images and is ignored. The default is dependent on the selected target architecture. For ARMv6 and later architectures the default is BE8, for older architectures the default is BE32. BE32 format has been deprecated by ARM.-march=name[+extension...]โ specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. This option can be used in conjunction with or instead of the-mcpu=option. ๐
Permissible names are: armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, armv9-a, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, armv9-a, iwmmxt and iwmmxt2.
Additionally, the following architectures, which lack support for the Thumb execution state, are recognized but support is deprecated: armv4.
Many of the architectures support extensions. These can be added by appending +extension to the architecture name. Extension options are processed in order and capabilities accumulate. An extension will also enable any necessary base extensions upon which it depends. For example, the +crypto extension will always enable the +simd extension. The exception to the additive construction is for extensions that are prefixed with +no...: these extensions disable the specified option and any other extensions that may depend on the presence of that extension. โจ
For example, -march=armv7-a+simd+nofp+vfpv4 is equivalent to writing -march=armv7-a+vfpv4 since the +simd option is entirely disabled by the +nofp option that follows it.
Most extension names are generically named, but have an effect that is dependent upon the architecture to which it is applied. For example, the +simd option can be applied to both armv7-a and armv8-a architectures, but will enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a and the ARMv8-A variant for armv8-a. ๐
The table below lists the supported extensions for each architecture. Architectures not mentioned do not support any extensions.
armv5te / armv6 / armv6j / armv6k / armv6kz / armv6t2 / armv6z / armv6zk
+fpโ the VFPv2 floating-point instructions. The extension+vfpv2can be used as an alias for this extension.+nofpโ disable the floating-point instructions.
armv7
The common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures.
+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension. Note that floating-point is not supported by the base ARMv7-M architecture, but is compatible with both the ARMv7-A and ARMv7-R architectures.+nofpโ disable the floating-point instructions.
armv7-a
+mpโ the multiprocessing extension.+secโ the security extension.+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension.+simdโ the Advanced SIMD (Neon) v1 plus the VFPv3 floating-point instructions, bestie. and the extensions+neonand+neon-vfpv3can be used as aliases for this extension ๐ซ+vfpv3โ the VFPv3 floating-point instructions, but with 32 double-precision registers ๐+vfpv3-d16-fp16โ VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations โจ+vfpv3-fp16โ VFPv3 floating-point instructions with 32 double-precision registers and the half-precision floating-point conversion operations ๐ฆ+vfpv4-d16โ the VFPv4 floating-point instructions, with 16 double-precision registers ๐+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers ๐+neon-fp16โ Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, plus the half-precision floating-point conversion operations ๐ธ+neon-vfpv4โ Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions ๐ฅ+nosimdโ turns off the Advanced SIMD instructions. note that it does not disable floating point, okay? ๐ซถ+nofpโ turns off both the floating-point and the Advanced SIMD instructions. all the way off ๐armv7veโ the extended version of the ARMv7-A architecture, and yes it comes with support for virtualization ๐ง+fpโ the VFPv4 floating-point instructions, with 16 double-precision registers. the extension+vfpv4-d16can be used as an alias for this one ๐+simdโ Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. the extension+neon-vfpv4can be used as an alias for this one โจ+vfpv3-d16โ the VFPv3 floating-point instructions, with 16 double-precision registers ๐+vfpv3โ the VFPv3 floating-point instructions, with 32 double-precision registers ๐ฆ+vfpv3-d16-fp16โ VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations ๐ธ+vfpv3-fp16โ VFPv3 floating-point instructions with 32 double-precision registers and the half-precision floating-point conversion operations ๐+vfpv4-d16โ the VFPv4 floating-point instructions, with 16 double-precision registers ๐+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers ๐ฅ+neonโ Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extension+neon-vfpv3can be used as an alias for this one ๐+neon-fp16โ Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations ๐+nosimdโ disables the Advanced SIMD instructions (and nope, it does not disable floating point) ๐+nofpโ disables the floating-point and Advanced SIMD instructions ๐
armv8-aโ the moment ๐+crcโ the Cyclic Redundancy Check (CRC) instructions โญ+simdโ the ARMv8-A Advanced SIMD and floating-point instructions โจ+cryptoโ the cryptographic instructions ๐+nocryptoโ disables the cryptographic instructions ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+sbโ Speculation Barrier Instruction ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions ๐งฟ
armv8.1-aโ glow up edition ๐+simdโ the ARMv8.1-A Advanced SIMD and floating-point instructions โจ+cryptoโ the cryptographic instructions. this also enables the Advanced SIMD and floating-point instructions ๐+nocryptoโ disables the cryptographic instructions ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+sbโ Speculation Barrier Instruction ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions ๐งฟ
armv8.2-aarmv8.3-aโ these two share the same extension set, so here it is ๐ซถ+fp16โ the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions ๐ธ+fp16fmlโ the half-precision floating-point fmla extension. this also enables the half-precision floating-point extension and Advanced SIMD and floating-point instructions ๐+simdโ the ARMv8.1-A Advanced SIMD and floating-point instructions โจ+cryptoโ the cryptographic instructions. this also enables the Advanced SIMD and floating-point instructions ๐+dotprodโ enables the Dot Product extension. this also enables Advanced SIMD instructions ๐+nocryptoโ disables the cryptographic extension ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+sbโ Speculation Barrier Instruction ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions ๐งฟ+i8mmโ 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐ข+bf16โ Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐ง
armv8.4-aโ okay she's iconic ๐+fp16โ the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension ๐ธ+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension โจ+cryptoโ the cryptographic instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension ๐+nocryptoโ disables the cryptographic extension ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+sbโ Speculation Barrier Instruction ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions ๐งฟ+i8mmโ 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐ข+bf16โ Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐ง
armv8.5-aโ and she keeps the same energy ๐ฅ+fp16โ the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension ๐ธ+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension โจ+cryptoโ the cryptographic instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension ๐+nocryptoโ disables the cryptographic extension ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐ข+bf16โ Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐ง
armv8.6-aโ same set again, no cap ๐+fp16โ the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension ๐ธ+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension โจ+cryptoโ the cryptographic instructions. this also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension ๐+nocryptoโ disables the cryptographic extension ๐ซ+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐ข+bf16โ Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐ง
armv7-rโ the R stands for Real, we love her ๐+fp.spโ the single-precision VFPv3 floating-point instructions. the extension+vfpv3xdcan be used as an alias for this one ๐+fpโ the VFPv3 floating-point instructions with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this one ๐+vfpv3xd-d16-fp16โ the single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations โจ+vfpv3-d16-fp16โ the VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations ๐ธ+nofpโ disables the floating-point extension ๐ซ+idivโ the ARM-state integer division instructions โ
+noidivโ Disables the ARM-state integer division extension. ๐armv7e-m๐ฆ+fpโ The single-precision VFPv4 floating-point instructions. โจ+fpv5โ The single-precision FPv5 floating-point instructions. ๐+fp.dpโ The single- and double-precision FPv5 floating-point instructions. ๐+nofpโ Disable the floating-point extensions. ๐
armv8.1-m.main๐ธ+dspโ The DSP instructions. ๐ต+mveโ The M-Profile Vector Extension (MVE) integer instructions. ๐ฅ+mve.fpโ The M-Profile Vector Extension (MVE) integer and single precision floating-point instructions. ๐+fpโ The single-precision floating-point instructions. โญ+fp.dpโ The single- and double-precision floating-point instructions. ๐+nofpโ Disable the floating-point extension. ๐+cdecp0,+cdecp1, ... ,+cdecp7โ Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7. ๐+pacbtiโ Enable the Pointer Authentication and Branch Target Identification Extension. ๐ก๏ธ
armv8-m.main๐ง+dspโ The DSP instructions. ๐ถ+nodspโ Disable the DSP extension. ๐ซ+fpโ The single-precision floating-point instructions. โจ+fp.dpโ The single- and double-precision floating-point instructions. ๐+nofpโ Disable the floating-point extension. ๐+cdecp0,+cdecp1, ... ,+cdecp7โ Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7. ๐
armv8-r๐+crcโ The Cyclic Redundancy Check (CRC) instructions. ๐+fp.spโ The single-precision FPv5 floating-point instructions. ๐ซ+simdโ The ARMv8-A Advanced SIMD and floating-point instructions. ๐+cryptoโ The cryptographic instructions. ๐+nocryptoโ Disable the cryptographic instructions. ๐+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. ๐ฅ
๐ก -march=native causes the compiler to auto-detect the architecture of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. ๐
-mtune=nameโ This option specifies the name of the target ARM processor for which GCC should tune the performance of the code. For some ARM implementations better performance can be obtained by using this option. ๐ฏ
Permissible names are:
arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm740t, strongarm, strongarm110, strongarm1100, strongarm1110, arm8, arm810, arm9, arm9e, arm920, arm920t, arm922t, arm946e-s, arm966e-s, arm968e-s, arm926ej-s, arm940t, arm9tdmi, arm10tdmi, arm1020t, arm1026ej-s, arm10e, arm1020e, arm1022e, arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1156t2-s, arm1156t2f-s, arm1176jz-s, arm1176jzf-s, generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710, ares, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus, cortex-m0, cortex-m0plus, cortex-m1, cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-m85, cortex-x1, cortex-x1c, cortex-m1.small-multiply, cortex-m0.small-multiply, cortex-m0plus.small-multiply, exynos-m1, marvell-pj4, neoverse-n1, neoverse-n2, neoverse-v1, xscale, iwmmxt, iwmmxt2, ep9312, fa526, fa626, fa606te, fa626te, fmp626, fa726te, star-mc1, xgene1.
Additionally, this option can specify that GCC should tune the performance of the code for a big.LITTLE system. Permissible names are: cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55. ๐๏ธ
-mtune=generic-arch specifies that GCC should tune the performance for a blend of processors within architecture arch. The aim is to generate code that run well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range, and avoiding performance pitfalls of other CPUs. The effects of this option may change in future GCC versions as CPU models come and go. ๐
-mtune permits the same extension options as -mcpu, but the extension options do not affect the tuning of the generated code. ๐ค
-mtune=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. ๐ป
-mcpu=name[+extension...]โ This specifies the name of the target ARM processor. GCC uses this name to derive the name of the target ARM architecture (as if specified by-march) and the ARM processor type for which to tune for performance (as if specified by-mtune). Where this option is used in conjunction with-marchor-mtune, those options take precedence over the appropriate part of this option. ๐๏ธ
Many of the supported CPUs implement optional architectural extensions. Where this is so the architectural extensions are normally enabled by default. If implementations that lack the extension exist, then the extension syntax can be used to disable those extensions that have been omitted. For floating-point and Advanced SIMD (Neon) instructions, the settings of the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions. ๐ก
For example, cortex-a9 can be found in three major configurations: integer only, with just a floating-point unit or with floating-point and Advanced SIMD. The default is to enable all the instructions, but the extensions +nosimd and +nofp can be used to disable just the SIMD or both the SIMD and floating-point instructions respectively. ๐ง
Permissible names for this option are the same as those for -mtune. ๐
The following extension options are common to the listed CPUs:
+nodspโ Disable the DSP instructions oncortex-m33,cortex-m35p,cortex-m55andcortex-m85. Also disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85. ๐ซ+nopacbtiโ Disable the Pointer Authentication and Branch Target Identification Extension oncortex-m85. ๐+nomveโ Disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85. โ+nomve.fpโ Disable the M-Profile Vector Extension (MVE) single precision floating-point instructions oncortex-m55andcortex-m85. ๐ซ+cdecp0,+cdecp1, ... ,+cdecp7โ Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7 oncortex-m55. โ+nofpโ Disables the floating-point instructions onarm9e,arm946e-s,arm966e-s,arm968e-s,arm10e,arm1020e,arm1022e,arm926ej-s,arm1026ej-s,cortex-r5,cortex-r7,cortex-r8,cortex-m4,cortex-m7,cortex-m33,cortex-m35pcortex-m4,cortex-m7,cortex-m33,cortex-m35p,cortex-m55andcortex-m85. Disables the floating-point and SIMD instructions ongeneric-armv7-a,cortex-a5,cortex-a7,cortex-a8,cortex-a9,cortex-a12,cortex-a15,cortex-a17,cortex-a15.cortex-a7,cortex-a17.cortex-a7,cortex-a32,cortex-a35,cortex-a53andcortex-a55. ๐ซ+nofp.dpโ Disables the double-precision component of the floating-point instructions oncortex-r5,cortex-r7,cortex-r8,cortex-r52,cortex-r52plusandcortex-m7. โ+nosimdโ Disables the SIMD (but not floating-point) instructions ongeneric-armv7-a,cortex-a5,cortex-a7andcortex-a9. ๐ซ+cryptoโ Enables the cryptographic instructions oncortex-a32,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,exynos-m1,xgene1,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53andcortex-a75.cortex-a55. ๐
Additionally the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a. ๐ฏ
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information. โน๏ธ
-mcpu=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. ๐ป
-mfpu=nameโ This specifies what floating-point hardware (or hardware emulation) is available on the target. Permissible names are:auto,vfpv2,vfpv3,vfpv3-fp16,vfpv3-d16,vfpv3-d16-fp16,vfpv3xd,vfpv3xd-fp16,neon-vfpv3,neon-fp16,vfpv4,vfpv4-d16,fpv4-sp-d16,neon-vfpv4,fpv5-d16,fpv5-sp-d16,fp-armv8,neon-fp-armv8andcrypto-neon-fp-armv8. Note thatneonis an alias forneon-vfpv3andvfpis an alias forvfpv2. ๐
The setting auto is the default and is special. It causes the compiler to select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march. ๐ค
Okay bestie, we're still deep in the ARM options and honestly this section is giving โจ ARM lore dump โจ โ but it's all important, so buckle up ๐
If the selected floating-point hardware includes the NEON extension (like, say, -mfpu=neon), heads up: floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. Why? Because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic โ specifically, denormal values get treated as zero โ so using NEON instructions may lead to a loss of precision. ๐ฌ
You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas. ๐
-mfp16-format=nameโ specify the format of the__fp16half-precision floating-point type. Permissible names arenone,ieee, andalternative; the default isnone, in which case the__fp16type is not defined at all. ๐-mstructure-size-boundary=nโ the sizes of all structures and unions get rounded up to a multiple of the number of bits set by this option. Permissible values are8,32and64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is8. A value of64is only allowed if the underlying ABI supports it.
Specifying a larger number can produce faster, more efficient code, but it can also increase the size of the program. Different values are potentially incompatible. Code compiled with one value cannot necessarily expect to work with code or libraries compiled with another value, if they exchange information using structures or unions. ๐ซ
This option is deprecated. She's retired, bestie.
-mabort-on-noreturnโ generate a call to the functionabortat the end of anoreturnfunction. It is executed if the function tries to return. (Snitch behaviour, honestly ๐)-mlong-calls,-mno-long-callsโ tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction.
Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the short_call attribute, functions that are inside the scope of a #pragma no_long_calls directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the long_call attribute or the section attribute, and functions that are within the scope of a #pragma long_calls directive are always turned into long calls. ๐
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a #pragma long_calls_off directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers. ๐ฆ
-msingle-pic-baseโ treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function. The runtime system is responsible for initializing this register with an appropriate value before execution begins. (So like, runtime's problem now ๐ )-mpic-register=regโ specify the register to be used for PIC addressing. For standard PIC base case, the default is any suitable register determined by compiler. For single PIC base case, the default isR9if target is EABI based or stack-checking is enabled, otherwise the default isR10.-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. This permits using PC-relative addressing operations to access data known to be in the data segment. For non-VxWorks RTP targets, this option is enabled by default. When disabled on such targets, it will enable-msingle-pic-baseby default. โจ-mpoke-function-nameโ write the name of each function into the text section, directly preceding the function prologue. The generated code is similar to this:
t0
.ascii "arm_poke_function_name", 0
.align
t1
.word 0xff000000 + (t1 - t0)
arm_poke_function_name
mov ip, sp
stmfd sp!, {fp, ip, lr, pc}
sub fp, ip, #4
When performing a stack backtrace, code can inspect the value of pc stored at fp + 0. If the trace function then looks at location pc - 12 and the top 8 bits are set, then we know that there is a function name embedded immediately preceding this location and has length ((pc[-3]) & 0xff000000). ๐
-mthumb,-marmโ select between generating code that executes in ARM and Thumb states. The default for most configurations is to generate code that executes in ARM state, but the default can be changed by configuring GCC with the--with-mode=stateconfigure option.
You can also override the ARM and Thumb mode for each function by using the target("thumb") and target("arm") function attributes or pragmas. ๐
-mflip-thumbโ switch ARM/Thumb modes on alternating functions. This option is provided for regression testing of mixed Thumb/ARM code generation, and is not intended for ordinary use in compiling code. (Test-only behaviour, she's not for the general public ๐)-mtpcs-frameโ generate a stack frame that is compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that does not call any other functions.) The default is-mno-tpcs-frame. ๐-mtpcs-leaf-frameโ generate a stack frame that is compliant with the Thumb Procedure Call Standard for all leaf functions. (A leaf function is one that does not call any other functions.) The default is-mno-apcs-leaf-frame. ๐-mcallee-super-interworkingโ gives all externally visible functions in the file being compiled an ARM instruction set header which switches to Thumb mode before executing the rest of the function. This allows these functions to be called from non-interworking code. This option is not valid in AAPCS configurations because interworking is enabled by default. ๐ซ-mcaller-super-interworkingโ allows calls via function pointers (including virtual functions) to execute correctly regardless of whether the target code has been compiled for interworking or not. There is a small overhead in the cost of executing a function pointer if this option is enabled. This option is not valid in AAPCS configurations because interworking is enabled by default. ๐ซ-mtp=nameโ specify the access model for the thread local storage pointer. The valid models aresoft, which generates calls to__aeabi_read_tp,cp15, which fetches the thread pointer fromcp15directly (supported in the arm6k architecture), andauto, which uses the best available method for the selected processor. The default setting isauto. โจ-mtls-dialect=dialectโ specify the dialect to use for accessing thread local storage. Two dialects are supported โgnuandgnu2. Thegnudialect selects the original GNU scheme for supporting local and global dynamic TLS models. Thegnu2dialect selects the GNU descriptor scheme, which provides better performance for shared libraries. The GNU descriptor scheme is compatible with the original scheme, but does require new assembler, linker and library support. Initial and local exec TLS models are unaffected by this option and always use the original scheme. ๐-mword-relocationsโ only generate absolute relocations on word-sized values (i.e.R_ARM_ABS32). This is enabled by default on targets (uClinux, SymbianOS) where the runtime loader imposes this restriction, and when-fpicor-fPICis specified. This option conflicts with-mslow-flash-data. โ๏ธ-mfix-cortex-m3-ldrdโ some Cortex-M3 cores can cause data corruption whenldrdinstructions with overlapping destination and base registers are used. This option avoids generating these instructions. This option is enabled by default when-mcpu=cortex-m3is specified. ๐ญ-mfix-cortex-a57-aes-1742098,-mno-fix-cortex-a57-aes-1742098,-mfix-cortex-a72-aes-1655431,-mno-fix-cortex-a72-aes-1655431โ enable (disable) mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions. This option is enabled by default when either-mcpu=cortex-a57or-mcpu=cortex-a72is specified. ๐ ๏ธ-munaligned-access,-mno-unaligned-accessโ enables (or disables) reading and writing of 16- and 32- bit values from addresses that are not 16- or 32- bit aligned. By default unaligned access is disabled for all pre-ARMv6, all ARMv6-M and for ARMv8-M Baseline architectures, and enabled for all other architectures. If unaligned access is not enabled then words in packed data structures are accessed a byte at a time. ๐ข
The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending upon the setting of this option. If unaligned access is enabled then the preprocessor symbol __ARM_FEATURE_UNALIGNED is also defined. โจ
-mneon-for-64bitsโ this option is deprecated and has no effect. (She's literally just vibing in the manpage, doing nothing ๐)-mslow-flash-dataโ assume loading data from flash is slower than fetching instruction. Therefore literal load is minimized for better performance. This option is only supported when compiling for ARMv7 M-profile and off by default. It conflicts with-mword-relocations. โ๏ธ-masm-syntax-unifiedโ assume inline assembler is using unified asm syntax. The default is currently off which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated. ๐-mrestrict-itโ restricts generation of IT blocks to conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This option is on by default for ARMv8-A Thumb mode. ๐-mprint-tune-infoโ print CPU tuning information as comment in assembler file. This is an option used only for regression testing of the compiler and not intended for ordinary use in compiling code. This option is disabled by default. ๐ฅ-mverbose-cost-dumpโ okay so this one makes the compiler dump its whole cost model, verbose mode, into the debug dump files ๐ it's provided for use in debugging the compiler, so it's strictly for the compiler-dev girlies. If that's not you, you truly do not need it, bestie.-mpure-codeโ constant data does not get to sit in code sections, no ma'am ๐ and on top of that, when you're compiling for ELF object format, every text section gets the ELF processor-specific section attributeSHF_ARM_PURECODEattached to it. She's specialized though: this option is only available when generating non-pic code for M-profile targets. ๐-mcmseโ generates secure code exactly as per the "ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification" ๐ which lives athttps://developer.arm.com/documentation/ecm0359818/latest/.-mfix-cmse-cve-2021-35465โ patches up a potential security issue with theVLLDMinstruction in some M-profile devices when you're using CMSE (CVE-2021-365465) ๐ญ security girlies stay winning fr fr. It's enabled by default when the option-mcpu=is used withcortex-m33,cortex-m35p,cortex-m55,cortex-m85orstar-mc1. And if you wanna rawdog it,-mno-fix-cmse-cve-2021-35465disables the mitigation. ๐-mstack-protector-guard=guard,-mstack-protector-guard-offset=offsetโ generates stack protection code with the canary sitting at guard ๐ค the supported locations areglobalfor a global canary, ortlsfor a canary you reach through the TLS register. Now listen carefully:-mstack-protector-guard-offset=is for use with-fstack-protector-guard=tlsand not for use in user-land code. periodt. ๐-mfdpic,-mno-fdpicโ selects the FDPIC ABI, which uses 64-bit function descriptors to represent pointers to functions โจ when the compiler is configured forarm-*-uclinuxfdpiceabitargets, this option is on by default and implies-fPIEif none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and you should explicitly provide the PIC/PIE-related options as needed.
Heads up bestie: static linking is not supported, because it would still involve the dynamic linker when the program self-relocates ๐ if that behavior is acceptable, use -static and -Wl,-dynamic-linker options.
The opposite -mno-fdpic option is useful (and required) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs.
-mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]]โ turns on branch protection features (armv8.1-m.main only, so check yourself before you wreck yourself ๐). The flavors go like this:noneโ generates code without branch protection or return address signing. literally nothing, no vibes.standard[+leaf]โ generates code with all branch protection features enabled at their standard level.pac-ret[+leaf]โ generates code with return address signing set to its standard level, which is to sign all functions that save the return address to memory.leafโ when return address signing is enabled, also sign leaf functions even if they do not write the return address to memory. ๐+btiโ add landing-pad instructions at the permitted targets of indirect branch instructions. ๐ฌ
If the +pacbti architecture extension is not enabled, then all branch protection and return address signing operations are constrained to use only the instructions defined in the architectural-NOP space. The generated code will remain backwards-compatible with earlier versions of the architecture, but the additional security can be enabled at run time on processors that support the PACBTI extension. ๐ง
Branch target enforcement using BTI can only be enabled at runtime if all code in the application has been compiled with at least -mbranch-protection=bti. every last bit of it, no skipping.
Any setting other than none is supported only on armv8-m.main or later.
The default is to generate code without branch protection or return address signing. (iconic, unbothered, moisturized ๐ธ)
๐ AVR Options ๐
These options are defined for AVR implementations, so if you're out here programming microcontrollers, this section is your main character era:
-mmcu=mcuโ specify the AVR instruction set architecture (ISA) or device type. The default for this option isavr2.
Quick note before we dive in ๐ a complete device support consists of startup code crtmcu.o, a device header avr/io*.h, a device library libmcu.a and a device-specs file specs-mcu (see https://gcc.gnu.org/wiki/avr-gcc#spec-files). Only the latter is provided by the compiler, according to the supported mcus below. The rest is supported by AVR-LibC (https://www.nongnu.org/avr-libc/), or by means of atpack files from the hardware manufacturer (https://gcc.gnu.org/wiki/avr-gcc#atpack).
The following AVR devices and ISAs are supported ๐ซถ:
avr2โ "Classic" devices with up to 8 KiB of program memory. mcu =attiny22,attiny26,at90s2313,at90s2323,at90s2333,at90s2343,at90s4414,at90s4433,at90s4434,at90c8534,at90s8515,at90s8535.avr25โ "Classic" devices with up to 8 KiB of program memory and with theMOVWinstruction. mcu =attiny13,attiny13a,attiny24,attiny24a,attiny25,attiny261,attiny261a,attiny2313,attiny2313a,attiny43u,attiny44,attiny44a,attiny45,attiny48,attiny441,attiny461,attiny461a,attiny4313,attiny84,attiny84a,attiny85,attiny87,attiny88,attiny828,attiny841,attiny861,attiny861a,ata5272,ata6616c,at86rf401.avr3โ "Classic" devices with 16 KiB up to 64 KiB of program memory. mcu =at76c711,at43usb355.avr31โ "Classic" devices with 128 KiB of program memory. mcu =atmega103,at43usb320.avr35โ "Classic" devices with 16 KiB up to 64 KiB of program memory and with theMOVWinstruction. mcu =attiny167,attiny1634,atmega8u2,atmega16u2,atmega32u2,ata5505,ata6617c,ata664251,at90usb82,at90usb162.avr4โ "Enhanced" devices with up to 8 KiB of program memory. mcu =atmega48,atmega48a,atmega48p,atmega48pa,atmega48pb,atmega8,atmega8a,atmega8hva,atmega88,atmega88a,atmega88p,atmega88pa,atmega88pb,atmega8515,atmega8535,ata5795,ata6285,ata6286,ata6289,ata6612c,at90pwm1,at90pwm2,at90pwm2b,at90pwm3,at90pwm3b,at90pwm81.avr5โ "Enhanced" devices with 16 KiB up to 64 KiB of program memory. mcu =atmega16,atmega16a,atmega16hva,atmega16hva2,atmega16hvb,atmega16hvbrevb,atmega16m1,atmega16u4,atmega161,atmega162,atmega163,atmega164a,atmega164p,atmega164pa,atmega165,atmega165a,atmega165p,atmega165pa,atmega168,atmega168a,atmega168p,atmega168pa,atmega168pb,atmega169,atmega169a,atmega169p,atmega169pa,atmega32,atmega32a,atmega32c1,atmega32hvb,atmega32hvbrevb,atmega32m1,atmega32u4,atmega32u6,atmega323,atmega324a,atmega324p,atmega324pa,atmega324pb,atmega325,atmega325a,atmega325p,atmega325pa,atmega328,atmega328p,atmega328pb,atmega329,atmega329a,atmega329p,atmega329pa,atmega3250,atmega3250a,atmega3250p,atmega3250pa,atmega3290,atmega3290a,atmega3290p,atmega3290pa,atmega406,atmega64,atmega64a,atmega64c1,atmega64hve,atmega64hve2,atmega64m1,atmega64rfr2,atmega640,atmega644,atmega644a,atmega644p,atmega644pa,atmega644rfr2,atmega645,atmega645a,atmega645p,atmega649,atmega649a,atmega649p,atmega6450,atmega6450a,atmega6450p,atmega6490,atmega6490a,atmega6490p,ata5790,ata5790n,ata5791,ata6613c,ata6614q,ata5782,ata5831,ata8210,ata8510,ata5787,ata5835,ata5700m322,ata5702m322,at90pwm161,at90pwm216,at90pwm316,at90can32,at90can64,at90scr100,at90usb646,at90usb647,at94k,m3000. (yes bestie, that's the whole roster, I counted ๐ )avr51โ "Enhanced" devices with 128 KiB of program memory. mcu =atmega128,atmega128a,atmega128rfa1,atmega128rfr2,atmega1280,atmega1281,atmega1284,atmega1284p,atmega1284rfr2,at90can128,at90usb1286,at90usb1287.avr6โ "Enhanced" devices with 3-byte PC, i.e. with more than 128 KiB of program memory. mcu =atmega256rfr2,atmega2560,atmega2561,atmega2564rfr2.avrxmega2โ "XMEGA" devices with more than 8 KiB and up to 64 KiB of program memory. mcu =atxmega8e5,atxmega16a4,atxmega16a4u,atxmega16c4,atxmega16d4,atxmega16e5,atxmega32a4,atxmega32a4u,atxmega32c3,atxmega32c4,atxmega32d3,atxmega32d4,atxmega32e5,avr64da28,avr64da28s,avr64da32,avr64da32s,avr64da48,avr64da48s,avr64da64,avr64da64s,avr64db28,avr64db32,avr64db48,avr64db64,avr64dd14,avr64dd20,avr64dd28,avr64dd32,avr64du28,avr64du32,avr64ea28,avr64ea32,avr64ea48,avr64sd28,avr64sd32,avr64sd48.
avrxmega3โ okay this one is a whole vibe ๐ "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space. Themcu =list here is absolutely enormous, buckle up bestie:"attiny202","attiny204","attiny212","attiny214","attiny402","attiny404","attiny406","attiny412","attiny414","attiny416","attiny416auto","attiny417","attiny424","attiny426","attiny427","attiny804","attiny806","attiny807","attiny814","attiny816","attiny817","attiny824","attiny826","attiny827","attiny1604","attiny1606","attiny1607","attiny1614","attiny1616","attiny1617","attiny1624","attiny1626","attiny1627","attiny3214","attiny3216","attiny3217","attiny3224","attiny3226","attiny3227","atmega808","atmega809","atmega1608","atmega1609","atmega3208","atmega3209","atmega4808","atmega4809","avr16dd14","avr16dd20","avr16dd28","avr16dd32","avr16du14","avr16du20","avr16du28","avr16du32","avr16ea28","avr16ea32","avr16ea48","avr16eb14","avr16eb20","avr16eb28","avr16eb32","avr16la14","avr16la20","avr16la28","avr16la32","avr32da28","avr32da28s","avr32da32","avr32da32s","avr32da48","avr32da48s","avr32db28","avr32db32","avr32db48","avr32dd14","avr32dd20","avr32dd28","avr32dd32","avr32du14","avr32du20","avr32du28","avr32du32","avr32ea28","avr32ea32","avr32ea48","avr32eb14","avr32eb20","avr32eb28","avr32eb32","avr32la14","avr32la20","avr32la28","avr32la32","avr32sd20","avr32sd28","avr32sd32". likeโฆ that's the whole roster, we ate โจavrxmega4โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory.mcu ="atxmega64a3","atxmega64a3u","atxmega64a4u","atxmega64b1","atxmega64b3","atxmega64c3","atxmega64d3","atxmega64d4","avr128da28","avr128da28s","avr128da32","avr128da32s","avr128da48","avr128da48s","avr128da64","avr128da64s","avr128db28","avr128db32","avr128db48","avr128db64".avrxmega5โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM.mcu ="atxmega64a1","atxmega64a1u". tiny list, big power ๐ซถavrxmega6โ "XMEGA" devices with more than 128 KiB of program memory.mcu ="atxmega128a3","atxmega128a3u","atxmega128b1","atxmega128b3","atxmega128c3","atxmega128d3","atxmega128d4","atxmega192a3","atxmega192a3u","atxmega192c3","atxmega192d3","atxmega256a3","atxmega256a3b","atxmega256a3bu","atxmega256a3u","atxmega256c3","atxmega256d3","atxmega384c3","atxmega384d3".avrxmega7โ "XMEGA" devices with more than 128 KiB of program memory and more than 64 KiB of RAM.mcu ="atxmega128a1","atxmega128a1u","atxmega128a4u".avrtinyโ "TINY" Tiny core devices with 512 B up to 4 KiB of program memory.mcu ="attiny4","attiny5","attiny9","attiny10","attiny102","attiny104","attiny20","attiny40". smol but mighty ๐avr1โ This ISA is implemented by the minimal AVR core and supported for assembler only.mcu ="attiny11","attiny12","attiny15","attiny28","at90s1200".
Now the option tea โ๏ธ back at the top level:
-mabsdataโ Assume that all data in static storage can be accessed byLDS/STSinstructions. Heads up bestie, this option has only an effect on reduced Tiny devices like ATtiny40. See also the"absdata"AVR Variable Attributes,variable attribute.-maccumulate-argsโ Accumulate outgoing function arguments and acquire/release the needed stack space for outgoing function arguments once in function prologue/epilogue. Without this option, outgoing arguments are pushed before calling a function and popped afterwards.
Popping the arguments after the function call can be expensive on AVR, so that accumulating the stack space might lead to smaller executables, because arguments need not be removed from the stack after such a function call.
This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack, like calls to printf-like functions.
-mbranch-cost=costโ Set the branch costs for conditional branch instructions to cost. Reasonable values for cost are small, non-negative integers. The default branch cost is0.-mcall-prologuesโ Function prologues/epilogues are expanded as calls to appropriate subroutines. Code size is smaller. slay ๐-mdouble=bits-mlong-double=bitsโ Set the size (in bits) of thedoubleorlong doubletype, respectively. Possible values for bits are32and64. Whether or not a specific value for bits is allowed depends on the--with-double=and--with-long-double=configure options (https://gcc.gnu.org/install/configure.html#avr), and the same applies for the default values of the options.-mgas-isr-prologuesโ Interrupt service routines (ISRs) may use the__gcc_isrpseudo instruction supported by GNU Binutils. If this option is on, the feature can still be disabled for individual ISRs by means of the AVR Function Attributes,,"no_gccisr"function attribute. This feature is activated per default if optimization is on (but not with-Og,@pxref{Optimize Options}), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683).-mint8โ Assumeintto be an 8-bit integer. This affects the sizes of all types: acharis 1 byte, anintis 1 byte, alongis 2 bytes, andlong longis 4 bytes. Please note that this option does not conform to the C standards, but it results in smaller code size.-mmain-is-OS_taskโ Do not save registers inmain. The effect is the same like attaching attribute AVR Function Attributes,,"OS_task"tomain. It is activated per default if optimization is on.-mno-interruptsโ Generated code is not compatible with hardware interrupts. Code size is smaller.-mrelaxโ Try to replaceCALLresp.JMPinstruction by the shorterRCALLresp.RJMPinstruction if applicable. Setting-mrelaxjust adds the--mlink-relaxoption to the assembler's command line and the--relaxoption to the linker's command line.
Jump relaxing is performed by the linker because jump offsets are not known before code is located. Therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from instructions in the assembler code.
Relaxing must be turned on if linker stubs are needed, see the section on EIND and linker stubs below.
-mstrict-Xโ Use address registerXin a way proposed by the hardware. This means thatXis only used in indirect, post-increment or pre-decrement addressing.
Without this option, the X register may be used in the same way as Y or Z, which then is emulated by additional instructions. For example, loading a value with X+const addressing with a small non-negative const < 64 to a register Rn is performed as
adiw r26, const ; X += const
ld <Rn>, X ; <Rn> = *X
sbiw r26, const ; X -= const
-mtiny-stackโ Only change the lower 8 bits of the stack pointer.-mfract-convert-truncateโ Allow to use truncation instead of rounding towards zero for fractional fixed-point types.-nodevicelibโ Don't link against AVR-LibC's device specific librarylib<mcu>.a.-nodevicespecsโ Don't add-specs=device-specs/specs-mcuto the compiler driver's command line. The user takes responsibility for supplying the sub-processes like compiler proper, assembler and linker with appropriate command line options. This means that the user has to supply her private device specs file by means of-specs=path-to-specs-file. There is no more need for option-mmcu=mcu.
This option can also serve as a replacement for the older way of specifying custom device-specs files that needed -B some-path to point to a directory which contains a folder named device-specs, which contains a specs file named specs-mcu, where mcu was specified by -mmcu=mcu. iykyk ๐
-Waddr-space-convertโ Warn about conversions between address spaces in the case where the resulting address space is not contained in the incoming address space.-Wmisspelled-isrโ Warn if the ISR is misspelled, i.e. without__vectorprefix. Enabled by default. she's looking out for you fr fr ๐ซถ
๐ฅ "EIND" and Devices with More Than 128 Ki Bytes of Flash ๐ฅ
Pointers in the implementation are 16 bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can target any code address in the range of 64 Ki words.
In order to facilitate indirect jump on devices with more than 128 Ki bytes of program memory space, there is a special function register called EIND that serves as most significant part of the target address when EICALL or EIJMP instructions are used.
Indirect jumps and calls on these devices are handled as follows by the compiler and are subject to some limitations:
- The compiler never sets
EIND. - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions or might readEINDdirectly in order to emulate an indirect call/jump by means of aRETinstruction. - The compiler assumes that
EINDnever changes during the startup code or during the application. In particular,EINDis not saved/restored in function or interrupt service routine prologue/epilogue. - For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads sometimes also called trampolines. Thus, the indirect call/jump jumps to such a stub. The stub contains a direct jump to the desired address.
- Linker relaxation must be turned on so that the linker generates the stubs correctly in all situations. See the compiler option
-mrelaxand the linker option--relax. There are corner cases where the linker is supposed to generate stubs but aborts without relaxation and without a helpful error message. ๐ not the silent abort bestie - The default linker script is arranged for code with
EIND = 0. If code is supposed to work for a setup withEIND != 0, a custom linker script has to be used in order to place the sections whose name start with.trampolinesinto the segment whereEINDpoints to. - The startup code from
libgccnever setsEIND. Ngl, startup code is a whole collab betweenlibgccand AVR-LibC, so if you wanna know what AVR-LibC does toEIND, go read the AVR-LibC user manual (https://www.nongnu.org/avr-libc/user-manual/). ๐ - It is legit for your own user-specific startup code to set up
EINDearly โ like, super early โ for example with init code chilling in section.init3. That code runs before the general startup code that inits RAM and calls constructors, but after the lil bit of AVR-LibC startup code that setsEINDto the segment where the vector table lives. ๐ซถ
#include <avr/io.h>
static void
__attribute__((section(".init3"),naked,used,no_instrument_function))
init3_set_eind (void)
{
__asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
"out %i0,r24" :: "n" (&EIND) : "r24","memory");
}
The __trampolines_start symbol is defined in the linker script. periodt.
- Stubs get generated automatically by the linker if and only if these two conditions are met:
- The address of a label is taken by means of the
gsmodifier (short for generate stubs, iykyk) like so:
- The address of a label is taken by means of the
LDI r24, lo8(gs(<func>))
LDI r25, hi8(gs(<func>))
- The final location of that label is in a code segment outside the segment where the stubs are located.
- The compiler emits those
gsmodifiers for code labels in these situations, bestie:- Taking address of a function or code label. ๐
- Computed goto.
- If prologue-save function is used, see
-mcall-prologuescommand-line option. - Switch/case dispatch tables. And if you do not want such dispatch tables, you can pass the
-fno-jump-tablescommand-line option. no cap. - C and C++ constructors/destructors called during startup/shutdown.
- If the tools hit a
gs()modifier explained above.
- Jumping to non-symbolic addresses like this is not supported, so don't even try it:
int main (void)
{
/* Call function at word address 0x2 */
return ((int(*)(void)) 0x2)();
}
Instead, a stub has to be set up โ meaning the function has to be called through a symbol (func_4 in the example):
int main (void)
{
extern int func_4 (void);
/* Call function at byte address 0x4 */
return func_4();
}
and then the application gets linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script. two paths, same slay. โจ
๐ Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers ๐
Some AVR devices support memories bigger than the 64 KiB range that 16-bit pointers can reach. To access memory outside that 64 KiB range, the content of a RAMP register is used as the high part of the address: the X, Y, Z address register gets concatenated with the RAMPX, RAMPY, RAMPZ special function register, respectively, to get a wide address. Similarly, RAMPD is used together with direct addressing. it's giving address glow-up ๐
- The startup code initializes the
RAMPspecial function registers with zero. - If an AVR Named Address Spaces named address space other than generic or
__flashis used, thenRAMPZis set as needed before the operation. - If the device supports RAM larger than 64 KiB and the compiler needs to change
RAMPZto accomplish an operation,RAMPZis reset to zero after the operation. ๐งน - If the device comes with a specific
RAMPregister, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it. - RAM larger than 64 KiB is not supported by GCC for AVR targets. If you use inline assembler to read from locations outside the 16-bit address range and change one of the
RAMPregisters, you must reset it to zero after the access. like, mandatory mandatory. ๐ญ
๐ธ AVR Built-in Macros ๐ธ
GCC defines several built-in macros so your code can vibe-check for the presence or absence of features. Almost any of the following built-in macros are deduced from device capabilities and thus triggered by the -mmcu= command-line option.
For even more AVR-specific built-in macros see AVR Named Address Spaces and AVR Built-in Functions. โจ
__AVR_ARCH__โ Build-in macro that resolves to a decimal number that identifies the architecture and depends on the-mmcu=mcuoption. Possible values are:
2, 25, 3, 31, 35, 4, 5, 51, 6
for mcu=avr2, avr25, avr3, avr31, avr35, avr4, avr5, avr51, avr6,
respectively and
100, 102, 103, 104, 105, 106, 107
for mcu=avrtiny, avrxmega2, avrxmega3, avrxmega4, avrxmega5, avrxmega6, avrxmega7, respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4. ๐
__AVR_Device__โ Setting-mmcu=devicedefines this built-in macro which reflects the device's name. For example,-mmcu=atmega8defines the built-in macro__AVR_ATmega8__,-mmcu=attiny261adefines__AVR_ATtiny261A__, etc.
The built-in macros' names follow the scheme __AVR_Device__ where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase. ๐
If device is not a device but only a core architecture like avr51, this macro is not defined.
__AVR_DEVICE_NAME__โ Setting-mmcu=devicedefines this built-in macro to the device's name. For example, with-mmcu=atmega8the macro is defined toatmega8.
If device is not a device but only a core architecture like avr51, this macro is not defined.
__AVR_XMEGA__โ The device / architecture belongs to the XMEGA family of devices.__AVR_HAVE_ADIW__โ The device has theADIWandSBIWinstructions.__AVR_HAVE_ELPM__โ The device has theELPMinstruction.__AVR_HAVE_ELPMX__โ The device has theELPM Rn,ZandELPM Rn,Z+instructions.__AVR_HAVE_LPMX__โ The device has theLPM Rn,ZandLPM Rn,Z+instructions.__AVR_HAVE_MOVW__โ The device has theMOVWinstruction to perform 16-bit register-register moves.__AVR_HAVE_MUL__โ The device has a hardware multiplier. ๐ฅ__AVR_HAVE_JMP_CALL__โ The device has theJMPandCALLinstructions. This is the case for devices with more than 8 KiB of program memory.__AVR_HAVE_EIJMP_EICALL__,__AVR_3_BYTE_PC__โ The device has theEIJMPandEICALLinstructions. This is the case for devices with more than 128 KiB of program memory. This also means that the program counter (PC) is 3 bytes wide.__AVR_2_BYTE_PC__โ The program counter (PC) is 2 bytes wide. This is the case for devices with up to 128 KiB of program memory.__AVR_HAVE_8BIT_SP__,__AVR_HAVE_16BIT_SP__โ The stack pointer (SP) register is treated as 8-bit respectively 16-bit register by the compiler. The definition of these macros is affected by-mtiny-stack.__AVR_HAVE_SPH__,__AVR_SP8__โ The device has the SPH (high part of stack pointer) special function register or has an 8-bit stack pointer, respectively. The definition of these macros is affected by-mmcu=and in the cases of-mmcu=avr2and-mmcu=avr25also by-msp8.__AVR_HAVE_RAMPD__,__AVR_HAVE_RAMPX__,__AVR_HAVE_RAMPY__,__AVR_HAVE_RAMPZ__โ The device has theRAMPD,RAMPX,RAMPY,RAMPZspecial function register, respectively.__NO_INTERRUPTS__โ This macro reflects the-mno-interruptscommand-line option.__AVR_ERRATA_SKIP__,__AVR_ERRATA_SKIP_JMP_CALL__โ Some AVR devices (AT90S8515, ATmega103) must not skip 32-bit instructions because of a hardware erratum. Skip instructions areSBRS,SBRC,SBIS,SBICandCPSE. The second macro is only defined if__AVR_HAVE_JMP_CALL__is also set. ๐__AVR_ISA_RMW__โ The device has Read-Modify-Write instructions (XCH, LAC, LAS and LAT).__AVR_SFR_OFFSET__=offsetโ Instructions that can address I/O special function registers directly likeIN,OUT,SBI, etc. may use a different address as if addressed by an instruction to access RAM likeLDorSTS. This offset depends on the device architecture and has to be subtracted from the RAM address in order to get the respective I/O address.__AVR_SHORT_CALLS__โ The-mshort-callscommand line option is set.__AVR_PM_BASE_ADDRESS__=addrโ Some devices support reading from flash memory by means ofLD*instructions. The flash memory is seen in the data address space at an offset of__AVR_PM_BASE_ADDRESS__. If this macro is not defined, this feature is not available. If defined, the address space is linear and there is no need to put.rodatainto RAM. This is handled by the default linker description file, and is currently available foravrtinyandavrxmega3. Even more convenient, there is no need to use address spaces like__flashor features like attributeprogmemandpgm_read_*. iconic, honestly. ๐__WITH_AVRLIBC__โ The compiler is configured to be used together with AVR-LibC. See the--with-avrlibcconfigure option.__HAVE_DOUBLE_MULTILIB__โ Defined if-mdouble=acts as a multilib option.__HAVE_DOUBLE32__,__HAVE_DOUBLE64__โ Defined if the compiler supports 32-bit double resp. 64-bit double. The actual layout is specified by option-mdouble=.__DEFAULT_DOUBLE__โ The size in bits ofdoubleif-mdouble=is not set. To test the layout ofdoublein a program, use the built-in macro__SIZEOF_DOUBLE__.__HAVE_LONG_DOUBLE32__,__HAVE_LONG_DOUBLE64__,__HAVE_LONG_DOUBLE_MULTILIB__,__DEFAULT_LONG_DOUBLE__โ Same as above, but forlong doubleinstead ofdouble.__WITH_DOUBLE_COMPARISON__โ Reflects the--with-double-comparison={tristate|bool|libf7}configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to2or3.__WITH_LIBF7_LIBGCC__,__WITH_LIBF7_MATH__,__WITH_LIBF7_MATH_SYMBOLS__โ Reflects the--with-libf7={libgcc|math|math-symbols}configure option (https://gcc.gnu.org/install/configure.html#avr). ๐ฆ
๐ AVR Internal Options ๐
The following options are used internally by the compiler and to communicate between device specs files and the compiler proper. You don't need to set these options by hand, in particular they are not optimization options. Using these options in the wrong way may lead to sub-optimal or wrong code. They are documented for completeness, and in order to get a better understanding of device specs (https://gcc.gnu.org/wiki/avr-gcc#spec-files) files.
bestie these are internals okay ๐ญ you are NOT supposed to be hand-setting them, they're literally the compiler talking to itself. They are not optimization options. Do them wrong and you get sub-optimal or straight-up wrong code ๐ they're here for completeness and so you can actually understand device specs files. iykyk.
-mn-flash=numโ Assume that the flash memory has a size ofnumtimes 64 KiB. This determines which__flashNaddress spaces are available.-mrmwโ Assume that the device supports the Read-Modify-Write instructionsXCH,LAC,LASandLAT.-mshort-callsโ Assume thatRJMPandRCALLcan target the whole program memory. This option is used for multilib generation and selection for the devices from architectureavrxmega3.-mskip-bugโ Generate code without skips (CPSE,SBRS,SBRC,SBIS,SBIC) over 32-bit instructions.-msp8โ Treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. This option is used by the compiler to select and build multilibs for architecturesavr2andavr25. These architectures mix devices with and withoutSPH.
๐ฆ Blackfin Options ๐ฆ
-mcpu=cpu[-sirevision]โ Specifies the name of the target Blackfin processor. Currently, cpu can be one ofbf512,bf514,bf516,bf518,bf522,bf523,bf524,bf525,bf526,bf527,bf531,bf532,bf533,bf534,bf536,bf537,bf538,bf539,bf542,bf544,bf547,bf548,bf549,bf542m,bf544m,bf547m,bf548m,bf549m,bf561,bf592.
The optional sirevision specifies the silicon revision of the target Blackfin processor. Any workarounds available for the targeted silicon revision are enabled. If sirevision is none, no workarounds are enabled. If sirevision is any, all workarounds for the targeted processor are enabled. The __SILICON_REVISION__ macro is defined to two hexadecimal digits representing the major and minor numbers in the silicon revision. If sirevision is none, the __SILICON_REVISION__ is not defined. If sirevision is any, the __SILICON_REVISION__ is defined to be 0xffff. If this optional sirevision is not used, GCC assumes the latest known silicon revision of the targeted Blackfin processor.
GCC defines a preprocessor macro for the specified cpu. For the bfin-elf toolchain, this option causes the hardware BSP provided by libgloss to be linked in if -msim is not given.
Without this option, bf532 is used as the processor by default.
note that support forbf561is incomplete ๐ forbf561, only the preprocessor macro is defined. that's it. that's the whole vibe.
-msimโ Specifies that the program will be run on the simulator. This causes the simulator BSP provided by libgloss to be linked in. This option has effect only forbfin-elftoolchain. Certain other options, such as-mid-shared-libraryand-mfdpic, imply-msim.-momit-leaf-frame-pointerโ Don't keep the frame pointer in a register for leaf functions. This avoids the instructions to save, set up and restore frame pointers and makes an extra register available in leaf functions.-mspecld-anomalyโ When enabled, the compiler ensures that the generated code does not contain speculative loads after jump instructions. If this option is used,__WORKAROUND_SPECULATIVE_LOADSis defined.-mno-specld-anomalyโ Don't generate extra code to prevent speculative loads from occurring.-mcsync-anomalyโ When enabled, the compiler ensures that the generated code does not containCSYNCorSSYNCinstructions too soon after conditional branches. If this option is used,__WORKAROUND_SPECULATIVE_SYNCSis defined.-mno-csync-anomalyโ Don't generate extra code to preventCSYNCorSSYNCinstructions from occurring too soon after a conditional branch.-mlow64kโ When enabled, the compiler is free to take advantage of the knowledge that the entire program fits into the low 64k of memory.-mno-low64kโ Assume that the program is arbitrarily large. This is the default.-mstack-check-l1โ Do stack checking using information placed into L1 scratchpad memory by the uClinux kernel.-mid-shared-libraryโ Generate code that supports shared libraries via the library ID method. This allows for execute in place and shared libraries in an environment without virtual memory management. This option implies-fPIC. With abfin-elftarget, this option implies-msim.-mno-id-shared-libraryโ Generate code that doesn't assume ID-based shared libraries are being used. This is the default.-mleaf-id-shared-libraryโ Generate code that supports shared libraries via the library ID method, but assumes that this library or executable won't link against any other ID shared libraries. That allows the compiler to use faster code for jumps and calls.-mno-leaf-id-shared-libraryโ Do not assume that the code being compiled won't link against any ID shared libraries. Slower code is generated for jump and call insns.-mshared-library-id=nโ Specifies the identification number of the ID-based shared library being compiled. Specifying a value of0generates more compact code; specifying other values forces the allocation of that number to the current library but is no more space- or time-efficient than omitting this option.-msep-dataโ Generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute in place in an environment without virtual memory management by eliminating relocations against the text section.-mno-sep-dataโ Generate code that assumes that the data segment follows the text segment. This is the default.-mlong-calls,-mno-long-callsโ Tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 24-bit addressing range of the offset-based version of subroutine call instruction.
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.
-mfast-fpโ Link with the fast floating-point library. This library relaxes some of the IEEE floating-point standard's rules for checking inputs against Not-a-Number (NAN), in the interest of performance.-minline-pltโ Enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without-mfdpic.-mmulticoreโ Build a standalone application for multicore Blackfin processors. This option causes proper start files and link scripts supporting multicore to be used, and defines the macro__BFIN_MULTICORE. It can only be used with-mcpu=bf561[-sirevision].
This option can be used with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, the single-application/dual-core programming model is used. In this model, the main function of Core B should be named as coreb_main.
If this option is not used, the single-core application programming model is used.
-mcoreaโ Build a standalone application for Core A of BF561 when using the one-application-per-core programming model. Proper start files and link scripts are used to support Core A, and the macro__BFIN_COREAis defined. This option can only be used in conjunction with-mmulticore.-mcorebโ Build a standalone application for Core B of BF561 when using the one-application-per-core programming model. Proper start files and link scripts are used to support Core B, and the macro__BFIN_COREBis defined. When this option is used,coreb_mainshould be used instead ofmain. This option can only be used in conjunction with-mmulticore.-msdramโ Build a standalone application for SDRAM. Proper start files and link scripts are used to put the application into SDRAM, and the macro__BFIN_SDRAMis defined. The loader should initialize SDRAM before loading the application.-micplbโ Assume that ICPLBs are enabled at run time. This has an effect on certain anomaly workarounds. For Linux targets, the default is to assume ICPLBs are enabled; for standalone applications the default is off.
๐ C6X Options ๐
-march=nameโ This specifies the name of the target architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. Permissible names are:c62x,c64x,c64x+,c67x,c67x+,c674x.-mbig-endianโ Generate code for a big-endian target.-mlittle-endianโ Generate code for a little-endian target. This is the default.-msimโ Choose startup files and linker script suitable for the simulator.-msdata=defaultโ Put small global and static data in the.neardatasection, which is pointed to by registerB14. Put small uninitialized global and static data in the.bsssection, which is adjacent to the.neardatasection. Put small read-only data into the.rodatasection. The corresponding sections used for large pieces of data are.fardata,.farand.const.-msdata=allโ Put all data, not just small objects, into the sections reserved for small data, and use addressing relative to theB14register to access them.-msdata=noneโ Make no use of the sections reserved for small data, and use absolute addresses to access all data. Put all initialized global and static data in the.fardatasection, and all uninitialized data in the.farsection. Put all constant data into the.constsection.
๐ธ CRIS Options ๐ธ
These options are defined specifically for the CRIS ports.
-march=architecture-type,-mcpu=architecture-typeโ Generate code for the specified architecture. The choices for architecture-type arev3,v8andv10for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. Default isv0.
okay that's all for this lil chunk, more coming, stay tuned bestie ๐
-mtune=architecture-typeโ okay so this one tunes everything applicable about the code it spits out toarchitecture-type, except the ABI and the set of available instructions ๐ . The choices for architecture-type? Same as for-march=architecture-type, no cap ๐ซถ-mmax-stack-frame=nโ warns you when a function's stack frame goes over n bytes. like a lil vibe check on your stack frame ๐-metrax4,-metrax100โ bestie these are just synonyms โจ-metrax4means-march=v3and-metrax100means-march=v8, that's the whole thing.-mmul-bug-workaround,-mno-mul-bug-workaroundโ works around a bug in themulsandmuluinstructions for the CPU models where it actually applies. It is disabled by default, so if you need it you gotta ask for it ๐-mpdebugโ turns on CRIS-specific verbose, debug-related info in the assembly code ๐. Bonus effect: it also turns off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file.-mcc-initโ do not use condition-code results from a previous instruction. Always emit compare and test instructions before you use condition codes. fresh start energy, no leftovers ๐-mno-side-effectsโ do not emit instructions with side effects in addressing modes other than post-increment ๐ซ-mstack-align,-mno-stack-align,-mdata-align,-mno-data-align,-mconst-align,-mno-const-alignโ these options (and theirno-twins) arrange โ or eliminate the arrangements โ for the stack frame, individual data and constants to be aligned for the maximum single data access size of the chosen CPU model. The default is to arrange for 32-bit alignment. Important: ABI details like structure layout are not affected by these, bestie ๐-m32-bit,-m16-bit,-m8-bitโ similar vibe to the stack-, data- and const-align options above, but these arrange for the stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned. Default is 32-bit alignment โญ-mno-prologue-epilogue,-mprologue-epilogueโ with-mno-prologue-epilogue, the normal function prologue and epilogue that set up the stack frame are omitted, and no return instructions or return sequences get generated in the code ๐ญ
Use this option only together with visual inspection of the compiled code: no warnings or errors are generated when call-saved registers must be saved, or storage for local variables needs to be allocated. like it will just. not tell you. ๐
-melfโ legacy no-op option. iconic in its uselessness tbh ๐ฆ-simโ arranges to link with input-output functions from a simulator library. Code, initialized data and zero-initialized data are all allocated consecutively ๐ธ-sim2โ like-sim, but it passes linker options to locate initialized data at0x40000000and zero-initialized data at0x80000000๐
C-SKY Options ๐ง
GCC supports these options when compiling for C-SKY V2 processors โจ
-march=archโ specifies the C-SKY target architecture. The valid values for arch are:ck801,ck802,ck803,ck807, andck810. The default isck810๐-mcpu=cpuโ specifies the C-SKY target processor. The valid values for cpu are:ck801,ck801t,ck802,ck802t,ck802j,ck803,ck803h,ck803t,ck803ht,ck803f,ck803fh,ck803e,ck803eh,ck803et,ck803eht,ck803ef,ck803efh,ck803ft,ck803eft,ck803efht,ck803r1,ck803hr1,ck803tr1,ck803htr1,ck803fr1,ck803fhr1,ck803er1,ck803ehr1,ck803etr1,ck803ehtr1,ck803efr1,ck803efhr1,ck803ftr1,ck803eftr1,ck803efhtr1,ck803s,ck803st,ck803se,ck803sf,ck803sef,ck803seft,ck807e,ck807ef,ck807,ck807f,ck810e,ck810et,ck810ef,ck810eft,ck810,ck810v,ck810f,ck810t,ck810fv,ck810tv,ck810ft, andck810ftv. yes that is a lot of them. the list ate, fr fr ๐ฅ-mbig-endian,-EB,-mlittle-endian,-ELโ select big- or little-endian code. The default is little-endian ๐ซ (and yes,-EBand-ELare the short lil nicknames for those).-mfloat-abi=nameโ specifies which floating-point ABI to use. Permissible values are:soft,softfpandhard.- Specifying
softcauses GCC to generate output containing library calls for floating-point operations. softfpallows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions.hardallows generation of floating-point instructions and uses FPU-specific calling conventions.
- Specifying
The default depends on the specific target configuration. And bestie, listen: the hard-float and soft-float ABIs are not link-compatible โ you must compile your entire program with the same ABI, and link with a compatible set of libraries. no mixing, periodt ๐จ
-mhard-float,-msoft-floatโ select hardware or software floating-point implementations. The default is soft float ๐-mdouble-float,-mno-double-floatโ when-mhard-floatis in effect, enable generation of double-precision float instructions. This is the default except when compiling for CK803 โ-mfdivdu,-mno-fdivduโ when-mhard-floatis in effect, enable generation offrecipd,fsqrtd, andfdivdinstructions. This is the default except when compiling for CK803 ๐งฎ-mfpu=fpuโ select the floating-point processor. This option can only be used with-mhard-float(so don't try it solo, it won't work ๐ ). The values for fpu are:fpv2_sf, which is equivalent to-mno-double-float -mno-fdivdufpv2, which is-mdouble-float -mno-divdufpv2_divd, which is-mdouble-float -mdivdu
-melrw,-mno-elrwโ enable the extendedlrwinstruction. This option defaults to on for CK801 and off otherwise ๐๏ธ-mistack,-mno-istackโ enable interrupt stack instructions; the default is off. Heads up: the-mistackoption is required to handle theinterruptandisrfunction attributes โก-mmpโ enable multiprocessor instructions; the default is off ๐งฉ-mcpโ enable coprocessor instructions; the default is off ๐ง-mcacheโ enable coprocessor instructions; the default is off (yes, the original says coprocessor here too โ iconic copy energy, keeping it exactly as it is ๐)-msecurityโ enable C-SKY security instructions; the default is off ๐-mtrustโ enable C-SKY trust instructions; the default is off ๐ค-mdsp,-medsp,-mvdspโ enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively. All of these options default to off ๐๏ธ-mdiv,-mno-divโ generate divide instructions. Default is off โ-msmart,-mno-smartโ generate code for Smart Mode, using only registers numbered0-7to allow use of 16-bit instructions. This option is ignored for CK801 where this is the required behavior, and it defaults to on for CK802. For other targets, the default is off ๐ง-mhigh-registers,-mno-high-registersโ generate code using the high registers numbered16-31. This option is not supported on CK801, CK802, or CK803, and is enabled by default for other processors โฌ๏ธ-manchor,-mno-anchorโ generate code using global anchor symbol addresses โ-mpushpop,-mno-pushpopโ generate code usingpushandpopinstructions. This option defaults to on ๐-mmultiple-stld,-mstm,-mno-multiple-stld,-mno-stmโ generate code usingstmandldminstructions. This option isn't supported on CK801 but is enabled by default on other processors ๐-mconstpool,-mno-constpoolโ create constant pools in the compiler instead of deferring it to the assembler. This option is the default and is required for correct code generation on CK801 and CK802, and is optional on other processors ๐-mstack-size,-mno-stack-sizeโ emit.stack_sizedirectives for each function in the assembly output. This option defaults to off ๐-mccrt,-mno-ccrtโ generate code for the C-SKY compiler runtime instead oflibgcc. This option defaults to off ๐งฐ-mbranch-cost=nโ set the branch costs to roughly n instructions. The default is1๐ฟ-msched-prolog,-mno-sched-prologโ permit scheduling of function prologue and epilogue sequences.
Using this option can result in code that is not compliant with the C-SKY V2 ABI prologue requirements and that cannot be debugged or backtraced. It is disabled by default. so likeโฆ be careful bestie ๐ญ
-msimโ links the librarylibsemi.a, which is in compatible with simulator. Applicable to ELF compiler only ๐ฅ๏ธ
Darwin Options ๐
These options are defined for all architectures running the Darwin operating system ๐
FSF GCC on Darwin does not create "fat" object files; it creates an object file for the single architecture that GCC was built to target. Apple's GCC on Darwin does create "fat" files if multiple -arch options are used; it does so by running the compiler or linker multiple times and joining the results together with lipo ๐ฅ
The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can be used to override this ๐ฏ
The Darwin tools vary in their behavior when presented with an ISA mismatch. The assembler, as, only permits instructions to be used that are valid for the subtype of the file it is generating, so you cannot put 64-bit instructions in a ppc750 object file. The linker for shared libraries, /usr/bin/libtool, fails and prints an error if asked to create a shared library with a less restrictive subtype than its input files (for instance, trying to put a ppc970 object file in a ppc7400 library). The linker for executables, ld, quietly gives the executable the most restrictive subtype of any of its input files ๐ค
-Fdirโ Add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by-Ioptions and are scanned in a left-to-right order ๐
Like, a framework directory is just a directory that has frameworks in it, bestie ๐ A framework is a directory with a Headers and/or PrivateHeaders directory sitting directly inside it that ends in .framework. The name of the framework is the name of that directory minus the .framework. The headers that belong to the framework live in one of those two directories, and Headers gets searched first. โจ
A subframework is a framework directory that lives inside a framework's Frameworks directory. Includes of subframework headers can only show up in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework ๐ฏ A subframework should not have the same name as a framework โ if you break that rule you get a warning. And currently a subframework cannot have subframeworks; in the future the mechanism may be extended to support this. The standard frameworks live in /System/Library/Frameworks and /Library/Frameworks. An example include looks like "#include <Framework/header.h>", where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory. ๐
-iframeworkdir โ Like-Fexcept the directory is treated as a system directory. The main difference between-iframeworkand-Fis that with-iframeworkthe compiler does not warn about constructs contained within header files found via dir. This option is valid only for the C family of languages.-gusedโ Emit debugging information for symbols that are used. Forstabsdebugging format, this enables-feliminate-unused-debug-symbols. This is by default ON. ๐-gfullโ Emit debugging information for all symbols and types. all of them. every single one. ๐-fconstant-cfstringsโ This one is literally just an alias for-mconstant-cfstrings.-mconstant-cfstringsโ When the NeXT runtime is being used (the default on these systems), override any-fconstant-string-classsetting and cause"@"...""literals to be laid out as constant CoreFoundation strings.-mmacosx-version-min=versionโ The earliest version of MacOS X that this executable will run on is version. Typical values supported for version include12,10.12, and10.5.8.
If the compiler was built to use the system's headers by default, then the default for this option is the system version on which the compiler is running, otherwise the default is to make choices that are compatible with as many systems and code bases as possible. ๐
-mkernelโ Enable kernel development mode ๐ง The-mkerneloption sets-static,-fno-common,-fno-use-cxa-atexit,-fno-exceptions,-fno-non-call-exceptions,-fapple-kext,-fno-weakand-fno-rttiwhere applicable. This mode also sets-mno-altivec,-msoft-float,-fno-builtinand-mlong-branchfor PowerPC targets.-mone-byte-boolโ Override the defaults for"bool"so that"sizeof(bool)==1". By defaultsizeof(bool)is4when compiling for Darwin/PowerPC and1when compiling for Darwin/x86, so this option has no effect on x86.
โ ๏ธ Warning: The -mone-byte-bool switch causes GCC to generate code that is not binary compatible with code generated without that switch. Using this switch may require recompiling all other modules in a program, including system libraries. Use this switch to conform to a non-default data model. ๐
-mfix-and-continue,-ffix-and-continue,-findirect-dataโ Generate code suitable for fast turnaround development, such as to allow GDB to dynamically load.ofiles into already-running programs.-findirect-dataand-ffix-and-continueare provided for backwards compatibility.-all_loadโ Loads all members of static archive libraries. Seeman ld(1)for more information.-arch_errors_fatalโ Cause the errors having to do with files that have the wrong architecture to be fatal.-bind_at_loadโ Causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.-bundleโ Produce a Mach-o bundle format file. Seeman ld(1)for more information.-bundle_loaderexecutable โ This option specifies the executable that will load the build output file being linked. Seeman ld(1)for more information.-dynamiclibโ When passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand.-force_cpusubtype_ALLโ This causes GCC's output file to have theALLsubtype, instead of one controlled by the-mcpuor-marchoption.
And here comes the big ol' guest list ๐ all of these get passed to the Darwin linker, and the Darwin linker man page describes them in detail:
-allowable_clientclient_name-client_name-compatibility_version-current_version-dead_strip-dependency-file-dylib_file-dylinker_install_name-dynamic-exported_symbols_list-filelist-flat_namespace-force_flat_namespace-headerpad_max_install_names-image_base-init-install_name-keep_private_externs-multi_module-multiply_defined-multiply_defined_unused-noall_load-no_dead_strip_inits_and_terms-nofixprebinding-nomultidefs-noprebind-noseglinkedit-pagezero_size-prebind-prebind_all_twolevel_modules-private_bundle-read_only_relocs-sectalign-sectobjectsymbols-whyload-seg1addr-sectcreate-sectobjectsymbols-sectorder-segaddr-segs_read_only_addr-segs_read_write_addr-seg_addr_table-seg_addr_table_filename-seglinkedit-segprot-segs_read_only_addr-segs_read_write_addr-single_module-static-sub_library-sub_umbrella-twolevel_namespace-umbrella-undefined-unexported_symbols_list-weak_reference_mismatches-whatsloaded
(yes bestie, some of them are listed twice in the original, no I'm not fixing that, that's just how it ate ๐ )
๐ง DEC Alpha Options ๐ง
These -m options are defined for the DEC Alpha implementations:
-mno-soft-float,-msoft-floatโ Use (do not use) the hardware floating-point instructions for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. Unless they are replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines issue floating-point operations. If you are compiling for an Alpha without floating-point operations, you must ensure that the library is built so as not to call them.
Note that Alpha implementations without floating-point operations are required to have floating-point registers. ๐
-mfp-reg,-mno-fp-regsโ Generate code that uses (does not use) the floating-point register set.-mno-fp-regsimplies-msoft-float. If the floating-point register set is not used, floating-point operands are passed in integer registers as if they were integers and floating-point results are passed in$0instead of$f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with-mno-fp-regsmust also be compiled with that option. โ ๏ธ
A typical use of this option is building a kernel that does not use, and hence need not save and restore, any floating-point registers. ๐ง
-mieeeโ The Alpha architecture implements floating-point hardware optimized for maximum performance. It is mostly compliant with the IEEE floating-point standard. However, for full compliance, software assistance is required. This option generates code fully IEEE-compliant code except that the inexact-flag is not maintained (see below). If this option is turned on, the preprocessor macro"_IEEE_FP"is defined during compilation. The resulting code is less efficient but is able to correctly support denormalized numbers and exceptional IEEE values such as not-a-number and plus/minus infinity. Other Alpha compilers call this option-ieee_with_no_inexact.
DEBIAN SPECIFIC:</> This option is on by default for alpha-linux-gnu, unless -ffinite-math-only (which is part of the -ffast-math set) is specified, because the software functions in the GNU libc math libraries generate denormalized numbers, NaNs, and infs (all of which will cause a program to SIGFPE when it attempts to use the results without -mieee). ๐ญ
-mieee-with-inexactโ This is like-mieeeexcept the generated code also maintains the IEEE inexact-flag. Turning on this option causes the generated code to implement fully-compliant IEEE math. In addition to"_IEEE_FP","_IEEE_FP_EXACT"is defined as a preprocessor macro. On some Alpha implementations the resulting code may execute significantly slower than the code generated by default. Since there is very little code that depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this option-ieee_with_inexact.-mfp-trap-mode=trap-mode โ This option controls what floating-point related traps are enabled. Other Alpha compilers call this option-fptmtrap-mode. The trap mode can be set to one of four values:nโ This is the default (normal) setting. The only traps that are enabled are the ones that cannot be disabled in software (e.g., division by zero trap).uโ In addition to the traps enabled byn, underflow traps are enabled as well.suโ Likeu, but the instructions are marked to be safe for software completion (see Alpha architecture manual for details).suiโ Likesu, but inexact traps are enabled as well.
-mfp-rounding-mode=rounding-mode โ Selects the IEEE rounding mode. Other Alpha compilers call this option-fprmrounding-mode. The rounding-mode can be one of:nโ Normal IEEE rounding mode. Floating-point numbers are rounded towards the nearest machine number or towards the even machine number in case of a tie.mโ Round towards minus infinity.cโ Chopped rounding mode. Floating-point numbers are rounded towards zero.
dโ Dynamic rounding mode. There's this field chilling in the floating-point control register (fpcr, peek the Alpha architecture reference manual for the deets) and it controls which rounding mode is actually in effect. The C library sets this register up for rounding towards plus infinity, so unless your program goes in and messes with thefpcrdirectly,d= round towards plus infinity. Simple as that bestie ๐-mtrap-precision=trap-precision` โ ok so on the Alpha architecture, floating-point traps are imprecise ๐ญ which is basically the worst. It means that without some software help, there is literally no way to recover from a floating trap, and program execution normally just has to be terminated. GCC can spit out code that helps operating system trap handlers figure out the exact location that caused the floating-point trap though ๐ฆ Depending on what your application actually needs, you can pick different levels of precision:pโ Program precision. This one's the default, and it means a trap handler can only identify which program caused a floating-point exception. That's it, that's all you get.fโ Function precision. Now the trap handler can determine the function that caused the floating-point exception. Glow up โจiโ Instruction precision. The trap handler can determine the exact instruction that caused the floating-point exception. Main character precision honestly ๐
Other Alpha compilers ship the equivalent options but they're named -scope_safe and -resumption_safe.
-mieee-conformantโ this marks the generated code as IEEE conformant. ๐จ Do not use this option unless you also specify-mtrap-precision=iand either-mfp-trap-mode=suor-mfp-trap-mode=sui. Its only effect is to emit the line.eflag 48in the function prologue of the generated assembly file. That's the whole entire job fr fr.-mbuild-constantsโ normally GCC looks at a 32- or 64-bit integer constant and asks itself "can I build this out of smaller constants in two or three instructions?" If it can't, it just outputs the constant as a literal and generates code to load it from the data segment at run time.
Use this option to force GCC to construct all integer constants using code, even if that takes more instructions (the maximum is six). The classic use case: building a shared library dynamic loader. It's itself a shared library, so it has to relocate itself in memory before it can even find the variables and constants in its own data segment. Iconic recursion moment ๐
-mbwx-mno-bwx-mcix-mno-cix-mfix-mno-fix-mmax-mno-max
These tell GCC whether it should generate code that uses the optional BWX, CIX, FIX and MAX instruction sets. The default is to use whatever instruction sets are supported by the CPU type you specified via the -mcpu= option โ or, if you didn't specify one, by the CPU that GCC was built on.
-mfloat-vax-mfloat-ieee
Generate code that uses (or does not use ๐ซ ) VAX F and G floating-point arithmetic instead of IEEE single and double precision.
-mexplicit-relocs-mno-explicit-relocs
Older Alpha assemblers had literally no way to generate symbol relocations except through assembler macros, and using those macros means you can't get optimal instruction scheduling ๐ GNU binutils as of version 2.12 supports a new syntax that lets the compiler explicitly mark which relocations apply to which instructions. This option is mostly useful for debugging, since GCC detects the capabilities of the assembler when it's built and sets the default accordingly.
-msmall-data-mlarge-data
When -mexplicit-relocs is in effect, static data gets accessed via gp-relative relocations. With -msmall-data, objects that are 8 bytes long or smaller get placed in a small data area (the ".sdata" and ".sbss" sections) and accessed via 16-bit relocations off of the $gp register. This caps the small data area at 64KB, but the payoff is that those variables are directly accessible via a single instruction. Tiny but mighty ๐
The default is -mlarge-data. With that one, the data area is limited to just below 2GB. Programs that need more than 2GB of data have to use malloc or mmap to allocate the data in the heap instead of in the program's data segment.
When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.
-msmall-text-mlarge-text
With -msmall-text, the compiler assumes that the code of the entire program (or shared library) fits in 4MB, and is therefore reachable with a branch instruction. When -msmall-data is used, the compiler can assume that all local symbols share the same $gp value, and thus it can reduce the number of instructions required for a function call from 4 to 1. Efficiency slay ๐
The default is -mlarge-text.
-mcpu=cpu_type` โ sets the instruction set and the instruction scheduling parameters for machine type cpu_type. You can specify either the EV style name or the corresponding chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors and picks the default values for the instruction set from the processor you specify. If you don't specify a processor type, GCC defaults to the processor on which the compiler was built.
Supported values for cpu_type are:
ev4ev4521064
Schedules as an EV4 and has no instruction set extensions.
ev521164
Schedules as an EV5 and has no instruction set extensions.
ev5621164a
Schedules as an EV5 and supports the BWX extension.
pca5621164pc21164PC
Schedules as an EV5 and supports the BWX and MAX extensions.
ev621264
Schedules as an EV6 and supports the BWX, FIX, and MAX extensions.
ev6721264a
Schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions.
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor. ๐
-mtune=cpu_type` โ sets only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed. Just vibes, not architecture, yk?
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.
-mmemory-latency=time` โ sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. So like, it's giving "it depends" energy.
Valid options for time are:
- number A decimal number representing clock cycles.
L1L2L3main
The compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note that L3 is only valid for EV5. ๐
๐ฆ eBPF Options ๐ฆ
- *
-mframe-limit=bytes*** โ this specifies the hard limit for frame sizes, in bytes. Currently, the value that can be specified should be less than or equal to32767`. Defaults to whatever limit is imposed by the version of the Linux kernel targeted. - *
-mkernel=version*** โ this specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to determine which instructions to use, what kernel helpers to allow, etc. Currently, *version* can be one of4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9,4.10,4.11,4.12,4.13,4.14,4.15,4.16,4.17,4.18,4.19,4.20,5.0,5.1,5.2,latestandnative`. yes bestie that really is a whole list ๐ธ -mbig-endianโ generate code for a big-endian target.-mlittle-endianโ generate code for a little-endian target. This is the default.-mjmpextโ enable generation of extra conditional-branch instructions. Enabled for CPU v2 and above.-mjmp32โ enable 32-bit jump instructions. Enabled for CPU v3 and above.-malu32โ enable 32-bit ALU instructions. Enabled for CPU v3 and above.- *
-mcpu=version*** โ this specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default isv3`.
Supported values for version are:
v1โ The first stable eBPF ISA with no special features or extensions.v2โ Supports the jump extensions, as in-mjmpext.v3โ All features ofv2, plus:- 32-bit jump operations, as in
-mjmp32 - 32-bit ALU operations, as in
-malu32
- 32-bit jump operations, as in
-mco-reโ enable BPF Compile Once - Run Everywhere (CO-RE) support. Requires and is implied by-gbtf. โจ-mno-co-reโ disable BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is enabled by default when generating BTF debug information for the BPF target.-mxbpfโ generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture:- Save and restore callee-saved registers at function entry and exit, respectively.
๐ FR30 Options ๐
These options are defined specifically for the FR30 port.
-msmall-modelโ use the small address space model. This can produce smaller code, but it does assume that all symbolic values and addresses fit into a 20-bit range. So like, cute and compact but only if everything actually fits ๐ซถ-mno-lsimโ assume that runtime support has been provided and so there's no need to include the simulator library (libsim.a) on the linker command line.
๐ FT32 Options ๐
These options are defined specifically for the FT32 port.
-msimโ specifies that the program will be run on the simulator. This causes an alternate runtime startup and library to be linked. ๐จ You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed.-mlraโ enable Local Register Allocation. This is still experimental for FT32, so by default the compiler uses standard reload. (Experimental!! be careful bestie ๐)-mnodivโ do not usedivandmodinstructions.-mft32bโ enable use of the extended instructions of the FT32B processor.-mcompressโ compress all code using the Ft32B code compression scheme.-mnopmโ do not generate code that reads program memory.
๐ FRV Options ๐
-mgpr-32โ only use the first 32 general-purpose registers.-mgpr-64โ use all 64 general-purpose registers.-mfpr-32โ only use the first 32 floating-point registers, bestie. That's it, that's the whole vibe. ๐-mfpr-64โ use all 64 floating-point registers. Go big or go home, fr fr.-mhard-floatโ do your floating-point math with actual hardware instructions, like nature intended. โก-msoft-floatโ do that same floating-point math with library routines instead. Slower but softer, like a cozy blanket for your FPU. ๐งธ-malloc-ccโ dynamically allocate condition code registers. Fancy and flexible โจ-mfixed-ccโ nope, don't dynamically allocate condition code registers. Just use"icc0"and"fcc0"and that's it. Simple living. ๐-mdwordโ change the ABI to use double word insns. We're doing things double now.-mno-dwordโ do not use double word instructions. Put those back.-mdoubleโ use floating-point double instructions. Two times the float, two times the fun. ๐-mno-doubleโ do not use floating-point double instructions. Single float only, no cap.-mmediaโ use media instructions. It's giving multimedia main character energy. ๐ฌ-mno-mediaโ do not use media instructions. The media era is over, bestie.-mmuladdโ use multiply and add/subtract instructions. Math girlies, this one's for you. ๐งฎโจ-mno-muladdโ do not use multiply and add/subtract instructions. We're on a math break.-mfdpicโ select the FDPIC ABI, which uses function descriptors to represent pointers to functions. Okay so here's the tea: without any PIC/PIE-related options, it implies-fPIE. With-fpicor-fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address. With-fPICor-fPIE, GOT offsets are computed with 32 bits. And with a bfin-elf target, this option implies-msim. That's the whole rundown, iykyk. ๐-minline-pltโ enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without-mfdpic. It's enabled by default if optimizing for speed and compiling for shared libraries (i.e.,-fPICor-fpic), or when an optimization option such as-O3or above is present in the command line. It's giving "free real estate" for your PLT entries. ๐-mTLSโ assume a large TLS segment when generating thread-local code. Big TLS energy. ๐ช-mtlsโ do not assume a large TLS segment when generating thread-local code. Keep it smol. ๐ฃ-mgprel-roโ enable the use of"GPREL"relocations in the FDPIC ABI for data that is known to be in read-only sections. It's enabled by default, except for-fpicor-fpie: even though it may help make the global offset table smaller, it trades 1 instruction for 4. With-fPICor-fPIE, it trades 3 instructions for 4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it is not,-mno-gprel-rocan be used to disable it. Math queen behavior, honestly. ๐-multilib-library-picโ link with the (library, not FD) pic libraries. It's implied by-mlibrary-pic, as well as by-fPICand-fpicwithout-mfdpic. You should never have to use it explicitly. It's the option that uses you, not the other way around. ๐-mlinked-fpโ follow the EABI requirement of always creating a frame pointer whenever a stack frame is allocated. This option is enabled by default and can be disabled with-mno-linked-fp. Frame pointers stay winning. ๐-mlong-callsโ use indirect addressing to call functions outside the current compilation unit. This allows the functions to be placed anywhere within the 32-bit address space. Long-distance relationship with your functions, and it's working. ๐-malign-labelsโ try to align labels to an 8-byte boundary by inserting NOPs into the previous packet. This option only has an effect when VLIW packing is enabled. It doesn't create new packets; it merely adds NOPs to existing ones. Not me adding NOPs to the group chat ๐-mlibrary-picโ generate position-independent EABI code. PIC but make it EABI. โจ-macc-4โ use only the first four media accumulator registers. Keep it to a quartet. ๐ถ-macc-8โ use all eight media accumulator registers. Full octet, no holding back. ๐ค-mpackโ pack VLIW instructions. Tetris but for instructions. ๐งฉ-mno-packโ do not pack VLIW instructions. Leave them spread out like your laundry. ๐งบ-mno-eflagsโ do not mark ABI switches in e_flags. We're keeping secrets from the flags. ๐คซ-mcond-moveโ enable the use of conditional-move instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. So like, don't get too attached, bestie. ๐
-mno-cond-moveโ disable the use of conditional-move instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version. Also on the chopping block, rip. ๐ญ
-msccโ enable the use of conditional set instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. Enjoy it while it lasts. ๐ธ
-mno-sccโ disable the use of conditional set instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version. Another one destined for the archives. ๐ฆ
-mcond-execโ enable the use of conditional execution (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. Live in the moment, okay? โจ
-mno-cond-execโ disable the use of conditional execution.
This switch is mainly for debugging the compiler and will likely be removed in a future version. Gone too soon, probably. ๐ฅ
-mvliw-branchโ run a pass to pack branches into VLIW instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. It's giving "limited edition" energy. โณ
-mno-vliw-branchโ do not run a pass to pack branches into VLIW instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version. Same energy, different day.
-mmulti-cond-execโ enable optimization of"&&"and"||"in conditional execution (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. The "&&" girlies are thriving rn. ๐
-mno-multi-cond-execโ disable optimization of"&&"and"||"in conditional execution.
This switch is mainly for debugging the compiler and will likely be removed in a future version. "&&" and "||" are on their own now, bestie.
-mnested-cond-execโ enable nested conditional execution optimizations (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version. Nested, like your feelings about deprecated flags. ๐ช
-mno-nested-cond-execโ disable nested conditional execution optimizations.
This switch is mainly for debugging the compiler and will likely be removed in a future version. Unnested, unbothered, unproblematic. ๐ง
-moptimize-membarโ this switch removes redundant"membar"instructions from the compiler-generated code. It is enabled by default. Marie Kondo-ing those membar instructions. โจ๐งน-mno-optimize-membarโ this switch disables the automatic removal of redundant"membar"instructions from the generated code. Keep all your membars, even the redundant ones. You're a collector. ๐๏ธ-mtomcat-statsโ cause gas to print out tomcat statistics. Meow. ๐ฑ- *
-mcpu=cpu* โ select the processor type for which to generate code. Possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple. Pick your fighter. ๐
GNU/Linux Options ๐ง
These -m options are defined for GNU/Linux targets:
-mglibcโ use the GNU C library. This is the default except on*-*-linux-*uclibc*,*-*-linux-*musl*and*-*-linux-*android*targets. The classic, the icon, the glibc. ๐-muclibcโ use uClibc C library. This is the default on*-*-linux-*uclibc*targets. uClibc stans, rise up. ๐ซถ-mmuslโ use the musl C library. This is the default on*-*-linux-*musl*targets. musl hive, this one's for you. ๐ธ-mbionicโ use Bionic C library. This is the default on*-*-linux-*android*targets. Android's very own libc, living its best life. ๐ค-mandroidโ compile code compatible with Android platform. This is the default on*-*-linux-*android*targets.
When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, this option makes the GCC driver pass Android-specific options to the linker. Finally, this option causes the preprocessor macro "__ANDROID__" to be defined. It's giving "I contain multitudes." ๐
-tno-android-ccโ disable compilation effects of-mandroid, i.e., do not enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default. Turning off the Android compiler vibes specifically. ๐ซ-tno-android-ldโ disable linking effects of-mandroid, i.e., pass standard Linux linking options to the linker. Turning off the Android linker vibes specifically. Standard Linux gang, we're back. ๐ง
H8/300 Options ๐๏ธ
These -m options are defined for the H8/300 implementations:
-mrelaxโ shorten some address references at link time, when possible; uses the linker option-relax. Shortening like a good lil' crop top. โ๏ธ-mhโ generate code for the H8/300H. H is for "hot." ๐ฅ-msโ generate code for the H8S. S is for "slay." ๐-mnโ generate code for the H8S and H8/300H in the normal mode. This switch must be used either with-mhor-ms. It doesn't go anywhere alone, it needs a buddy. ๐ซถ-ms2600โ generate code for the H8S/2600. This switch must be used with-ms. It's a-msexclusive, no gatecrashing. ๐๏ธ-mexrโ extended registers are stored on stack before execution of function with monitor attribute. Default option is-mexr. This option is valid only for H8S targets. Stack 'em up. ๐-mno-exrโ extended registers are not stored on stack before execution of function with monitor attribute. Default option is-mno-exr. This option is valid only for H8S targets. Keeping those registers out of the stack, respectfully. ๐-mint32โ make"int"data 32 bits by default.intgot a lil' upgrade, good for them. โฌ๏ธ-malign-300โ on the H8/300H and H8S, use the same alignment rules as for the H8/300. The default for the H8/300H and H8S is to align longs and floats on 4-byte boundaries.-malign-300causes them to be aligned on 2-byte boundaries. This option has no effect on the H8/300. Alignment consistency, we love to see it. ๐
HPPA Options ๐
These -m options are defined for the HPPA family of computers:
- *
-march=architecture-type* โ generate code for the specified architecture. The choices for architecture-type are1.0for PA 1.0,1.1for PA 1.1, and2.0for PA 2.0 processors. Refer to/usr/lib/sched.modelson an HP-UX system to determine the proper architecture option for your machine. Code compiled for lower numbered architectures runs on higher numbered architectures, but not the other way around. Forward compatible only, bestie, no time travel backwards. โฉ -mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0
Synonyms for -march=1.0, -march=1.1, and -march=2.0 respectively. Just different names for the same slay. โจ
-matomic-libcallsโ generate libcalls for atomic loads and stores when sync libcalls are disabled. This option is enabled by default. It only affects the generation of atomic libcalls by the HPPA backend.
Both the sync and libatomic libcall implementations use locking. As a result, processor stores are not atomic with respect to other atomic operations. Processor loads up to DImode are atomic with respect to other atomic operations provided they are implemented as a single access.
The PA-RISC architecture does not support any atomic operations in hardware except for the "ldcw" instruction. Thus, all atomic support is implemented using sync and atomic libcalls. Sync libcall support is in libgcc.a. Atomic libcall support is in libatomic.
This option generates "__atomic_exchange" calls for atomic stores. It also provides special handling for atomic DImode accesses on 32-bit targets. Atomicity is complicated, okay? But this option's got you. ๐
-mbig-switchโ does nothing. Preserved for backward compatibility. It's the NPC of compiler options. ๐ง-mcaller-copiesโ the caller does the copying of function arguments that get passed by hidden reference. Lowkey powerful, highkey risky: it is not compatible with the default 32-bit runtime, so use with care. That said, only aggregates bigger than eight bytes go by hidden reference anyway, and this option gives you better compatibility with OpenMP. ๐ซถ-mcoherent-ldcwโ use theldcw/ldcdcoherent cache-control hint.-mdisable-fpregsโ floating-point registers? Gone. Off. Not invited. Equivalent to-msoft-float.-mdisable-indexingโ stops the compiler from using indexing address modes. Why would you want this? It dodges some rather obscure problems when you're compiling MIG generated code under MACH. niche but real. ๐-mfast-indirect-callsโ generates code that assumes calls never cross space boundaries, which lets GCC emit faster indirect calls. Slay. But it does not work in the presence of shared libraries or nested functions. periodt.- *
-mfixed-range=register-range* โ generate code that treats the given register range as fixed registers. A fixed register is one the register allocator cannot touch, which is exactly the vibe you want when compiling kernel code. ๐ A register range is two registers separated by a dash, and you can list multiple ranges separated by commas. -mgasโ turn on the use of assembler directives that only GAS understands.-mgnu-ldโ use options specific to GNUld. This passes-sharedtoldwhen building a shared library, and it's the default when GCC is configured (explicitly or implicitly) with the GNU linker. Important: this does not change whichldgets called, it only changes what parameters get handed to thatld. Theldthat gets called is decided by the--with-ldconfigure option, then GCC's program search path, and finally by the user'sPATH. Wanna see which linker GCC is using? Print it withgcc -print-prog-name=ld. Heads up bestie: this option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*. ๐-mhp-ldโ use options specific to HPld. This passes-btoldwhen building a shared library, and passes+Accept TypeMismatchtoldon all links. It's the default when GCC is configured (explicitly or implicitly) with the HP linker. Same deal as above: it does not affect whichldis called, only what parameters get passed to it. Whichldgets called =--with-ldconfigure option, GCC's program search path, and finally yourPATH. Peep it withgcc -print-prog-name=ld. Only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*. โญ-mlinker-optโ enables the optimization pass in the HP-UX linker. Big caveat: this makes symbolic debugging impossible. ๐ญ It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers where they throw bogus error messages when linking some programs.-mlong-callsโ generate code that uses long call sequences, so a call can always reach linker generated stubs. By default, long calls only get generated when the distance from the call site to the beginning of the function or translation unit (whichever applies) exceeds a predefined limit set by the branch type in use. Normal calls are limited at 7,600,000 and 240,000 bytes, respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at 240,000 bytes.
Distances are measured from the beginning of functions when you're using the -ffunction-sections option, or when using -mgas and -mno-portable-runtime together under HP-UX with the SOM linker.
Normally you do not want this option because it degrades performance. However, it can be useful in large applications, especially when partial linking is used to build the application.
What types of long calls get used depends on the capabilities of the assembler and linker, plus the type of code being generated. On systems that support long absolute calls, and long pic symbol-difference or pc-relative calls, the impact should be relatively small. But on 32-bit ELF systems in pic code, an indirect call is used โ and it is quite long. ๐
-mlong-load-storeโ generate 3-instruction load and store sequences, as the HP-UX 10 linker sometimes requires. Equivalent to the+koption to the HP compilers.-mjump-in-delayโ this option is ignored and provided for compatibility purposes only. it's giving ghost option ๐ป-mno-space-regsโ generate code that assumes the target has no space registers. That lets GCC generate faster indirect calls and use unscaled index address modes. Such code is suitable for level 0 PA systems and kernels. ๐-morderedโ assume memory references are ordered and barriers aren't needed.-mportable-runtimeโ use the portable calling conventions proposed by HP for ELF systems.- *
-mschedule=cpu-type* โ schedule code according to the constraints for the machine type cpu-type. The choices for cpu-type are7007100, 7100LC, 7200, 7300and8000. Go check/usr/lib/sched.modelson an HP-UX system to figure out the proper scheduling option for your machine. Default scheduling is8000. ๐ -msioโ generate the predefine_SIOfor server IO. The default is-mwsio, which generates the predefines__hp9000s700,__hp9000s700__and_WSIOfor workstation IO. These options are available under HP-UX and HI-UX.-msoft-floatโ generate output containing library calls for floating point. โ ๏ธ Warning: the requisite libraries are not available for all HPPA targets. Normally the facilities of the machine's usual C compiler get used, but that can't be done directly in cross-compilation โ you have to make your own arrangements to provide suitable library functions for cross-compilation.
Also, -msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with it. Specifically, you need to compile libgcc.a (the library that comes with GCC) with -msoft-float for this to work. no skipping that step bestie ๐จ
-msoft-multโ use software integer multiplication. This disables the use of thexmpyuinstruction. ๐งฎ- *
-munix=unix-std* โ generate compiler predefines and select a startfile for the specified UNIX standard. The choices for unix-std are93,95and98.93is supported on all HP-UX versions,95is available on HP-UX 10.10 and later, and98is available on HP-UX 11.11 and later. The default values are93for HP-UX 10.00,95for HP-UX 10.10 through to 11.00, and98for HP-UX 11.11 and later.
-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, plus the startfile unix95.o. -munix=98 provides additional predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, plus the startfile unix98.o.
It's important to note that this option changes the interfaces for various library routines. It also affects the operational behavior of the C library. So extreme care is needed when using this option. ๐ณ
Library code that's meant to operate with more than one UNIX standard must test, set and restore the variable __xpg4_extended_mask as appropriate. Most GNU software doesn't provide this capability.
-nolibdldโ suppress the generation of link options to searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later.-staticโ the HP-UX implementation ofsetlocaleinlibchas a dependency onlibdld.sl, and there isn't an archive version oflibdld.sl. So when-staticis specified, special link options are needed to resolve that dependency.
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when -static is specified โ which causes the resulting binary to be dynamic. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to stop the GCC driver from adding these link options. ๐
-threadsโ add support for multithreading with the dce thread library under HP-UX. This option sets flags for both the preprocessor and the linker.
โจ IA-64 Options โจ
These are the -m options defined for the Intel IA-64 architecture. buckle up ๐ฆ
-mbig-endianโ generate code for a big-endian target. This is the default for HP-UX.-mlittle-endianโ generate code for a little-endian target. This is the default for AIX5 and GNU/Linux.-mgnu-as,-mno-gnu-asโ generate (or don't) code for the GNU assembler. This is the default.-mgnu-ld,-mno-gnu-ldโ generate (or don't) code for the GNU linker. This is the default.-mno-picโ generate code that does not use a global pointer register. The result is not position independent code, and it violates the IA-64 ABI. ๐ฉ-mvolatile-asm-stop,-mno-volatile-asm-stopโ generate (or don't) a stop bit immediately before and after volatile asm statements.-mregister-names,-mno-register-namesโ generate (or don't)in,loc, andoutregister names for the stacked registers. This may make assembler output more readable. ๐-mno-sdata,-msdataโ disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs.-mconstant-gpโ generate code that uses a single constant global pointer value. Useful when compiling kernel code.-mauto-picโ generate code that is self-relocatable. This implies-mconstant-gp. Useful when compiling firmware code.-minline-float-divide-min-latencyโ generate code for inline divides of floating-point values using the minimum latency algorithm.-minline-float-divide-max-throughputโ generate code for inline divides of floating-point values using the maximum throughput algorithm.-mno-inline-float-divideโ do not generate inline code for divides of floating-point values.-minline-int-divide-min-latencyโ generate code for inline divides of integer values using the minimum latency algorithm.-minline-int-divide-max-throughputโ generate code for inline divides of integer values using the maximum throughput algorithm.-mno-inline-int-divideโ do not generate inline code for divides of integer values.-minline-sqrt-min-latencyโ bestie, this one makes inline square roots use the minimum latency algorithm. Fast fast fast ๐๏ธโจ-minline-sqrt-max-throughputโ same inline square roots but with the maximum throughput algorithm instead. Different flavor, same sqrt ๐-mno-inline-sqrtโ okay so do NOT generate inline code forsqrt. Leave it out, we don't want it ๐ซ-mfused-madd,-mno-fused-maddโ do (or don't ๐) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions, so by default-mfused-maddis the vibe.-mno-dwarf2-asm,-mdwarf2-asmโ don't (or do) generate assembler code for the DWARF line number debugging info. This is lowkey useful when you're not using the GNU assembler ๐ ๏ธ-mearly-stop-bits,-mno-early-stop-bitsโ lets stop bits be placed earlier than immediately preceding the instruction that triggered the stop bit. This can improve instruction scheduling, but ngl it doesn't always do so. it's giving "sometimes slay, sometimes meh" ๐-mfixed-range=register-rangeโ generate code treating the given register range as fixed registers. A fixed register is one the register allocator just cannot use, periodt. Super useful when you're compiling kernel code ๐ A register range is two registers separated by a dash, and you can stack multiple ranges separated by a comma.-mtls-size=tls-sizeโ specify the bit size of immediate TLS offsets. Valid values are14,22, and64. That's the whole menu bestie ๐-mtune=cpu-typeโ tune the instruction scheduling for a particular CPU. Valid values areitanium,itanium1,merced,itanium2, andmckinleyโจ-milp32,-mlp64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. These are HP-UX specific flags, iykyk ๐-mno-sched-br-data-spec,-msched-br-data-specโ (dis/en)able data speculative scheduling before reload. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is disabled. ๐ซ-msched-ar-data-spec,-mno-sched-ar-data-specโ (en/dis)able data speculative scheduling after reload. Same deal: generatesld.ainstructions and the matching check instructions (ld.c/chk.a). The default setting is enabled ๐ซถ-mno-sched-control-spec,-msched-control-specโ (dis/en)able control speculative scheduling. Heads up, this feature is available only during region scheduling (i.e. before reload). It results in generation of theld.sinstructions and the corresponding check instructionschk.s. The default setting is disabled ๐-msched-br-in-data-spec,-mno-sched-br-in-data-specโ (en/dis)able speculative scheduling of the instructions that depend on the data speculative loads before reload. This is only effective with-msched-br-data-specenabled. The default setting is enabled โจ-msched-ar-in-data-spec,-mno-sched-ar-in-data-specโ (en/dis)able speculative scheduling of the instructions that depend on the data speculative loads after reload. Only effective with-msched-ar-data-specenabled. The default setting is enabled ๐-msched-in-control-spec,-mno-sched-in-control-specโ (en/dis)able speculative scheduling of the instructions that depend on the control speculative loads. Only effective with-msched-control-specenabled. The default setting is enabled ๐ธ-mno-sched-prefer-non-data-spec-insns,-msched-prefer-non-data-spec-insnsโ if enabled, data-speculative instructions are only chosen for a schedule if there are literally no other choices at that moment. This makes the use of data speculation way more conservative. The default setting is disabled ๐ซ-mno-sched-prefer-non-control-spec-insns,-msched-prefer-non-control-spec-insnsโ if enabled, control-speculative instructions are only chosen for a schedule when there's no other choice. Makes control speculation much more conservative. The default setting is disabled ๐-mno-sched-count-spec-in-critical-path,-msched-count-spec-in-critical-pathโ if enabled, speculative dependencies get considered while computing the instruction priorities. Makes the speculation a little bit more conservative. The default setting is disabled ๐-msched-spec-ldcโ use a simple data speculation check. This option is on by default โญ-msched-control-spec-ldcโ use a simple check for control speculation. This option is on by default ๐ฅ-msched-stop-bits-after-every-cycleโ place a stop bit after every cycle when scheduling. This option is on by default ๐-msched-fp-mem-deps-zero-costโ assume that floating-point stores and loads are not likely to cause a conflict when they're placed into the same instruction group. This option is disabled by default ๐ญ-msel-sched-dont-check-control-specโ generate checks for control speculation in selective scheduling. This flag is disabled by default ๐ซ-msched-max-memory-insns=max-insnsโ limit on the number of memory insns per instruction group, which gives lower priority to subsequent memory insns trying to schedule into that same instruction group. Frequently useful for preventing cache bank conflicts ๐ The default value is1.-msched-max-memory-insns-hard-limitโ makes the limit frommsched-max-memory-insnsa hard limit, disallowing more than that number in an instruction group. Otherwise the limit is "soft", meaning non-memory operations are preferred when the limit is reached, but memory operations may still be scheduled ๐ซถ
๐ฆ LM32 Options ๐ฆ
These -m options are defined for the LatticeMico32 architecture, bestie:
-mbarrel-shift-enabledโ enable barrel-shift instructions โจ-mdivide-enabledโ enable divide and modulus instructions ๐-mmultiply-enabledโ enable multiply instructions ๐ฅ-msign-extend-enabledโ enable sign extend instructions โญ-muser-enabledโ enable user-defined instructions ๐
๐ LoongArch Options ๐
These command-line options are defined for LoongArch targets, no cap:
-march=cpu-typeโ generate instructions for the machine type cpu-type. In contrast to-mtune=cpu-type, which merely tunes the generated code for the specified cpu-type,-march=cpu-typelets GCC generate code that may not run at all on processors other than the one indicated ๐ญ Specifying-march=cpu-typeimplies-mtune=cpu-type, except where noted otherwise.
The choices for cpu-type are:
nativeโ this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines ๐ซ ). Using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set.loongarch64โ a generic CPU with 64-bit extensions ๐la464โ LoongArch LA464 CPU with LBT, LSX, LASX, LVZ โจ
-mtune=cpu-typeโ optimize the output for the given processor, specified by microarchitecture name ๐-mabi=base-abi-typeโ generate code for the specified calling convention. base-abi-type can be one of:lp64dโ uses 64-bit general purpose registers and 32/64-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits ๐lp64fโ uses 64-bit general purpose registers and 32-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits ๐ธlp64sโ uses 64-bit general purpose registers and no floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits ๐
-mfpu=fpu-typeโ generate code for the specified FPU type, which can be one of:64โ allow the use of hardware floating-point instructions for 32-bit and 64-bit operations โญ32โ allow the use of hardware floating-point instructions for 32-bit operations โจnone,0โ prevent the use of hardware floating-point instructions ๐ซ
-msoft-floatโ force-mfpu=noneand prevents the use of floating-point registers for parameter passing. Heads up: this option may change the target ABI ๐ณ-msingle-floatโ force-mfpu=32and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI too ๐-mdouble-floatโ force-mfpu=64and allow the use of 32/64-bit floating-point registers for parameter passing. And yep, this option may change the target ABI as well ๐ซถ-mbranch-cost=nโ set the cost of branches to roughly n instructions ๐ฅ-mcheck-zero-division,-mno-check-zero-divisonโ trap (or do not trap) on integer division by zero. The default is-mcheck-zero-divisionfor-O0or-Og, and-mno-check-zero-divisionfor other optimization levels. (And yes, bestie, the original really does spell the negative one-mno-check-zero-divisonโ that missingiis iconic and we respect it ๐)-mcond-move-int,-mno-cond-move-intโ conditional moves for integral data in general-purpose registers are enabled (disabled). The default is-mcond-move-int๐-mcond-move-float,-mno-cond-move-floatโ conditional moves for floating-point registers are enabled (disabled). The default is-mcond-move-float๐ธ-mmemcpy,-mno-memcpyโ force (or do not force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which lets GCC inline most constant-sized copies โจ Setting the optimization level to-Osalso forces the use ofmemcpy, but-mno-memcpymay override this behavior if it's explicitly specified, regardless of the order these options appear on the command line ๐-mstrict-align,-mno-strict-alignโ avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. The default is-mno-strict-align๐ฆ-msmall-data-limit=numberโ put global and static data smaller than number bytes into a special section (on some targets). The default value is0๐-mmax-inline-memcpy-size=nโ inline all block moves (such as calls tomemcpyor structure copies) less than or equal to n bytes. The default value of n is1024๐ฅ-mcmodel=code-modelโ ok so this one sets the code model, and your choices are:tiny-staticโ bestieโฆ not implemented yet ๐ญtinyโ also not implemented yet ๐normalโ the text segment has to live inside a 128MB addressing space, and the data segment has to live inside a 2GB addressing space.mediumโ now both the text segment and the data segment need to be within 2GB addressing space.largeโ not implemented yet ๐extremeโ this one does not limit the size of the code segment and data segment at all โจ. Lowkey important:-mcmodel=extremeis incompatible with-fpltand-mno-explicit-relocs.
The default code model is normal, periodt.
-mexplicit-relocs,-mno-explicit-relocsโ so this is a choose-your-fighter between using or not using assembler relocation operators when dealing with symbolic addresses. The alternative vibe is to use assembler macros instead, which may limit instruction scheduling but allows linker relaxation ๐ซถ. What's the default, you ask? It gets determined by the assembler capability detected during GCC build-time, plus whatever-mrelaxis set to: it's-mexplicit-relocsif the assembler supports relocation operators but-mrelaxis not enabled, and-mno-explicit-relocsotherwise. iykyk.-mdirect-extern-access,-mno-direct-extern-accessโ do not use or use GOT to access external symbols. The default is-mno-direct-extern-access: GOT is used for external symbols with default visibility, but not used for other external symbols.
With -mdirect-extern-access, GOT is not used and all external symbols are PC-relatively addressed ๐ฏ. Heads up though, it's only suitable for environments where no dynamic link is performed, like firmwares, OS kernels, executables linked with -static or -static-pie. And -mdirect-extern-access is not compatible with -fPIC or -fpic. No cap.
-mrelax,-mno-relaxโ take (or do not take ๐) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option is also passed to the assembler. The default is figured out during GCC build-time by detecting corresponding assembler support:-mrelaxif the assembler supports both the-mrelaxoption and the conditional branch relaxation, and-mno-relaxotherwise. And bestie, that conditional branch relaxation is required, or else the.aligndirectives and conditional branch instructions in the assembly code outputted by GCC may get rejected by the assembler because of a relocation overflow ๐ญ.-mpass-mrelax-to-as,-mno-pass-mrelax-to-asโ pass (or do not pass) the-mrelaxor-mno-relaxoption to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption, and-mno-pass-mrelax-to-asotherwise. This option is mostly useful for debugging, or for interoperation with assemblers different from the build-time one ๐ง.
โจ M32C Options โจ
-mcpu=nameโ pick the CPU you're generating code for, bestie. name may be one ofr8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series ๐ .-msimโ says that the program is gonna be run on the simulator ๐ฎ. This causes an alternate runtime library to be linked in, which supports stuff like file I/O. You must not use this option when generating programs that will run on real hardware โ instead you must provide your own runtime library for whatever I/O functions are needed. Fr fr, respect the boundary.-memregs=numberโ specifies how many memory-based pseudo-registers GCC uses during code generation. These pseudo-registers get used like real registers, so there's a whole tradeoff between GCC's ability to fit the code into available registers and the performance penalty of using memory instead of registers โ๏ธ. Note that all modules in a program must be compiled with the same value for this option. And because of that, you must not use this option with GCC's default runtime libraries ๐.
๐ M32R/D Options ๐
These -m options are defined for Renesas M32R/D architectures:
-m32r2โ generate code for the M32R/2.-m32rxโ generate code for the M32R/X.-m32rโ generate code for the M32R. This is the default โญ.-mmodel=smallโ assume all objects live in the lower 16MB of memory (so that their addresses can be loaded with theld24instruction), and assume all subroutines are reachable with theblinstruction. This is the default.
The addressability of a particular object can be set with the model attribute โ๏ธ.
-mmodel=mediumโ assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume all subroutines are reachable with theblinstruction.-mmodel=largeโ assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume subroutines may not be reachable with theblinstruction (the compiler generates the much slowerseth/add3/jlinstruction sequence ๐).-msdata=noneโ disable use of the small data area. Variables are put into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default.
The small data area consists of sections .sdata and .sbss. Objects may be explicitly put in the small data area with the section attribute using one of these sections ๐ซ.
-msdata=sdataโ put small global and static data in the small data area, but do not generate special code to reference them.-msdata=useโ put small global and static data in the small data area, and generate special instructions to reference them ๐ฅ.-G numโ put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is8. The-msdataoption must be set to one ofsdataorusefor this option to have any effect.
All modules should be compiled with the same -G num value. Compiling with different values of num may or may not work; if it doesn't, the linker gives an error message โ and thank goodness, because incorrect code is not generated ๐.
-mdebugโ makes the M32R-specific code in the compiler display some statistics that might help in debugging programs ๐.-malign-loopsโ align all loops to a 32-byte boundary.-mno-align-loopsโ do not enforce a 32-byte alignment for loops. This is the default.-missue-rate=numberโ issue number instructions per cycle. number can only be1or2.-mbranch-cost=numberโ number can only be1or2. If it's1then branches are preferred over conditional code; if it's2, then the opposite applies ๐.-mflush-trap=numberโ specifies the trap number to use to flush the cache. The default is12. Valid numbers are between0and15inclusive.-mno-flush-trapโ specifies that the cache cannot be flushed by using a trap ๐ซ.-mflush-func=nameโ specifies the name of the operating system function to call to flush the cache. The default is_flush_cache, but a function call is only used if a trap is not available.-mno-flush-funcโ indicates that there is no OS function for flushing the cache.
๐ M680x0 Options ๐
These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below ๐.
-march=archโ generate code for a specific M680x0 or ColdFire instruction set architecture. Permissible values of arch for M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures are selected according to Freescale's ISA classification, and the permissible values are:isaa,isaaplus,isabandisacโจ.
GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture ๐ง .
-mcpu=cpuโ generate code for a specific M680x0 or ColdFire processor. The M680x0 cpus are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire cpus are given by the table below, which also classifies the CPUs into families ๐:- Family
51:5151ac51ag51cn51em51je51jf51jg51jm51mm51qe51qm - Family
5206:520252045206 - Family
5206e:5206e - Family
5208:52075208 - Family
5211a:5210a5211a - Family
5213:521152125213 - Family
5216:52145216 - Family
52235:522305223152232522335223452235 - Family
5225:52245225 - Family
52259:522525225452255522565225852259 - Family
5235:5232523352345235523x - Family
5249:5249 - Family
5250:5250 - Family
5271:52705271 - Family
5272:5272 - Family
5275:52745275 - Family
5282:528052815282528x - Family
53017:53011530125301353014530155301653017 - Family
5307:5307 - Family
5329:532753285329532x - Family
5373:53725373537x - Family
5407:5407 - Family
5475:547054715472547354745475547x548054815482548354845485
- Family
-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected ๐ซ.
GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the table above.
-mtune=tuneโ tune the code for a particular microarchitecture within the constraints set by-marchand-mcpu. The M680x0 microarchitectures are:68000,68010,68020,68030,68040,68060andcpu32. The ColdFire microarchitectures are:cfv1,cfv2,cfv3,cfv4andcfv4e๐ธ.
You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively.
GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range ๐ซถ.
GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above. ๐
-m68000,-mc68000โ bestie, this makes output for a 68000. It's the default when the compiler was configured for 68000-based systems, and it's literally equivalent to-march=68000.
Reach for this one for microcontrollers with a 68000 or EC000 core โ that's the 68008, 68302, 68306, 68307, 68322, 68328 and 68356. โจ
-m68010โ output for a 68010. Default when the compiler is configured for 68010-based systems. Equivalent to-march=68010. ๐-m68020,-mc68020โ output for a 68020. Default when the compiler is configured for 68020-based systems. Equivalent to-march=68020. ๐ฆ-m68030โ output for a 68030. Default when the compiler is configured for 68030-based systems. Equivalent to-march=68030. ๐ธ-m68040โ output for a 68040. Default when the compiler is configured for 68040-based systems. Equivalent to-march=68040.
Heads up: this option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. So use it if your 68040 doesn't have code to emulate those instructions. ๐
-m68060โ output for a 68060. Default when the compiler is configured for 68060-based systems. Equivalent to-march=68060.
This one inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use it if your 68060 doesn't have code to emulate those instructions. ๐ซถ
-mcpu32โ output for a CPU32. Default when the compiler is configured for CPU32-based systems. Equivalent to-march=cpu32.
Use this for microcontrollers with a CPU32 or CPU32+ core, which includes the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360. ๐
-m5200โ output for a 520X ColdFire CPU. Default when the compiler is configured for 520X-based systems. It's equivalent to-mcpu=5206, and ngl it's now deprecated in favor of that option. ๐
Use it for microcontrollers with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
-m5206eโ output for a 5206e ColdFire CPU. The option is now deprecated in favor of the equivalent-mcpu=5206e.-m528xโ output for a member of the ColdFire 528X family. The option is now deprecated in favor of the equivalent-mcpu=528x.-m5307โ output for a ColdFire 5307 CPU. The option is now deprecated in favor of the equivalent-mcpu=5307.-m5407โ output for a ColdFire 5407 CPU. The option is now deprecated in favor of the equivalent-mcpu=5407.-mcfv4eโ output for a ColdFire V4e family CPU (e.g. 547x/548x). This includes use of hardware floating-point instructions. The option is equivalent to-mcpu=547x, and is now deprecated in favor of that option. ๐-m68020-40โ output for a 68040, but without using any of the new instructions. The result is code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.
The option is equivalent to -march=68020 -mtune=68020-40. โจ
-m68020-60โ output for a 68060, without using any of the new instructions. Same deal: code that runs relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68060.
The option is equivalent to -march=68020 -mtune=68020-60. ๐
-mhard-float,-m68881โ generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro__HAVE_68881__on M680x0 targets and__mcffpu__on ColdFire targets. ๐-msoft-floatโ do not generate floating-point instructions; use library calls instead. This is the default for 68000, 68010, and 68832 targets. It's also the default for ColdFire devices that have no FPU. ๐-mdiv,-mno-divโ generate (or don't generate) ColdFire hardware divide and remainder instructions. If-marchis used without-mcpu, the default isonfor ColdFire architectures andofffor M680x0 architectures. Otherwise the default is taken from the target CPU (either the default CPU, or the one specified by-mcpu). Case in point: the default isofffor-mcpu=5206andonfor-mcpu=5206e.
GCC defines the macro __mcfhwdiv__ when this option is enabled. ๐ฅ
-mshortโ treat typeintas being 16 bits wide, likeshort int. On top of that, parameters passed on the stack are also aligned to a 16-bit boundary even on targets whose API mandates promotion to 32-bit. ๐-mno-shortโ do not treat typeintas 16 bits wide. This is the default.-mnobitfield,-mno-bitfieldโ do not use the bit-field instructions. The-m68000,-mcpu32and-m5200options imply-mnobitfield. ๐-mbitfieldโ do use the bit-field instructions. The-m68020option implies-mbitfield. This is the default if you use a configuration designed for a 68020.-mrtdโ use a different function-calling convention, in which functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. This saves one instruction in the caller, since there's no need to pop the arguments there. โจ
Okay so this calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler. ๐ญ
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. ๐
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.)
The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.
The default is -mno-rtd. ๐ซถ
-malign-int,-mno-align-intโ control whether GCC alignsint,long,long long,float,double, andlong doublevariables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory. ๐ธ
Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k. ๐จ
Use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors. ๐ฆ
-mno-strict-align,-mstrict-alignโ do not (do) assume that unaligned memory references are handled by the system. ๐-msep-dataโ generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies-fPIC. โญ-mno-sep-dataโ generate code that assumes that the data segment follows the text segment. This is the default.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies-fPIC. ๐-mno-id-shared-libraryโ generate code that doesn't assume ID-based shared libraries are being used. This is the default.-mshared-library-id=nโ specifies the identification number of the ID-based shared library being compiled. Specifying a value of0generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option. ๐-mxgot,-mno-xgotโ when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors, this option is not needed;-fPICsuffices.
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
If this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol. ๐
Note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. If you have such a linker, you should only need to use -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do. ๐
These options have no effect unless GCC is generating position-independent code.
-mlong-jump-table-offsetsโ use 32-bit offsets inswitchtables. The default is to use 16-bit offsets. ๐ฅ
๐ MCore Options ๐
These are the -m options defined for the Motorola M*Core processors. Let's get into it ๐ซถ
-mhardlit,-mno-hardlitโ inline constants into the code stream if it can be done in two instructions or less. โจ-mdiv,-mno-divโ use the divide instruction. (Enabled by default). ๐-mrelax-immediate,-mno-relax-immediateโ allow arbitrary-sized immediates in bit operations.-mwide-bitfields,-mno-wide-bitfieldsโ always treat bit-fields asint-sized. ๐-m4byte-functions,-mno-4byte-functionsโ force all functions to be aligned to a 4-byte boundary. ๐-mcallgraph-data,-mno-callgraph-dataโ turn on (or off) emitting callgraph info. the receipts of who called whom ๐-mslow-bytes,-mno-slow-bytesโ prefer grabbing whole words when you're reading byte-sized quantities. lowkey a glow-up for speed ๐ฆ-mlittle-endian,-mbig-endianโ generate code for a little-endian target. โจ-m210,-m340โ generate code for the210processor. ๐-mno-lsimโ assume somebody already handed you the runtime support, so leave the simulator library (libsim.a) off the linker command line. not your problem anymore, bestie ๐-mstack-increment=sizeโ set the max amount for a single stack increment operation. Big values can make programs with functions that gobble a huge amount of stack space run faster, but they can also absolutely trigger a segmentation fault if the stack gets extended too much ๐ญ. Default is0x1000.
๐ง MicroBlaze Options ๐ง
-msoft-floatโ use software emulation for floating point (this is the default). ๐-mhard-floatโ use hardware floating-point instructions. slay, actual silicon ๐-mmemcpyโ don't optimize block moves, just use"memcpy". let the library girl handle it ๐-mno-clearbssโ > this option is deprecated. use-fno-zero-initialized-in-bssinstead. currently not the vibe โ-mcpu=cpu-typeโ use the features of, and schedule code for, the given CPU. Supported values look likevX.YY.Z, whereXis a major version,YYis the minor version, andZis compatibility code. Example values:v3.00.a,v4.00.b,v5.00.a,v5.00.b,v6.00.a. โจ-mxl-soft-mulโ use software multiply emulation (default). ๐ธ-mxl-soft-divโ use software emulation for divides (default). ๐ซถ-mxl-barrel-shiftโ use the hardware barrel shifter. iconic bit-wrangling energy ๐-mxl-pattern-compareโ use pattern compare instructions. โจ-msmall-dividesโ use table lookup optimization for small signed integer divisions. ๐-mxl-stack-checkโ > deprecated. use-fstack-checkinstead. ๐-mxl-gp-optโ use GP-relative".sdata"/".sbss"sections. ๐-mxl-multiply-highโ use multiply high instructions for the high part of a 32x32 multiply. ๐ฅ-mxl-float-convertโ use hardware floating-point conversion instructions. โญ-mxl-float-sqrtโ use the hardware floating-point square root instruction. ๐ฆ-mbig-endianโ generate code for a big-endian target. ๐-mlittle-endianโ generate code for a little-endian target. ๐-mxl-reorderโ use reorder instructions (swap and byte reversed load/store). ๐-mxl-mode-app-modelโ select application model app-model. The valid models are:executableโ normal executable (default), uses startup codecrt0.o. ๐ผxmdstubโ for use with the Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. This uses startup filecrt1.oand sets the start address of the program to0x800. ๐ต๏ธbootstrapโ for applications that are loaded using a bootloader. This model uses startup filecrt2.owhich does not contain a processor reset vector handler. This is suitable for transferring control on a processor reset to the bootloader rather than the application. ๐ฅพnovectorsโ for applications that do not require any of the MicroBlaze vectors. This option may be useful for applications running within a monitoring application. This model usescrt3.oas a startup file. ๐
Option-xl-mode-app-modelis a deprecated alias for-mxl-mode-app-model. (ya, themgot added later ๐)
-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. This lets data be referenced by offset from the start of the text address instead of the GOT, since PC-relative addressing is not supported. ๐ฏ
๐ MIPS Options ๐
-EBโ generate big-endian code. ๐-ELโ generate little-endian code. This is the default formips*el-*-*configurations. ๐-march=archโ generate code that runs on arch, which can be the name of a generic MIPS ISA, or the name of a particular processor. The ISA names are:mips1,mips2,mips3,mips4,mips32,mips32r2,mips32r3,mips32r5,mips32r6,mips64,mips64r2,mips64r3,mips64r5andmips64r6. The processor names are:4kc,4km,4kp,4ksc,4kec,4kem,4kep,4ksd,5kc,5kf,20kc,24kc,24kf2_1,24kf1_1,24kec,24kef2_1,24kef1_1,34kc,34kf2_1,34kf1_1,34kn,74kc,74kf2_1,74kf1_1,74kf3_2,1004kc,1004kf2_1,1004kf1_1,i6400,i6500,interaptiv,loongson2e,loongson2f,loongson3a,gs464,gs464e,gs264e,m4k,m14k,m14kc,m14ke,m14kec,m5100,m5101,octeon,octeon+,octeon2,octeon3,orion,p5600,p6600,r2000,r3000,r3900,r4000,r4400,r4600,r4650,r4700,r5900,r6000,r8000,rm7000,rm9000,r10000,r12000,r14000,r16000,sb1,sr71000,vr4100,vr4111,vr4120,vr4130,vr4300,vr5000,vr5400,vr5500,xlrandxlp. The special valuefrom-abiselects the most compatible architecture for the selected ABI (that is,mips1for 32-bit ABIs andmips3for 64-bit ABIs). ๐ฎโ๐จ that's a lot of names, bestie.
The native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor. ๐ฅ๏ธ
In processor names, a final 000 can be abbreviated as k (for example, -march=r2k). Prefixes are optional, and vr may be written r. literally shortening it for the aesthetic ๐
Names of the form nf2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. For compatibility reasons, nf is accepted as a synonym for nf2_1 while nx and bfx are accepted as synonyms for nf1_1. ๐
GCC defines two macros based on the value of this option. The first is "_MIPS_ARCH", which gives the name of target architecture, as a string. The second has the form "_MIPS_ARCH_foo", where foo is the capitalized value of "_MIPS_ARCH". For example, -march=r2000 sets "_MIPS_ARCH" to "r2000" and defines the macro "_MIPS_ARCH_R2000". โจ
Note that the "_MIPS_ARCH" macro uses the processor names given above. In other words, it has the full prefix and does not abbreviate 000 as k. In the case of from-abi, the macro names the resolved architecture (either "mips1" or "mips3"). It names the default architecture when no -march option is given. ๐
-mtune=archโ optimize for arch. Among other things, this option controls the way instructions are scheduled, and the perceived cost of arithmetic operations. The list of arch values is the same as for-march. ๐ฅ
When this option is not used, GCC optimizes for the processor specified by -march. By using -march and -mtune together, it is possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family. main character treatment for one sibling ๐
-mtune defines the macros "_MIPS_TUNE" and "_MIPS_TUNE_foo", which work in the same way as the -march ones described above. ๐ซ
-mips1โ Equivalent to-march=mips1.-mips2โ Equivalent to-march=mips2.-mips3โ Equivalent to-march=mips3.-mips4โ Equivalent to-march=mips4.-mips32โ Equivalent to-march=mips32.-mips32r3โ Equivalent to-march=mips32r3.-mips32r5โ Equivalent to-march=mips32r5.-mips32r6โ Equivalent to-march=mips32r6.-mips64โ Equivalent to-march=mips64.-mips64r2โ Equivalent to-march=mips64r2.-mips64r3โ Equivalent to-march=mips64r3.-mips64r5โ Equivalent to-march=mips64r5.-mips64r6โ Equivalent to-march=mips64r6.-mips16,-mno-mips16โ generate (or don't generate) MIPS16 code. If GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE. ๐ง
MIPS16 code generation can also be controlled on a per-function basis by means of "mips16" and "nomips16" attributes. ๐ฏ
-mflip-mips16โ generate MIPS16 code on alternating functions. This option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code. > bestie, this is a lab experiment, not a flex ๐งช-minterlink-compressed,-mno-interlink-compressedโ require (or don't require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa. ๐
For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed. ๐
-minterlink-mips16,-mno-interlink-mips16โ aliases of-minterlink-compressedand-mno-interlink-compressed. These options predate the microMIPS ASE and are retained for backwards compatibility. vintage but valid ๐๐-mabi=32,-mabi=o64,-mabi=n32,-mabi=64,-mabi=eabiโ generate code for the given ABI. ๐
Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead. ๐ฆ
For information about the O64 ABI, see <https://gcc.gnu.org/projects/mipso64-abi.html>. ๐
GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. You can select this combination with -mabi=32 -mfp64. This ABI relies on the "mthc1" and "mfhc1" instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors. โ ๏ธ
The register assignments for arguments and return values remain the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved. ๐
Okay bestie, we're still deep in MIPS land and honestly? It's giving โจarchitecture loreโจ. Buckle up, there's a LOT here. ๐
Two extra variants of the o32 ABI exist so the world can transition from 32-bit to 64-bit registers without everything catching fire. Meet FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension is a whole rules-girl: it mandates that all code must execute correctly whether it's run using 32-bit or 64-bit registers. You can interlink that code with either FP32 or FP64 โ but not both, pick a lane. The FP64A extension is like FP64's cousin who refuses odd numbers: it forbids the use of odd-numbered single-precision registers. You'd use it together with the "FRE" mode of FPUs in MIPS32R5 processors, and it lets both FP32 and FP64A code interlink and run in the same process without switching FPU modes. Teamwork! ๐ซถ
-mabicalls,-mno-abicallsโ generate (or don't generate) code that plays nice with SVR4-style dynamic objects.-mabicallsis the default on SVR4-based systems. ๐-mshared,-mno-sharedโ generate (or don't generate) code that is fully position-independent and can therefore be linked into shared libraries. Heads up: this option only affects-mabicalls.
So like, all -mabicalls code has traditionally been position-independent, no matter what -fPIC and -fpic are doing. BUT, as an extension, the GNU toolchain lets executables use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. That whole mode gets selected by -mno-shared.
Also -mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. But don't panic โ the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. And using -mno-shared generally makes executables both smaller and quicker. Win-win. ๐ฅ
-mshared is the default.
-mplt,-mno-pltโ assume (or don't assume) that the static and dynamic linkers support PLTs and copy relocations. This option only affects-mno-shared -mabicalls. And for the n64 ABI, this option has no effect without-msym32.
You can make -mplt the default by configuring GCC with --with-mips-plt. Otherwise the default is -mno-plt.
-mxgot,-mno-xgotโ lift (or don't lift) the usual restrictions on the size of the global offset table.
Normally GCC uses a single instruction to load values from the GOT. Relatively efficient, sure, but it only works if the GOT is smaller than about 64k. Anything bigger and the linker starts yelling at you with an error like this:
relocation truncated to fit: R_MIPS_GOT16 foobar
If that happens, recompile your code with -mxgot. It works with very large GOTs, though the code is also less efficient โ because now it takes three instructions to fetch the value of a global symbol. ๐ญ
Note that some linkers can create multiple GOTs. If you've got one of those fancy linkers, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do, bestie.
And these options have no effect unless GCC is generating position independent code. Periodt.
-mgp32โ assume general-purpose registers are 32 bits wide.-mgp64โ assume general-purpose registers are 64 bits wide.-mfp32โ assume floating-point registers are 32 bits wide.-mfp64โ assume floating-point registers are 64 bits wide.-mfpxxโ do not assume the width of floating-point registers. Mystery girl energy. ๐ฆ-mhard-floatโ use floating-point coprocessor instructions. Real hardware, no pretending.-msoft-floatโ do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.-mno-floatโ equivalent to-msoft-float, but additionally asserts that the program being compiled does not perform any floating-point operations at all. This option is presently supported only by some bare-metal MIPS configurations, where it may select a special set of libraries that lack all floating-point support (including, for example, the floating-point"printf"formats).
โ ๏ธ If code compiled with -mno-float accidentally contains floating-point operations, it is likely to suffer a link-time or run-time failure. Not a vibe. ๐
-msingle-floatโ assume the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ assume the floating-point coprocessor supports double-precision operations. This is the default. ๐-modd-spreg,-mno-odd-spregโ enable the use of odd-numbered single-precision floating-point registers for the o32 ABI. This is the default for processors that are known to support these registers. But when you're using the o32 FPXX ABI,-mno-odd-spregis set by default.-mabs=2008,-mabs=legacyโ these control how the special not-a-number (NaN) IEEE 754 floating-point data gets treated with the"abs.fmt"and"neg.fmt"machine instructions.
By default, or when -mabs=legacy is used, the legacy treatment is selected. In that case these instructions are considered arithmetic and avoided wherever correct operation is required and the input operand might be a NaN. Instead, a longer sequence of instructions that manipulate the sign bit of the floating-point datum manually gets used โ unless the -ffinite-math-only option has also been specified.
The -mabs=2008 option selects the IEEE 754-2008 treatment. Here these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. So these instructions are therefore always used for the respective operations. Slay. โจ
-mnan=2008,-mnan=legacyโ these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.
-mnan=legacy selects the legacy encoding. In this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.
-mnan=2008 selects the IEEE 754-2008 encoding. In this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0. They literally just swapped. ๐
The default is -mnan=legacy unless GCC has been configured with --with-nan=2008.
-mllsc,-mno-llscโ use (or don't use)ll,sc, andsyncinstructions to implement atomic memory built-in functions. When neither option is specified, GCC uses the instructions if the target architecture supports them.
-mllsc is useful if the runtime environment can emulate the instructions, and -mno-llsc can be useful when compiling for nonstandard ISAs. You can make either option the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations; see the installation documentation for details.
-mdsp,-mno-dspโ use (or don't use) revision 1 of the MIPS DSP ASE. This option defines the preprocessor macro__mips_dsp. It also defines__mips_dsp_revto1.-mdspr2,-mno-dspr2โ use (or don't use) revision 2 of the MIPS DSP ASE. This option defines the preprocessor macros__mips_dspand__mips_dspr2. It also defines__mips_dsp_revto2.-msmartmips,-mno-smartmipsโ use (or don't use) the MIPS SmartMIPS ASE.-mpaired-single,-mno-paired-singleโ use (or don't use) paired-single floating-point instructions. This option requires hardware floating-point support to be enabled.-mdmx,-mno-mdmxโ use (or don't use) MIPS Digital Media Extension instructions. This option can only be used when generating 64-bit code and requires hardware floating-point support to be enabled.-mips3d,-mno-mips3dโ use (or don't use) the MIPS-3D ASE. Note that the option-mips3dimplies-mpaired-single. Package deal. ๐-mmicromips,-mno-micromipsโ generate (or don't generate) microMIPS code.
MicroMIPS code generation can also be controlled on a per-function basis by means of "micromips" and "nomicromips" attributes.
-mmt,-mno-mtโ use (or don't use) MT Multithreading instructions.-mmcu,-mno-mcuโ use (or don't use) the MIPS MCU ASE instructions.-meva,-mno-evaโ use (or don't use) the MIPS Enhanced Virtual Addressing instructions.-mvirt,-mno-virtโ use (or don't use) the MIPS Virtualization (VZ) instructions.-mxpa,-mno-xpaโ use (or don't use) the MIPS eXtended Physical Address (XPA) instructions.-mcrc,-mno-crcโ use (or don't use) the MIPS Cyclic Redundancy Check (CRC) instructions.-mginv,-mno-ginvโ use (or don't use) the MIPS Global INValidate (GINV) instructions.-mloongson-mmi,-mno-loongson-mmiโ use (or don't use) the MIPS Loongson MultiMedia extensions Instructions (MMI).-mloongson-ext,-mno-loongson-extโ use (or don't use) the MIPS Loongson EXTensions (EXT) instructions.-mloongson-ext2,-mno-loongson-ext2โ use (or don't use) the MIPS Loongson EXTensions r2 (EXT2) instructions.-mlong64โ force"long"types to be 64 bits wide. See-mlong32for an explanation of the default and the way that the pointer size is determined.-mlong32โ force"long","int", and pointer types to be 32 bits wide.
The default size of "int"s, "long"s and pointers depends on the ABI. All the supported ABIs use 32-bit "int"s. The n64 ABI uses 64-bit "long"s, as does the 64-bit EABI; the others use 32-bit "long"s. Pointers are the same size as "long"s, or the same size as integer registers, whichever is smaller.
-msym32,-mno-sym32โ assume (or don't assume) that all symbols have 32-bit values, regardless of the selected ABI. This option is useful in combination with-mabi=64and-mno-abicallsbecause it allows GCC to generate shorter and faster references to symbolic addresses. Speedrun strats. โญ-G numโ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. GCC can then generate more efficient accesses to the data; see-mgpoptfor details.
The default -G option depends on the configuration.
-mlocal-sdata,-mno-local-sdataโ extend (or don't extend) the-Gbehavior to local data too, such as to static variables in C.-mlocal-sdatais the default for all configurations. ๐
So if the linker is out here complaining that your application is using wayyy too much small data ๐ญ bestie, you might wanna try rebuilding the less performance-critical parts with -mno-local-sdata. You might also wanna build large libraries with -mno-local-sdata, so that those libraries leave more room for the main program. ๐ซถ
-mextern-sdata,-mno-extern-sdataโ Assume (or, with thenoversion, do not assume) that externally-defined data lives in a small data section if the size of that data is within the-Glimit.-mextern-sdatais the default for all configurations, no cap. ๐
If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that's no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a "section" attribute to Var's definition. And if Var is common? Then you must link the application with a high-enough -G setting. Periodt.
The easiest way of satisfying these restrictions is to just compile and link every module with the same -G option. Iconic. But maybe you wanna build a library that supports several different small data limits โ and you can, by compiling the library with the highest supported -G setting and additionally using -mno-extern-sdata to stop the library from making assumptions about externally-defined data. Chef's kiss. ๐
-mgpopt,-mno-gpoptโ Use (or don't use) GP-relative accesses for symbols that are known to be in a small data section; see-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations. โจ
-mno-gpopt is giving "my $gp register might not hold the value of _gp" energy, and it's useful in exactly those cases. For example, if the code is part of a library that might get used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In situations like that, the boot monitor itself is usually compiled with -G0.) ๐
Heads up though: -mno-gpopt implies -mno-local-sdata and -mno-extern-sdata.
-membedded-data,-mno-embedded-dataโ Allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. This gives slightly slower code than the default, but it reduces the amount of RAM required when executing, so it may be preferred for some embedded systems. ๐-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ Put uninitializedconstvariables in the read-only data section. This option is only meaningful in conjunction with-membedded-data.-mcode-readable=settingโ Specify whether GCC may generate code that reads from executable sections. There are three possible settings, babe: ๐-mcode-readable=yesโ Instructions may freely access executable sections. This is the default setting.-mcode-readable=pcrelโ MIPS16 PC-relative load instructions can access executable sections, but other instructions must not do so. This option is useful on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set. It's also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM. โญ-mcode-readable=noโ Instructions must not access executable sections. This option can be useful on targets that are configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM.
-msplit-addresses,-mno-split-addressesโ Enable (or disable) use of the%hi()and%lo()assembler relocation operators. This option has been superseded by-mexplicit-relocsbut is retained for backwards compatibility. ๐-mexplicit-relocs,-mno-explicit-relocsโ Use (or don't use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by-mno-explicit-relocs, is to use assembler macros instead.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators. ๐
-mcheck-zero-division,-mno-check-zero-divisionโ Trap (or, with thenoversion, do not trap) on integer division by zero.
The default is -mcheck-zero-division. ๐
-mdivide-traps,-mdivide-breaksโ MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but it's only supported on MIPS II and later. Also โ and this is the tea โ โ some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE). Use-mdivide-trapsto allow conditional traps on architectures that support them, and-mdivide-breaksto force the use of breaks.
The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. And divide-by-zero checks can be completely disabled using -mno-check-zero-division. ๐
-mload-store-pairs,-mno-load-store-pairsโ Enable (or disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default but only takes effect when the selected architecture is known to support bonding. โก-munaligned-access,-mno-unaligned-accessโ Enable (or disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So-mno-unaligned-accessmay be needed by kernel. ๐-mmemcpy,-mno-memcpyโ Force (or don't force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. ๐ฆ-mlong-calls,-mno-long-callsโ Disable (or, with thenoversion, do not disable) use of thejalinstruction. Calling functions usingjalis more efficient but requires the caller and callee to be in the same 256 megabyte segment. no pressure or anything bestie ๐ญ
This option has no effect on abicalls code. The default is -mno-long-calls.
-mmad,-mno-madโ Enable (or disable) use of themad,maduandmulinstructions, as provided by the R4650 ISA. โจ-mimadd,-mno-imaddโ Enable (or disable) use of themaddandmsubinteger instructions. The default is-mimaddon architectures that supportmaddandmsub, except for the 74k architecture where it was found to generate slower code. ๐ฌ-mfused-madd,-mno-fused-maddโ Enable (or disable) use of the floating-point multiply-accumulate instructions, when they are available. The default is-mfused-madd.
On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances. ๐ On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions. slay.
-nocppโ Tell the MIPS assembler to not run its preprocessor over user assembler files (with a.ssuffix) when assembling them. ๐-mfix-24k,-mno-fix-24kโ Work around the 24K E48 (lost data on stores during refill) errata. The workarounds are implemented by the assembler rather than by GCC. ๐ ๏ธ-mfix-r4000,-mno-fix-r4000โ Work around certain R4000 CPU errata, and bestie there are a few: ๐ญ- A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
- A double-word or a variable shift may give an incorrect result if executed while an integer multiplication is in progress.
- An integer division may give an incorrect result if started in a delay slot of a taken branch or a jump.
-mfix-r4400,-mno-fix-r4400โ Work around certain R4400 CPU errata:- A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
-mfix-r10000,-mno-fix-r10000โ Work around certain R10000 errata:ll/scsequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier. ๐
This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise. ๐
-mfix-r5900,-mno-fix-r5900โ Do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer, and always schedule anopinstruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip. ๐ The workaround is implemented by the assembler rather than by GCC.-mfix-rm7000,-mno-fix-rm7000โ Work around the RM7000dmult/dmultuerrata. The workarounds are implemented by the assembler rather than by GCC. ๐ ๏ธ-mfix-vr4120,-mno-fix-vr4120โ Work around certain VR4120 errata:dmultudoes not always produce the correct result.divandddivdo not always produce the correct result if one of the operands is negative.
The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the mips64vr*-elf configurations. ngl that's a pretty specific niche ๐ญ
Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. These errata are handled by the assembler, not by GCC itself.
-mfix-vr4130โ Work around the VR4130mflo/mfhierrata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids usingmfloandmfhiif the VR4130macc,macchi,dmaccanddmacchiinstructions are available instead. โจ-mfix-sb1,-mno-fix-sb1โ Work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2F1andF2floating-point errata.) ๐ซถ-mr10k-cache-barrier=settingโ Specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors. ๐
okay bestie, we're deep in it now, so let's talk about the R10K's little habit of โจguessingโจ
Like a lot of processors out there, the R10K tries to predict how a conditional branch is gonna go, and then it speculatively executes instructions from the branch it thinks is "taken". If it guessed wrong, it aborts those instructions later. Cute, right? ๐ Except โ and this is the tea โ on the R10K, even aborted instructions can have side effects. ๐
This problem only affects kernel stores, and depending on your system, kernel loads too. For example: a speculatively-executed store might load the target memory into cache and mark that cache line as dirty, even if the store itself gets aborted later. Then if a DMA operation writes to that same area of memory before the "dirty" line is flushed, the cached data just... overwrites the DMA-ed data. ๐ For the full description (including other potential problems), go read the R10K processor manual, bestie.
One workaround is to insert cache barrier instructions before every memory access that might be speculatively executed and that might have side effects even if aborted. -mr10k-cache-barrier=setting controls GCC's implementation of this workaround. It assumes that aborted accesses to any byte in these regions do not have side effects:
- the memory occupied by the current function's stack frame;
- the memory occupied by an incoming stack argument;
- the memory occupied by an object with a link-time-constant address.
It is the kernel's responsibility to ensure that speculative accesses to these regions are indeed safe. No cap, that's on you. ๐ซถ
If the input program contains a function declaration like:
void foo (void);
then the implementation of foo must allow j foo and jal foo to be executed speculatively. GCC honors this restriction for functions it compiles itself. It expects non-GCC functions (like hand-written assembly code, iykyk) to do the same.
The option has three forms:
-mr10k-cache-barrier=load-storeโ Insert a cache barrier before a load or store that might be speculatively executed and that might have side effects even if aborted.-mr10k-cache-barrier=storeโ Insert a cache barrier before a store that might be speculatively executed and that might have side effects even if aborted.-mr10k-cache-barrier=noneโ Disable the insertion of cache barriers. This is the default setting.
-mflush-func=func,-mno-flush-funcโ Specifies the function to call to flush the I and D caches, or to not call any such function at all. If it is called, the function must take the same arguments as the common_flush_func, that is: the address of the memory range for which the cache is being flushed, the size of the memory range, and the number3(to flush both caches, obvi). The default depends on the target GCC was configured for, but it's commonly either_flush_funcor__cpu_flush.mbranch-cost=num โ Set the cost of branches to roughly num "simple" instructions. This cost is only a heuristic and is not guaranteed to produce consistent results across releases, so don't come for me. A zero cost redundantly selects the default, which is based on the-mtunesetting.-mbranch-likely,-mno-branch-likelyโ Enable or disable use of Branch Likely instructions, regardless of what the default is for the selected architecture. By default, Branch Likely instructions may be generated if they're supported by the selected architecture. โจException alertโจ: for the MIPS32 and MIPS64 architectures and the processors that implement those architectures, Branch Likely instructions are not generated by default, because the MIPS32 and MIPS64 architectures specifically deprecate their use.-mcompact-branches=never,-mcompact-branches=optimal,-mcompact-branches=alwaysโ These options control which form of branches will be generated. The default is-mcompact-branches=optimal.- The
-mcompact-branches=neveroption ensures that compact branch instructions will never be generated. - The
-mcompact-branches=alwaysoption ensures that a compact branch instruction will be generated if available for MIPS Release 6 onwards. If a compact branch instruction isn't available (or pre-R6), a delay slot form of the branch will be used instead. - If it's used for MIPS16/microMIPS targets, it will be just ignored right now. The behaviour for MIPS16/microMIPS may change in future, since they do have some compact branch instructions.
- The
-mcompact-branches=optimaloption will cause a delay slot branch to be used if one is available in the current ISA and the delay slot is successfully filled. If the delay slot isn't filled, a compact branch will be chosen if one is available.
- The
-mfp-exceptions,-mno-fp-exceptionsโ Specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled. For instance, on the SB-1, if FP exceptions are disabled and we're emitting 64-bit code, then we can use both FP pipes. Otherwise, we can only use one FP pipe. ๐ค-mvr4130-align,-mno-vr4130-alignโ The VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel. This option only has an effect when optimizing for the VR4130. It normally makes code faster, but at the expense of making it bigger. It's enabled by default at optimization level-O3.-msynci,-mno-synciโ Enable (disable) generation ofsynciinstructions on architectures that support it. Thesynciinstructions (if enabled) are generated when__builtin___clear_cacheis compiled. This option defaults to-mno-synci, but the default can be overridden by configuring GCC with--with-synci. When compiling code for single processor systems, it's generally safe to usesynci. However, on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior. ๐จ so be careful bestie.-mrelax-pic-calls,-mno-relax-pic-callsโ Try to turn PIC calls that are normally dispatched via register$25into direct calls. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call.-mrelax-pic-callsis the default if GCC was configured to use an assembler and a linker that support the.relocassembly directive and-mexplicit-relocsis in effect. With-mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone without any help from the compiler. team work makes the dream work ๐-mmcount-ra-address,-mno-mcount-ra-addressโ Emit (do not emit) code that allows_mcountto modify the calling function's return address. When enabled, this option extends the usual_mcountinterface with a newra-addressparameter, which has typeintptr_t *and is passed in register$12._mcountcan then modify the return address by doing both of the following:- Returning the new address in register
$31. - Storing the new address in
*ra-address, ifra-addressis nonnull.
- Returning the new address in register
The default is -mno-mcount-ra-address.
-mframe-header-opt,-mno-frame-header-optโ Enable (disable) frame header optimization in the o32 ABI. When using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. When enabled, this optimization will suppress the allocation of the frame header if it can be determined that it's unused. This optimization is off by default at all optimization levels.-mlxc1-sxc1,-mno-lxc1-sxc1โ When applicable, enable (disable) the generation oflwxc1,swxc1,ldxc1,sdxc1instructions. Enabled by default. โจ-mmadd4,-mno-madd4โ When applicable, enable (disable) the generation of 4-operandmadd.s,madd.dand related instructions. Enabled by default. ๐ฅ
๐ MMIX Options ๐
These options are defined for the MMIX:
-mlibfuncs,-mno-libfuncsโ Specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.-mepsilon,-mno-epsilonโ Generate floating-point comparison instructions that compare with respect to therEepsilon register.-mabi=mmixware,-mabi=gnuโ Generate code that passes function parameters and return values that (in the called function) are seen as registers$0and up, as opposed to the GNU ABI which uses global registers$231and up.-mzero-extend,-mno-zero-extendโ When reading data from memory in sizes shorter than 64 bits, use (do not use) zero-extending load instructions by default, rather than sign-extending ones.-mknuthdiv,-mno-knuthdivโ Make the result of a division yielding a remainder have the same sign as the divisor. With the default,-mno-knuthdiv, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, the latter being almost exclusively used. ๐ค-mtoplevel-symbols,-mno-toplevel-symbolsโ Prepend (do not prepend) a:to all global symbols, so the assembly code can be used with thePREFIXassembly directive.-melfโ Generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator.-mbranch-predict,-mno-branch-predictโ Use (do not use) the probable-branch instructions, when static branch prediction indicates a probable branch.-mbase-addresses,-mno-base-addressesโ Generate (do not generate) code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register. The register is used for one or more base address requests within the range0to255from the value held in the register. The generally leads to short and fast code, but the number of different data items that can be addressed is limited. This means that a program that uses lots of static data may require-mno-base-addresses.-msingle-exit,-mno-single-exitโ Force (do not force) generated code to have a single exit point in each function.
๐ธ MN10300 Options ๐ธ
These -m options are defined for Matsushita MN10300 architectures:
-mmult-bugโ okay so this makes GCC generate code that dodges the bugs in the multiply instructions on MN10300 processors. It's the default, bestie, so you're already getting it whether you asked or not ๐-mno-mult-bugโ do not generate that bug-avoiding code for the MN10300 multiply instructions. Live dangerously, I guess ๐-mam33โ generate code using the features that are specific to the AM33 processor. glow-up time โจ-mno-am33โ don't use those AM33-specific features. This is the default.-mam33-2โ generate code using features specific to the AM33/2.0 processor. the sequel era ๐-mam34โ generate code using features specific to the AM34 processor.-mtune=cpu-typeโ use the timing characteristics of the CPU type you name when scheduling instructions. Important: this does not change the targeted processor type, it just tunes the scheduling vibe. The CPU type has to be one ofmn10300,am33,am33-2oram34.-mreturn-pointer-on-d0โ when GCC generates a function that returns a pointer, this returns that pointer in botha0andd0. If you don't do this, the pointer only comes back ina0, and trying to call such a function without a prototype results in errors ๐ญ Heads up: this option is on by default, so use-mno-return-pointer-on-d0to turn it off.-mno-crt0โ don't link in the C run-time initialization object file. bye bye startup code ๐ซถ-mrelaxโ tells the linker "bestie please run a relaxation optimization pass" to shorten branches, calls and absolute memory addresses. The catch: this option only does anything when you use it on the command line for the final link step.
fr fr this one makes symbolic debugging impossible. choose your fighter ๐
-mliwโ lets the compiler generate Long Instruction Word instructions when the target is AM33 or later. This is the default. It defines the preprocessor macro__LIW__.-mno-liwโ does not allow Long Instruction Word instructions. Defines the preprocessor macro__NO_LIW__.-msetlbโ lets the compiler generateSETLBandLccinstructions when the target is AM33 or later. Default behavior. Defines the preprocessor macro__SETLB__.-mno-setlbโ nope, noSETLBorLccinstructions allowed. Defines the preprocessor macro__NO_SETLB__.
๐ฆ Moxie Options ๐ฆ
-mebโ generate big-endian code. This is the default formoxie-*-*configurations.-melโ generate little-endian code.-mmul.xโ generatemul.xandumul.xinstructions. This is the default formoxiebox-*-*configurations.-mno-crt0โ don't link in the C run-time initialization object file. (Yes, same name as the MN10300 one, different vibes, same energy ๐ซถ)
๐ธ MSP430 Options ๐ธ
These options are defined for the MSP430:
-masm-hexโ force the assembly output to always use hex constants. Normally those constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. (aesthetic purposes. iconic. ๐ )-mmcu=โ select the MCU to target. This gets used to create a C preprocessor symbol based on the MCU name: uppercased and wrapped with__on both ends. That symbol then gets used by themsp430.hheader file to pick an MCU-specific supplementary header file.
The option also sets which ISA to use. If the MCU name is one that's known to support only the 430 ISA, then that's what gets selected โ otherwise the 430X ISA is selected. There's also a generic MCU name msp430 you can use to select the 430 ISA, and similarly the generic MCU name msp430x selects the 430X ISA.
On top of all that, an MCU-specific linker script gets added to the linker command line. The script's name is the MCU name with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and makes the linker go searching for a script called xxx.ld ๐
The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However, an external devices.csv file can be used to extend device support beyond what's hard-coded. lowkey obsessed with the flexibility ๐
GCC looks for the devices.csv file using these methods, in this precedence order โ first beats second, second beats third:
Include path specified with -I and -L
devices.csv will be searched for in each of the directories specified by include paths and linker library search paths.
Path specified by the environment variable MSP430_GCC_INCLUDE_DIR
Set the global environment variable MSP430_GCC_INCLUDE_DIR to the full path of the directory containing devices.csv, and GCC will search that directory for devices.csv. If it finds it there, that directory also gets registered as an include path and a linker library path. So header files and linker scripts in that directory can be used without you manually putting -I and -L on the command line. convenience queen ๐
The msp430-elf{,bare}/include/devices directory
Finally, GCC checks msp430-elf{,bare}/include/devices from the toolchain root directory. This directory doesn't exist in a default installation, but if you made it and copied devices.csv in there, then the MCU data gets read. As above, this directory also gets registered as an include path and a linker library path.
If none of those search methods find devices.csv, then the hard-coded MCU data is used. back to basics ๐
-mwarn-mcu-mno-warn-mcuโ this turns warnings on or off for conflicts between the MCU name specified by-mmcuand the ISA set by the-mcpuoption and/or the hardware multiply support set by the-mhwmultoption. It also toggles warnings about unrecognized MCU names. This option is on by default.-mcpu=โ specifies which ISA to use. Accepted values aremsp430,msp430xandmsp430xv2. Heads up: this option is deprecated. Use the-mmcu=option to select the ISA instead.-msimโ link to the simulator runtime libraries and linker script. This overrides any scripts that would've been selected by the-mmcu=option.-mlargeโ use large-model addressing (20-bit pointers, 20-bitsize_t).-msmallโ use small-model addressing (16-bit pointers, 16-bitsize_t).-mrelaxโ this option gets passed to the assembler and the linker, and lets the linker do certain optimizations that literally can't be done until the final link. the ultimate last-minute glow-up โจmhwmult=โ describes the type of hardware multiply supported by the target. (yes bestie, no dash, that's really how it's written, don't @ me ๐) Accepted values arenonefor no hardware multiply,16bitfor the original 16-bit-only multiply supported by early MCUs,32bitfor the 16/32-bit multiply supported by later MCUs, andf5seriesfor the 16/32-bit multiply supported by F5-series MCUs. You can also give a value ofauto, which tells GCC to deduce the hardware multiply support from the MCU name provided by the-mmcuoption. If no-mmcuoption is specified, or if the MCU name isn't recognized, then no hardware multiply support is assumed.autois the default setting.
Hardware multiplies are normally performed by calling a library routine โ this saves space in the generated code. When compiling at -O3 or higher, though, the hardware multiplier is invoked inline. That makes for bigger, but faster code. trade-offs, they're everywhere ๐ฆ
The hardware multiply routines disable interrupts while running and restore the previous interrupt state when they finish. That makes them safe to use inside interrupt handlers as well as in normal code. ๐ฅ
-minrtโ enable the use of a minimum runtime environment โ no static initializers or constructors. This is intended for memory-constrained devices. The compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required.-mtiny-printfโ enable reduced code sizeprintfandputslibrary functions. Caveat time: the tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications ๐ญ
Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it's sent to write.
This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.
-mmax-inline-shift=โ this option takes an integer between 0 and 64 inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When that value needs to be exceeded, anmspabihelper function is used instead. The default value is4.
This only affects cases where a shift by multiple positions can't be completed with a single instruction (e.g. all shifts >1 on the 430 ISA).
Shifts of a 32-bit value are at least twice as costly, so the value you pass for this option gets divided by 2 and that resulting value is used instead. math is math โจ
-mcode-region=-mdata-region=โ these options tell the compiler where to place functions and data that don't have one of thelower,upper,eitherorsectionattributes. Possible values arelower,upper,eitherorany. The first three behave like the corresponding attribute. The fourth possible value โanyโ is the default. It leaves placement entirely up to the linker script and how it assigns the standard sections (.text,.data, etc) to the memory regions.-msilicon-errata=โ this option passes on a request to the assembler to enable the fixes for the named silicon errata.-msilicon-errata-warn=โ this option passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied.-mwarn-devices-csv-mno-warn-devices-csvโ warn ifdevices.csvisn't found or there's a problem parsing it (default: on).
๐ NDS32 Options ๐
These options are defined for NDS32 implementations:
-mbig-endianโ generate code in big-endian mode.-mlittle-endianโ generate code in little-endian mode.-mreduced-regsโ use reduced-set registers for register allocation.-mfull-regsโ use full-set registers for register allocation.-mcmovโ generate conditional move instructions.-mno-cmovโ do not generate conditional move instructions.-mext-perfโ generate performance extension instructions. go faster, bestie ๐ฅ-mno-ext-perfโ do not generate performance extension instructions.-mext-perf2โ bestie, turn ON the performance extension 2 instructions โจ-mno-ext-perf2โ and this one does NOT generate them, ok? literally just the off switch ๐ซ-mext-stringโ generate string extension instructions ๐งต-mno-ext-stringโ do not generate string extension instructions ๐ โโ๏ธ-mv3pushโ generatev3 push25/pop25instructions ๐ซธ-mno-v3pushโ do not generatev3 push25/pop25instructions ๐ซท-m16-bitโ generate 16-bit instructions ๐ผ-mno-16-bitโ do not generate 16-bit instructions, no cap ๐- *
-misr-vector-size=num* โ specify the size of each interrupt vector, and queen it must be4or16, those are the only options, periodt ๐ - *
-mcache-block-size=num* โ specify the size of each cache block. it must be a power of 2 between4and512, so like, do the math first ๐งฎ - *
-march=arch* โ specify the name of the target architecture ๐๏ธ - *
-mcmodel=code-model* โ set the code model to one of these, pick your fighter:smallAll the data and read-only data segments must be within512KBaddressing space. The text segment must be within16MBaddressing space. small but mighty fr ๐ฃmediumThe data segment must be within512KBwhile the read-only data segment can be within4GBaddressing space. The text segment should be still within16MBaddressing space. mid-size, mid-energy ๐ฅlargeAll the text and data segments can be within4GBaddressing space. big girl energy ๐
-mctor-dtorโ enable constructor/destructor feature ๐๏ธ-mrelaxโ guide the linker to relax instructions ๐งโโ๏ธ it's giving zen
๐ฆ Nios II Options ๐ฆ
okay so these are the options defined for the Altera Nios II processor, buckle up bestie, there's a lot ๐
-Gnum โ put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is8. tiny objects get the VIP small-data treatment ๐- *
-mgpopt=option* -mgpopt-mno-gpoptโ generate (or do NOT generate) GP-relative accesses. These option names below are recognized, and they are very much a vibe ladder:noneDo not generate GP-relative accesses. nada. zero. ๐localGenerate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also use GP-relative addressing for objects that have been explicitly placed in a small data section via a"section"attribute. keeping it local ๐globalAs forlocal, but also generate GP-relative accesses for small data objects that are external, weak, or common. โ ๏ธ If you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same-Gsetting. no mixing, bestie, it's giving consistency check ๐dataGenerate GP-relative accesses for all data objects in the program. โ ๏ธ If you use this option, the entire data and BSS segments of your program must fit in64Kof memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. that's a real constraint, not a drill ๐ซallGenerate GP-relative addresses for function pointers as well as data pointers. โ ๏ธ If you use this option, the entire text, data, and BSS segments of your program must fit in64Kof memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. ALL of it. every last byte. iconic but risky ๐
k so, -mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none โ memorize that, iykyk ๐ง
The default is -mgpopt except when -fpic or -fPIC is specified to generate position-independent code. Note that the Nios II ABI does not permit GP-relative accesses from shared libraries ๐
You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In this case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section ๐ญ yeah, it just runs out of room
- *
-mgprel-sec=regexp* โ this option specifies additional section names that can be accessed via GP-relative addressing. It is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression ๐
This option does not affect the behavior of the -G option, and the specified sections are in addition to the standard ".sdata" and ".sbss" small-data sections that are recognized by -mgpopt โจ
- *
-mr0rel-sec=regexp* โ this option specifies names of sections that can be accessed via a 16-bit offset from"r0"; that is, in the low32Kor high32Kof the 32-bit address space. It is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression ๐ฏ
In contrast to the use of GP-relative addressing for small data, zero-based addressing is never generated by default and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory ๐ (so like, you're on your own here, bestie)
-mel-mebโ generate little-endian (default) or big-endian (experimental) code, respectively.-mebis literally labeled experimental, so proceed with caution ๐งช- *
-march=arch* โ this specifies the name of the target Nios II architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. Permissible names are:r1,r2๐
The preprocessor macro __nios2_arch__ is available to programs, with value 1 or 2, indicating the targeted ISA level ๐ข
-mbypass-cache-mno-bypass-cacheโ force all load and store instructions to always bypass cache by using I/O variants of the instructions. The default is not to bypass the cache ๐ช-mno-cache-volatile-mcache-volatileโ volatile memory access bypass the cache using the I/O variants of the load and store instructions. The default is not to bypass the cache ๐-mno-fast-sw-div-mfast-sw-divโ do not use table-based fast divide for small numbers. The default is to use the fast divide at-O3and above โก-mno-hw-mul-mhw-mul-mno-hw-mulx-mhw-mulx-mno-hw-div-mhw-divโ enable or disable emitting"mul","mulx"and"div"family of instructions by the compiler. The default is to emit"mul"and not emit"div"and"mulx"๐งฎ-mbmx-mno-bmx-mcdx-mno-cdxโ enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. โ ๏ธ Enabling these instructions also requires-march=r2. Since these instructions are optional extensions to the R2 architecture, the default is not to emit them ๐- *
-mcustom-insn*=N - *
-mno-custom-insn* โ each-mcustom-insn=N option enables use of a custom instruction with encoding N when generating code that uses insn. For example,-mcustom-fadds=253generates custom instruction253for single-precision floating-point add operations instead of the default behavior of using a library call ๐
The following values of insn are supported. Except as otherwise noted, floating-point operations are expected to be implemented with normal IEEE 754 semantics and correspond directly to the C operators or the equivalent GCC built-in functions ๐
๐ Single-precision floating point ๐
fadds,fsubs,fdivs,fmulsโ Binary arithmetic operations โfnegsโ Unary negation โfabssโ Unary absolute value โจfcmpeqs,fcmpges,fcmpgts,fcmples,fcmplts,fcmpnesโ Comparison operations โ๏ธfmins,fmaxsโ Floating-point minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified ๐ป๐บfsqrtsโ Unary square root operation โfcoss,fsins,ftans,fatans,fexps,flogsโ Floating-point trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified ๐
๐ Double-precision floating point ๐
faddd,fsubd,fdivd,fmuldโ Binary arithmetic operations โfnegdโ Unary negation โfabsdโ Unary absolute value โจfcmpeqd,fcmpged,fcmpgtd,fcmpled,fcmpltd,fcmpnedโ Comparison operations โ๏ธfmind,fmaxdโ Double-precision minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified ๐ป๐บfsqrtdโ Unary square root operation โfcosd,fsind,ftand,fatand,fexpd,flogdโ Double-precision trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified ๐
๐ง Conversions ๐ง
fextsdโ Conversion from single precision to double precision ๐ชftruncdsโ Conversion from double precision to single precision ๐ชfixsi,fixsu,fixdi,fixduโ Conversion from floating point to signed or unsigned integer types, with truncation towards zero โ๏ธroundโ Conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the__builtin_lroundffunction when-fno-math-errnois used ๐ฏfloatis,floatus,floatid,floatudโ Conversion from signed or unsigned integer types to floating-point types ๐ช
In addition, all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. sorry bestie, it's a package deal ๐
Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or only operand of a unary operation) is given to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction that returns a double-precision result returns the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC automatically generates the necessary code sequences to write register X and/or read register Y when double-precision floating-point instructions are used ๐คฏ like it just handles it, slay
fwrxโ Writesrc1into the least significant half ofXandsrc2into the most significant half ofXโ๏ธfwryโ Writesrc1intoYโ๏ธfrdxhi,frdxloโ Read the most or least (respectively) significant half ofXand store it indest๐frdyโ Read the value ofYand store it intodest๐
No cap, you can also grab more local control over how Nios II custom instructions get generated by using the target("custom-insn=N") and target("no-custom-insn") function attributes or pragmas. Cute, right? ๐
-mcustom-fpu-cfg=nameโ this one turns on a predefined, named set of custom instruction encodings (peep-mcustom-insnabove for the deets). Right now these sets are the ones that exist:-mcustom-fpu-cfg=60-1is equivalent to:-mcustom-fmuls=252-mcustom-fadds=253-mcustom-fsubs=254-fsingle-precision-constant-mcustom-fpu-cfg=60-2is equivalent to:-mcustom-fmuls=252-mcustom-fadds=253-mcustom-fsubs=254-mcustom-fdivs=255-fsingle-precision-constant-mcustom-fpu-cfg=72-3is equivalent to:-mcustom-floatus=243-mcustom-fixsi=244-mcustom-floatis=245-mcustom-fcmpgts=246-mcustom-fcmples=249-mcustom-fcmpeqs=250-mcustom-fcmpnes=251-mcustom-fmuls=252-mcustom-fadds=253-mcustom-fsubs=254-mcustom-fdivs=255-fsingle-precision-constant-mcustom-fpu-cfg=fph2is equivalent to:-mcustom-fabss=224-mcustom-fnegs=225-mcustom-fcmpnes=226-mcustom-fcmpeqs=227-mcustom-fcmpges=228-mcustom-fcmpgts=229-mcustom-fcmples=230-mcustom-fcmplts=231-mcustom-fmaxs=232-mcustom-fmins=233-mcustom-round=248-mcustom-fixsi=249-mcustom-floatis=250-mcustom-fsqrts=251-mcustom-fmuls=252-mcustom-fadds=253-mcustom-fsubs=254-mcustom-fdivs=255
Custom instruction assignments you hand over with individual -mcustom-insn= options override the ones from -mcustom-fpu-cfg=, and bestie, that's true no matter what order the options show up in on the command line. Order who? Never heard of her. ๐
Oh and btw, you can get more local control over picking a FPU configuration by using the target("custom-fpu-cfg=name") function attribute or pragma.
The name fph2 is short for Nios II Floating Point Hardware 2 Component โ say that five times fast, I dare you. ๐ธ Also pls note: the custom instructions that -mcustom-fmins=233 and -mcustom-fmaxs=234 enable only get generated if -ffinite-math-only is specified. And the custom instruction that -mcustom-round=248 enables only gets generated if -fno-math-errno is specified. And unlike literally every other configuration over here, -fsingle-precision-constant is not set.
๐ฆ These extra -m options are for the Altera Nios II ELF (bare-metal) target ๐ฆ
-mhalโ link with HAL BSP. This suppresses linking with the GCC-provided C runtime startup and termination code, and is typically used together with-msys-crt0=to say where the alternate startup code that the HAL BSP provides actually lives.-msmallcโ link with a limited version of the C library,-lsmallc, instead of Newlib. Tiny library, big heart. ๐ซถ-msys-crt0=startfileโ startfile is the file name of the startfile (crt0) to use when linking. This option is only useful when you pair it with-mhal, iykyk.-msys-lib=systemlibโ systemlib is the library name of the library that provides the low-level system calls the C library needs, like"read"and"write". This one is typically used to link with a library that a HAL BSP provides.
๐ Nvidia PTX Options ๐
These options are defined for Nvidia PTX:
-m64โ Ignored, but preserved for backward compatibility. Only 64-bit ABI is supported, so likeโฆ there's nothing else to be. Main character only. โจ-march=architecture-stringโ generate code for the specified PTX ISA target architecture (e.g.sm_35). The valid architecture strings aresm_30,sm_35,sm_53,sm_70,sm_75andsm_80. The default depends on how the compiler has been configured, see--with-arch.
This option sets the value of the preprocessor macro "__PTX_SM__"; for instance, for sm_35, it has the value 350.
-misa=architecture-stringโ alias of-march=. Same vibe, different name. ๐-march-map=architecture-stringโ select the closest available-march=value that is not more capable. For instance, for-march-map=sm_50select-march=sm_35, and for-march-map=sm_53select-march=sm_53.-mptx=version-stringโ generate code for the specified PTX ISA version (e.g.7.0). Valid version strings include3.1,6.0,6.3, and7.0. The default PTX ISA version is6.0, unless a higher version is required for the specified PTX ISA target architecture via option-march=.
This option sets the values of the preprocessor macros "__PTX_ISA_VERSION_MAJOR__" and "__PTX_ISA_VERSION_MINOR__"; for instance, for 3.1 the macros have the values 3 and 1, respectively.
-mmainkernelโ link in code for a__mainkernel. This is for stand-alone instead of offloading execution. Solo era. ๐-moptimizeโ apply partitioned execution optimizations. This is the default when any level of optimization is selected. Slay, she's already on by default.-msoft-stackโ generate code that does not use".local"memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or"alloca"), and when global memory is used for underlying storage, makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option-mgomp.-muniform-simtโ switch to a code generation variant that lets you execute all threads in each warp, while maintaining memory state and side effects as if only one thread in each warp was active outside of OpenMP SIMD regions. All atomic operations and calls to runtime (malloc,free,vprintf) are conditionally executed (iff current lane index equals the master lane index), and the register being assigned is copied via a shuffle instruction from the master lane. Outside of SIMD regions lane 0 is the master; inside, each thread sees itself as the master. Shared memory array"int __nvptx_uni[]"stores all-zeros or all-ones bitmasks for each warp, indicating current mode (0outside of SIMD regions). Each thread can bitwise-and the bitmask at position"tid.y"with the current lane index to compute the master lane index. Not me understanding warp politics better than my own group chat ๐ญ-mgompโ generate code for use in OpenMP offloading: enables-msoft-stackand-muniform-simtoptions, and selects the corresponding multilib variant. Combo deal, bestie. ๐
๐ OpenRISC Options ๐
These options are defined for OpenRISC:
-mboard=nameโ configure a board specific runtime. This will be passed to the linker for newlib board library linking. The default is"or1ksim".-mnewlibโ this option is ignored; it's for compatibility purposes only. This used to select linker and preprocessor options for use with newlib. She's retired but we still invite her to the party. ๐-msoft-div-mhard-divโ select software or hardware divide ("l.div","l.divu") instructions. The default is hardware divide.-msoft-mul-mhard-mulโ select software or hardware multiply ("l.mul","l.muli") instructions. The default is hardware multiply.-msoft-float-mhard-floatโ select software or hardware for floating point operations. The default is software.-mdouble-floatโ when-mhard-floatis selected, enables generation of double-precision floating point instructions. By default functions from libgcc are used to perform double-precision floating point operations.-munordered-floatโ when-mhard-floatis selected, enables generation of unordered floating point compare and set flag ("lf.sfun*") instructions. By default functions from libgcc are used to perform unordered floating point compare and set flag operations.-mcmovโ enable generation of conditional move ("l.cmov") instructions. By default the equivalent will be generated using set and branch.-mrorโ enable generation of rotate right ("l.ror") instructions. By default functions from libgcc are used to perform rotate right operations.-mroriโ enable generation of rotate right with immediate ("l.rori") instructions. By default functions from libgcc are used to perform rotate right with immediate operations.-msextโ enable generation of sign extension ("l.ext*") instructions. By default memory loads are used to perform sign extension.-msfimmโ enable generation of compare and set flag with immediate ("l.sf*i") instructions. By default extra instructions will be generated to store the immediate to a register first.-mshftimmโ enable generation of shift with immediate ("l.srai","l.srli","l.slli") instructions. By default extra instructions will be generated to store the immediate to a register first.-mcmodel=smallโ generate OpenRISC code for the small model: the GOT is limited to 64k. This is the default model.-mcmodel=largeโ generate OpenRISC code for the large model: the GOT may grow up to 4G in size.
๐ PDP-11 Options ๐
These options are defined for the PDP-11:
-mfpuโ use hardware FPP floating point. This is the default. (FIS floating point on the PDP-11/40 is not supported.) Implies-m45.-msoft-floatโ do not use hardware floating point.-mac0โ return floating-point results in ac0 (fr0 in Unix assembler syntax).-mno-ac0โ return floating-point results in memory. This is the default.-m40โ generate code for a PDP-11/40. Implies-msoft-float-mno-split.-m45โ generate code for a PDP-11/45. This is the default.-m10โ generate code for a PDP-11/10. Implies-msoft-float-mno-split.-mint16-mno-int32โ use 16-bit"int". This is the default.-mint32-mno-int16โ use 32-bit"int".-msplitโ target has split instruction and data space. Implies-m45.-munix-asmโ use Unix assembler syntax.-mdec-asmโ use DEC assembler syntax.-mgnu-asmโ use GNU assembler syntax. This is the default.-mlraโ use the new LRA register allocator. By default, the old"reload"allocator is used.
๐ธ PowerPC Options ๐ธ
These are listed under
๐ง PRU Options ๐ง
These command-line options are defined for the PRU target:
-minrtโ link with a minimum runtime environment, with no support for static initializers and constructors. Using this option can significantly reduce the size of the final ELF binary. But beware, bestie: the compiler could still generate code with static initializers and constructors. It is up to the programmer to make sure the source program will not use those features. That's on you, gorgeous. ๐-mmcu=mcuโ tells GCC which PRU MCU variant you're building for ๐ . Wanna know the exact list of supported MCUs? Go check Newlib, bestie, that's where it lives.-mno-relaxโ makes GCC hand--no-relaxover to the linker instead of the usual--relaxoption. no relaxing today, we're locked in ๐-mloopโ lets GCC (or doesn't let GCC, depending) use theLOOPinstruction.-mabi=variantโ pick the ABI variant your code gets compiled for.-mabi=tigives you the unmodified TI ABI, while-mabi=gnugives you a GNU variant that copes more naturally with certain GCC assumptions. Here's the tea on what actually differs โ:- Function Pointer Size โ the TI ABI says function (code) pointers are 16-bit, whereas GNU only supports 32-bit data and code pointers.
- Optional Return Value Pointer โ any function return value bigger than 64 bits gets passed via a hidden pointer as the first argument of the function. But the TI ABI mandates that this pointer can be
NULLin case the caller isn't even using the returned value. GNU, on the other hand, always passes and expects a valid return value pointer. noNULLbesties allowed ๐ค
The current -mabi=ti implementation just raises a compile error the moment any of the above code constructs gets detected. Which means โ as a direct consequence โ the standard C library cannot be built, and it gets omitted when you link with -mabi=ti. so sad, truly ๐
Also, relaxation is a GNU feature, and for safety reasons it's disabled when you're using -mabi=ti. Why? Because the TI toolchain does not emit relocations for QBBx instructions, so the GNU linker can't adjust them when it's shortening adjacent LDI32 pseudo instructions. iykyk.
๐ RISC-V Options ๐
These command-line options are defined for RISC-V targets:
-mbranch-cost=nโ set the cost of branches to roughly n instructions.-mplt,-mno-pltโ when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC. The default is-mplt.-mabi=ABI-stringโ specify the integer and floating-point calling convention โจ.ABI-stringis made up of two parts: the size of integer types, and the registers used for floating-point types. So for example,-march=rv64ifd -mabi=lp64dmeans that long and pointers are 64-bit (which implicitly definesintto be 32-bit), and that floating-point values up to 64 bits wide get passed in F registers. Now contrast that with-march=rv64ifd -mabi=lp64f, which still lets the compiler generate code using the F and D extensions, but only allows floating-point values up to 32 bits long to be passed in registers ๐ซถ. Or-march=rv64ifd -mabi=lp64, where literally no floating-point arguments get passed in registers at all.
The default for this argument is system dependent, so if you want a specific calling convention you should specify one explicitly, bestie. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Heads up tho โ some calling conventions are straight-up impossible to implement on some ISAs: for example, -march=rv32if -mabi=ilp32d is invalid because the ABI requires 64-bit values be passed in F registers, but F registers are only 32 bits wide ๐. There's also the ilp32e ABI that can only be used with the rv32e architecture. This ABI is not well specified at present, and is subject to change. you've been warned ๐
-mfdiv,-mno-fdivโ do or don't use hardware floating-point divide and square root instructions. This requires the F or D extensions for floating-point registers. The default is to use them if the specified architecture has these instructions.-mdiv,-mno-divโ do or don't use hardware instructions for integer division. This requires the M extension. The default is to use them if the specified architecture has these instructions.-misa-spec=ISA-spec-stringโ specify which version of the RISC-V Unprivileged (formerly User-Level) ISA specification you want to produce code conforming to. The possibilities for ISA-spec-string are:2.2โ produce code conforming to version 2.2.20190608โ produce code conforming to version 20190608.20191213โ produce code conforming to version 20191213.
The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version.
-march=ISA-stringโ generate code for the given RISC-V ISA (e.g.rv64im). ISA strings must be lower-case, no yelling allowed ๐. Examples includerv64i,rv32g,rv32e, andrv32imaf.
When -march= isn't specified, use the setting from -mcpu.
If neither -march nor -mcpu= is specified, the default for this argument is system dependent โ so if you want a specific architecture extensions, specify one explicitly, okay bestie?
-mcpu=processor-stringโ use the architecture of, and optimize the output for, the given processor, specified by a particular CPU name. The permissible values for this option are:sifive-e20,sifive-e21,sifive-e24,sifive-e31,sifive-e34,sifive-e76,sifive-s21,sifive-s51,sifive-s54,sifive-s76,sifive-u54, andsifive-u74. that's a whole squad fr fr ๐ฅ-mtune=processor-stringโ optimize the output for the given processor, specified by microarchitecture or a particular CPU name. The permissible values for this option are:rocket,sifive-3-series,sifive-5-series,sifive-7-series,thead-c906,size, and all valid options for-mcpu=.
When -mtune= isn't specified, use the setting from -mcpu โ and the default is rocket if both are unspecified.
Now, the size choice is not intended for use by end-users, okay? It's used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but it does not override the pipeline info. This helps reduce code size while still giving good performance. it's giving "trust the process" ๐
-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a 2 raised to num-byte boundary. If-mpreferred-stack-boundaryisn't specified, the default is 4 (16 bytes or 128-bits).
โ ๏ธ Warning: if you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. all or nothing, no half-vibes ๐ญ
-msmall-data-limit=nโ put global and static data smaller than n bytes into a special section (on some targets).-msave-restore,-mno-save-restoreโ do or don't use smaller but slower prologue and epilogue code that calls library functions. The default is to use fast inline prologues and epilogues. speed over size, iconic behavior โญ-minline-atomics,-mno-inline-atomicsโ do or don't use smaller but slower subword atomic emulation code that callslibatomicfunctions. The default is to use fast inline subword atomics that do not requirelibatomic.-mshorten-memrefs,-mno-shorten-memrefsโ do or do not attempt to make more use of compressed load/store instructions by replacing a load/store ofbase register + large offsetwith a new load/store ofnew base + small offset. If the new base gets stored in a compressed register, then the new load/store can itself be compressed ๐ฆ. Currently targets 32-bit integer load/stores only.-mstrict-align,-mno-strict-alignโ do not or do generate unaligned memory accesses. The default is set depending on whether the processor we're optimizing for supports fast unaligned access or not.-mcmodel=medlowโ generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This is the default code model. the main character of code models ๐-mcmodel=medanyโ generate code for the medium-any code model. The program and its statically defined symbols must be within any single 2 GiB address range. Programs can be statically or dynamically linked.
Just so you know: the code generated by the medium-any code model is position-independent, but it is not guaranteed to function correctly when linked into position-independent executables or libraries. read that twice, bestie ๐
-mexplicit-relocs,-mno-exlicit-relocsโ use or do not use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit optimization. (and yes, the typo in-mno-exlicit-relocsis real, we don't make the rules ๐)-mrelax,-mno-relaxโ take advantage of linker relaxations to reduce the number of instructions required to materialize symbol addresses. The default is to take advantage of linker relaxations.-mriscv-attribute,-mno-riscv-attributeโ emit (or do not emit) a RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32. don't be out here with old binutils, it's giving outdated ๐-mcsr-check,-mno-csr-checkโ enables or disables the CSR checking.-malign-data=typeโ control how GCC aligns variables and constants of array, structure, or union types. Supported values for type arexlen, which uses x register width as the alignment value, andnatural, which uses natural alignment.xlenis the default.-mbig-endianโ generate big-endian code. This is the default when GCC is configured for ariscv64be-*-*orriscv32be-*-*target.-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for ariscv64-*-*orriscv32-*-*but not ariscv64be-*-*orriscv32be-*-*target.-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ generate stack protection code using a canary at guard. The supported locations areglobalfor a global canary, ortlsfor a per-thread canary in the TLS block ๐.
With that latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as the base register for reading the canary, and from what offset from that base register. There is no default register or offset, because this is entirely for use within the Linux kernel. kernel girlies only ๐
๐ RL78 Options ๐
-msimโ links in additional target libraries to support operation within a simulator.-mmul=none,-mmul=g10,-mmul=g13,-mmul=g14,-mmul=rl78โ specifies the type of hardware multiplication and division support to be used. The simplest isnone, which uses software for both multiplication and division โ and that's the default. Theg13value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. Theg14value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The valuerl78is an alias forg14, and the valuemg10is an alias fornone. aliases stay aliasing, periodt ๐
In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are: "__RL78_MUL_NONE__", "__RL78_MUL_G13__" or "__RL78_MUL_G14__".
-mcpu=g10โ targets the RL78 G10 core, also called the S1 core.-mcpu=g13โ targets the RL78 G13 core, a.k.a. the S2 core.-mcpu=g14โ targets the RL78 G14 core, a.k.a. the S3 core, a.k.a. just plain RL78.-mcpu=rl78โ same vibe, the RL78 core ๐
Specifies which RL78 core you're targeting, bestie. Default is the G14 core โ also known as the S3 core, or literally just RL78, no cap. The G13 (S2) core doesn't have multiply or divide instructions, and the way it handles those is via a hardware peripheral instead. The G10 (S1) core has no register banks at all, so it uses a whole different calling convention. โจ
If you set this option it also picks the type of hardware multiply support to use, unless something overrides that with an explicit -mmul=none on the command line. So: -mcpu=g13 turns on the G13 hardware multiply peripheral, and -mcpu=g10 disables hardware multiplication entirely. ๐
Important, queens: even though RL78/G14 is the default target, actually saying-mcpu=g14or-mcpu=rl78on the command line does change how the toolchain behaves, because it also turns on G14 hardware multiply support. If you don't pass those on the command line, then software multiplication routines get used โ even though the code is targeting the RL78 core. That's for backwards compatibility with older toolchains that didn't have hardware multiply and divide support. Not a bug, just โจlegacy vibesโจ.
Also, a C preprocessor macro is defined based on how you set this option. Possible values: "__RL78_G10__", "__RL78_G13__" or "__RL78_G14__".
-mg10โ alias for the matching-mcpu=option-mg13โ alias for the matching-mcpu=option-mg14โ alias for the matching-mcpu=option-mrl78โ alias for the matching-mcpu=option
These are aliases for the corresponding -mcpu= option. They're provided for backwards compatibility. ๐ซถ
-mallregsโ let the compiler use every available register, bestie
Lets the compiler use all of the available registers. By default, registers r24..r31 are reserved for use in interrupt handlers. Flip this on and those registers can be used in ordinary functions too. more registers, more power ๐ฅ
-m64bit-doublesโ makesdouble64 bits wide-m32bit-doublesโ makesdouble32 bits wide
Makes the double data type 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. Default is -m32bit-doubles.
-msave-mduc-in-interruptsโ interrupt handlers should preserve the MDUC registers-mno-save-mduc-in-interruptsโ don't bother
Says that interrupt handler functions should preserve the MDUC registers. You only need this if normal code might be using the MDUC registers โ like, say, because it's doing multiplication and division. Default is to ignore the MDUC registers, since that makes interrupt handlers faster. Heads up: you gotta pass the target option -mg13 for this to work at all, because the feature only exists on the G13 target (S2 core). And the MDUC registers only get saved if the interrupt handler actually does a multiplication or division, or it calls another function. ๐ง
IBM RS/6000 and PowerPC Options ๐
These -m options are defined for the IBM RS/6000 and PowerPC:
-mpowerpc-gpopt/-mno-powerpc-gpoptโ allow (or don't allow) the optional PowerPC General Purpose group instructions-mpowerpc-gfxopt/-mno-powerpc-gfxoptโ allow (or don't allow) the optional PowerPC Graphics group instructions-mpowerpc64/-mno-powerpc64โ extra 64-bit PowerPC64 instructions, treat GPRs as 64-bit-mmfcrf/-mno-mfcrfโ move from condition register field instruction-mpopcntb/-mno-popcntbโ popcount + double-precision FP reciprocal estimate-mpopcntd/-mno-popcntdโ popcount instruction-mfprnd/-mno-fprndโ FP round to integer instructions-mcmpb/-mno-cmpbโ compare bytes instruction-mhard-dfp/-mno-hard-dfpโ decimal floating-point instructions
You use these options to say which instructions are available on the processor you're using. The default value of these is decided when GCC is configured. Specifying -mcpu=cpu_type overrides whatever you set here. And fr fr, the recommendation is: use -mcpu=cpu_type instead of the big list above. ๐
Specifying -mpowerpc-gpopt lets GCC use the optional PowerPC architecture instructions in the General Purpose group, floating-point square root included. Specifying -mpowerpc-gfxopt lets GCC use the optional ones in the Graphics group, floating-point select included. โจ
The -mmfcrf option lets GCC generate the move from condition register field instruction โ that's the one implemented on the POWER4 processor and other processors supporting the PowerPC V2.01 architecture. The -mpopcntb option lets GCC generate the popcount and double-precision FP reciprocal estimate instruction, implemented on POWER5 and friends supporting PowerPC V2.02. The -mpopcntd option lets GCC generate the popcount instruction implemented on POWER7 and other PowerPC V2.06 processors. The -mfprnd option lets GCC generate the FP round to integer instructions implemented on POWER5+ and other PowerPC V2.03 processors. The -mcmpb option lets GCC generate the compare bytes instruction implemented on POWER6 and other PowerPC V2.05 processors. And the -mhard-dfp option lets GCC generate the decimal floating-point instructions implemented on some POWER processors. ๐
The -mpowerpc64 option lets GCC generate the additional 64-bit instructions found in the full PowerPC64 architecture, and treats GPRs as 64-bit, doubleword quantities. GCC defaults to -mno-powerpc64.
๐ -mcpu=cpu_type ๐
-mcpu=cpu_typeโ set architecture type, register usage, and instruction scheduling parameters for machine type cpu_type
Supported values for cpu_type are 401, 403, 405, 405fp, 440, 440fp, 464, 464fp, 476, 476fp, 505, 601, 602, 603, 603e, 604, 604e, 620, 630, 740, 7400, 7450, 750, 801, 821, 823, 860, 970, 8540, a2, e300c2, e300c3, e500mc, e500mc64, e5500, e6500, ec603e, G3, G4, G5, titan, power3, power4, power5, power5+, power6, power6x, power7, power8, power9, power10, powerpc, powerpc64, powerpc64le, rs64, and native.
-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endianness), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes.
Specifying native as the cpu type detects and selects the architecture option that matches the host processor of the system doing the compilation. -mcpu=native does nothing if GCC doesn't recognize the processor. ๐ญ
The other options specify a specific processor. Code generated under those runs best on that processor, and may not run at all on others. ๐
The -mcpu options automatically enable or disable the following options:
-maltivec -mfprnd -mhard-float -mmfcrf -mmultiple -mpopcntb
-mpopcntd -mpowerpc64 -mpowerpc-gpopt -mpowerpc-gfxopt -mmulhw
-mdlmzb -mmfpgpr -mvsx -mcrypto -mhtm -mpower8-fusion
-mpower8-vector -mquad-memory -mquad-memory-atomic -mfloat128
-mfloat128-hardware -mprefixed -mpcrel -mmma -mrop-protect
The particular options set for any particular CPU varies between compiler versions, depending on what setting seems to produce optimal code for that CPU โ it doesn't necessarily reflect the actual hardware's capabilities. If you wanna set an individual option to a particular value, you can specify it after the -mcpu option, like -mcpu=970 -mno-altivec. โจ
On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option at present, because AIX doesn't have full support for these options. You can still enable or disable them individually if you're sure it'll work in your environment. ๐ซก
๐ฆ -mtune=cpu_type ๐ฆ
-mtune=cpu_typeโ set instruction scheduling parameters for machine type cpu_type, without touching architecture type or register usage
Sets the instruction scheduling parameters for machine type cpu_type, but does not set the architecture type or register usage the way -mcpu=cpu_type does. The same values for cpu_type are used for -mtune as for -mcpu. If both are specified, the code generated uses the architecture and registers set by -mcpu, but the scheduling parameters set by -mtune. periodt ๐
-mcmodel=smallโ PowerPC64 code for the small model-mcmodel=mediumโ PowerPC64 code for the medium model-mcmodel=largeโ PowerPC64 code for the large model
-mcmodel=small generates PowerPC64 code for the small model: the TOC is limited to 64k.
-mcmodel=medium generates PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size. This is the default for 64-bit Linux.
-mcmodel=large generates PowerPC64 code for the large model: the TOC may be up to 4G in size, and other data and code is only limited by the 64-bit address space. ๐
-maltivec/-mno-altivecโ generate code that uses (does not use) AltiVec instructions-mvrsave/-mno-vrsaveโ generate VRSAVE instructions when generating AltiVec code-msecure-pltโ non-executable.pltand.gotsections, PowerPC 32-bit SYSV ABI option-mbss-pltโ BSS.pltsection filled in byld.so, PowerPC 32-bit SYSV ABI option-misel/-mno-iselโ turn generation of ISEL instructions on or off-mvsx/-mno-vsxโ use (don't use) vector/scalar (VSX) instructions-mcrypto/-mno-cryptoโ enable (disable) built-ins for the cryptographic instructions added in version 2.07 of the PowerPC ISA-mhtm/-mno-htmโ enable (disable) built-ins for the Hardware Transactional Memory (HTM) instructions added in version 2.07 of the PowerPC ISA-mpower8-fusion/-mno-power8-fusionโ keep (don't keep) some integer operations adjacent so they can be fused on power8 and later
-maltivec / -mno-altivec generates code that uses (does not use) AltiVec instructions, and also enables the use of built-in functions that allow more direct access to the AltiVec instruction set. You may also need to set -mabi=altivec to adjust the current ABI with AltiVec ABI enhancements. ๐ง
When -maltivec is used, the element order for AltiVec intrinsics such as vec_splat, vec_extract, and vec_insert matches array element order corresponding to the endianness of the target. That is: element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform. iykyk ๐
-mvrsave / -mno-vrsave generates VRSAVE instructions when generating AltiVec code.
-msecure-plt generates code that lets ld and ld.so build executables and shared libraries with non-executable .plt and .got sections. This is a PowerPC 32-bit SYSV ABI option.
-mbss-plt generates code that uses a BSS .plt section that ld.so fills in, and requires .plt and .got sections that are both writable and executable. Also a PowerPC 32-bit SYSV ABI option. ๐
-misel / -mno-isel enables or disables the generation of ISEL instructions.
-mvsx / -mno-vsx generates code that uses (does not use) vector/scalar (VSX) instructions, and also enables the use of built-in functions that allow more direct access to the VSX instruction set.
-mcrypto / -mno-crypto enables (or disables) the use of the built-in functions that allow direct access to the cryptographic instructions added in version 2.07 of the PowerPC ISA. ๐ฅ
-mhtm / -mno-htm enables (or disables) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions added in version 2.07 of the PowerPC ISA.
-mpower8-fusion / -mno-power8-fusion generates code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors. (Yes bestie, "does not keeps" โ we're quoting the source exactly, no editing the canon. ๐)
-mpower8-vector,-mno-power8-vectorโ turns on (or off, bestie) the generation of code that uses the vector and scalar instructions added in version 2.07 of the PowerPC ISA. It also opens the door for built-in functions that give you more direct access to those vector instructions. ๐-mquad-memory,-mno-quad-memoryโ generate code that uses (or doesn't use) the non-atomic quad word memory instructions. Heads up though:-mquad-memoryrequires you to be in 64-bit mode. No 64-bit? No quad-memory. periodt.-mquad-memory-atomic,-mno-quad-memory-atomicโ same energy but for the atomic quad word memory instructions. And yes,-mquad-memory-atomicalso requires 64-bit mode. ๐-mfloat128,-mno-float128โ enable or disable the__float128keyword for IEEE 128-bit floating point, and pick whether you want software emulation or actual hardware instructions for it.
Okay real talk: to use the IEEE 128-bit floating point support you must have the VSX instruction set enabled (-mvsx). And it's only supported on Linux, sorry not sorry. The default for -mfloat128 is enabled on PowerPC Linux systems that use the VSX instruction set, and disabled everywhere else.
If you're on a 64-bit system and you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9), the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ like if you don't specify ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ it's software emulation city. ๐ญ
-mfloat128-hardware,-mno-float128-hardwareโ enable or disable using ISA 3.0 hardware instructions to back the__float128data type. The default for-mfloat128-hardwareis enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems. โจ-m32,-m64โ generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux, obviously). The 32-bit environment setsint,longand pointer to 32 bits โ and generates code that runs on any PowerPC variant. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits, and generates code for PowerPC64, just like-mpowerpc64.-mfull-toc,-mno-fp-in-toc,-mno-sum-in-toc,-mminimal-tocโ these modify how the TOC (Table Of Contents) gets generated. Every executable file has one, btw.-mfull-tocis selected by default. In that case GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also puts floating-point constants in the TOC. But โ plot twist โ only 16,384 entries are available in the TOC. ๐
If you get a linker error saying you've overflowed the available TOC space, you can shrink the TOC usage with -mno-fp-in-toc and -mno-sum-in-toc. Here's the tea: -mno-fp-in-toc stops GCC from putting floating-point constants in the TOC, and -mno-sum-in-toc forces GCC to generate code that calculates the sum of an address and a constant at run time instead of putting that sum into the TOC. You can specify one or both. Each one makes GCC produce very slightly slower and larger code โ the trade-off is that you conserve TOC space. ๐ซถ
If you still run out of TOC space even after both of those, specify -mminimal-toc instead. This option makes GCC create only one TOC entry for every file. When you use it, GCC produces code that is slower and larger, but it uses extremely little TOC space. You might wanna use this only on files that contain less frequently-executed code. iykyk.
-maix64,-maix32โ enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bit"long"type, and all the infrastructure needed to support them. Specifying-maix64implies-mpowerpc64, while-maix32disables the 64-bit ABI and implies-mno-powerpc64. GCC defaults to-maix32.-mxl-compat,-mno-xl-compatโ produce code that conforms more closely to IBM XL compiler semantics when using AIX-compatible ABI. It passes floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. It does not assume that the most significant double in a 128-bitlong doublevalue is properly rounded when comparing values and converting todouble. And it uses XL symbol names forlong doublesupport routines.
The AIX calling convention was extended โ but not initially documented โ to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared. IBM XL compilers access floating-point arguments that don't fit in the RSA from the stack when a subroutine is compiled without optimization. Because always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not enabled by default and is only necessary when calling subroutines compiled by IBM XL compilers without optimization. ๐ฎโ๐จ
-mpeโ support IBM RS/6000 SP Parallel Environment (PE). It links an application written to use message passing with special startup code so the application can run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the-specs=option to specify the appropriate directory location. And โ important โ the Parallel Environment does not support threads, so-mpeand-pthreadare incompatible. ๐ซ-malign-natural,-malign-powerโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux,-malign-naturaloverrides the ABI-defined alignment of larger types (like floating-point doubles) on their natural size-based boundary.-malign-powertells GCC to follow the ABI-specified alignment rules. GCC defaults to the standard alignment defined in the ABI.
On 64-bit Darwin, natural alignment is the default, and -malign-power is not supported. ๐
-msoft-float,-mhard-floatโ generate code that does not use (or does use) the floating-point register set. Software floating-point emulation is provided if you use-msoft-float, and you also pass the option to GCC when linking. Don't forget the linking part, bestie.-mmultiple,-mno-multipleโ generate code that uses (or doesn't use) the load multiple word instructions and the store multiple word instructions. These instructions are generated by default on POWER systems, and not generated on PowerPC systems.
โ ๏ธ Do not use -mmultiple on little-endian PowerPC systems, because those instructions don't work when the processor is in little-endian mode. The exceptions are PPC740 and PPC750, which permit these instructions in little-endian mode. So likeโฆ know your chip. ๐ฅ
-mupdate,-mno-updateโ generate code that uses (or doesn't use) the load or store instructions that update the base register to the address of the calculated memory location. These instructions are generated by default.
If you use -mno-update, there's a small window between the time the stack pointer is updated and the address of the previous frame is stored โ which means code that walks the stack frame across interrupts or signals may get corrupted data. That's a no-no. ๐ญ
-mavoid-indexed-addresses,-mno-avoid-indexed-addressesโ generate code that tries to avoid (or not avoid) the use of indexed load or store instructions. These instructions can incur a performance penalty on Power6 processors in certain situations โ like when stepping through large arrays that cross a 16M boundary. This option is enabled by default when targeting Power6 and disabled otherwise.-mfused-madd,-mno-fused-maddโ generate code that uses (or doesn't use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used. The machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. Glow up. โจ-mmulhw,-mno-mulhwโ generate code that uses (or doesn't use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These instructions are generated by default when targeting those processors.-mdlmzb,-mno-dlmzbโ generate code that uses (or doesn't use) the string-searchdlmzbinstruction on the IBM 405, 440, 464 and 476 processors. This instruction is generated by default when targeting those processors. ๐-mno-bit-align,-mbit-alignโ on System V.4 and embedded PowerPC systems, do not (or do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.
For example: by default, a structure containing nothing but 8 "unsigned" bit-fields of length 1 is aligned to a 4-byte boundary and has a size of 4 bytes. By using -mno-bit-align, the structure is aligned to a 1-byte boundary and is 1 byte in size. Cute and compact. ๐
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems, do not (or do) assume that unaligned memory references are handled by the system.-mrelocatable,-mno-relocatableโ generate code that allows (or doesn't allow) a static executable to be relocated to a different address at run time. A simple embedded PowerPC system loader should relocate the entire contents of".got2"and 4-byte locations listed in the".fixup"section โ that's a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with-mrelocatableor-mrelocatable-lib. Also,-mrelocatablecode aligns the stack to an 8-byte boundary. ๐ฆ-mrelocatable-lib,-mno-relocatable-libโ like-mrelocatable,-mrelocatable-libgenerates a".fixup"section to allow static executables to be relocated at run time โ but-mrelocatable-libdoes not use the smaller stack alignment of-mrelocatable. Objects compiled with-mrelocatable-libmay be linked with objects compiled with any combination of the-mrelocatableoptions. So flexible. So iconic. ๐-mno-toc,-mtocโ on System V.4 and embedded PowerPC systems, do not (or do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program. โญ
okay bestie, OPTIONS round idk we're deep in PowerPC land and it's giving very much โendianness is a lifestyleโ ๐โจ buckle up, here's the tea:
-mlittle,-mlittle-endianโ on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode ๐-mlittle-endianis literally just-mlittle, same vibe.-mbig,-mbig-endianโ on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode ๐ธ-mbig-endianis the same as-mbig. no cap.-mdynamic-no-picโ on Darwin and Mac OS X systems, compile code so it's not relocatable, but its external references are relocatable โจ the resulting code is suitable for applications, but not shared libraries. periodt.-msingle-pic-baseโ treat the register used for PIC addressing as read-only, instead of loading it in the prologue for each function ๐ the runtime system is responsible for initializing this register with an appropriate value before execution begins. it's giving โtrust the runtime, bestie.โ-mprioritize-restricted-insns=priorityโ this controls the priority assigned to dispatch-slot restricted instructions during the second scheduling pass ๐ the argumentprioritytakes0,1, or2to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions.-msched-costly-dep=dependence_typeโ controls which dependences are considered costly by the target during instruction scheduling ๐ the argumentdependence_typetakes one of these values:noโ no dependence is costly.allโ all dependences are costly.true_store_to_loadโ a true dependence from store to load is costly.store_to_loadโ any dependence from store to load is costly.numberโ any dependence for which the latency is greater than or equal tonumberis costly.
-minsert-sched-nops=schemeโ controls which NOP insertion scheme is used during the second scheduling pass ๐ฆ the argumentschemetakes one of these values:noโ don't insert NOPs.padโ pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's grouping.regroup_exactโ insert NOPs to force costly dependent insns into separate groups. insert exactly as many NOPs as needed to force an insn to a new group, according to the estimated processor grouping.numberโ insert NOPs to force costly dependent insns into separate groups. insertnumberNOPs to force an insn to a new group.
-mcall-sysvโ on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement ๐ this is the default unless you configured GCC usingpowerpc-*-eabiaix.-mcall-sysv-eabi,-mcall-eabiโ specify both-mcall-sysvand-meabioptions ๐ two-for-one, slay.-mcall-sysv-noeabiโ specify both-mcall-sysvand-mno-eabioptions.-mcall-aixdescโ on System V.4 and embedded PowerPC systems, compile code for the AIX operating system ๐ธ-mcall-linuxโ on System V.4 and embedded PowerPC systems, compile code for the Linux-based GNU system ๐ง-mcall-freebsdโ on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system ๐-mcall-netbsdโ on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system ๐-mcall-openbsdโ on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system ๐ก-mtraceback=traceback_typeโ select the type of traceback table ๐ valid values fortraceback_typearefull,part, andno.-maix-struct-returnโ return all structures in memory (as specified by the AIX ABI) ๐ฆ-msvr4-struct-returnโ return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI) โจ-mabi=abi-typeโ extend the current ABI with a particular extension, or remove such extension ๐ valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default.-mabi=ibmlongdoubleโ change the current ABI to use IBM extended-precisionlong double๐ซถ this is not likely to work if your system defaults to using IEEE extended-precisionlong double. if you change thelong doubletype from IEEE extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. requires-mlong-double-128to be enabled.-mabi=ieeelongdoubleโ change the current ABI to use IEEE extended-precisionlong doubleโจ this is not likely to work if your system defaults to using IBM extended-precisionlong double. if you change thelong doubletype from IBM extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. requires-mlong-double-128to be enabled.-mabi=elfv1โ change the current ABI to use the ELFv1 ABI ๐ this is the default ABI for big-endian PowerPC 64-bit Linux. overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐ญ-mabi=elfv2โ change the current ABI to use the ELFv2 ABI ๐ this is the default ABI for little-endian PowerPC 64-bit Linux. overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐ฅ-mgnu-attribute,-mno-gnu-attributeโ emit.gnu_attributeassembly directives to set tag/value pairs in a.gnu.attributessection that specify ABI variations in function parameters or return values ๐-mprototype,-mno-prototypeโ on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped ๐ otherwise, the compiler must insert an instruction before every non-prototyped call to set or clear bit 6 of the condition code register (CR) to indicate whether floating-point values are passed in the floating-point registers in case the function takes variable arguments. with-mprototype, only calls to prototyped variable argument functions set or clear the bit.-msimโ on embedded PowerPC systems, assume that the startup module is calledsim-crt0.oand that the standard C libraries arelibsim.aandlibc.a๐ธ this is the default forpowerpc-*-eabisimconfigurations.-mmvmeโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibmvme.aandlibc.a๐ฆ-madsโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.aโจ-myellowknifeโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a๐-mvxworksโ on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system ๐-membโ on embedded PowerPC systems, set thePPC_EMBbit in the ELF flags header to indicate that eabi extended relocations are used ๐ฏ-meabi,-mno-eabiโ on System V.4 and embedded PowerPC systems do (do not) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications ๐ selecting-meabimeans that the stack is aligned to an 8-byte boundary, a function__eabiis called frommainto set up the EABI environment, and the-msdataoption can use bothr2andr13to point to two separate small data areas ๐ selecting-mno-eabimeans that the stack is aligned to a 16-byte boundary, no EABI initialization function is called frommain, and the-msdataoption only usesr13to point to a single small data area. the-meabioption is on by default if you configured GCC using one of thepowerpc*-*-eabi*options.-msdata=eabiโ on System V.4 and embedded PowerPC systems, put small initializedconstglobal and static data in the.sdata2section, which is pointed to by registerr2โจ put small initialized non-constglobal and static data in the.sdatasection, which is pointed to by registerr13. put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. the-msdata=eabioption is incompatible with the-mrelocatableoption ๐ the-msdata=eabioption also sets the-memboption.-msdata=sysvโ on System V.4 and embedded PowerPC systems, put small global and static data in the.sdatasection, which is pointed to by registerr13๐ put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. the-msdata=sysvoption is incompatible with the-mrelocatableoption.-msdata=default,-msdataโ on System V.4 and embedded PowerPC systems, if-meabiis used, compile code the same as-msdata=eabi, otherwise compile code the same as-msdata=sysv๐-msdata=dataโ on System V.4 and embedded PowerPC systems, put small global data in the.sdatasection ๐ put small uninitialized global data in the.sbsssection. do not use registerr13to address small data however. this is the default behavior unless other-msdataoptions are used.-msdata=none,-mno-sdataโ on embedded PowerPC systems, put all initialized global and static data in the.datasection, and all uninitialized data in the.bsssection ๐ซถ-mreadonly-in-sdataโ put read-only objects in the.sdatasection as well ๐ธ this is the default.-mblock-move-inline-limit=numโ inline all block moves (such as calls tomemcpyor structure copies) less than or equal tonumbytes ๐ the minimum value fornumis 32 bytes on 32-bit targets and 64 bytes on 64-bit targets. the default value is target-specific.-mblock-compare-inline-limit=numโ generate non-looping inline code for all block compares (such as calls tomemcmpor structure compares) less than or equal tonumbytes ๐ฆ ifnumis0, all inline expansion (non-loop and loop) of block compare is disabled. the default value is target-specific.-mblock-compare-inline-loop-limit=numโ generate an inline expansion using loop code for all block compares that are less than or equal tonumbytes, but greater than the limit for non-loop inline block compare expansion โจ if the block length is not constant, at mostnumbytes will be compared beforememcmpis called to compare the remainder of the block. the default value is target-specific.-mstring-compare-inline-limit=numโ so this one caps how many bytes of string comparison get inlined: it compares at most num string bytes with inline code. If the difference (or the end of the string) isn't found by the time the inline compare ends, a call to"strcmp"or"strncmp"handles the rest of the comparison for you. The default is 64 bytes. ๐-G numโ on embedded PowerPC systems, this drops global and static items that are less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS section. By default, num is8. The-G numswitch also gets passed along to the linker. And listen: all modules should be compiled with the same-G numvalue โ keep it consistent, bestie, or things get weird. โจ-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, these do (or do not) emit register names in the assembly language output using symbolic forms.-mlongcall,-mno-longcallโ by default this assumes all calls are far away, so a longer and more expensive calling sequence is required. This is needed for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call gets generated if the compiler knows the call can't possibly be that far away. You can override this setting with the"shortcall"function attribute, or with#pragma longcall(0).
Some linkers can detect out-of-range calls and generate glue code on the fly. On those systems, long calls are unnecessary and just generate slower code. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. There are plans to add this feature to the GNU linker for 32-bit PowerPC systems too.
On PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, GCC can generate long calls using an inline PLT call sequence (peep -mpltseq). But PowerPC with -mbss-plt and PowerPC64 ELFv1 (big-endian) do not support inline PLT calls. ๐
On Darwin/PPC systems, #pragma longcall generates "jbsr callee, L42", plus a branch island (glue code). Those two target addresses represent the callee and the branch island. The Darwin/PPC linker prefers the first address and generates a "bl callee" if the PPC "bl" instruction reaches the callee directly; otherwise, the linker generates "bl L42" to call the branch island. The branch island gets appended to the body of the calling function; it computes the full 32-bit address of the callee and jumps to it.
On Mach-O (Darwin) systems, this option directs the compiler to emit the glue for every direct call, and the Darwin linker decides whether to use it or discard it.
In the future, GCC may ignore all longcall specifications when the linker is known to generate glue. ๐ฎ
-mpltseq,-mno-pltseqโ implement (or don't implement)-fno-pltand long calls using an inline PLT call sequence that supports lazy linking and long calls to functions in dlopen'd shared libraries. Inline PLT calls are only supported on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, and they're enabled by default if that support is detected when configuring GCC โ and for 32-bit PowerPC specifically, if GCC was configured with--enable-secureplt. Heads up:-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together. ๐-mtls-markers,-mno-tls-markersโ mark (or don't mark) calls to"__tls_get_addr"with a relocation specifying the function argument. That relocation lets the linker reliably associate the function call with the argument setup instructions for TLS optimization, which in turn lets GCC schedule the sequence better. โจ-mrecip,-mno-recipโ this option enables use of the reciprocal estimate and reciprocal square root estimate instructions, with extra Newton-Raphson steps to boost precision, instead of doing a divide or square root and divide for floating-point arguments. You should use the-ffast-mathoption when using-mrecipโ or at least-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math. ngl, note that while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision can drop by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994) for reciprocal square roots. ๐-mrecip=optโ this one controls which reciprocal estimate instructions may actually be used. opt is a comma-separated list of options, which may be preceded by a"!"to invert the option:allโ enable all estimate instructions. ๐defaultโ enable the default instructions, equivalent to-mrecip.noneโ disable all estimate instructions, equivalent to-mno-recip.divโ enable the reciprocal approximation instructions for both single and double precision.divfโ enable the single-precision reciprocal approximation instructions.divdโ enable the double-precision reciprocal approximation instructions.rsqrtโ enable the reciprocal square root approximation instructions for both single and double precision.rsqrtfโ enable the single-precision reciprocal square root approximation instructions.rsqrtdโ enable the double-precision reciprocal square root approximation instructions.
So for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions except for the "FRSQRTE", "XSRSQRTEDP", and "XVRSQRTEDP" instructions which handle the double-precision reciprocal square root calculations. cute, right? ๐
-mrecip-precision,-mno-recip-precisionโ assume (or don't assume) that the reciprocal estimate instructions provide higher-precision estimates than the PowerPC ABI mandates. Selecting-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precision. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they don't provide an estimate that converges after three steps. ๐-mveclibabi=typeโ specifies the ABI type to use for vectorizing intrinsics using an external library. The only type supported at present ismass, which says to use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using external libraries. GCC currently emits calls to"acosd2","acosf4","acoshd2","acoshf4","asind2","asinf4","asinhd2","asinhf4","atan2d2","atan2f4","atand2","atanf4","atanhd2","atanhf4","cbrtd2","cbrtf4","cosd2","cosf4","coshd2","coshf4","erfcd2","erfcf4","erfd2","erff4","exp2d2","exp2f4","expd2","expf4","expm1d2","expm1f4","hypotd2","hypotf4","lgammad2","lgammaf4","log10d2","log10f4","log1pd2","log1pf4","log2d2","log2f4","logd2","logf4","powd2","powf4","sind2","sinf4","sinhd2","sinhf4","sqrtd2","sqrtf4","tand2","tanf4","tanhd2", and"tanhf4"when generating code for power7. Both-ftree-vectorizeand-funsafe-math-optimizationsmust also be enabled. And the MASS libraries must be specified at link time. ๐ฅ-mfriz,-mno-frizโ generate (or don't generate) the"friz"instruction when the-funsafe-math-optimizationsoption is used to optimize rounding of floating-point values to 64-bit integer and back to floating point. Fair warning bestie: the"friz"instruction does not return the same value if the floating-point number is too large to fit in an integer. ๐ญ-mpointers-to-nested-functions,-mno-pointers-to-nested-functionsโ generate (or don't generate) code to load up the static chain register ("r11") when calling through a pointer on AIX and 64-bit Linux systems where a function pointer points to a 3-word descriptor giving the function address, the TOC value to be loaded in register"r2", and the static chain value to be loaded in register"r11".-mpointers-to-nested-functionsis on by default. And heads up: you cannot call through pointers to nested functions, or pointers to functions compiled in other languages that use the static chain, if you're using-mno-pointers-to-nested-functions. ๐-msave-toc-indirect,-mno-save-toc-indirectโ generate (or don't generate) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. If the TOC value isn't saved in the prologue, it gets saved just before the call through the pointer. The-mno-save-toc-indirectoption is the default.-mcompat-align-parm,-mno-compat-align-parmโ generate (or don't generate) code to pass structure parameters with a maximum alignment of 64 bits, for compatibility with older versions of GCC.
Older versions of GCC (prior to 4.9.0) incorrectly did not align a structure parameter on a 128-bit boundary when that structure contained a member requiring 128-bit alignment. This is fixed in more recent versions of GCC. This option may be used to generate code that's compatible with functions compiled with older versions of GCC. ๐ซถ
The -mno-compat-align-parm option is the default.
-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offset,-mstack-protector-guard-symbol=symbolโ generate stack protection code using a canary at guard. Supported locations areglobalfor global canary, ortlsfor per-thread canary in the TLS block (the default with GNU libc version2.4or later).
With that latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as the base register for reading the canary, and from what offset from that base register. The default for those is as specified in the relevant ABI. And -mstack-protector-guard-symbol=symbol overrides the offset with a symbol reference to a canary in the TLS block. โจ
-mpcrel,-mno-pcrelโ generate (or don't generate) pc-relative addressing. The-mpcreloption requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled. ๐-mprefixed,-mno-prefixedโ generate (or don't generate) addressing modes using prefixed load and store instructions. The-mprefixedoption requires that the option-mcpu=power10(or later) is enabled. ๐-mmma,-mno-mmaโ generate (or don't generate) the MMA instructions. The-mmmaoption requires that the option-mcpu=power10(or later) is enabled. ๐-mrop-protect,-mno-rop-protectโ turns ROP protection instructions on (or off) when the target processor can actually back it ๐ช. Heads up fr: right now this option also disables the shrink-wrap optimization (-fshrink-wrap), it's a package deal bestie.-mprivileged,-mno-privilegedโ generate (or don't generate) code that will run in privileged state ๐. That's the whole vibe.-mblock-ops-unaligned-vsx,-mno-block-ops-unaligned-vsxโ generate (or don't) unaligned vsx loads and stores for inline expansion ofmemcpyandmemmoveโจ.--param rs6000-vect-unroll-limit=โ the vectorizer checks with target info to figure out whether unrolling the main vectorized loop would even be worth it, and by how much ๐. This parameter sets the upper bound of how much the vectorizer will unroll the main loop. The default value is four, lowkey iconic.
๐ RX Options ๐
These command-line options are defined for RX targets, bestie:
-m64bit-doubles,-m32bit-doublesโ make thedoubledata type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles. Note that RX floating-point hardware only works on 32-bit values, which is literally why the default is-m32bit-doubles๐ .-fpu,-nofpuโ enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series ๐.
Floating-point instructions are only generated for 32-bit floating-point values, however, so the FPU hardware is not used for doubles if the -m64bit-doubles option is used, no cap.
Note: If the-fpuoption is enabled then-funsafe-math-optimizationsis also enabled automatically ๐ญ. This is because the RX FPU instructions are themselves unsafe. It's giving chaos but okay.
-mcpu=nameโ selects the type of RX CPU to be targeted. Currently three types are supported: the generic RX600 and RX200 series hardware, and the specific RX610 CPU. The default is RX600 โจ.
The only difference between RX600 and RX610 is that the RX610 does not support the MVTIPL instruction ๐ซ.
The RX200 series does not have a hardware floating-point unit and so -nofpu is enabled by default when this type is selected.
-mbig-endian-data,-mlittle-endian-dataโ store data (but not code) in the big-endian format. The default is-mlittle-endian-data, i.e. to store data in the little-endian format ๐.-msmall-data-limit=Nโ specifies the maximum size in bytes of global and static variables which can be placed into the small data area ๐. Using the small data area can lead to smaller and faster code, but the size of the area is limited and it is up to the programmer to ensure that the area does not overflow. Also, when the small data area is used, one of the RX's registers (usuallyr13) is reserved for use pointing to this area, so it is no longer available for use by the compiler. This could result in slower and/or larger code if variables are pushed onto the stack instead of being held in this register ๐.
Note, common variables (variables that have not been initialized) and constants are not placed into the small data area as they are assigned to other sections in the output executable.
The default value is zero, which disables this feature. Note, this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register. It is up to the programmer to experiment and discover whether this feature is of benefit to their program ๐. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen.
-msim,-mno-simโ use the simulator runtime. The default is to use the libgloss board-specific runtime ๐ฆ.-mas100-syntax,-mno-as100-syntaxโ when generating assembler output, use a syntax that is compatible with Renesas's AS100 assembler โจ. This syntax can also be handled by the GAS assembler, but it has some restrictions so it is not generated by default.-mmax-constant-size=Nโ specifies the maximum size, in bytes, of a constant that can be used as an operand in a RX instruction. Although the RX instruction set does allow constants of up to 4 bytes in length to be used in instructions, a longer value equates to a longer instruction ๐. Thus in some circumstances it can be beneficial to restrict the size of constants that are used in instructions. Constants that are too big are instead placed into a constant pool and referenced via register indirection.
The value N can be between 0 and 4. A value of 0 (the default) or 4 means that constants of any size are allowed ๐ .
-mrelaxโ enable linker relaxation. Linker relaxation is a process whereby the linker attempts to reduce the size of a program by finding shorter versions of various instructions โ๏ธ. Disabled by default.-mint-register=Nโ specify the number of registers to reserve for fast interrupt handler functions. The value N can be between 0 and 4. A value of 1 means that registerr13is reserved for the exclusive use of fast interrupt handlers. A value of 2 reservesr13andr12. A value of 3 reservesr13,r12andr11, and a value of 4 reservesr13throughr10. A value of 0, the default, does not reserve any registers ๐.-msave-acc-in-interruptsโ specifies that interrupt handler functions should preserve the accumulator register ๐. This is only necessary if normal code might use the accumulator register, for example because it performs 64-bit multiplications. The default is to ignore the accumulator as this makes the interrupt handlers faster โก.-mpid,-mno-pidโ enables the generation of position independent data ๐. When enabled, any access to constant data is done via an offset from a base address held in a register. This allows the location of constant data to be determined at run time without requiring the executable to be relocated, which is a benefit to embedded applications with tight memory constraints. Data that can be modified is not affected by this option.
Note, using this feature reserves a register, usually r13, for the constant data base address. This can result in slower and/or larger code, especially in complicated functions ๐.
The actual register chosen to hold the constant data base address depends upon whether the -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register r13 and proceeding downwards, registers are allocated first to satisfy the requirements of -mint-register, then -mpid and finally -msmall-data-limit ๐ง. Thus it is possible for the small data area register to be r8 if both -mint-register=4 and -mpid are specified on the command line.
By default this feature is not enabled. The default can be restored via the -mno-pid command-line option โจ.
-mno-warn-multiple-fast-interrupts,-mwarn-multiple-fast-interruptsโ prevents GCC from issuing a warning message if it finds more than one fast interrupt handler when it is compiling a file ๐. The default is to issue a warning for each extra fast interrupt handler found, as the RX only supports one such interrupt.-mallow-string-insns,-mno-allow-string-insnsโ enables or disables the use of the string manipulation instructionsSMOVF,SCMPU,SMOVB,SMOVU,SUNTIL,SWHILEand also theRMPAinstruction ๐ . These instructions may prefetch data, which is not safe to do if accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more information.)
The default is to allow these instructions, but it is not possible for GCC to reliably detect all circumstances where a string instruction might be used to access an I/O register, so their use cannot be disabled automatically ๐ญ. Instead it is reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space.
When the instructions are enabled, GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__, otherwise it defines the symbol __RX_DISALLOW_STRING_INSNS__ ๐ธ.
-mjsr,-mno-jsrโ use only (or not only)JSRinstructions to access functions. This option can be used when code size exceeds the range ofBSRinstructions ๐. Note that-mno-jsrdoes not mean to not useJSRbut instead means that any type of branch may be used, periodt.
Note: The generic GCC command-line option-ffixed-reghas special significance to the RX port when used with theinterruptfunction attribute ๐ซถ. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registersr10,r11,r12and/orr13and only provided that the normal use of the corresponding registers have been restricted via the-ffixed-regor-mint-registercommand-line options.
๐ S/390 and zSeries Options ๐
These are the -m options defined for the S/390 and zSeries architecture, bestie ๐.
-mhard-float,-msoft-floatโ use (do not use) the hardware floating-point instructions and registers for floating-point operations ๐ฅ. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. When-mhard-floatis specified, the compiler generates IEEE floating-point instructions. This is the default โจ.-mhard-dfp,-mno-hard-dfpโ use (do not use) the hardware decimal-floating-point instructions for decimal-floating-point operations ๐. When-mno-hard-dfpis specified, functions inlibgcc.aare used to perform decimal-floating-point operations. When-mhard-dfpis specified, the compiler generates decimal-floating-point hardware instructions. This is the default for-march=z9-ecor higher ๐.-mlong-double-64,-mlong-double-128โ these switches control the size oflong doubletype ๐. A size of 64 bits makes thelong doubletype equivalent to thedoubletype. This is the default.-mbackchain,-mno-backchainโ store (do not store) the address of the caller's frame as backchain pointer into the callee's stack frame ๐ฆ. A backchain may be needed to allow debugging using tools that do not understand DWARF call frame information. When-mno-packed-stackis in effect, the backchain pointer is stored at the bottom of the stack frame; when-mpacked-stackis in effect, the backchain is placed into the topmost word of the 96/160 byte register save area โญ.
In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain. BUT โ and this is the tea โ using the backchain for debugging purposes usually requires that the whole binary is built with -mbackchain. Also note: the combo of -mbackchain, -mpacked-stack and -mhard-float? Not supported, bestie, don't try it. If you wanna build a linux kernel, use -msoft-float. ๐ซถ
The default is to not maintain the backchain.
-mpacked-stack,-mno-packed-stackโ use (or don't use, no pressure) the packed stack layout. When-mno-packed-stackis specified, the compiler uses all fields of the 96/160 byte register save area only for their default purpose, and unused fields still take up stack space (wasteful, lowkey ๐ญ). When-mpacked-stackis specified, register save slots are densely packed at the top of the register save area, and unused space gets reused for other purposes โ allowing for more efficient use of the available stack space. โจ However, when-mbackchainis also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain.
As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel, use -msoft-float.
The default is to not use the packed stack layout.
-msmall-exec,-mno-small-execโ generate (or don't generate) code using the"bras"instruction to do subroutine calls. This only works reliably if the total executable size does not exceed 64k. The default is to use the"basr"instruction instead, which does not have this limitation. ๐-m64,-m31โ when-m31is specified, generate code compliant to the GNU/Linux for S/390 ABI. When-m64is specified, generate code compliant to the GNU/Linux for zSeries ABI. This lets GCC, in particular, generate 64-bit instructions. For the s390 targets, the default is-m31, while the s390x targets default to-m64.-mzarch,-mesaโ when-mzarchis specified, generate code using the instructions available on z/Architecture. When-mesais specified, generate code using the instructions available on ESA/390. Heads up bestie:-mesais not possible with-m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is-mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is-mzarch.-mhtm,-mno-htmโ the-mhtmoption enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions.-mhtmis enabled by default when using-march=zEC12. ๐ฅ-mvx,-mno-vxโ when-mvxis specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context, a GAS.gnu_attributecommand will be added to mark the resulting binary with the ABI used.-mvxis enabled by default when using-march=z13.-mzvector,-mno-zvectorโ the-mzvectoroption enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support forvectorto be used as a keyword to define vector type variables and arguments.vectoris only available when GNU extensions are enabled โ it will not be expanded when requesting strict standard compliance, e.g. with-std=c99. In addition to the GCC low-level builtins,-mzvectorenables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. In order to make use of these builtins, the header filevecintrin.hneeds to be included.-mzvectoris disabled by default.-mmvcle,-mno-mvcleโ generate (or don't generate) code using the"mvcle"instruction to perform block moves. When-mno-mvcleis specified, use a"mvc"loop instead. This is the default unless optimizing for size.-mdebug,-mno-debugโ print (or don't print) additional debug information when compiling. The default is to not print debug information.- *
-march=cpu-type* โ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. Possible values for cpu-type arez900/arch5,z990/arch6,z9-109,z9-ec/arch7,z10/arch8,z196/arch9,zEC12,z13/arch11,z14/arch12,z15/arch13,z16/arch14, andnative.
The default is -march=z900.
Specifying native as the cpu type can be used to select the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor. ๐
-mtune=cpu-type โ tune to cpu-type everything applicable about the generated code, *except for the ABI and the set of available instructions. The list of *cpu-type values is the same as for-march. The default is the value used for-march.-mtpf-trace,-mno-tpf-traceโ generate code that adds (or does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS.-mtpf-trace-skip,-mno-tpf-trace-skipโ generate code that changes (or does not change) the default branch targets enabled by-mtpf-traceto point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying-mtpf-trace.-mfused-madd,-mno-fused-maddโ generate code that uses (or does not use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used.- *
-mwarn-framesize=framesize* โ emit a warning if the current function exceeds the given frame size. Because this is a compile-time check, it doesn't need to be a real problem when the program runs. It is intended to identify functions that most probably cause a stack overflow. It's useful to be used in an environment with limited stack size, e.g. the linux kernel. -mwarn-dynamicstackโ emit a warning if the function calls"alloca"or uses dynamically-sized arrays. This is generally a bad idea with a limited stack size. โ ๏ธ-mstack-guard=stack-guard, *-mstack-size=stack-size* โ if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows *downward, bestie ๐). If the *stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to be used to help debugging stack overflow problems. The additionally emitted code causes only little overhead and hence can also be used in production-like systems without greater performance degradation. The given values have to be exact powers of 2, and stack-size has to be greater than stack-guard without exceeding 64k. In order to be efficient, the extra code makes the assumption that the stack starts at an address aligned to the value given by stack-size. The stack-guard option can only be used in conjunction with stack-size.- *
-mhotpatch=pre-halfwords*,post-halfwords โ if the hotpatch option is enabled, a"hot-patching"function prologue is generated for all functions in the compilation unit. The funtion label is prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label,2 * post-halfwordsbytes are appended, using the largest NOP like instructions the architecture allows (maximum 1000000).
If both arguments are zero, hotpatching is disabled.
This option can be overridden for individual functions with the "hotpatch" attribute.
๐ธ SH Options ๐ธ
These -m options are defined for the SH implementations:
-m1โ generate code for the SH1.-m2โ generate code for the SH2.-m2eโ generate code for the SH2e.-m2a-nofpuโ generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.-m2a-single-onlyโ generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.-m2a-singleโ generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.-m2aโ generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.-m3โ generate code for the SH3.-m3eโ generate code for the SH3e.-m4-nofpuโ generate code for the SH4 without a floating-point unit.-m4-single-onlyโ generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.-m4-singleโ generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.-m4โ generate code for the SH4.-m4-100โ generate code for SH4-100.-m4-100-nofpuโ generate code for SH4-100 in such a way that the floating-point unit is not used.-m4-100-singleโ generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.-m4-100-single-onlyโ generate code for SH4-100 in such a way that no double-precision floating-point operations are used.-m4-200โ generate code for SH4-200.-m4-200-nofpuโ generate code for SH4-200 without in such a way that the floating-point unit is not used.-m4-200-singleโ generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.-m4-200-single-onlyโ okay bestie, this one generates code for the SH4-200 and does it in such a way that no double-precision floating-point operations are used. Single precision only, no cap. ๐-m4-300โ Generate code for SH4-300. That's it, that's the vibe. โจ-m4-300-nofpuโ Generate code for SH4-300 in such a way that the floating-point unit is not used. FPU? Not invited. ๐ซ-m4-300-singleโ Generate code for SH4-300 in such a way that no double-precision floating-point operations are used. ๐-m4-300-single-onlyโ Same energy as above: generate code for SH4-300 in such a way that no double-precision floating-point operations are used. ๐-m4-340โ Generate code for SH4-340 (no MMU, no FPU). It's giving bare metal. ๐-m4-500โ Generate code for SH4-500 (no FPU). It passes-isa=sh4-nofputo the assembler. Slay. โจ-m4a-nofpuโ Generate code for the SH4al-dsp, or for a SH4a in such a way that the floating-point unit is not used. ๐ฆ-m4a-single-onlyโ Generate code for the SH4a, in such a way that no double-precision floating-point operations are used. ๐-m4a-singleโ Generate code for the SH4a assuming the floating-point unit is in single-precision mode by default. ๐-m4aโ Generate code for the SH4a. Iconic. ๐-m4alโ Same as-m4a-nofpu, except that it implicitly passes-dspto the assembler. GCC doesn't generate any DSP instructions at the moment. Noted, bestie. ๐-mbโ Compile code for the processor in big-endian mode. Big endian energy. ๐-mlโ Compile code for the processor in little-endian mode. Tiny endian vibes. ๐ญ-mdalignโ Align doubles at 64-bit boundaries. Note that this changes the calling conventions, and thus some functions from the standard C library do not work unless you recompile it first with-mdalign. So like, recompile or perish. ๐ญ-mrelaxโ Shorten some address references at link time, when possible; uses the linker option-relax. Chill. ๐ง-mbigtableโ Use 32-bit offsets inswitchtables. The default is to use 16-bit offsets. Size matters. ๐-mbitopsโ Enable the use of bit manipulation instructions on SH2A. Bit twiddling supremacy. ๐ช-mfmovdโ Enable the use of the instructionfmovd. Check-mdalignfor alignment constraints. Don't skip the alignment check, babe. ๐-mrenesasโ Comply with the calling conventions defined by Renesas. Respect. ๐ซถ-mno-renesasโ Comply with the calling conventions defined for GCC before the Renesas conventions were available. This option is the default for all targets of the SH toolchain. Old school cool. ๐-mnomacsaveโ Mark theMACregister as call-clobbered, even if-mrenesasis given. TheMACregister said no thanks. ๐-mieee,-mno-ieeeโ Control the IEEE compliance of floating-point comparisons, which affects the handling of cases where the result of a comparison is unordered. By default-mieeeis implicitly enabled. If-ffinite-math-onlyis enabled,-mno-ieeeis implicitly set, which results in faster floating-point greater-equal and less-equal comparisons. The implicit settings can be overridden by specifying either-mieeeor-mno-ieee. IEEE drama, but make it fast. โก-minline-ic_invalidateโ Inline code to invalidate instruction cache entries after setting up nested function trampolines. This option has no effect if-musermodeis in effect and the selected code generation option (e.g.-m4) does not allow the use of theicbiinstruction. If the selected code generation option does not allow the use of theicbiinstruction, and-musermodeis not in effect, the inlined code manipulates the instruction cache address array directly with an associative write. This not only requires privileged mode at run time, but it also fails if the cache line had been mapped via the TLB and has become unmapped. Careful, bestie. โ ๏ธ-misizeโ Dump instruction size and location in the assembly code. For the nosy girlies who need receipts. ๐-mpadstructโ This option is deprecated. It pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. Do not use, fr fr. ๐ซ-matomic-model=modelโ Sets the model of atomic operations and additional parameters as a comma separated list. For details on the atomic built-in functions see __atomic Builtins. The following models and parameters are supported:noneโ Disable compiler generated atomic sequences and emit library calls for atomic operations. This is the default if the target is notsh*-*-linux*.soft-gusaโ Generate GNU/Linux compatible gUSA software atomic sequences for the atomic built-in functions. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for SH3* and SH4* single-core systems. This option is enabled by default when the target issh*-*-linux*and SH3* or SH4*. When the target is SH4A, this option also partially utilizes the hardware atomic instructionsmovli.landmovco.lto create more efficient code, unlessstrictis specified.soft-tcbโ Generate software atomic sequences that use a variable in the thread control block. This is a variation of the gUSA sequences which can also be used on SH1* and SH2* targets. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for single-core systems. When using this model, thegbr-offset=parameter has to be specified as well.soft-imaskโ Generate software atomic sequences that temporarily disable interrupts by settingSR.IMASK = 1111. This model works only when the program runs in privileged mode and is only suitable for single-core systems. Additional support from the interrupt/exception handling code of the system is not required. This model is enabled by default when the target issh*-*-linux*and SH1* or SH2*.hard-llcsโ Generate hardware atomic sequences using themovli.landmovco.linstructions only. This is only available on SH4A and is suitable for multi-core systems. Since the hardware instructions support only 32 bit atomic variables, access to 8 or 16 bit variables is emulated with 32 bit accesses. Code compiled with this option is also compatible with other software atomic model interrupt/exception handling systems if executed on an SH4A system. Additional support from the interrupt/exception handling code of the system is not required for this model.gbr-offset=โ This parameter specifies the offset in bytes of the variable in the thread control block structure that should be used by the generated atomic sequences when thesoft-tcbmodel has been selected. For other models this parameter is ignored. The specified value must be an integer multiple of four and in the range 0-1020.strictโ This parameter prevents mixed usage of multiple atomic models, even if they are compatible, and makes the compiler generate atomic sequences of the specified model only.
-mtasโ Generate thetas.bopcode for__atomic_test_and_set. Notice that depending on the particular hardware and software configuration this can degrade overall performance due to the operand cache line flushes that are implied by thetas.binstruction. On multi-core SH4A processors thetas.binstruction must be used with caution since it can result in data corruption for certain cache configurations. This one is spicy. ๐ถ๏ธ-mprefergotโ When generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table. GOT > PLT, apparently. ๐-musermode,-mno-usermodeโ Don't allow (allow) the compiler generating privileged mode code. Specifying-musermodealso implies-mno-inline-ic_invalidateif the inlined code would not work in user mode.-musermodeis the default when the target issh*-*-linux*. If the target is SH1* or SH2*,-musermodehas no effect, since there is no user mode. No user mode, no problem. ๐-multcost=numberโ Set the cost to assume for a multiply insn. Multiplication has a price, bestie. ๐ธ-mdiv=strategyโ Set the division strategy to be used for integer division operations.strategycan be one of:call-div1โ Calls a library function that uses the single-step division instructiondiv1to perform the operation. Division by zero calculates an unspecified result and does not trap. This is the default except for SH4, SH2A and SHcompact.call-fpโ Calls a library function that performs the operation in double precision floating point. Division by zero causes a floating-point exception. This is the default for SHcompact with FPU. Specifying this for targets that do not have a double precision FPU defaults tocall-div1.call-tableโ Calls a library function that uses a lookup table for small divisors and thediv1instruction with case distinction for larger divisors. Division by zero calculates an unspecified result and does not trap. This is the default for SH4. Specifying this for targets that do not have dynamic shift instructions defaults tocall-div1.- When a division strategy has not been specified the default strategy is selected based on the current target. For SH2A the default strategy is to use the
divsanddivuinstructions instead of library function calls.
-maccumulate-outgoing-argsโ Reserve space once for outgoing arguments in the function prologue rather than around each call. Generally beneficial for performance and size. Also needed for unwinding to avoid changing the stack frame around conditional code. Efficient queen. ๐-mdivsi3_libfunc=nameโ Set the name of the library function used for 32-bit signed division toname. This only affects the name used in the call division strategies, and the compiler still expects the same sets of input/output/clobbered registers as if this option were not present. Rename responsibly. โจ-mfixed-range=register-rangeโ Generate code treating the given register range as fixed registers. A fixed register is one that the register allocator cannot use. This is useful when compiling kernel code. A register range is specified as two registers separated by a dash. Multiple register ranges can be specified separated by a comma. Kernel girlies, this one's for you. ๐ซถ-mbranch-cost=numโ Assumenumto be the cost for a branch instruction. Higher numbers make the compiler try to generate more branch-free code if possible. If not specified the value is selected depending on the processor type that is being compiled for. Branch out, but make it efficient. ๐ฆ-mzdcbranch,-mno-zdcbranchโ okay so bestie, do we assume the zero displacement conditional branch instructionsbtandbfare fast, or do we not? That's literally the whole question. Drop-mzdcbranchand the compiler starts preferring zero displacement branch code sequences like the little overachiever it is ๐ . This is turned on by default when you're generating code for SH4 and SH4A. And if you want it gone-gone, you can explicitly turn it off by passing-mno-zdcbranch. Periodt.-mcbranch-force-delay-slotโ this one forces the usage of delay slots for conditional branches, and if it can't find a suitable instruction to put there, it just stuffs the delay slot with anop๐ญ. By default this option is disabled. You'd enable it to work around hardware bugs, like the ones found in the original SH7055. Hardware being messy is so not the vibe.-mfused-madd,-mno-fused-maddโ generate code that uses (or does not use) the floating-point multiply and accumulate instructions โจ. These instructions get generated by default if hardware floating point is being used. And heads up: the machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. Glow-up behavior fr fr.-mfsca,-mno-fscaโ allow or disallow the compiler to emit thefscainstruction for sine and cosine approximations ๐ธ. The option-mfscamust be used in combination with-funsafe-math-optimizations. It's enabled by default when generating code for SH4A. And using-mno-fscadisables sine and cosine approximations even if-funsafe-math-optimizationsis in effect. No sine for you, bestie ๐.-mfsrra,-mno-fsrraโ allow or disallow the compiler to emit thefsrrainstruction for reciprocal square root approximations ๐ฆ. The option-mfsrramust be used in combination with-funsafe-math-optimizationsand-ffinite-math-only. It's enabled by default when generating code for SH4A. Using-mno-fsrradisables reciprocal square root approximations even if-funsafe-math-optimizationsand-ffinite-math-onlyare in effect. Two options deep and it still says no? iconic behavior ๐.-mpretend-cmoveโ prefer zero-displacement conditional branches for conditional move instruction patterns. Result? Potentially faster code on the SH4 processor ๐ฅ. We love a speed-up.-mfdpicโ generate code using the FDPIC ABI. That's it, that's the whole thing ๐.
โ๏ธ Solaris 2 Options โ๏ธ
These -m options are supported on Solaris 2:
-mclear-hwcapโ-mclear-hwcaptells the compiler to remove the hardware capabilities generated by the Solaris assembler ๐. This is only necessary when object files use ISA extensions that aren't supported by the current machine, but check at runtime whether or not to use them.-mimpure-textโ-mimpure-text, used in addition to-shared, tells the compiler to not pass-z textto the linker when linking a shared object. Using this option, you can link position-dependent code into a shared object.
And-mimpure-textsuppresses the "relocations remain against allocatable but non-writable sections" linker error message ๐. However โ and this is the important part โ the necessary relocations trigger copy-on-write, and the shared object is not actually shared across processes. Instead of using-mimpure-text, you should compile all source code with-fpicor-fPIC. Do it the right way bestie, I'm begging ๐ซถ.
These switches are supported in addition to the above on Solaris 2:
-pthreadsโ this is a synonym for-pthread. Same thing, different name, no cap โจ.
๐ช SPARC Options ๐ช
These -m options are supported on the SPARC:
-mno-app-regs,-mapp-regsโ specify-mapp-regsto generate output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications. Like the global register 1, each global register 2 through 4 is then treated as an allocable register that is clobbered by function calls. This is the default.
To be fully SVR4 ABI-compliant at the cost of some performance loss, specify -mno-app-regs. You should compile libraries and system software with this option ๐.
-mflat,-mno-flatโ with-mflat, the compiler does not generate save/restore instructions and uses a "flat" or single register window model. This model is compatible with the regular register window model. The local registers and the input registers (0--5) are still treated as "call-saved" registers and are saved on the stack as needed.
With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode ๐
.
-mfpu,-mhard-floatโ generate output containing floating-point instructions. This is the default.-mno-fpu,-msoft-floatโ generate output containing library calls for floating point.
โ ๏ธ Warning: the requisite libraries are not available for all SPARC targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. The embedded targetssparc-*-aoutandsparclite-*-*do provide software floating-point support.
Also, -msoft-float changes the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float in order for this to work. All of it or none of it, that's the rule ๐.
-mhard-quad-floatโ generate output containing quad-word (long double) floating-point instructions.-msoft-quad-floatโ generate output containing library calls for quad-word (long double) floating-point instructions. The functions called are those specified in the SPARC ABI. This is the default.
As of this writing, there are no SPARC implementations that have hardware support for the quad-word floating-point instructions. They all invoke a trap handler for one of these instructions, and then the trap handler emulates the effect of the instruction. Because of the trap handler overhead, this is much slower than calling the ABI library routines ๐ญ. Thus the -msoft-quad-float option is the default.
-mno-unaligned-doubles,-munaligned-doublesโ assume that doubles have 8-byte alignment. This is the default.
With -munaligned-doubles, GCC assumes that doubles have 8-byte alignment only if they are contained in another type, or if they have an absolute address. Otherwise, it assumes they have 4-byte alignment. Specifying this option avoids some rare compatibility problems with code generated by other compilers. It is not the default because it results in a performance loss, especially for floating-point code ๐.
-muser-mode,-mno-user-modeโ do not generate code that can only run in supervisor mode. This is relevant only for thecasainstruction emitted for the LEON3 processor. This is the default.-mfaster-structs,-mno-faster-structsโ with-mfaster-structs, the compiler assumes that structures should have 8-byte alignment. This enables the use of pairs oflddandstdinstructions for copies in structure assignment, in place of twice as manyldandstpairs. However, the use of this changed alignment directly violates the SPARC ABI ๐. Thus, it's intended only for use on targets where the developer acknowledges that their resulting code is not directly in line with the rules of the ABI. Know what you're doing, bestie.-mstd-struct-return,-mno-std-struct-returnโ with-mstd-struct-return, the compiler generates checking code in functions returning structures or unions to detect size mismatches between the two sides of function calls, as per the 32-bit ABI.
The default is -mno-std-struct-return. This option has no effect in 64-bit mode.
-mlra,-mno-lraโ enable Local Register Allocation ๐ฅ. This is the default for SPARC since GCC 7, so-mno-lraneeds to be passed to get old Reload. Nostalgia mode activated, I guess.-mcpu=cpu_type โ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type โจ. Supported values for cpu_type arev7,cypress,v8,supersparc,hypersparc,leon,leon3,leon3v7,leon5,sparclite,f930,f934,sparclite86x,sparclet,tsc701,v9,ultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7andm8.
Native Solaris and GNU/Linux toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor ๐.
Default instruction scheduling parameters are used for values that select an architecture and not an implementation. These are v7, v8, sparclite, sparclet, v9.
Here is a list of each supported architecture and their supported implementations, bestie, take notes ๐:
v7โcypress,leon3v7v8โsupersparc,hypersparc,leon,leon3,leon5sparcliteโf930,f934,sparclite86xsparcletโtsc701v9โultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7,m8
By default (unless configured otherwise), GCC generates code for the V7 variant of the SPARC architecture. With -mcpu=cypress, the compiler additionally optimizes it for the Cypress CY7C602 chip, as used in the SPARCStation/SPARCServer 3xx series. This is also appropriate for the older SPARCStation 1, 2, IPX etc.
With -mcpu=v8, GCC generates code for the V8 variant of the SPARC architecture. The only difference from V7 code is that the compiler emits the integer multiply and integer divide instructions which exist in SPARC-V8 but not in SPARC-V7. With -mcpu=supersparc, the compiler additionally optimizes it for the SuperSPARC chip, as used in the SPARCStation 10, 1000 and 2000 series ๐ฆ.
With -mcpu=sparclite, GCC generates code for the SPARClite variant of the SPARC architecture. This adds the integer multiply, integer divide step and scan (ffs) instructions which exist in SPARClite but not in SPARC-V7. With -mcpu=f930, the compiler additionally optimizes it for the Fujitsu MB86930 chip, which is the original SPARClite, with no FPU. With -mcpu=f934, the compiler additionally optimizes it for the Fujitsu MB86934 chip, which is the more recent SPARClite with FPU ๐ธ.
With -mcpu=sparclet, GCC generates code for the SPARClet variant of the SPARC architecture. This adds the integer multiply, multiply/accumulate, integer divide step and scan (ffs) instructions which exist in SPARClet but not in SPARC-V7. With -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip ๐.
With -mcpu=v9, GCC spits out code for the V9 flavor of the SPARC architecture ๐
โ that brings 64-bit integer and floating-point move instructions, 3 extra floating-point condition code registers (yes, three, count 'em), and conditional move instructions. Then with -mcpu=ultrasparc, the compiler additionally optimizes for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, it additionally optimizes for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, it additionally optimizes for Sun UltraSPARC T1 chips. With -mcpu=niagara2, it additionally optimizes for Sun UltraSPARC T2 chips. With -mcpu=niagara3, it additionally optimizes for Sun UltraSPARC T3 chips. With -mcpu=niagara4, it additionally optimizes for Sun UltraSPARC T4 chips. With -mcpu=niagara7, it additionally optimizes for Oracle SPARC M7 chips. And with -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips. (the way it just keeps going, iconic honestly ๐)
-mtune=cpu_typeโ this one sets the instruction scheduling parameters for machine type cpu_type, but lowkey refuses to set the instruction set or register set the way-mcpu=cpu_typedoes. Same values accepted as-mcpu=cpu_type, but honestly only the ones that pick out a particular CPU implementation are useful:cypress,supersparc,hypersparc,leon,leon3,leon3v7,leon5,f930,f934,sparclite86x,tsc701,ultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7andm8. Oh and with native Solaris and GNU/Linux toolchains you can also usenativeโจ-mv8plus,-mno-v8plusโ with-mv8plus, GCC generates code for the SPARC-V8+ ABI. The glow-up from the V8 ABI is that the global and out registers are treated as 64 bits wide. This is on by default on Solaris in 32-bit mode for all SPARC-V9 processors.-mvis,-mno-visโ with-mvis, GCC generates code that takes advantage of the UltraSPARC Visual Instruction Set extensions. Default is-mno-vis, bestie. Sorry.-mvis2,-mno-vis2โ with-mvis2, GCC generates code that takes advantage of version 2.0 of the UltraSPARC Visual Instruction Set extensions. Default is-mvis2when you're targeting a cpu that supports such instructions, like UltraSPARC-III and later. Heads up: setting-mvis2also sets-mvis๐ฆ-mvis3,-mno-vis3โ with-mvis3, GCC generates code that takes advantage of version 3.0 of the UltraSPARC Visual Instruction Set extensions. Default is-mvis3when targeting a cpu that supports such instructions, such as niagara-3 and later. Setting-mvis3also sets-mvis2and-mvis. It's a whole bundle, she's generous ๐-mvis4,-mno-vis4โ with-mvis4, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. Default is-mvis4when targeting a cpu that supports such instructions, such as niagara-7 and later. Setting-mvis4also sets-mvis3,-mvis2and-mvis.-mvis4b,-mno-vis4bโ with-mvis4b, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions, plus the additional VIS instructions introduced in the Oracle SPARC Architecture 2017. Default is-mvis4bwhen targeting a cpu that supports such instructions, such asm8and later. Setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvis. The whole chain, slay โจ-mcbcond,-mno-cbcondโ with-mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. Default is-mcbcondwhen targeting a CPU that supports such instructions, such as Niagara-4 and later.-mfmaf,-mno-fmafโ with-mfmaf, GCC generates code that takes advantage of the UltraSPARC Fused Multiply-Add Floating-point instructions. Default is-mfmafwhen targeting a CPU that supports such instructions, such as Niagara-3 and later ๐ฅ-mfsmuld,-mno-fsmuldโ with-mfsmuld, GCC generates code that takes advantage of the Floating-point Multiply Single to Double (FsMULd) instruction. Default is-mfsmuldwhen targeting a CPU supporting the architecture versions V8 or V9 with FPU โ with one exception,-mcpu=leon.-mpopc,-mno-popcโ with-mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. Default is-mpopcwhen targeting a CPU that supports such an instruction, such as Niagara-2 and later.-msubxc,-mno-subxcโ with-msubxc, GCC generates code that takes advantage of the UltraSPARC Subtract-Extended-with-Carry instruction. Default is-msubxcwhen targeting a CPU that supports such an instruction, such as Niagara-7 and later.-mfix-at697fโ turns on the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). Tiny bug, big yikes ๐ซถ-mfix-ut699โ turns on the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor. Two for one ๐-mfix-ut700โ turns on the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ turns on the documented workaround for the back-to-back store errata of the GR712RC processor.
Okay so these -m options are supported in addition to the above on SPARC-V9 processors in 64-bit environments ๐
-m32,-m64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits.-mcmodel=whichโ set the code model to one of:medlowโ The Medium/Low code model: 64-bit addresses, programs must be linked in the low 32 bits of memory. Programs can be statically or dynamically linked.medmidโ The Medium/Middle code model: 64-bit addresses, programs must be linked in the low 44 bits of memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.medanyโ The Medium/Anywhere code model: 64-bit addresses, programs may be linked anywhere in memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.embmedanyโ The Medium/Anywhere code model for embedded systems: 64-bit addresses, the text and data segments must be less than 2GB in size, both starting anywhere in memory (determined at link time). The global register%g4points to the base of the data segment. Programs are statically linked and PIC is not supported. No PIC?? in this economy?? ๐ญ
-mmemory-model=mem-modelโ set the memory model in force on the processor to one of:defaultโ The default memory model for the processor and operating system.rmoโ Relaxed Memory Orderpsoโ Partial Store Ordertsoโ Total Store Orderscโ Sequential Consistency
These memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's PSTATE.MM field. Very official, very iconic ๐
-mstack-bias,-mno-stack-biasโ with-mstack-bias, GCC assumes that the stack pointer, and frame pointer if present, are offset by-2047which must be added back when making stack frame references. This is the default in 64-bit mode. Otherwise, assume no such offset is present.
๐ Options for System V ๐
These extra options are available on System V Release 4 for compatibility with other compilers on those systems:
-Gโ create a shared object. It is recommended that-symbolicor-sharedbe used instead. (bestie, they're telling you to use the other ones, take the hint ๐)-Qyโ identify the versions of each tool used by the compiler, in a.identassembler directive in the output.-Qnโ refrain from adding.identdirectives to the output file (this is the default).-YP,dirsโ search the directories dirs, and no others, for libraries specified with-l.-Ym,dirโ look in the directory dir to find the M4 preprocessor. The assembler uses this option.
๐ฆ V850 Options ๐ฆ
These -m options are defined for V850 implementations:
-mlong-calls,-mno-long-callsโ treat all calls as being far away (near). If calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer.-mno-ep,-mepโ do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into theepregister, and use the shortersldandsstinstructions. The-mepoption is on by default if you optimize โจ-mno-prolog-function,-mprolog-functionโ do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. The external functions are slower, but use less code space if more than one function saves the same number of registers. The-mprolog-functionoption is on by default if you optimize.-mspaceโ try to make the code as small as possible. At present, this just turns on the-mepand-mprolog-functionoptions. Tiny code, tiny vibes ๐-mtda=nโ put static or global variables whose size is n bytes or less into the tiny data area that registereppoints to. The tiny data area can hold up to 256 bytes in total (128 bytes for byte references).-msda=nโ put static or global variables whose size is n bytes or less into the small data area that registergppoints to. The small data area can hold up to 64 kilobytes.-mzda=nโ put static or global variables whose size is n bytes or less into the first 32 kilobytes of memory.-mv850โ specify that the target processor is the V850.-mv850e3v5โ specify that the target processor is the V850E3V5. The preprocessor constant__v850e3v5__is defined if this option is used.-mv850e2v4โ specify that the target processor is the V850E3V5. This is an alias for the-mv850e3v5option.-mv850e2v3โ specify that the target processor is the V850E2V3. The preprocessor constant__v850e2v3__is defined if this option is used.-mv850e2โ specify that the target processor is the V850E2. The preprocessor constant__v850e2__is defined if this option is used.-mv850e1โ bestie, this says the target processor is the V850E1 ๐ . When you use it, the preprocessor constants__v850e1__and__v850e__get defined. two for the price of one, iconic.-mv850esโ target is the V850ES. this is literally just an alias for-mv850e1, no cap.-mv850eโ target is the V850E, and the preprocessor constant__v850e__is defined when you use it โจ.
okay so if you don't pick any of -mv850, -mv850e, -mv850e1, -mv850e2, -mv850e2v3 or -mv850e3v5, then a default target processor gets chosen for you and the relevant __v850*__ preprocessor constant is defined. the compiler's got you ๐ซถ.
and the preprocessor constants __v850 and __v851__? those are always defined, no matter which processor variant you're targeting. always on, main character constants ๐.
-mdisable-callt,-mno-disable-calltโ this one suppresses the generation of the"CALLT"instruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture.
it's enabled by default when the RH850 ABI is in use (peep -mrh850-abi), and disabled by default when the GCC ABI is in use. and if "CALLT" instructions are being generated, then the C preprocessor symbol __V850_CALLT__ is defined ๐
-mrelax,-mno-relaxโ pass on (or do not pass on, your choice bestie) the-mrelaxcommand-line option to the assembler.-mlong-jumps,-mno-long-jumpsโ disable (or re-enable) the generation of PC-relative jump instructions ๐.-msoft-float,-mhard-floatโ disable (or re-enable) the generation of hardware floating point instructions. this is only significant when the target architecture is V850E2V3 or higher, so don't stress otherwise. if hardware floating point instructions are being generated then the C preprocessor symbol__FPU_OK__is defined, otherwise the symbol__NO_FPU__is defined ๐.-mloopโ enables the use of the e3v5LOOPinstruction. it's not enabled by default when the e3v5 architecture is selected, because its use is still experimental โ so, like, proceed with awareness ๐.-mrh850-abi,-mghsโ enables support for the RH850 version of the V850 ABI. this is the default. with this version of the ABI the following rules apply:- Integer sized structures and unions are returned via a memory pointer rather than a register.
- Large structures and unions (more than 8 bytes in size) are passed by value.
- Functions are aligned to 16-bit boundaries.
- The
-m8byte-aligncommand-line option is supported. - The
-mdisable-calltcommand-line option is enabled by default. The-mno-disable-calltcommand-line option is not supported ๐ซ.
when this version of the ABI is enabled, the C preprocessor symbol __V850_RH850_ABI__ is defined โจ.
-mgcc-abiโ enables support for the old GCC version of the V850 ABI. with this version of the ABI the following rules apply:- Integer sized structures and unions are returned in register
r10. - Large structures and unions (more than 8 bytes in size) are passed by reference.
- Functions are aligned to 32-bit boundaries, unless optimizing for size.
- The
-m8byte-aligncommand-line option is not supported. - The
-mdisable-calltcommand-line option is supported but not enabled by default.
- Integer sized structures and unions are returned in register
when this version of the ABI is enabled, the C preprocessor symbol __V850_GCC_ABI__ is defined ๐.
-m8byte-align,-mno-8byte-alignโ enables support for"double"and"long long"types to be aligned on 8-byte boundaries. the default is to restrict the alignment of all objects to at most 4-bytes. when-m8byte-alignis in effect, the C preprocessor symbol__V850_8BYTE_ALIGN__is defined ๐ธ.-mbig-switchโ generate code suitable for big switch tables. only use this if the assembler/linker complain about out of range branches within a switch table, fr fr.-mapp-regsโ this option causesr2andr5to be used in the code generated by the compiler. this setting is the default ๐.-mno-app-regsโ this option causesr2andr5to be treated as fixed registers.
๐ซ VAX Options ๐ซ
these -m options are defined for the VAX:
-munixโ do not output certain jump instructions ("aobleq"and so on) that the Unix assembler for the VAX cannot handle across long ranges.-mgnuโ do output those jump instructions, on the assumption that the GNU assembler is being used.-mgโ output code for G-format floating-point numbers instead of D-format.-mlra,-mno-lraโ enable Local Register Allocation. this is still experimental for the VAX, so by default the compiler uses standard reload ๐ง.
๐ Visium Options ๐
-mdebugโ a program which performs file I/O and is destined to run on an MCM target should be linked with this option. it causes the librarieslibc.aandlibdebug.ato be linked. the program should be run on the target under the control of the GDB remote debugging stub โจ.-msimโ a program which performs file I/O and is destined to run on the simulator should be linked with option. this causes librarieslibc.aandlibsim.ato be linked.-mfpu,-mhard-floatโ generate code containing floating-point instructions. this is the default ๐ .-mno-fpu,-msoft-floatโ generate code containing library calls for floating-point.
heads up bestie:-msoft-floatchanges the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option. in particular, you need to compilelibgcc.a, the library that comes with GCC, with-msoft-floatin order for this to work ๐ญ.
- *
-mcpu=cpu_type* โ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. supported values for cpu_type aremcm,gr5andgr6.
mcm is a synonym of gr5 present for backward compatibility.
by default (unless configured otherwise), GCC generates code for the GR5 variant of the Visium architecture.
with -mcpu=gr6, GCC generates code for the GR6 variant of the Visium architecture. the only difference from GR5 code is that the compiler will generate block move instructions ๐ฅ.
-mtune=cpu_type โ set the instruction scheduling parameters for machine type cpu_type, but *do not set the instruction set or register set that the option-mcpu=cpu_type* would.-msv-modeโ generate code for the supervisor mode, where there are no restrictions on the access to general registers. this is the default.-muser-modeโ generate code for the user mode, where the access to some general registers is forbidden: on the GR5, registersr24tor31cannot be accessed in this mode; on the GR6, only registersr29tor31are affected ๐.
๐ VMS Options ๐
these -m options are defined for the VMS implementations:
-mvms-return-codesโ return VMS condition codes from"main". the default is to return POSIX-style condition (e.g. error) codes.-mdebug-main=prefix โ flag the *first routine whose name starts with *prefix as the main routine for the debugger ๐.-mmalloc64โ default to 64-bit memory allocation routines.-mpointer-size=size โ set the default size of pointers. possible options for size are32orshortfor 32 bit pointers,64orlongfor 64 bit pointers, andnofor supporting **only 32 bit pointers. the later option disables"pragma pointer_size"๐ซถ.
๐ฆ VxWorks Options ๐ฆ
the options in this section are defined for all VxWorks targets. options specific to the target hardware are listed with the other options for that target.
-mrtpโ GCC can generate code for both VxWorks kernels and real time processes (RTPs). this option switches from the former to the latter. it also defines the preprocessor macro__RTP__โจ.-non-staticโ link an RTP executable against shared libraries rather than static libraries. the options-staticand-sharedcan also be used for RTPs;-staticis the default.-Bstatic,-Bdynamicโ these options are passed down to the linker. they are defined for compatibility with Diab.-Xbind-lazyโ enable lazy binding of function calls. this option is equivalent to-Wl,-z,nowand is defined for compatibility with Diab.-Xbind-nowโ disable lazy binding of function calls. this option is the default and is defined for compatibility with Diab ๐.
โญ x86 Options โญ
these -m options are defined for the x86 family of computers.
-march=cpu-type โ generate instructions for the machine type cpu-type. in contrast to-mtune=cpu-type, which merely *tunes the generated code for the specified *cpu-type,-march=cpu-type allows GCC to generate code that may not run at all on processors other than the one indicated ๐. specifying-march=cpu-type implies-mtune=cpu-type, except where noted otherwise.
the choices for cpu-type are:
nativeโ this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines). using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set ๐ฅ๏ธ.x86-64โ a generic CPU with 64-bit extensions.x86-64-v2,x86-64-v3,x86-64-v4โ these choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. on ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.
since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value ๐.
i386โ Original Intel i386 CPU.i486โ Intel i486 CPU. (No scheduling is implemented for this chip.)i586,pentiumโ Intel Pentium CPU with no MMX support.lakemontโ Intel Lakemont MCU, based on Intel Pentium CPU.pentium-mmxโ Intel Pentium MMX CPU, based on Pentium core with MMX instruction set support.pentiumproโ Intel Pentium Pro CPU.
i686โ bestie when you pair this with-march, it rolls out the Pentium Pro instruction set, so your code runs on literally every i686 family chip out there. When you use it with-mtunetho, it means the exact same thing asgeneric. โจpentium2โ Intel Pentium II CPU, i.e. Pentium Pro core energy but now with MMX and FXSR instruction set support. ๐pentium3,pentium3mโ Intel Pentium III CPU, again the Pentium Pro core, serving MMX, FXSR and SSE instruction set support.pentium-mโ Intel Pentium M, which is the low-power version of the Intel Pentium III CPU, bringing MMX, SSE, SSE2 and FXSR instruction set support. This is the one Centrino notebooks used, iconic. ๐ซถpentium4,pentium4mโ Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support.prescottโ the improved version of the Intel Pentium 4 CPU, with MMX, SSE, SSE2, SSE3 and FXSR instruction set support.noconaโ also an improved version of the Intel Pentium 4 CPU, and it's giving 64-bit extensions, MMX, SSE, SSE2, SSE3 and FXSR instruction set support.core2โ Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF and FXSR instruction set support.nehalem,corei7โ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support.westmereโ Intel Westmere CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR and PCLMUL instruction set support.sandybridge,corei7-avxโ Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE and PCLMUL instruction set support.ivybridge,core-avx-iโ Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND and F16C instruction set support.haswell,core-avx2โ Intel Haswell CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE and HLE instruction set support.broadwellโ Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX and PREFETCHW instruction set support. (yes bestie,MOVBEreally does show up twice in the list, that's fr fr what it says ๐ญ)skylakeโ Intel Skylake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES and SGX instruction set support.skylake-avx512โ Intel Skylake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support. ๐cascadelakeโ Intel Cascade Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support.cannonlakeโ Intel Cannon Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA and SHA instruction set support.cooperlakeโ Intel Cooper Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.icelake-clientโ Intel Ice Lake Client CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support.icelake-serverโ Intel Ice Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD and CLWB instruction set support.tigerlakeโ Intel Tiger Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, MOVDIRI, MOVDIR64B, CLWB, AVX512VP2INTERSECT and KEYLOCKER instruction set support.rocketlakeโ Intel Rocket Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support.alderlake,raptorlake,meteorlakeโ Intel Alder Lake/Raptor Lake/Meteor Lake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL and AVX-VNNI instruction set support.sapphirerapids,emeraldrapidsโ Intel Sapphire Rapids/Emerald Rapids CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16 and AVX512BF16 instruction set support. ๐ฅgraniterapidsโ Intel Granite Rapids CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16, AVX512BF16, AMX-FP16 and PREFETCHI instruction set support.graniterapids-dโ Intel Granite Rapids D CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512FP16, AVX512BF16, AMX-FP16, PREFETCHI and AMX-COMPLEX instruction set support.bonnell,atomโ Intel Bonnell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.silvermont,slmโ Intel Silvermont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW and RDRND instruction set support.goldmontโ Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT and FSGSBASE instruction set support.goldmont-plusโ Intel Goldmont Plus CPU, and she comes with 64-bit extensions, plusMOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,PCLMUL,PREFETCHW,RDRND,AES,SHA,RDSEED,XSAVE,XSAVEC,XSAVES,XSAVEOPT,CLFLUSHOPT,FSGSBASE,PTWRITE,RDPIDandSGXinstruction set support. โจtremontโ Intel Tremont CPU, 64-bit extensions +MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,PCLMUL,PREFETCHW,RDRND,AES,SHA,RDSEED,XSAVE,XSAVEC,XSAVES,XSAVEOPT,CLFLUSHOPT,FSGSBASE,PTWRITE,RDPID,SGX,CLWB,GFNI-SSE,MOVDIRI,MOVDIR64B,CLDEMOTEandWAITPKGinstruction set support. ๐ฆsierraforestโ Intel Sierra Forest CPU, 64-bit extensions +MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PREFETCHW,PCLMUL,RDRND,XSAVE,XSAVEC,XSAVES,XSAVEOPT,FSGSBASE,PTWRITE,RDPID,SGX,GFNI-SSE,CLWB,MOVDIRI,MOVDIR64B,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKL,AVX-VNNI,AVXIFMA,AVXVNNIINT8,AVXNECONVERT,CMPCCXADD,ENQCMDandUINTRinstruction set support. ๐ฅgrandridgeโ Intel Grand Ridge CPU, 64-bit extensions +MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PREFETCHW,PCLMUL,RDRND,XSAVE,XSAVEC,XSAVES,XSAVEOPT,FSGSBASE,PTWRITE,RDPID,SGX,GFNI-SSE,CLWB,MOVDIRI,MOVDIR64B,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKL,AVX-VNNI,AVXIFMA,AVXVNNIINT8,AVXNECONVERT,CMPCCXADD,ENQCMDandUINTRinstruction set support. ๐knlโ Intel Knights Landing CPU, 64-bit extensions +MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,AVX,XSAVE,PCLMUL,FSGSBASE,RDRND,F16C,AVX2,BMI,BMI2,LZCNT,FMA,MOVBE,HLE,RDSEED,ADCX,PREFETCHW,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1instruction set support. (yes bestie,MOVBEreally does show up twice up in there, we're just vibing. ๐ญ)knmโ Intel Knights Mill CPU, 64-bit extensions +MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,AVX,XSAVE,PCLMUL,FSGSBASE,RDRND,F16C,AVX2,BMI,BMI2,LZCNT,FMA,MOVBE,HLE,RDSEED,ADCX,PREFETCHW,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1,AVX5124VNNIW,AVX5124FMAPSandAVX512VPOPCNTDQinstruction set support. ๐k6โ AMD K6 CPU, and her whole personality isMMXinstruction set support. ๐ธk6-2,k6-3โ the glow-up versions of the AMD K6 CPU, now servingMMXand3DNow!instruction set support. โจathlon,athlon-tbirdโ AMD Athlon CPU withMMX,3dNOW!, enhanced3DNow!andSSEprefetch instructions support. ๐athlon-4,athlon-xp,athlon-mpโ the improved AMD Athlon CPU, and she bringsMMX,3DNow!, enhanced3DNow!and fullSSEinstruction set support. ๐ฅk8,opteron,athlon64,athlon-fxโ processors based on the AMD K8 core with x86-64 instruction set support, including the AMD Opteron, Athlon 64, and Athlon 64 FX processors. (This supersetsMMX,SSE,SSE2,3DNow!, enhanced3DNow!and 64-bit instruction set extensions.) ๐k8-sse3,opteron-sse3,athlon64-sse3โ improved versions of the AMD K8 cores, now withSSE3instruction set support. โจamdfam10,barcelonaโ CPUs based on AMD Family 10h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSE4A,3DNow!, enhanced3DNow!,ABMand 64-bit instruction set extensions.) ๐bdver1โ CPUs based on AMD Family 15h cores with x86-64 instruction set support. (This supersetsFMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver2โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,AVX2,XOP,LWP,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)znver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT, and 64-bit instruction set extensions.) ๐ฆznver2โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD, and 64-bit instruction set extensions.) ๐ฆznver3โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES, and 64-bit instruction set extensions.) ๐znver4โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNIand 64-bit instruction set extensions.) ๐ฅznver5โ AMD Family 1ah core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNI,AVXVNNI,MOVDIRI,MOVDIR64B,AVX512VP2INTERSECT,PREFETCHIand 64-bit instruction set extensions.) ๐btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSSE3,SSE4A,CX16,ABMand 64-bit instruction set extensions.)btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includesMOVBE,F16C,BMI,AVX,PCLMUL,AES,SSE4.2,SSE4.1,CX16,ABM,SSE4A,SSSE3,SSE3,SSE2,SSE,MMXand 64-bit instruction set extensions. ๐winchip-c6โ IDT WinChip C6 CPU, dealt in same way as i486 with additionalMMXinstruction set support. ๐winchip2โ IDT WinChip 2 CPU, dealt in same way as i486 with additionalMMXand3DNow!instruction set support. ๐c3โ VIA C3 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.) ๐ซถc3-2โ VIA C3-2 (Nehemiah/C5XL) CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.) ๐ซถc7โ VIA C7 (Esther) CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถsamuel-2โ VIA Eden Samuel 2 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.) ๐ซถnehemiahโ VIA Eden Nehemiah CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.) ๐ซถestherโ VIA Eden Esther CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถeden-x2โ VIA Eden X2 CPU with x86-64,MMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถeden-x4โ VIA Eden X4 CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,AVXandAVX2instruction set support. (No scheduling is implemented for this chip.) ๐ซถnanoโ Generic VIA Nano CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถnano-1000โ VIA Nano 1xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถnano-2000โ VIA Nano 2xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถnano-3000โ VIA Nano 3xxx CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) ๐ซถnano-x2โ VIA Nano Dual Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) ๐ซถnano-x4โ VIA Nano Quad Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) ๐ซถlujiazuiโ the ZHAOXIN lujiazui CPU ๐ it's got x86-64, plusMOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PCLMUL,RDRND,XSAVE,XSAVEOPT,FSGSBASE,CX16,ABM,BMI,BMI2,FXSR,RDSEEDinstruction set support all up in there. And okay, yes, these chips do support AVX and F16C, but those are not enabled by-march=lujiazuiโ for performance reasons, bestie. It's giving "we could but we won't" ๐geodeโ the AMD Geode embedded processor ๐ withMMXand3DNow!instruction set support. Little guy, big vibes.
-mtune=cpu-type ๐
So -mtune= tunes everything applicable about the generated code to the cpu-type โ except for the ABI and the set of available instructions. Like, it's about the vibe of the codegen, not what instructions you're allowed to use.
Picking a specific cpu-type schedules things appropriately for that particular chip. But here's the tea โ โ the compiler does not generate any code that can't run on the default machine type unless you also throw a -march=cpu-type in there. For example, if GCC is configured for i686-pc-linux-gnu, then -mtune=pentium4 gives you code that's tuned for Pentium 4 but still runs on i686 machines. No cap.
The choices for cpu-type are literally the same as for -march. But -mtune also supports 2 extra choices for cpu-type, and they're kinda special:
generic โจ
Produces code optimized for the most common IA32/AMD64/EM64T processors. Now โ if you know the CPU your code is gonna run on, you should use the corresponding -mtune or -march option instead of -mtune=generic. But if you have literally no idea what CPUs your users will have?? Then yeah, use this one. It's the "idk just make it work everywhere" queen ๐
As new processors show up in the marketplace, the behavior of this option will change. So if you upgrade to a newer version of GCC, the code generation controlled by this option shifts to reflect whatever processors are most common when that version of GCC drops. It's a moving target, bestie, keep up ๐ฆ
And notice ๐จ there is no -march=generic option. Why? Because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. Meanwhile -mtune indicates the processor (or, in this case, a whole collection of processors) for which the code is optimized. Different jobs, different girls ๐
intel ๐ฅ
Produces code optimized for the most current Intel processors โ which are Haswell and Silvermont for this version of GCC. Again: if you know the CPU your code will run on, use the corresponding -mtune or -march option instead of -mtune=intel. But if you want your application to perform better on both Haswell and Silvermont, then use this one, periodt.
As new Intel processors get deployed in the marketplace, the behavior of this option will change. So if you upgrade to a newer version of GCC, code generation controlled by this option changes to reflect the most current Intel processors at the time that version of GCC is released. Ever-evolving icon behavior ๐ซ
And once again ๐จ there is no -march=intel option โ because -march indicates the instruction set the compiler can use, and there's no common instruction set applicable to all processors. -mtune, though, indicates the processor (or collection of processors) for which code is optimized. Same energy as the generic situation fr fr.
-mcpu=cpu-typeโ a deprecated synonym for-mtune. Like, it exists, it works, but it's giving "old money that got repossessed" ๐ use-mtuneinstead, bestie.
-mfpmath=unit ๐ธ
Generates floating-point arithmetic for the selected unit. The choices for unit are:
387โ use the standard 387 floating-point coprocessor that's present on the majority of chips (and emulated otherwise). Code compiled with this option runs almost everywhere, which is lowkey iconic. But the temporary results get computed in 80-bit precision instead of the precision specified by the type, so you get slightly different results compared to most other chips ๐ฌ Check-ffloat-storefor a more detailed description of that whole situation.
This is the default choice for non-Darwin x86-32 targets.
sseโ use scalar floating-point instructions present in the SSE instruction set. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set only supports single-precision arithmetic, so double and extended-precision arithmetic are still done using387. A later version โ present only in Pentium 4 and AMD x86-64 chips โ supports double-precision arithmetic too. Glow up โจ
For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option actually take effect. For the x86-64 compiler, these extensions are enabled by default. Lucky them ๐
The resulting code should be considerably faster in the majority of cases and avoids the numerical instability problems of 387 code โ but โ ๏ธ it may break some existing code that expects temporaries to be 80 bits.
This is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled.
sse,387sse+387bothโ attempt to utilize both instruction sets at once. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE it doubles the execution resources too. Use this option with care though ๐จ because it is still experimental โ the GCC register allocator does not model separate functional units well, resulting in unstable performance. It's giving messy, ngl.
-masm=dialectโ output assembly instructions using the selecteddialect. Also affects which dialect is used for basicasmand extendedasm. Supported choices (in dialect order) areattorintel. The default isatt. And heads up ๐ซถ Darwin does not supportintel.
-mieee-fp-mno-ieee-fpโ control whether or not the compiler uses IEEE floating-point comparisons. These correctly handle the case where the result of a comparison is unordered. Important little detail, bestie ๐ค
-m80387-mhard-floatโ generate output containing 80387 instructions for floating point. Hardware girlies, rise ๐ช
-mno-80387-msoft-floatโ generate output containing library calls for floating point. Software girlies, also rise ๐
Warning: the requisite libraries are not part of GCC. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. That's on you, babe ๐ญ
On machines where a function returns floating-point results in the 80387 register stack, some floating-point opcodes may be emitted even if -msoft-float is used. So like, mostly soft, but not fully soft. It's giving "mostly vegan" ๐ฅ
-mno-fp-ret-in-387โ do not use the FPU registers for return values of functions.
The usual calling convention has functions return values of types float and double in an FPU register โ even if there is no FPU. The idea being that the operating system should emulate an FPU. Cute of them ๐
The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead. Plot twist.
-mno-fancy-math-387โ okay so some 387 emulators do not support thesin,cosandsqrtinstructions for the 387. Specify this option to avoid generating those instructions. This option gets overridden when-marchindicates that the target CPU always has an FPU and so the instruction doesn't need emulation. And PSA ๐ข these instructions are not generated unless you also use the-funsafe-math-optimizationsswitch. Two-key combo, iykyk ๐
-malign-double-mno-align-doubleโ control whether GCC alignsdouble,long double, andlong longvariables on a two-word boundary or a one-word boundary. Aligningdoublevariables on a two-word boundary produces code that runs somewhat faster on a Pentium โ at the expense of more memory. Speed vs. RAM, the eternal trade ๐
On x86-64, -malign-double is enabled by default. Slay.
Warning: if you use the -malign-double switch, structures containing the above types are aligned differently than the published application binary interface specifications for the x86-32, and are not binary compatible with structures in code compiled without that switch. This is a real "you've been warned" moment bestie ๐ฉ
-m96bit-long-double-m128bit-long-doubleโ these switches control the size of thelong doubletype. The x86-32 application binary interface specifies the size to be 96 bits, so-m96bit-long-doubleis the default in 32-bit mode.
Modern architectures (Pentium and newer) prefer long double to be aligned to an 8- or 16-byte boundary. In arrays or structures conforming to the ABI, this isn't possible. So specifying -m128bit-long-double aligns long double to a 16-byte boundary by padding the long double with an additional 32-bit zero. Just add more bits, it's fine โจ
In the x86-64 compiler, -m128bit-long-double is the default choice, since its ABI specifies that long double is aligned on a 16-byte boundary.
Notice ๐ that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double. It's about alignment, not precision, periodt.
Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containinglong doublevariables, as well as modifying the function calling convention for functions takinglong double. Hence they are not binary-compatible with code compiled without that switch. Same energy as the last warning ๐จ
-mlong-double-64-mlong-double-80-mlong-double-128โ these switches control the size of thelong doubletype. A size of 64 bits makes thelong doubletype equivalent to thedoubletype โ this is the default for 32-bit Bionic C library. A size of 128 bits makes thelong doubletype equivalent to the__float128type โ this is the default for 64-bit Bionic C library. 80 is just... 80, you know? ๐ธ
Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containinglong doublevariables, as well as modifying the function calling convention for functions takinglong double. Hence they are not binary-compatible with code compiled without that switch. Yeah, same warning AGAIN. It's a recurring theme, bestie, they really want you to know ๐ญ
-malign-data=typeโ control how GCC aligns variables ๐ The supported values fortypeare:compatโ uses increased alignment value compatible with GCC 4.8 and earlier.abiโ uses alignment value as specified by the psABI.cachelineโ uses increased alignment value to match the cache line size.
compat is the default. Nostalgia core ๐
-mlarge-data-threshold=thresholdโ so when you've got-mcmodel=mediumturned on, any data object bigger than threshold gets shipped off to the large data section. ๐ซถ And this value has to be the same across every single object linked into the binary โ no vibes-based per-file choices, bestie โ and it defaults to65535.
-mrtdโ this one's a whole different function-calling convention โจ: functions that take a fixed number of arguments come back with theret numinstruction, which pops their arguments while returning. That saves one instruction in the caller, because there's nothing left to pop over there. Score. ๐
You can tell one specific function to use this calling sequence with the function attribute stdcall. And you can override the -mrtd option entirely for a function by using the function attribute cdecl.
โ ๏ธ Warning: this calling convention is incompatible with the one normally used on Unix, so you literally cannot use it if you need to call libraries compiled with the Unix compiler. ๐ซ
Also, you must provide function prototypes for all functions that take variable numbers of arguments (yes, printf is included in that, iykyk); otherwise incorrect code is generated for calls to those functions. ๐ญ
On top of that, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored โ but not here. Periodt.)
-mregparm=numโ controls how many registers get used to pass integer arguments. By default, no registers are used to pass arguments, and at most 3 registers can be used. You can control this behavior for one specific function with the function attributeregparm.
โ ๏ธ Warning: if you use this switch and num is nonzero, then you must build all modules with the same value, including any libraries. That means the system libraries and startup modules too. No skips. ๐
-msseregparmโ uses SSE register passing conventions forfloatanddoublearguments and return values. For one specific function, you can control this behavior with the function attributesseregparm.
โ ๏ธ Warning: if you use this switch then you must build all modules with the same value, including any libraries. Again: system libraries and startup modules are included, bestie.
-mvect8-ret-in-memโ returns 8-byte vectors in memory instead of MMX registers. On VxWorks this is the default, to match the ABI of the Sun Studio compilers up until version 12. Only use this option if you need to stay compatible with existing code produced by those previous compiler versions or older versions of GCC. ๐-mpc32-mpc64-mpc80โ these set the 80387 floating-point precision to 32, 64 or 80 bits. When-mpc32is specified, the significands of results of floating-point operations get rounded to 24 bits (single precision);-mpc64rounds the significands of results of floating-point operations to 53 bits (double precision); and-mpc80rounds the significands of results of floating-point operations to 64 bits (extended double precision), which is the default. When this option is used, floating-point operations in higher precisions are not available to the programmer without setting the FPU control word explicitly. ๐ง
Setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. ๐ฅ But note that some mathematical libraries assume extended-precision (80-bit) floating-point operations are enabled by default; routines in such libraries could suffer significant loss of accuracy, typically through so-called "catastrophic cancellation", when this option is used to set the precision to less than extended precision. ๐
-mdaz-ftzโ the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register are used to control floating-point calculations. SSE and AVX instructions, including scalar and vector instructions, could benefit from enabling the FTZ and DAZ flags when-mdaz-ftzis specified. Don't set FTZ/DAZ flags when-mno-daz-ftzor-sharedis specified โ note that-mdaz-ftzwill set FTZ/DAZ flags even with-shared. ๐ธ-mstackrealignโ realigns the stack at entry. On the x86, the-mstackrealignoption generates an alternate prologue and epilogue that realign the run-time stack if necessary. This supports mixing legacy codes that keep 4-byte stack alignment with modern codes that keep 16-byte stack alignment for SSE compatibility. See also the attributeforce_align_arg_pointer, which applies to individual functions. ๐-mpreferred-stack-boundary=numโ attempts to keep the stack boundary aligned to a 2 raised to num byte boundary. If-mpreferred-stack-boundaryisn't specified, the default is4(16 bytes or 128 bits).
โ ๏ธ Warning: when generating code for the x86-64 architecture with SSE extensions disabled,-mpreferred-stack-boundary=3can be used to keep the stack boundary aligned to an 8 byte boundary. Since the x86-64 ABI requires 16 byte stack alignment, this is ABI incompatible and is intended to be used in a controlled environment where stack space is an important limitation. This option leads to wrong code when functions compiled with 16 byte stack alignment (such as functions from a standard library) are called with a misaligned stack. In that case, SSE instructions may lead to misaligned memory access traps. ๐ฑ In addition, variable arguments are handled incorrectly for 16 byte aligned objects (including x87long doubleand__int128), leading to wrong results. You must build all modules with-mpreferred-stack-boundary=3, including any libraries โ and yes, that includes the system libraries and startup modules.
-mincoming-stack-boundary=numโ assumes the incoming stack is aligned to a 2 raised to num byte boundary. If-mincoming-stack-boundaryisn't specified, the one specified by-mpreferred-stack-boundaryis used.
On Pentium and Pentium Pro, double and long double values should be aligned to an 8-byte boundary (see -malign-double) or they suffer significant run time performance penalties. On Pentium III, the Streaming SIMD Extension (SSE) data type __m128 may not work properly if it isn't 16-byte aligned. ๐
To ensure proper alignment of these values on the stack, the stack boundary must be as aligned as that required by any value stored on the stack. Further, every function must be generated such that it keeps the stack aligned. So calling a function compiled with a higher preferred stack boundary from a function compiled with a lower preferred stack boundary most likely misaligns the stack. It's recommended that libraries that use callbacks always use the default setting. ๐
This extra alignment does consume extra stack space, and generally increases code size. Code that's sensitive to stack space usage โ like embedded systems and operating system kernels โ may want to reduce the preferred alignment to -mpreferred-stack-boundary=2.
-mmmx-msse-msse2-msse3-mssse3-msse4-msse4a-msse4.1-msse4.2-mavx-mavx2-mavx512f-mavx512pf-mavx512er-mavx512cd-mavx512vl-mavx512bw-mavx512dq-mavx512ifma-mavx512vbmi-msha-maes-mpclmul-mclflushopt-mclwb-mfsgsbase-mptwrite-mrdrnd-mf16c-mfma-mpconfig-mwbnoinvd-mfma4-mprfchw-mrdpid-mprefetchwt1-mrdseed-msgx-mxop-mlwp-m3dnow-m3dnowa-mpopcnt-mabm-madx-mbmi-mbmi2-mlzcnt-mfxsr-mxsave-mxsaveopt-mxsavec-mxsaves-mrtm-mhle-mtbm-mmwaitx-mclzero-mpku-mavx512vbmi2-mavx512bf16-mavx512fp16-mgfni-mvaes-mwaitpkg-mvpclmulqdq-mavx512bitalg-mmovdiri-mmovdir64b-menqcmd-muintr-mtsxldtrk-mavx512vpopcntdq-mavx512vp2intersect-mavx5124fmaps-mavx512vnni-mavxvnni-mavx5124vnniw-mcldemote-mserialize-mamx-tile-mamx-int8-mamx-bf16-mhreset-mkl-mwidekl-mavxifma-mavxvnniint8-mavxneconvert-mcmpccxadd-mamx-fp16-mprefetchi-mraoint-mamx-complex
These switches enable the use of instructions in the MMX, SSE, SSE2, SSE3, SSSE3, SSE4, SSE4A, SSE4.1, SSE4.2, AVX, AVX2, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX512VL, AVX512BW, AVX512DQ, AVX512IFMA, AVX512VBMI, SHA, AES, PCLMUL, CLFLUSHOPT, CLWB, FSGSBASE, PTWRITE, RDRND, F16C, FMA, PCONFIG, WBNOINVD, FMA4, PREFETCHW, RDPID, PREFETCHWT1, RDSEED, SGX, XOP, LWP, 3DNow!, enhanced 3DNow!, POPCNT, ABM, ADX, BMI, BMI2, LZCNT, FXSR, XSAVE, XSAVEOPT, XSAVEC, XSAVES, RTM, HLE, TBM, MWAITX, CLZERO, PKU, AVX512VBMI2, GFNI, VAES, WAITPKG, VPCLMULQDQ, AVX512BITALG, MOVDIRI, MOVDIR64B, AVX512BF16, ENQCMD, AVX512VPOPCNTDQ, AVX5124FMAPS, AVX512VNNI, AVX5124VNNIW, SERIALIZE, UINTR, HRESET, AMXTILE, AMXINT8, AMXBF16, KL, WIDEKL, AVXVNNI, AVX512-FP16, AVXIFMA, AVXVNNIINT8, AVXNECONVERT, CMPCCXADD, AMX-FP16, PREFETCHI, RAOINT, AMX-COMPLEX or CLDEMOTE extended instruction sets. ๐ Each one has a corresponding -mno- option to disable use of these instructions.
These extensions are also available as built-in functions: see x86 Built-in Functions, for details of the functions enabled and disabled by these switches.
To generate SSE/SSE2 instructions automatically from floating-point code (as opposed to 387 instructions), see -mfpmath=sse. โจ
GCC depresses SSEx instructions when -mavx is used. Instead, it generates new AVX instructions or AVX equivalence for all SSEx instructions when needed. ๐
These options enable GCC to use these extended instructions in generated code, even without -mfpmath=sse. Applications that perform run-time CPU detection must compile separate files for each supported architecture, using the appropriate flags. In particular, the file containing the CPU detection code should be compiled without these options. ๐ซถ
-mdump-tune-featuresโ this option instructs GCC to dump the names of the x86 performance tuning features and default settings. Those names can then be used in-mtune-ctrl=feature-list. ๐-mtune-ctrl=feature-listโ okay so this is the โจfine grainโจ dial for x86 code generation features, bestie.feature-listis a comma separated list of feature names. Peep-mdump-tune-featurestoo. When you specify one, the feature gets turned on unless it's got a^in front of it, in which case it gets turned off. ๐๏ธ
Heads up though: -mtune-ctrl=feature-list is meant for GCC developers, iykyk. If you use it you might wander into code paths nobody tested, and that can literally result in compiler ICEs or runtime errors. ๐ Not a cute look.
-mno-defaultโ tells GCC to turn off all the tunable features. ๐ See also-mtune-ctrl=feature-listand-mdump-tune-features.-mcldโ makes GCC emit a"cld"instruction in the prologue of functions that use string instructions. Why do we care? Because string instructions depend on the DF flag to pick between autoincrement mode and autodecrement mode, and while the ABI says the DF flag should be cleared when you enter a function, some operating systems simply do not respect that โ they don't clear DF in their exception dispatchers. ๐ So the exception handler can get invoked with DF already set, which means wrong direction mode when string instructions run. Messy. This option can be on by default for 32-bit x86 targets if GCC was configured with the--enable-cldconfigure option. And in that case, you can suppress the"cld"instructions with the-mno-cldcompiler option. ๐ซถ-mvzeroupperโ instructs GCC to emit a"vzeroupper"instruction before control flow gets transferred out of the function, which minimizes the AVX to SSE transition penalty and removes unnecessary"zeroupper"intrinsics. Transition penalty?? Not on our watch. โจ-mprefer-avx128โ tells GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. Go small or go home. ๐-mprefer-vector-width=optโ tells GCC to useopt-bit vector width in instructions instead of the default on the platform you picked.-mmove-max=bitsโ sets the maximum number of bits that can be efficiently moved from memory to memory tobits. Valid values forbitsare128,256and512. ๐ง-mstore-max=bitsโ sets the maximum number of bits that can be efficiently stored to memory tobits. Valid values forbitsare128,256and512. ๐งnoneโ no extra limitations applied to GCC beyond whatever the selected platform already defines.128โ prefer 128-bit vector width for instructions.256โ prefer 256-bit vector width for instructions.512โ prefer 512-bit vector width for instructions.
-mcx16โ lets GCC generate"CMPXCHG16B"instructions in 64-bit code so it can do compare-and-exchange operations on 16-byte aligned 128-bit objects. So useful for atomic updates of data structures that are bigger than one machine word. ๐ The compiler uses this instruction to implement__syncBuiltins. But plot twist: for__atomicBuiltins operating on 128-bit integers, a library call is always used. Always. No exceptions. ๐-msahfโ enables generation of"SAHF"instructions in 64-bit code. Backstory: early Intel Pentium 4 CPUs with Intel 64 support, before the Pentium 4 G1 step showed up in December 2005, were missing the"LAHF"and"SAHF"instructions that AMD64 supports. Those two are load and store instructions, respectively, for certain status flags. In 64-bit mode,"SAHF"is used to optimize the"fmod","drem", and"remainder"built-in functions โ see Other Builtins for the deets. ๐-mmovbeโ enables use of the"movbe"instruction to implement__builtin_bswap32and__builtin_bswap64. slay. ๐ฅ-mshstkโ the-mshstkoption enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). ๐ก๏ธ-mcrc32โ this one enables built-in functions__builtin_ia32_crc32qi,__builtin_ia32_crc32hi,__builtin_ia32_crc32siand__builtin_ia32_crc32diso they generate the"crc32"machine instruction. โญ-mmwaitโ enables built-in functions__builtin_ia32_monitor, and__builtin_ia32_mwaitso they generate the"monitor"and"mwait"machine instructions. ๐ธ-mrecipโ enables use of"RCPSS"and"RSQRTSS"instructions (plus their vectorized variants"RCPPS"and"RSQRTPS") with an extra Newton-Raphson step to bump precision, instead of"DIVSS"and"SQRTSS"(and their vectorized variants) for single-precision floating-point arguments. These instructions only get generated when-funsafe-math-optimizationsis enabled together with-ffinite-math-onlyand-fno-trapping-math. ๐ซถ
Now listen: while the throughput of that sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp. Like, the inverse of 1.0 equals 0.99999994. ๐ญ Close enough-ish?
Also note that GCC already implements 1.0f/sqrtf(x) in terms of "RSQRTSS" (or "RSQRTPS") with -ffast-math (or that option combo above), and doesn't need -mrecip.
And also-also: GCC emits that sequence with the additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the above option combination), and doesn't need -mrecip. periodt. ๐
-mrecip=optโ controls which reciprocal estimate instructions are allowed to be used.optis a comma-separated list of options, and each one may be preceded by a!to invert it:allโ enable all estimate instructions.defaultโ enable the default instructions, equivalent to-mrecip.noneโ disable all estimate instructions, equivalent to-mno-recip.divโ enable the approximation for scalar division.vec-divโ enable the approximation for vectorized division.sqrtโ enable the approximation for scalar square root.vec-sqrtโ enable the approximation for vectorized square root.
So like, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations, except for square root. See how that works? ๐
-mveclibabi=typeโ specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values fortypearesvmlfor the Intel short vector math library, andacmlfor the AMD math core library. To use this option, both-ftree-vectorizeand-funsafe-math-optimizationshave to be enabled, and an SVML or ACML ABI-compatible library must be specified at link time. no shortcuts bestie. ๐ซถ
GCC currently emits calls to "vmldExp2", "vmldLn2", "vmldLog102", "vmldPow2", "vmldTanh2", "vmldTan2", "vmldAtan2", "vmldAtanh2", "vmldCbrt2", "vmldSinh2", "vmldSin2", "vmldAsinh2", "vmldAsin2", "vmldCosh2", "vmldCos2", "vmldAcosh2", "vmldAcos2", "vmlsExp4", "vmlsLn4", "vmlsLog104", "vmlsPow4", "vmlsTanh4", "vmlsTan4", "vmlsAtan4", "vmlsAtanh4", "vmlsCbrt4", "vmlsSinh4", "vmlsSin4", "vmlsAsinh4", "vmlsAsin4", "vmlsCosh4", "vmlsCos4", "vmlsAcosh4" and "vmlsAcos4" for the corresponding function type when -mveclibabi=svml is used. And it emits "__vrd2_sin", "__vrd2_cos", "__vrd2_exp", "__vrd2_log", "__vrd2_log2", "__vrd2_log10", "__vrs4_sinf", "__vrs4_cosf", "__vrs4_expf", "__vrs4_logf", "__vrs4_log2f", "__vrs4_log10f" and "__vrs4_powf" for the corresponding function type when -mveclibabi=acml is used. ๐
-mabi=nameโ generate code for the specified calling convention. Permissible values aresysvfor the ABI used on GNU/Linux and other systems, andmsfor the Microsoft ABI. The default is to use the Microsoft ABI when targeting Microsoft Windows, and the SysV ABI on all other systems. You can control this behavior for specific functions by using the function attributes"ms_abi"and"sysv_abi". ๐-mforce-indirect-callโ force all calls to functions to be indirect. Useful when you're using Intel Processor Trace, where it generates more precise timing information for function calls. โฑ๏ธ-mmanual-endbrโ insert ENDBR instruction at function entry only via the"cf_check"function attribute. Useful when used with the option-fcf-protection=branchto control ENDBR insertion at the function entry. ๐-mcet-switchโ so by default, CET instrumentation is turned off on switch statements that use a jump table, and indirect branch track is disabled. Since jump tables are stored in read-only memory, this doesn't result in a direct loss of hardening. But if the jump table index is attacker-controlled, the indirect jump may not be constrained by CET. ๐ณ This option turns on CET instrumentation to enable indirect branch track for switch statements with jump tables, which leads to the jump targets being reachable via any indirect jumps.-mcall-ms2sysv-xloguesโ because 64-bit ABIs differ, any Microsoft ABI function that calls a System V ABI function has to consider RSI, RDI and XMM6-15 as clobbered. By default, the code for saving and restoring these registers is emitted inline, which makes for pretty lengthy prologues and epilogues. ๐ฎโ๐จ Using-mcall-ms2sysv-xloguesemits prologues and epilogues that use stubs in the static portion oflibgccto perform these saves and restores, which cuts down function size at the cost of a few extra instructions. trade-off queen. ๐-mtls-dialect=typeโ generate code to access thread-local storage using thegnuorgnu2conventions.gnuis the conservative default;gnu2is more efficient, but it may add compile- and run-time requirements that cannot be satisfied on all systems. ๐-mpush-args-mno-push-argsโ use PUSH operations to store outgoing parameters. This method is shorter and usually equally fast as the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance, because of improved scheduling and reduced dependencies. โจ-maccumulate-outgoing-argsโ if enabled, the maximum amount of space required for outgoing arguments is computed in the function prologue. This is faster on most modern CPUs because of reduced dependencies, improved scheduling and reduced stack usage when the preferred stack boundary is not equal to2. The drawback?? A notable increase in code size. ๐ญ And heads up: this switch implies-mno-push-args. periodt.-mthreadsโ turns on thread-safe exception handling over on MinGW, bestie ๐ and like, if your program depends on that, you have to compile and link everything with-mthreads, no exceptions (pun fully intended). At compile time it defines-D_MT; at link time it pulls in a special little thread helper library,-lmingwthrd, whose whole job is cleaning up all that per-thread exception-handling data. so iconic of it โจ-mms-bitfields,-mno-ms-bitfieldsโ flip bit-field layout on or off so it matches what the native Microsoft Windows compiler does. ๐ช
Okay so here's the tea: if "packed" gets used on a struct, or bit-fields show up at all, the Microsoft ABI might lay that struct out completely differently than GCC normally would ๐ญ. And especially when you're moving packed data between functions built by GCC and functions built by the native Microsoft compiler โ whether that's through a function call or as raw data sitting in a file โ sometimes you just need to read either format. So yeah.
This option is on by default for Microsoft Windows targets. lowkey also controllable locally through variable or type attributes. for the deets, go peek at x86 Variable Attributes and x86 Type Attributes ๐
Now, the Microsoft structure layout algorithm is honestly pretty simple, except for the bit-field packing part, which is giving chaos ๐. The padding and alignment of struct members โ and whether a bit-field can straddle a storage-unit boundary โ all comes down to these rules:
- Structure members get stored sequentially in the order they're declared, periodt: the first member lands at the lowest memory address, the last member at the highest.
- Every data object has an alignment requirement. For literally everything except structures, unions, and arrays, that requirement is either the size of the object or the current packing size (whichever you set with the
"aligned"attribute or the"pack"pragma) โ whichever is less. For structures, unions, and arrays, the alignment requirement is the largest alignment requirement of its members. And every object gets an offset so that:
offset % alignment_requirement == 0
- Adjacent bit-fields get packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size, and if the next bit-field fits into the current allocation unit without crossing the boundary imposed by the bit-fields' common alignment requirements.
Now MSVC reads zero-length bit-fields like this:
- If a zero-length bit-field gets inserted between two bit-fields that would normally be coalesced, then they are not coalesced.
like, for example:
struct
{
unsigned long bf_1 : 12;
unsigned long : 0;
unsigned long bf_2 : 12;
} t1;
t1 is 8 bytes with that zero-length bit-field in there. Remove it and t1 shrinks to 4 bytes. the way that zero-length bit-field is just occupying space for no reason ๐
- If a zero-length bit-field comes after a bit-field,
foo, and the alignment of that zero-length bit-field is greater than the member that follows it,bar, thenbargets aligned as if it were the type of the zero-length bit-field.
For example:
struct
{
char foo : 4;
short : 0;
char bar;
} t2;
struct
{
char foo : 4;
short : 0;
double bar;
} t3;
For t2, bar gets placed at offset 2 instead of offset 1. So t2 comes out to size 4. For t3, that zero-length bit-field doesn't mess with the alignment of bar at all โ and therefore doesn't change the size of the struct either.
Keeping all that in mind, here's what you really need to clock:
- If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field can affect the alignment of the structure as a whole. For example,
t2is 4 bytes in size, since the zero-length bit-field follows a normal bit-field and is of typeshort. - Even if a zero-length bit-field isn't followed by a normal bit-field, it can still affect the alignment of the structure:
struct
{
char foo : 6;
long : 0;
} t4;
Here, t4 takes up 4 bytes. yeah. one bit-field. four bytes. ๐ซ
- Zero-length bit-fields that follow non-bit-field members get ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
Here, t5 takes up 2 bytes. slay ๐
-mno-align-stringopsโ don't align the destination of inlined string operations. This one shrinks your code size and boosts performance when the destination is already aligned but GCC has no idea about it ๐-minline-all-stringopsโ by default GCC only inlines string operations when the destination is known to be aligned to at least a 4-byte boundary. This turns on way more inlining and grows your code size, but it can speed up code that leans on fast"memcpy"and"memset"for short lengths. It also enables inline expansion of"strlen"for all pointer alignments. go off โจ-minline-stringops-dynamicallyโ for string operations of unknown size, use run-time checks: inline code for small blocks, library call for large blocks. best of both worlds fr fr ๐-mstringop-strategy=algโ override the internal decision heuristic for which algorithm to use when inlining string operations. The allowed values for alg are:rep_byterep_4byterep_8byteโ expand using the i386"rep"prefix of the specified size.byte_looploopunrolled_loopโ expand into an inline loop.libcallโ always use a library call.
-mmemcpy-strategy=strategyโ override the internal decision heuristic that decides whether"__builtin_memcpy"should be inlined, and which inline algorithm to use when the expected size of the copy operation is known. strategy is a comma-separated list ofalg:max_size:dest_aligntriplets. alg is specified in-mstringop-strategy, and max_size says the max byte size that inline algorithm alg is allowed for. For the last triplet,max_sizemust be-1. Themax_sizevalues in the list have to be in increasing order. The minimal byte size for alg is0for the first triplet, and"max_size + 1"of the preceding range for the rest. ๐-mmemset-strategy=strategyโ same energy as-mmemcpy-strategy=, except it's here to control"__builtin_memset"expansion instead.-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. This skips all those instructions that save, set up, and restore frame pointers, and frees up an extra register in leaf functions ๐ Just know that-fomit-leaf-frame-pointeryanks the frame pointer out of leaf functions entirely, which might make debugging harder. ๐ซถ-mtls-direct-seg-refs,-mno-tls-direct-seg-refsโ controls whether TLS variables can be accessed using offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer has to be added in. Whether that's even valid depends on your operating system and whether it maps the segment to cover the entire TLS area.
For systems using the GNU C Library, the default is on. ๐
-msse2avx,-mno-sse2avxโ tells the assembler to encode SSE instructions with the VEX prefix. The option-mavxturns this on by default.-mfentry,-mno-fentryโ if profiling is active (-pg), put the profiling counter call before the prologue. Heads up though: on x86 architectures the attribute"ms_hook_prologue"isn't possible right now when you're using-mfentryand-pg. ๐ญ-mrecord-mcount,-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection holding pointers to each profiling call. super useful for automatically patching and out calls โจ-mnop-mcount,-mno-nop-mcountโ if profiling is active (-pg), generate the calls to the profiling functions as NOPs. Handy when they're meant to get patched in later dynamically. lowkey probably only useful together with-mrecord-mcount๐-minstrument-return=typeโ instrument function exit in-pg -mfentryinstrumented functions with a call to the specified function. This only instruments true returns ending withretโ it does not touch sibling calls ending withjump. Valid types arenone(don't instrument),call(generate a call to__return__), ornop5(generate a 5 byte nop). ๐ฏ-mrecord-return,-mno-record-returnโ generate a__return_locsection pointing to all the return instrumentation code.-mfentry-name=nameโ set the name of the__fentry__symbol that gets called at function entry for-pg -mfentryfunctions. โ๏ธ-mfentry-section=nameโ set the name of the section used to record-mrecord-mcountcalls (default is__mcount_loc). ๐ธ-mskip-rax-setup,-mno-skip-rax-setupโ when generating code for the x86-64 architecture with SSE extensions disabled,-mskip-rax-setuplets you skip setting up the RAX register when there are no variable arguments passed in vector registers.
Warning: since the RAX register is what avoids unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or jump to a random location. ๐ฑ GCC 4.4 or newer doesn't have those issues, regardless of the RAX register value. still though. bestie. be careful.
-m8bit-idiv,-mno-8bit-idivโ on some processors, like Intel Atom, 8-bit unsigned integer divide is much faster than 32-bit/64-bit integer divide ๐โโ๏ธ This option generates a run-time check. If both the dividend and the divisor are within the range 0 to 255, an 8-bit unsigned integer divide gets used instead of a 32-bit/64-bit integer divide. ate ๐-mavx256-split-unaligned-load,-mavx256-split-unaligned-storeโ split 32-byte AVX unaligned load and store. ๐ฅ-mstack-protector-guard=guardโ bestie, this one tells the compiler to build stack protection code with the canary sitting at guard. Your options areglobal(canary lives in a global) ortls(canary lives per-thread in the TLS block โ that's the default ๐ ). Heads up though: it only does literally anything when-fstack-protectoror-fstack-protector-allis also on. Otherwise it's just vibing.-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ ok so when you pickedtlsup there, these two get to shine โจ.-mstack-protector-guard-reg=regsays which segment register to use as the base register for reading the canary โ that's%fsor%gs.-mstack-protector-guard-offset=offsetsays from what offset from that base register you're reading. Defaults for both? Whatever the relevant ABI says, no cap. ๐ซถ-mgeneral-regs-onlyโ generate code that only touches general-purpose registers. This stops the compiler from using floating-point, vector, mask and bound registers. Very "we keep it simple here" energy. ๐-mrelax-cmpxchg-loopโ so when we're emitting a compare-and-swap loop for__syncBuiltins and__atomicBuiltins that don't have a native instruction, this optimizes for the highly contended case: it issues an atomic load before theCMPXCHGinstruction, and it uses thePAUSEinstruction to save CPU power when restarting the loop. Your CPU said thank you. ๐ฅ-mindirect-branch=choiceโ convert indirect call and jump with choice. Default iskeep, which keeps indirect call and jump unmodified (aka no notes, untouched ๐).thunkconverts indirect call and jump to call and return thunk.thunk-inlineconverts indirect call and jump to inlined call and return thunk.thunk-externconverts indirect call and jump to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute"indirect_branch".
Note that-mcmodel=largeis incompatible with-mindirect-branch=thunkand-mindirect-branch=thunk-externsince the thunk function may not be reachable in the large code model. Not compatible fr fr, they do not slay together. Also note that-mindirect-branch=thunk-externis compatible with-fcf-protection=branchsince the external thunk can be made to enable control-flow check. ๐
-mfunction-return=choiceโ convert function return with choice. Default iskeep, which keeps function return unmodified.thunkconverts function return to call and return thunk.thunk-inlineconverts function return to inlined call and return thunk.thunk-externconverts function return to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute"function_return".
Note that-mindirect-return=thunk-externis compatible with-fcf-protection=branchsince the external thunk can be made to enable control-flow check. And note that-mcmodel=largeis incompatible with-mfunction-return=thunkand-mfunction-return=thunk-externsince the thunk function may not be reachable in the large code model. ๐ญ
-mindirect-branch-registerโ force indirect call and jump via register. That's the whole thing, she's short and iconic. ๐-mharden-sls=choiceโ generate code to mitigate against straight line speculation (SLS) with choice. Default isnone, which disables all SLS hardening.returnenables SLS hardening for function returns.indirect-jmpenables SLS hardening for indirect jumps.allenables all SLS hardening. Pick your fighter, or pickalland let her cook. ๐-mindirect-branch-cs-prefixโ add CS prefix to call and jmp to indirect thunk with branch target in r8-r15 registers so that the call and jmp instruction length is 6 bytes, to allow them to be replaced withlfence; call *%r8-r15orlfence; jmp *%r8-r15at run-time. Very specific, very demure, very mindful. ๐
These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments. So yes bestie, there's more. ๐
-m32,-m64,-mx32,-m16,-miamcuโ generate code for a 16-bit, 32-bit or 64-bit environment. Let's break it down because there's a lot going on and all of it matters:- The
-m32option setsint,long, and pointer types to 32 bits, and generates code that runs in 32-bit mode. - The
-m64option setsintto 32 bits andlongand pointer types to 64 bits, and generates code for the x86-64 architecture. For Darwin only, the-m64option also turns off the-fno-picand-mdynamic-no-picoptions. - The
-mx32option setsint,long, and pointer types to 32 bits, and generates code for the x86-64 architecture. - The
-m16option is the same as-m32, except for that it outputs the.code16gccassembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode. - The
-miamcuoption generates code which conforms to Intel MCU psABI. It requires the-m32option to be turned on. No-m32, no-miamcu, that's the rule. ๐จ
- The
-mno-red-zoneโ do not use a so-called "red zone" for x86-64 code. The red zone is mandated by the x86-64 ABI; it's a 128-byte area beyond the location of the stack pointer that is not modified by signal or interrupt handlers, and therefore can be used for temporary data without adjusting the stack pointer. The flag-mno-red-zonedisables this red zone. She said "no red zone slander but also no red zone." ๐-mcmodel=smallโ generate code for the small code model: the program and its symbols must be linked in the lower 2 GB of the address space. Pointers are 64 bits. Programs can be statically or dynamically linked. This is the default code model, the main character, the one that shows up without being asked. ๐-mcmodel=kernelโ generate code for the kernel code model. The kernel runs in the negative 2 GB of the address space. This model has to be used for Linux kernel code. Not optional, bestie, it's mandatory behavior. ๐ซก-mcmodel=mediumโ generate code for the medium model: the program is linked in the lower 2 GB of the address space. Small symbols are also placed there. Symbols with sizes larger than-mlarge-data-thresholdare put into large data or BSS sections and can be located above 2GB. Programs can be statically or dynamically linked.-mcmodel=largeโ generate code for the large model. This model makes no assumptions about addresses and sizes of sections. She's free, she's unbothered, she assumes nothing. ๐ฆ-maddress-mode=longโ generate code for long address mode. Only supported for 64-bit and x32 environments. It's the default address mode for 64-bit environments.-maddress-mode=shortโ generate code for short address mode. Only supported for 32-bit and x32 environments. It's the default address mode for 32-bit and x32 environments. Matching set, we love a pair. ๐-mneeded,-mno-neededโ emitGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for Linux target to indicate the micro-architecture ISA level required to execute the binary. iykyk. โจ-mno-direct-extern-accessโ without-fpicnor-fPIC, always use the GOT pointer to access external symbols. With-fpicor-fPIC, treat access to protected symbols as local symbols. The default is-mdirect-extern-access.
Warning: shared libraries compiled with-mno-direct-extern-accessand executable compiled with-mdirect-extern-accessmay not be binary compatible if protected symbols are used in shared libraries and executable. This is the "do not mix these, I am begging you" corner of the manual. ๐
-munroll-only-small-loopsโ controls conservative small loop unrolling. It's default enabled byO2, and unrolls loop with less than 4 insns by 1 time. Explicit-f[no-]unroll-[all-]loopswould disable this flag to avoid any unintended unrolling behavior that user does not want. Nobody wants surprise unrolling, periodt. ๐-mlam=choiceโ LAM (linear-address masking) allows special bits in the pointer to be used for metadata. The default isnone. Withu48, pointer bits in positions 62:48 can be used for metadata; withu57, pointer bits in positions 62:57 can be used for metadata. Metadata bits said "we're here too." ๐
๐ป x86 Windows Options ๐ป
These additional options are available for Microsoft Windows targets:
-mconsoleโ this option specifies that a console application is to be generated, by instructing the linker to set the PE header subsystem type required for console applications. This option is available for Cygwin and MinGW targets and is enabled by default on those targets.-mdllโ available for Cygwin and MinGW targets. It specifies that a DLL โ a dynamic link library โ is to be generated, enabling the selection of the required runtime startup object and entry point. ๐-mnop-fun-dllimportโ available for Cygwin and MinGW targets. It specifies that the"dllimport"attribute should be ignored. Just straight up ignored, bestie, not read, not answered, left on seen. ๐-mthreadsโ available for MinGW targets. It specifies that MinGW-specific thread support is to be used.-municodeโ available for MinGW-w64 targets. It causes the"UNICODE"preprocessor macro to be predefined, and chooses Unicode-capable runtime startup code. ๐-mwin32โ available for Cygwin and MinGW targets. It specifies that the typical Microsoft Windows predefined macros are to be set in the pre-processor, but does not influence the choice of runtime library/startup code. Macros yes, runtime no. Stay in your lane. ๐-mwindowsโ available for Cygwin and MinGW targets. It specifies that a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately. โจ-fno-set-stack-executableโ available for MinGW targets. It specifies that the executable flag for the stack used by nested functions isn't set. This is necessary for binaries running in kernel mode of Microsoft Windows, since there the User32 API, which is used to set executable privileges, isn't available.-fwritable-relocated-rdataโ available for MinGW and Cygwin targets. It specifies that relocated-data in read-only section is put into the.datasection. This is a necessary for older runtimes not supporting modification of.rdatasections for pseudo-relocation.-mpe-aligned-commonsโ available for Cygwin and MinGW targets. It specifies that the GNU extension to the PE file format that permits the correct alignment of COMMON variables should be used when generating code. It is enabled by default if GCC detects that the target assembler found during configuration supports the feature. ๐
See also under x86 Options for standard options.
๐ฆ Xstormy16 Options ๐ฆ
These options are defined for Xstormy16:
-msimโ choose startup files and linker script suitable for the simulator. That's it, that's the whole Xstormy16 moment. ๐ธ
๐บ Xtensa Options ๐บ
These options are supported for Xtensa targets:
-mconst16,-mno-const16โ turns on/off usingCONST16instructions to load constant values. Real talk:CONST16currently isn't a standard option from Tensilica. When it's enabled,CONST16instructions are always used in place of the standardL32Rinstructions. And it's only enabled by default if theL32Rinstruction isn't available. Periodt. ๐-mfused-madd,-mno-fused-maddโ enable/disable fused multiply/add and multiply/subtract instructions in the floating-point option. Heads up: this has no effect if the floating-point option isn't also enabled. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and add/subtract operations. Lowkey useful when you need strict IEEE 754-compliant results: the fused multiply add/subtract instructions don't round the intermediate result, so they produce results with more bits of precision than the IEEE standard specifies. Disabling fused multiply add/subtract instructions also ensures the program output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. โจ-mserialize-volatile,-mno-serialize-volatileโ when this option is enabled, GCC insertsMEMWinstructions beforevolatilememory references to guarantee sequential consistency. Default is-mserialize-volatile. Use-mno-serialize-volatileto omit theMEMWinstructions. ๐ซถ-mforce-no-picโ for targets like GNU/Linux, where all user-mode Xtensa code must be position-independent code (PIC), this option disables PIC for compiling kernel code. ๐-mtext-section-literals,-mno-text-section-literalsโ these options control the treatment of literal pools. Default is-mno-text-section-literals, which places literals in a separate section in the output file. That allows the literal pool to be placed in a data RAM/ROM, and it also allows the linker to combine literal pools from separate object files to remove redundant literals and improve code size. With-mtext-section-literals, literals are interspersed in the text section to keep them as close as possible to their references. This may be necessary for large assembly files. Literals for each function are placed right before that function. ๐ง-mauto-litpools,-mno-auto-litpoolsโ these options also control the treatment of literal pools. Default is-mno-auto-litpools, which places literals in a separate section in the output file unless-mtext-section-literalsis used. With-mauto-litpools, the literals are interspersed in the text section by the assembler. The compiler does not produce explicit.literaldirectives and loads literals into registers withMOVIinstructions instead ofL32Rto let the assembler do relaxation and place literals as necessary. This option allows the assembler to create several literal pools per function and assemble very big functions, which may not be possible with-mtext-section-literals. ๐-mtarget-align,-mno-target-alignโ when enabled, GCC instructs the assembler to automatically align instructions to reduce branch penalties at the expense of some code density. The assembler attempts to widen density instructions to align branch targets and the instructions following call instructions. If there aren't enough preceding safe density instructions to align a target, no widening is performed. Default is-mtarget-align. These options do not affect the treatment of auto-aligned instructions likeLOOP, which the assembler always aligns, either by widening density instructions or by insertingNOPinstructions. ๐ธ-mlongcalls,-mno-longcallsโ when enabled, GCC instructs the assembler to translate direct calls to indirect calls unless it can determine that the target of a direct call is in the range allowed by the call instruction. This translation typically occurs for calls to functions in other source files. Specifically, the assembler translates a directCALLinstruction into anL32Rfollowed by aCALLXinstruction. Default is-mno-longcalls. This option should be used in programs where the call target can potentially be out of range. This option is implemented in the assembler, not the compiler, so the assembly code generated by GCC still shows direct call instructions โ look at the disassembled object code to see the actual instructions. Note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range. ๐ญ-mabi=nameโ generate code for the specified ABI. Permissible values are:call0,windowed. The default ABI is chosen by the Xtensa core configuration. โจ-mabi=call0โ when enabled, function parameters are passed in registersa2througha7, registersa12througha15are caller-saved, and registera15may be used as a frame pointer. When this version of the ABI is enabled, the C preprocessor symbol__XTENSA_CALL0_ABI__is defined. ๐-mabi=windowedโ when enabled, function parameters are passed in registersa10througha15, and the called function rotates the register window by 8 registers on entry so that its arguments are found in registersa2througha7. Registera7may be used as a frame pointer. The register window is rotated 8 registers back upon return. When this version of the ABI is enabled, the C preprocessor symbol__XTENSA_WINDOWED_ABI__is defined. ๐-mextra-l32r-costs=nโ specify an extra cost of instruction RAM/ROM access forL32Rinstructions, in clock cycles. This affects, when optimizing for speed, whether loading a constant from literal pool usingL32Ror synthesizing the constant from a small one with a couple of arithmetic instructions. The default value is0. ๐ฅ
๐ zSeries Options ๐
These are listed under
๐ธ ENVIRONMENT ๐ธ
ok so this section is all about the env vars that change how GCC does its thing ๐ซ Some of them work by giving you a place to stash directories or prefixes to look in when hunting down files. Others are just, like, telling GCC about the general vibe of the compilation environment.
Also real quick bestie โ you can also point at search spots with options like -B, -I and -L. Those win over anything you set in the environment, and the environment wins over whatever GCC's own configuration says. Priority order, periodt. ๐
LANG,LC_CTYPE,LC_MESSAGES,LC_ALLโ these control how GCC handles localization info, which is the whole reason it can play nice with different national conventions. GCC peeks at the locale categoriesLC_CTYPEandLC_MESSAGESif it was configured to do so. You can set these to any value your installation supports. A super typical one isen_GB.UTF-8โ that's English in the United Kingdom, encoded in UTF-8. ๐ฌ๐งโจ
LC_CTYPE is the one that specifies character classification. GCC uses it to figure out character boundaries in a string, and this is needed because some multibyte encodings contain quote and escape characters that would otherwise get read as a string end or an escape. messy ๐
LC_MESSAGES specifies the language for diagnostic messages.
If LC_ALL is set, it overrides both LC_CTYPE and LC_MESSAGES. If it's not set, then LC_CTYPE and LC_MESSAGES just default to whatever LANG says. And if none of these are set at all? GCC falls back to traditional C English behavior. classic.
TMPDIRโ if set, this tells GCC which directory to use for temporary files. GCC generates temp files to hold the output of one compilation stage that's about to be fed into the next stage as input. The example given is the output of the preprocessor, which becomes the input to the compiler proper. it's giving relay race ๐โโ๏ธGCC_COMPARE_DEBUGโ setting this is nearly equivalent to passing-fcompare-debugto the compiler driver. For the whole story, go see the documentation for that option.GCC_EXEC_PREFIXโ if it's set, this is the prefix used in the names of the subprograms the compiler executes. No slash gets added when this prefix is combined with the subprogram name, but you absolutely may specify a prefix that ends with a slash if that's your thing ๐
If GCC_EXEC_PREFIX isn't set, GCC tries to figure out a suitable prefix based on the pathname it was invoked with.
If GCC can't find the subprogram using the prefix you gave, it goes and looks in the usual places instead.
The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/, where prefix is the prefix of the installed compiler. In many cases prefix is the value of "prefix" when you ran the configure script.
Other prefixes given with -B take precedence over this one.
This prefix is also used to find files like crt0.o that get used for linking.
And it's used in a genuinely unusual way when finding directories to search for header files. For each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries replacing that beginning with the specified prefix to make an alternate directory name. So with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. And if a standard directory begins with the configured prefix, then the value of that prefix gets replaced by GCC_EXEC_PREFIX when looking for header files. lowkey wild ๐คฏ
COMPILER_PATHโ its value is a colon-separated list of directories, much likePATH. GCC tries these directories when searching for subprograms, but only if it couldn't find the subprograms usingGCC_EXEC_PREFIX.LIBRARY_PATHโ same deal, colon-separated list of directories, much likePATH. When GCC is configured as a native compiler, it tries the directories you list when searching for special linker files, if it couldn't find them usingGCC_EXEC_PREFIX. Linking with GCC also uses these directories when hunting for ordinary libraries for the-loption โ but directories specified with-Lcome first, no exceptions. ๐ฅLANGโ (yep, again) this one passes locale info to the compiler. One way that info gets used is deciding the character set used when character literals, string literals and comments are parsed in C and C++. When the compiler is configured to allow multibyte characters, these values ofLANGare recognized:C-JISโ recognize JIS characters.C-SJISโ recognize SJIS characters.C-EUCJPโ recognize EUCJP characters.
And if LANG is not defined, or it's set to literally anything else, then the compiler uses mblen and mbtowc as defined by the default locale to recognize and translate multibyte characters. ๐ถ
GCC_EXTRA_DIAGNOSTIC_OUTPUTโ if you set this to one of the values below, extra text gets emitted to stderr whenever fix-it hints are emitted. Just so you know,-fdiagnostics-parseable-fixitsand-fno-diagnostics-parseable-fixitstake precedence over this environment variable.fixits-v1โ emit parseable fix-it hints, equivalent to-fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.fixits-v2โ same asfixits-v1, except columns are expressed as display columns, as per-fdiagnostics-column-unit=display.
Some additional environment variables affect the behavior of the preprocessor. ๐
CPATH,C_INCLUDE_PATH,CPLUS_INCLUDE_PATH,OBJC_INCLUDE_PATHโ each one's value is a list of directories separated by a special character, much likePATH, where header files get looked for. That special character,PATH_SEPARATOR, is target-dependent and decided at GCC build time. For Microsoft Windows-based targets it's a semicolon, and for almost literally every other target it's a colon.
CPATH gives a list of directories searched as if they were specified with -I, but after any paths given with -I options on the command line. This environment variable is used no matter which language is being preprocessed.
The rest of these environment variables only apply when preprocessing the particular language they name. Each one gives a list of directories searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element tells the compiler to search its current working directory. Empty elements can sit at the beginning or the end of a path. For instance, if the value of CPATH is :/special/include, that does the same thing as -I. -I/special/include. agent of chaos behavior, honestly ๐ซถ
DEPENDENCIES_OUTPUTโ if this is set, its value specifies how to output dependencies for Make, based on the non-system header files the compiler processed. System header files get ignored in the dependency output.
The value can be just a file name โ in that case the Make rules get written to that file, and the target name is guessed from the source file name. Or the value can have the form file target, in which case the rules are written to the file file using target as the target name.
Basically, this env var is equivalent to combining the options -MM and -MF, with an optional -MT switch thrown in too. โจ
SUNPRO_DEPENDENCIESโ this variable is the same asDEPENDENCIES_OUTPUT(see above), except that system header files are not ignored, so it implies-Mrather than-MM. However, the dependence on the main input file is omitted. ๐ โโ๏ธSOURCE_DATE_EPOCHโ if set, its value specifies a UNIX timestamp to use in place of the current date and time in the__DATE__and__TIME__macros, so the embedded timestamps become reproducible. so iconic for reproducible builds ๐ฐ๏ธ
The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00, represented in ASCII. It's identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command.
The value should be a known timestamp, like the last modification time of the source or package, and it should be set by the build process.
๐ BUGS ๐
Want the instructions on reporting bugs? Go look at:
/usr/share/doc/gcc-13/README.Bugs
(In the original that's written as afile://URL โ<file:///usr/share/doc/gcc-13/README.Bugs>โ same place either way bestie ๐ )
๐ FOOTNOTES ๐
- On some systems,
gcc -sharedneeds to build supplementary stub code for constructors to work. On multi-libbed systems,gcc -sharedmust select the correct support libraries to link against. Failing to supply the correct flags may lead to subtle defects โ and nobody wants subtle defects, that's the worst kind ๐ญ Supplying them in cases where they're not necessary is innocuous though, so no stress. Also:-sharedsuppresses the addition of startup code to alter the floating-point environment, as done with-ffast-math,-Ofastor-funsafe-math-optimizationson some targets.
๐ซถ SEE ALSO ๐ซถ
gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1) and the Info entries for gcc, cpp, as, ld, binutils and gdb. the whole friend group fr fr ๐
๐ AUTHOR ๐
See the Info entry for gcc, or:
https://gcc.gnu.org/onlinedocs/gcc/Contributors.html
...for contributors to GCC. (In the original that's written as a URL in angle brackets: <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>.) shoutout to the contributors ๐
๐ COPYRIGHT ๐
Copyright (c) 1988-2023 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page.
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.
and that's a wrap on the whole entire manpage bestie ๐ฅน you read all 122 parts, that's main character energy no cap ๐ โจ this little cutie was put out by gcc-13 and it's dated 2026-09-10 โ go compile something iconic with it ๐ธ๐ฆ
๐ฆ where this page comes from
- ubuntu stonking: g++-13-sparc64-linux-gnu 13.5.0-1ubuntu1cross1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms