GCC(1)
๐ธ NAME ๐ธ
okay bestie, welcome to gcc(1) โ this is the page from the GNU manual, and it's the whole entire saga of the GNU project C and C++ compiler. yes that's the whole name. no notes. ๐
๐ SYNOPSIS ๐
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
so like, these are only the โจmost usefulโจ ones, the rest of the option buffet is down in OPTIONS. and g++ accepts mostly the same options as gcc, bestie. mostly. ๐ซถ
๐ DESCRIPTION ๐
when you invoke GCC, it normally does preprocessing, compilation, assembly and linking. the "overall options" are the girlies that let you stop this whole process at some intermediate stage. for example, -c is literally saying "don't run the linker bestie". then the output is just object files, output by the assembler. iconic behavior.
other options get passed along to one or more stages of processing. some options control the preprocessor, and others control the compiler itself. and yet other options control the assembler and the linker โ but most of those aren't documented here, because you rarely ever need to touch any of them. ๐
most of the command-line options 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. so if the description for a particular option doesn't mention a source language, you can use that option with all supported languages. periodt.
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. and when you compile C++ programs, you should invoke GCC as g++ instead. that's the vibe check right there. โจ
the gcc program accepts options and file names as operands. many options have multi-letter names, so โ and this is important โ multiple single-letter options may not be grouped: -dv is very different from -d -v. do not confuse them, i'm begging. ๐
you can mix options and other arguments. for the most part, the order you use doesn't matter. but 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 like, lowkey pay attention. ๐
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. so don't come for me about the missing twin, okay? ๐ญ
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. (yes that's real and yes they're serious about it. ๐ง)
๐ OPTIONS ๐
โจ Option Summary โจ
okay so here's the run-down of all the options, grouped by type. the actual explanations are in the following sections โ this part is just the guest list. no cap. ๐
๐ฆ 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]
โ ๏ธ Warning Options โ ๏ธ
okay so this is THE roster. Every single warning flag, all of them, right here โ and bestie, I am keeping every last one, because we do not gatekeep in this house. ๐โจ
housekeeping note: the list mixes -f flags and -W flags and that's just how it's printed โ I'm not rearranging, merging, or "tidying" anything. No edits. No skipping. Periodt. ๐
the opening act ๐
-fsyntax-only-fmax-errors=n-Wpedanticโ yes that one, we'll talk about her later-pedantic-errors-wโ lowercase, tiny, a whole mood
the big two + the entourage โจ
-Wextra-Wall-Wabi=n-Waddress-Wno-address-of-packed-member
the alloc / alloca girlies ๐
-Waggregate-return-Walloc-size-larger-than=byte-size-Walloc-zero-Walloca-Walloca-larger-than=byte-size
arrays, arithmetic, attributes ๐ธ
-Wno-aggressive-loop-optimizations-Warith-conversion-Warray-bounds-Warray-bounds=n-Warray-compare-Wno-attributes-Wattribute-alias=n-Wno-attribute-alias-Wno-attribute-warning
bidi, bool, builtins ๐ฆ
-Wbidi-chars=[none|unpaired|any|ucn]-Wbool-compare-Wbool-operation-Wno-builtin-declaration-mismatch-Wno-builtin-macro-redefined
the whole compatibility timeline ๐ (a journey)
-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
casts, chars, clobbering, conversion ๐
-Wcast-align-Wcast-align=strict-Wcast-function-type-Wcast-qual-Wchar-subscripts-Wclobbered-Wcomment-Wno-complain-wrong-lang-Wconversion-Wno-coverage-mismatch-Wno-cpp
dangling everything + the d-words ๐
-Wdangling-else-Wdangling-pointer-Wdangling-pointer=n-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
empty bodies and the e-squad ๐ง
-Wempty-body-Wno-endif-labels-Wenum-compare-Wenum-conversion-Wenum-int-mismatch-Werrorโ main character energy, honestly-Werror=*-Wexpansion-to-defined-Wfatal-errors
the format girlies ๐ (there are so many of them, obsessed)
-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
frames, free-likes, and the f-run ๐
-Wframe-address-Wframe-larger-than=byte-size-Wno-free-nonheap-object-Wno-if-not-aligned-Wno-ignored-attributes-Wignored-qualifiers
the implicit / int / inline zone ๐
-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
L + M, lit rally ๐ธ
-Wlarger-than=byte-size-Wlogical-not-parentheses-Wlogical-op-Wlong-long-Wno-lto-type-mismatch
the missing-ma'am collection ๐
-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
N through P, no notes โจ
-Wnonnull-Wnonnull-compare-Wnormalized=[none|id|nfc|nfkc]-Wnull-dereference-Wno-odr-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
R through S, the prequel ๐
-Wredundant-decls-Wrestrict-Wno-return-local-addr-Wreturn-type-Wno-scalar-storage-order-Wsequence-point
the shadow multiverse ๐
-Wshadow-Wshadow=global-Wshadow=local-Wshadow=compatible-local-Wno-shadow-ivar
shifts + signs ๐ฆ
-Wno-shift-count-negative-Wno-shift-count-overflow-Wshift-negative-value-Wno-shift-overflow-Wshift-overflow=n-Wsign-compare-Wsign-conversion
sizeof, stack, strict, stringop ๐
-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
suggest + switch + the s-tail ๐
-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
tautological through type-limits โญ
-Wtautological-compare-Wtrampolines-Wtrigraphs-Wtrivial-auto-var-init-Wtsan-Wtype-limits
U + the unsuffixed one ๐ซถ
-Wundef-Wuninitialized-Wunknown-pragmas-Wunsuffixed-float-constants
the whole -Wunused extended cinematic universe ๐ญ (there's a lot, we love her)
-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
V ๐
-Wno-varargs-Wvariadic-macros-Wvector-operation-performance-Wvla-Wvla-larger-than=byte-size-Wno-vla-larger-than-Wvolatile-register-var
W through Z, closing it out โจ
-Wwrite-strings-Wxor-used-as-pow-Wzero-length-bounds
๐ต๏ธ Static Analyzer Options ๐ต๏ธ
bestie, this next batch is the detective squad ๐ โ and yes, the name says "static analyzer" but the flags in here are a mix of -f and -W forms, and one of them (-Wanalyzer-too-complex) doesn't even have the -Wno- prefix like her siblings. Weird? A little. Iconic? Absolutely. I'm listing them all in order, no cap.
the -fanalyzer family ๐ธ
-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
the -fdump-analyzer-* dump girlies ๐พ (she dumps everything, zero chill)
-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
the -Wno-analyzer-* roster, first half ๐
-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
the odd one out ๐
-Wanalyzer-too-complexโ look at her, no-Wno-prefix, living her truth
the -Wno-analyzer-* roster, second half ๐
-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
๐ C and Objective-C-only Warning Options ๐
okay so these ones are the C and Objective-C exclusives โ the "you had to be there" crowd. Every single one, right here:
-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
๐ Debugging Options ๐
and now the debug era ๐ซถ โ where all the -g variants live. This is the section for when your code is doing something and you have zero clue what. Every flag, in order, untouched:
the -g origins ๐
-g-glevel-gdwarf-gdwarf-version-gbtf-gctf-gctflevel-ggdb
recording + strictness ๐พ
-grecord-gcc-switches-gno-record-gcc-switches-gstrict-dwarf-gno-strict-dwarf
assembler location support โจ
-gas-loc-support-gno-as-loc-support-gas-locview-support-gno-as-locview-support
columns, widths, frontiers, views ๐ธ
-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
the format + split crew ๐ฆ
-gvms-gz[=type]-gsplit-dwarf-gdescribe-dies-gno-describe-dies
the -f debug besties ๐
-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
bestie, that's the whole list for this chunk ๐ every flag accounted for, nothing dropped, nothing renamed. and we're not done โ more parts coming, keep scrolling. โจ
โจ Optimization Options โจ
okay bestie, optimization flags are literally the glow-up your code deserves. GCC has a whole squad of them and they're all here, no cap. Every single one is valid, and I'm not playing favorites (except maybe -O2, but that's a secret ๐คซ). Here's the full roster:
-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
the way this list is longer than my last essay... but every flag ate. periodt. ๐
โจ Program Instrumentation Options โจ
okay so this is the spy gear section. instrumentation? it's giving detective vibes, bestie. you wanna see what your program is actually doing, track coverage, sanitize the heck out of it โ all of that. here's the whole toolkit:
-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
ngl this section is lowkey underrated. every flag here is a little bodyguard for your binary. ๐ซถ
โจ Preprocessor Options โจ
preprocessor? that's the backstage crew that gets everything ready before the main show. macros, includes, character sets โ it's all happening here. don't sleep on these, bestie. here's the whole list:
-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
the way these flags are quietly running the whole operation... main character energy, honestly. โจ
โจ Assembler Options โจ
assembler options? short but mighty. just two lil baddies:
-Wa,option -Xassembler option
and yes, they ate. ๐
โจ Linker Options โจ
linker time! this is where all your object files and libraries come together like a group project that actually works. here's the whole squad:
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
fr fr, linking is the final boss of the build process, but these flags make it slay. ๐
โจ Directory Options โจ
directory options are giving GPS for your compiler. telling it where to find headers, libraries, plugins, all of it. here's the map:
-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
no cap, without these you'd be lost in the filesystem like it's a corn maze. ๐
โจ Code Generation Options โจ
code gen options? these are the aesthetic choices for your binary. calling conventions, position independence, visibility, unwinding โ it's all here. the whole vibe check:
-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
this section is iconic, honestly. every flag is a whole mood. ๐
โจ Developer Options โจ
and finally, developer options! this is the behind-the-scenes director's cut. debugging, dumping, reporting, timing โ all the juicy internal stuff. for when you wanna see how the sausage gets made. here's the full list:
-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]
and we're not even done yet, bestie. there's so much more coming, so don't touch that dial. ๐
Machine-Dependent Options ๐
okay so bestie, we're deep in the machine-dependent options now and there are SO many, but don't worry, I got you. These are the ones that change based on what processor you're targeting. Let's go architecture by architecture, no cap. ๐
AArch64 Options โจ
-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 ๐ฆ
-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 ๐
-march=gpu-mtune=gpu-mstack-size=bytes
ARC Options ๐ธ
-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 ๐ช
-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 ๐
-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 ๐ค
-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 ๐ฏ
-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 ๐
-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 ๐ฆ
-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 ๐
-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 ๐ง
-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 ๐ฆพ
-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 ๐ฆ
-mcpu=cpu-msim-memregs=number
M680x0 Options ๐
bestie, the M680x0 target came to serve and it brought a whole roster of flags. here's the full lineup, every single one, no crumbs left behind:
-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 ๐
the MCore crew said "we're lowkey niche and we're at peace with that" and honestly, respect:
-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 โจ
okay so MicroBlaze is the girl who has an option for everything, including opinions about multiplies and divides. look at this roster:
-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 ๐
MIPS said "we're the main character" and then dropped a flag list so long it needs its own zip code. every single one, bestie, deeply obsessed:
-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
MMIX Options ๐ฆ
MMIX is giving quiet-art-kid energy and honestly the flag names are kind of a vibe:
-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 ๐ธ
short, sweet, and every flag accounted for:
-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 ๐
literally four flags and one of them has a dot in the middle. iconic behavior:
-meb -mel -mmul.x -mno-crt0
MSP430 Options ๐ซถ
tiny chip, BIG roster. make it make sense (affectionate):
-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 ๐
every flag, right here, no notes:
-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 โญ
bestie the gpopt flags are everywhere on this one. here's the whole set:
-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 ๐
three flags. three. and they ate:
-m64 -mmainkernel -moptimize
OpenRISC Options ๐ง
float, mul, div, and a whole mood. the full list:
-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 ๐
the retro icon returned and it did NOT come empty-handed:
-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 ๐
See RS/6000 and PowerPC Options.
yep, that's it, it's just pointing you down the hall to the RS/6000 and PowerPC section. consider this your lil redirect, bestie ๐ซถ
PRU Options โจ
short, sharp, slay:
-mmcu=mcu -minrt -mno-relax -mloop -mabi=variant
RISC-V Options ๐ฅ
RISC-V came through with the whole menu and honestly it's a lot, but every flag matters so here we go:
-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 ๐ฆ
look at the -mcpu=g10 / g13 / g14 trio, they're giving sibling energy:
-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 ๐
okay THE big one. the PowerPC section is a maximalist queen and she's not sorry about it. brace yourself, bestie, here's every single flag:
-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
periodt. she's thorough. ๐
RX Options ๐ธ
every flag, present and correct:
-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 ๐
closing this part out with the S/390 and zSeries lineup. every single one, no skips:
-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 bestie, these are the SuperH ones โ just vibes and flag names, no notes attached, so I'm listing them exactly as they come ๐ธ
-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
โ๏ธ Solaris 2 Options
yes queen, Solaris gets her own lil corner:
-mclear-hwcap-mno-clear-hwcap-mimpure-text-mno-impure-text-pthreads
๐ฐ๏ธ SPARC Options
the whole SPARC roster, no edits, no skips:
-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
the x86 buffet. it's giving encyclopedia, and we love her for it ๐ absolutely nothing dropped:
-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
๐ช x86 Windows Options
windows girlies, this one's for you:
-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
- See S/390 and zSeries Options.
๐ Options Controlling the Kind of Output
okay so, storytime: compiling can involve up to four stages, and they always happen in this exact order โ preprocessing, compilation proper, assembly, and linking. no shuffling, bestie, the queue is the queue ๐
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 combines all the object files โ both the ones you just freshly compiled and the ones you passed in as input โ into an executable file. slay, that's the whole pipeline โจ
For any given input file, the file name suffix tells GCC what kind of compilation to do:
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. heads up bestie: you have to 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. again, you must link with thelibobjclibrary to make an Objective-C++ program work. and no cap:.Mrefers to a literal capitalM.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 (that's the default), or a 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. careful: in.cxxthe last two letters must both be literallyx. and likewise,.Crefers to a literal capitalC.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). these files are also called specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). these 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 also specify the input language explicitly with the -x option:
-x languageโ 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. ๐
heads up: some combinations do absolutely nothing at all. for example,-x cpp-output -Einstructsgccto do nothing. nothing! iconic behaviour honestly ๐
-cโ Compile or assemble the source files, but do NOT link. The linking stage simply is not done, bestie. 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. (Not them getting ignored too ๐)
-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. 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. ๐
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.*.
Ok so when you're compiling and then linking from multiple input files, a defaulted-or-explicitly-given dumppfx also goes through that whole dumpbase-transformation thing we just talked about (like, picture the foo.c + bar.c situation above, but without -c). And if neither -dumpdir nor -dumpbase got handed to us? Then the linker output base name โ minus auxdropsuf if you specified one, or the executable suffix otherwise โ plus a dash gets appended to the default dumppfx instead. ๐
But wait, plot twist ๐ซข โ unlike the earlier linking cases:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...
this does not append the output name main to dumppfx, because -dumpdir was explicitly specified. The whole vibe here is that your explicitly-specified dumppfx is allowed to contain the output name as part of the prefix if you want it to; only an explicitly-specified -dumpbase would get combined with it, so that we don't just yeet a meaningful option into the void. ๐๏ธโจ
When you're compiling and then linking from a single input file, the linker output base name only gets appended to the default dumppfx as described above if it does not share a base name with that single input file. We already covered this in the single-input linking cases earlier, but not the version with an explicit -dumpdir that inhibits the combination โ even if it gets overridden by -save-temps=*:
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. ๐
Let me sum it all up for you, bestie โ an intuitive though slightly imprecise data flow ๐ฆ: the primary output name gets broken into a directory part and a basename part; dumppfx is set to the former, unless it's overridden by -dumpdir or -save-temps=*; and dumpbase is set to the latter, unless it's overridden by -dumpbase. If there are multiple inputs, or we're linking, this dumpbase may get combined with dumppfx and taken from each input file. Auxiliary output names for each input are formed by combining dumppfx, dumpbase minus suffix, and the auxiliary output suffix; dump output names are only different in that the suffix from dumpbase is retained. ๐ธ
Now, 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 โ gets passed down with a trailing period replacing the compiler-added dash (if any), as a -dumpdir option to lto-wrapper. And because it's involved in linking, that program doesn't normally get any -dumpbase and -dumpbase-ext, and it ignores them. ๐
When running sub-compilers, lto-wrapper appends LTO stage names to the received dumppfx, makes sure it contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. Lowkey elegant, no cap. ๐
-vโ Prints (on standard error output) the commands executed to run the stages of compilation. It also prints the version number of the compiler driver program, and of the preprocessor, and of the compiler proper. So like, receipts for every stage. ๐งพ-###โ Just like-v, except the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or./-_. This is the move for shell scripts that want to capture the command lines the driver generates. ๐ฅ--helpโ Prints (on standard output) a description of the command-line options thatgccunderstands. If-vis also specified, then--helpgets passed along to the various processesgccinvokes too, so they can show off the command-line options they accept. And if-Wextrawas also specified (before the--helpoption), then command-line options with no documentation attached to them get displayed as well. ๐--target-helpโ Prints (on standard output) a description of 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, bestie:optimizersโ Displays all of the optimization options supported by the compiler.warningsโ Displays all of the options controlling warning messages produced by the compiler.targetโ Displays target-specific options. Unlike the--target-helpoption though, target-specific options of the linker and assembler are not displayed, because those tools don't currently support the extended--help=syntax.paramsโ Displays the values recognized by the--paramoption.languageโ Displays 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.commonโ Displays the options that are common to all languages.
And these are the supported qualifiers:
undocumentedโ Display only those options that are undocumented.joinedโ Display options taking an argument that appears after an equal sign in the same continuous piece of text, such as:--help=target.separateโ Display options taking an argument that appears as a separate word following the original option, such as:-o output-file.
So, for example, to display all the undocumented target-specific switches supported by the compiler, you'd 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, you'd use:
--help=warnings,^joined,^undocumented
Heads up 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 nothing left to display. 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. Each successive use displays its requested class of options, skipping the ones that have already been displayed. If --help is also specified anywhere on the command line, then it takes precedence over any --help= option. ๐
If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= is changed. Instead of describing the displayed options, an indication is given as to 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, iconic:
% 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
Obsessed with this diff trick, fr fr. ๐
--versionโ Displays the version number and copyrights of the invoked GCC. โจ-pass-exit-codesโ Normally thegccprogram exits with the code of1if any phase of the compiler returns a non-success return code. If you specify-pass-exit-codes, thegccprogram instead returns with the numerically highest error produced by any phase returning an error indication. 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. ๐-specs=fileโ Process file after the compiler reads in the standard specs file, in order to override the defaults that thegccdriver program uses when determining 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 are 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 .... ๐
-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. 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 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. ๐ง-fplugin=name.soโ loads up the plugin code sitting in the filename.so, which is assumed to be a shared object that the compiler willdlopen. The base name of that shared object file is what identifies the plugin when it comes to parsing arguments (peep-fplugin-arg-name-key=valueright below). Every plugin should define the callback functions listed in the Plugins API. ๐-fplugin-arg-name-key=valueโ defines an argument calledkeywith a value ofvaluefor the plugin calledname. So basically you're passing notes to your plugin bestie. ๐ซถ-fdump-ada-spec[-slim]โ for C and C++ source and include files, this generates the matching Ada specs. Ada girlies stay winning. โจ-fada-spec-parent=unitโ used together with-fdump-ada-spec[-slim]up there, it generates Ada specs as child units of parentunit. ๐-fdump-go-spec=fileโ for input files in any language, this generates the corresponding Go declarations infile. It writes Goconst,type,var, andfuncdeclarations, which lowkey might be a really useful way to start writing a Go interface to code written in some other language. ๐@fileโ reads command-line options fromfile. The options it reads get inserted in place of the original@fileoption. And listen: iffiledoesn't exist, or can't be read, then the option is treated literally and not removed. It stays right there. ๐
Options inside file are separated by whitespace. Wanna include a whitespace character inside an option? Surround the whole option in either single or double quotes. And any character at all (backslash included, bestie) can be included by prefixing that character with a backslash. The file may itself contain additional @file options โ and any of those get processed recursively, so it's files all the way down. ๐
โจ Compiling C++ Programs โจ
C++ source files conventionally use one of these 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 exact same way you'd call it for C programs (usually with the name gcc). She just knows. ๐
However โ and this is the important bit โ 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++. Two names, one icon. ๐
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. Pick your fighter. ๐ธ
โจ 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. Yeah. She's strict like that. ๐
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. Sneaky but legal. ๐
The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -Wpedantic is required in addition to -ansi. You gotta ask for the drama. ๐ญ
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. Respectful. ๐
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. They lose their VIP status. โจ
-std=โ determines 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. She's keeping receipts. ๐ง
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). See<https://gcc.gnu.org/c99status.html>for 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. Do not build your whole life on this one, bestie. ๐ญ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โ outputs to the givenfilenameprototyped 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. C-only party, everyone else is not invited. ๐
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. Receipts, receipts, receipts. ๐งพ
-fno-asmโ bestie, this one tells GCC to stop treatingasm,inlineandtypeofas keywords, so your code can use those words as plain old identifiers. If you still wanna reach for the keyword versions, use__asm__,__inline__and__typeof__instead โ they never lose their powers ๐ In C, -ansi implies -fno-asm.
In C++ tho, inline is a standard keyword and this switch does not touch it. So if that's your situation you probably want -fno-gnu-keywords instead โ that one kills typeof while leaving asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only affects asm and typeof, because inline is a standard keyword in ISO C99. And in C2X mode (-std=c2x or -std=gnu2x), it only affects asm, because typeof is a standard keyword in ISO C2X. the evolution โจ
-fno-builtin-fno-builtin-function
Okay so these two stop GCC from recognizing built-in functions that don't begin with the __builtin_ prefix. ๐
Here's the tea: GCC normally generates special code to handle certain built-in functions more efficiently. Like, calls to alloca may become single instructions that adjust the stack directly, and calls to memcpy may turn into inline copy loops. The resulting code is often smaller and faster โ but because the function calls no longer appear as calls, you cannot set a breakpoint on those calls, and you also can't change the behavior of the functions by linking against a different library. ๐ญ On top of that, when 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. queen behavior fr fr ๐
With the -fno-builtin-function option, only the built-in function function gets disabled โ just that one, nobody else. And function must not begin with __builtin_. If you name a function that isn't built-in in this version of GCC, the option is simply ignored, no harm done. Also heads up: there is no corresponding -fbuiltin-function option. So if you wanna enable built-in functions selectively while using -fno-builtin or -ffreestanding, you can define macros like this:
#define abs(n) __builtin_abs ((n))
#define strcpy(d, s) __builtin_strcpy ((d), (s))
iconic workaround, tbh ๐
-fcond-mismatchโ lets you have conditional expressions with mismatched types in the second and third arguments. The value of such an expression isvoid. ๐ But heads up bestie: this option is not supported for C++.-ffreestandingโ asserts that compilation targets a freestanding environment. This 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 is 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.-fgnu-tmโ when you specify -fgnu-tm, 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.
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 you're in C99 mode. ๐ฆ
Using this option is roughly equivalent to adding the gnu_inline function attribute to all inline functions.
Meanwhile, -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 behavior). That option is not supported in -std=c90 or -std=gnu90 mode.
Wanna check which semantics are in effect for inline functions? The preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ got you covered ๐
-fhostedโ asserts that compilation targets a hosted environment. This implies -fbuiltin. A hosted environment is one where the entire standard library is available, and wheremainhas 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. โ ๏ธ Heads up: this option should not be used for new code.-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 types declarations, like so:
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
These specify for which OpenMP and OpenACC offload targets code should be generated. ๐ The default behavior, equivalent to -foffload=default, is to generate code for all supported offload targets. The -foffload=disable form generates code only for the host fallback, while -foffload=target-list generates 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=options form. 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 -fopenacc is 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 their own. 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 -fopenmp is 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, -fopenmp implies -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, with#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran. Other OpenMP directives are just ignored. ๐-fopenmp-target-simd-clone-fopenmp-target-simd-clone=device-type
So on top of generating SIMD clones for functions marked with the declare simd directive, GCC also generates clones for functions marked with the OpenMP declare target directive that are suitable for vectorization when this option is in effect. ๐ธ The device-type may be one of none, host, nohost, and any, which correspond to keywords for the device_type clause of the declare target directive; clones are generated for the intersection of devices specified. -fopenmp-target-simd-clone is equivalent to -fopenmp-target-simd-clone=any, and -fno-openmp-target-simd-clone is 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's disabled by default. ๐คทโโ๏ธ
-fpermitted-flt-eval-methods=styleโ okay this one is a lil academic 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 doesn't specify the meaning of other positive values ofFLT_EVAL_METHOD. So code conforming to C11 may not have been written expecting the possibility of these 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. ๐ซถ
-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. โ ๏ธ This is only supported for C, not C++.
-fsigned-bitfields,-funsigned-bitfields,-fno-signed-bitfields,-fno-unsigned-bitfieldsโ so bestie, these four decide whether a bit-field is signed or unsigned when the declaration is out here being vague and uses neithersignednorunsigned. And the default? Signed, periodt. That's the consistent choice because the basic integer types likeintare signed types too. Consistency queen ๐-fsigned-charโ makes the typecharsigned, just likesigned char๐ซถ
Not me being extra but: this is literally equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. And likewise, -fno-signed-char is equivalent to -funsigned-char. It's giving mirror selfie ๐ช
-funsigned-charโ makes the typecharunsigned, just likeunsigned charโจ
Every kind of machine has a default for what char should be. It's either like unsigned char by default, or like signed char by default. No in-between, no grey area ๐
Ideally, a portable program should always write signed char or unsigned char when it actually depends on the signedness of an object. But ngl, so many programs have been written using plain old char and just expecting it to be signed, or expecting it to be unsigned, depending on whatever machines they were written for originally. This option, and its inverse, let you make a program like that work with the opposite default. Fixing legacy code one flag at a time ๐ญ
And lowkey important: the type char is always a distinct type from each of signed char and unsigned char, even though its behavior is always just like one of those two. Distinct. Iconic. Don't get it twisted ๐ธ
-fstrict-flex-arraysโ controls when the 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, which is the strictest of the strict. 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, which is the least strict. All trailing arrays of structures just get treated as flexible array members. YOLO mode ๐
-fstrict-flex-arrays=levelโ same mission as above: controls when the 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. Per-field customisation, we love to see it ๐
-fsso-struct=endiannessโ sets the default scalar storage order of structures and unions to theendiannessyou specify. The accepted values arebig-endian,little-endian, andnativefor the native endianness of the target (andnativeis the default). Heads up though: this option is not supported for C++ ๐
โ ๏ธ Warning: 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. Like, actually do not mix and match casually bestie, it will not go well ๐
๐ฆ Options Controlling C++ Dialect ๐ฆ
This section describes the command-line options that are only meaningful for C++ programs. But also, you can 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. Main character option, supporting cast vibes ๐
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 versionnof the C++ ABI. The default is version0. Okay so the lore here is deep, let's go ๐ง
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 get fixed. It's a moving target, she's evolving โญ
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 all the way 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, declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors. Multi-tasking queen โจ
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. But plot twist: it accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Not the oopsie ๐ญ
Version 13, which first appeared in G++ 8.2, fixes that accidental change in version 12. Redemption arc ๐
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 a G++ 10 ABI tag regression.
Version 16, which first appeared in G++ 11, changes the mangling of __alignof__ so it's distinct from that of alignof, and dependent operator names.
Version 17, which first appeared in G++ 12, fixes the 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 whenever it defines a symbol with an incorrect mangled name. This switch specifies which ABI version to use for that 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. And if you want compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option isn't provided but -Wabi=n is, then that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning. Teamwork, but make it flags ๐ค
-fno-access-controlโ turns off all access checking. This switch is mainly useful for working around bugs in the access control code. Living dangerously, bestie ๐จ-faligned-newโ enables support for C++17newof types that require more alignment thanvoid* ::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 honestly few users will need to override the default ofalignof(std::max_align_t). Leave the default alone, she's fine ๐
This flag is enabled by default for -std=c++17.
-fchar8_t,-fno-char8_tโ turns on support forchar8_tas adopted for C++20. This includes adding a whole newchar8_tfundamental 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_tand__cpp_lib_char8_tfeature test macros. That's a lot of glow-up in one flag โจ
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 it 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. So like, for example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified. Read it and weep ๐ญ
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โ checks that the pointer returned byoperator newis non-null before attempting to modify the storage it allocated. This check is normally unnecessary, because the C++ standard specifies thatoperator newonly returns0if it is declaredthrow(), and in that case the compiler always checks the return value even without this option. In all other cases, whenoperator newhas a non-empty exception specification, memory exhaustion is signalled by throwingstd::bad_alloc. See alsonew (nothrow). The compiler was already on it ๐ซก-fconcepts-fconcepts-tsโ okay so this turns on support for the C++ Concepts feature, which is the whole thing about constraining template arguments. With-std=c++20and above, Concepts are literally part of the language standard, so-fconceptsis just on by default, no action needed ๐
Some constructs that the earlier C++ Extensions for Concepts Technical Specification, ISO 19217 (2015), allowed but that didn't make it into the standard, can additionally be enabled with -fconcepts-ts. so extra, so special ๐
-fconstexpr-depth=nโ sets the max nested evaluation depth for C++11constexprfunctions ton. we need a limit here because otherwise how would we ever detect endless recursion during constant expression evaluation?? ๐ The minimum specified by the standard is512.-fconstexpr-cache-depth=nโ sets the max level of nested evaluation depth for C++11constexprfunctions that will be cached ton. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations, yay) against memory consumption (when the cache grows very large from highly recursive evaluations, not yay). The default is8. Very few users are likely to want to adjust it, but if your code does heavyconstexprcalculations you might want to experiment to find which value works best for you. main character tuning energy โจ-fconstexpr-fp-exceptโ Annex F of the C standard says 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. slay for well-defined values ๐ซถ
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++14constexprfunctions ton. again, we need a limit to detect infinite loops during constant expression evaluation. The default is262144(1<<18). ๐-fconstexpr-ops-limit=nโ sets the maximum number of operations during a singleconstexprevaluation. 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 resultingconstexprevaluation might take too long. The default is33554432(1<<25). that's a lot bestie ๐ญ-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 papers P1290, P1332, and P1429. This functionality is intended mostly for those interested in experimentation towards refining the feature to get it into shape for a future C++ standard. it's giving "work in progress, handle with care" ๐ฅ
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, not all three ๐
-fcontract-mode=[on|off]โ controls whether any contracts have any semantics at all. Defaults toon.-fcontract-assumption-mode=[on|off]โ[N4820]controls whether contracts with levelaxiomshould have theassumesemantic. Defaults toon.-fcontract-build-level=[off|default|audit]โ[N4820]specifies which level of contracts to generate checks for. Defaults todefault.-fcontract-continuation-mode=[on|off]โ[N4820]controls 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]โ controls 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. not me ignoring my responsibilities ๐"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. dramatic but valid ๐"check_maybe_continue","maybe"โ this contract is checked. If it fails, the violation handler is called. If the handler returns, execution continues normally.-fcoroutinesโ enables support for the C++ coroutines extension (experimental). ๐ฆ-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. no shortcuts, we're doing the full thing ๐ธ
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. read that twice bestie, it's important ๐ญ
โญ quick vibe check: -fno-enforce-eh-specs breaks the standard on purpose. use it only if you know exactly what you're doing.
-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โ permits 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. iconic behavior honestly โจ-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 implicitlyconstexpr, if they satisfy the requirements for aconstexprfunction. 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 functions ๐-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. don't let the linker catch you slippin' ๐-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. โ ๏ธ-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 it's a C++20 feature but doesn't turn itself on?? ๐ญ-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.) all or nothing, that's the rule ๐-fno-module-lazyโ disable lazy module importing and module mapper creation.-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 theCXX_MODULE_MAPPERenvironment variable is used, and if that is unset, an in-process default is provided. oracle?? we're being fancy now ๐-fmodule-onlyโ okay so this one only emits the Compiled Module Interface, and it inhibits any object file. Just the interface bestie, nothing else. ๐-fms-extensionsโ turnsWpedanticwarnings off for constructs used in MFC, like implicitintand getting a pointer to member function via non-standard syntax. Living that Visual Studio-adjacent life? This is your girl. ๐-fnew-inheriting-ctorsโ enables the P0136 adjustment to the semantics of C++11 constructor inheritance. It's part of C++17 but it's also considered a Defect Report against C++11 and C++14 โ messy legacy behavior fr fr. This flag is enabled by default unless-fabi-version=10or lower is specified. ๐-fnew-ttp-matchingโ enables the P0522 resolution to Core issue 150, template template parameters and default arguments: this lets a template with default template arguments be used as an argument for a template template parameter that has fewer template parameters. Slay. This flag is enabled by default for-std=c++17. โจ-fno-nonansi-builtinsโ disables built-in declarations of functions that are not mandated by ANSI/ISO C. These includeffs,alloca,_exit,index,bzero,conjf, and other related functions. No aliases for you. ๐ซ-fnothrow-optโ treats athrow()exception specification as if it were anoexceptspecification, so it can reduce or eliminate the text size overhead compared to a function with no exception specification at all. And get this โ if the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller, because the EH cleanups for those variables can be optimized away. ๐ The semantic effect is that an exception thrown out of a function with such an exception specification results in a call toterminaterather thanunexpected. So like. be aware. ๐-fno-operator-namesโ do not treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms as keywords. They're just vibes now, not keywords. ๐ธ-fno-optional-diagsโ disables diagnostics that the standard says a compiler does not need to issue. Right now, the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class. Lowkey optional, highkey disabled. ๐ฆ-fpermissiveโ downgrades some diagnostics about nonconformant code from errors to warnings. So using-fpermissiveallows some nonconforming code to compile. It's giving "I'll allow it" energy. ๐-fno-pretty-templatesโ okay so normally, when an error message refers to a specialization of a function template, the compiler prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (e.g.void f(T) [with T = int]rather thanvoid f(int)) so it's clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of these behaviors makes it harder to understand the error message rather than easier, you can use-fno-pretty-templatesto disable them. Sometimes you just want the raw truth. ๐ญ-fno-rttiโ disables generation of information about every class with virtual functions, the info used by the C++ run-time type identification features (dynamic_castandtypeid). If you don't use those parts of the language, you can save some space by using this flag. โจ Note that exception handling uses the same information, but G++ generates it as needed. Thedynamic_castoperator can still be used for casts that do not require run-time type information, i.e. casts tovoid *or to unambiguous base classes.
Careful bestie: mixing code compiled with-frttiwith that 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. Keep it consistent, I'm begging. ๐ฅบ
-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. This is 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. The flag -Wsized-deallocation warns about places that might want to 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 can be represented 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 to the enumerated type. Sneaky casts will sneak. ๐ป-fstrong-eval-orderโ evaluates member access, array subscripting, and shift expressions in left-to-right order, and evaluates assignment in right-to-left order, as adopted for C++17. Enabled by default with-std=c++17. And-fstrong-eval-order=someenables just the ordering of member access and shift expressions, and is the default without-std=c++17. Order matters, periodt. ๐-ftemplate-backtrace-limit=nโ sets the maximum number of template instantiation notes for a single warning or error to n. The default value is10. Ten notes and we're done, no more essays. ๐-ftemplate-depth=nโ sets the maximum instantiation depth for template classes to n. A limit on the template instantiation depth is needed to detect 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, as the compiler can run out of stack space before hitting1024in some situations. So like, 900 is the girl who knows her limits. ๐ซถ-fno-threadsafe-staticsโ do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe. Only if it truly doesn't need it, bestie. ๐-fuse-cxa-atexitโ registers destructors for objects with static storage duration with the__cxa_atexitfunction rather than theatexitfunction. This option is required for fully standards-compliant handling of static destructors, but only works if your C library supports__cxa_atexit. Check before you commit. ๐-fno-use-cxa-get-exception-ptrโ don't use the__cxa_get_exception_ptrruntime routine. This causesstd::uncaught_exceptionto be incorrect, but is necessary if the runtime routine is not available. Trade-offs, always trade-offs. ๐ญ-fvisibility-inlines-hiddenโ this switch declares that the user does not attempt to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.
The effect of this is that GCC may, effectively, mark inline methods with __attribute__ ((visibility ("hidden"))) so that they do not appear in the export table of a DSO and do not require a PLT indirection when used within the DSO. Enabling this option can have a dramatic effect on load and link times of a DSO as it massively reduces the size of 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 as hidden directly, because it does not affect static variables local to the function or cause the compiler to deduce that the function is defined in only one shared object.
You may mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do want to 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.
Explicitly instantiated inline methods are unaffected by this option as their linkage might otherwise cross a shared library boundary. ๐
-fvisibility-ms-compatโ this flag attempts to use visibility settings to make GCC's C++ linkage model compatible with that of Microsoft Visual Studio. Bridging worlds fr fr. ๐ฆ
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 is better to use -fvisibility=hidden and export those classes that are intended to be externally visible. Unfortunately it is possible for code to rely, perhaps accidentally, on the Visual Studio behavior. ๐ฌ
Among the consequences of these changes are that static data members of the same type with the same name but defined in different shared objects are different, so changing one does not change the other; and that pointers to function members defined in different shared objects may not compare equal. When this flag is given, it is a violation of the ODR to define types with the same name differently. Do not do that. Periodt. ๐
-fno-weakโ do not use weak symbol support, even if it is provided by the linker. By default, G++ uses weak symbols if they are available.
Real talk: this option exists only for testing, and should not be used by end-users; it results in inferior code and has no benefits. This option may be removed in a future release of G++. Leave it alone bestie, it's not for you. ๐
-fext-numeric-literals (C++ and Objective-C++ only)โ accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off these 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++โ do not 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.) Building the library itself, iconic behavior. ๐-flang-info-include-translate,-flang-info-include-translate-not,-flang-info-include-translate=headerโ inform of include translation events. The first will note accepted include translations, the second will note declined include translations. Theheaderform will inform of include translations relating to that specific header. Ifheaderis of the form"user"or<system>it will be resolved to a specific user or system header using the include path. Translation receipts, basically. ๐
-flang-info-module-cmiโ okay so this one is like the gossip girl of CMI pathnames ๐ it tells you about Compiled Module Interface pathnames. The bare version notes all read CMI pathnames. โจ-flang-info-module-cmi=module โ themoduleform will not reading a specific module's CMI (yes bestie, that's the exact vibe of the original โ it's giving "will not [report on] reading"). Now, module can be a named module or a header-unit (that second one is indicated by either being a pathname containing directory separators, or being enclosed in<>or"").-stdlib=libstdc++,libc++ โ ๐ when G++ is configured to support this option, it lets you specify alternate C++ runtime libraries. You've got two choices on the menu:libstdc++(the default, the native C++ runtime for G++) andlibc++, which is the C++ runtime installed on some operating systems (like, say, Darwin versions from Darwin11 onwards). The option switches G++ to use the headers from whichever library you picked, and to emit-lstdc++or-lc++respectively, whenever a C++ runtime is required for linking. ๐
Also, bestie, these warning options? They only have meanings for C++ programs:
-Wabi-tag(C++ and Objective-C++ only) โ warns when a type with an ABI tag is used in a context that does not have that ABI tag. Wanna know more about ABI tags? See C++ Attributes. ๐ฆ-Wcomma-subscript(C++ and Objective-C++ only) โ warns about uses of a comma expression inside a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23 (rip ๐). HOWEVER โ a comma expression wrapped in( )is not deprecated. Example time:
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 valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that is not valid in C++23 but used to be valid but deprecated in C++20 โ with a pedantic warning that can be disabled with -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're performing class template argument deduction (CTAD) on a type that has no explicitly written deduction guides. This warning is gonna point out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended. ๐ญ Certain style guides allow CTAD only on types that specifically "opt-in" โ i.e., on types that are 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 seems unusable because all the constructors or destructors in that class are 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 destructor. ๐-Wdangling-reference(C++ and Objective-C++ only) โ warns when a reference is bound to a temporary whose lifetime has ended. For example:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling
In the example above, two temporaries are created โ one for each argument โ and a reference to one of the temporaries is returned. But both temporaries are destroyed at the end of the full expression, so the reference r is dangling. ๐ฑ This warning also detects 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 as well, but only their object argument:
struct S {
const S& self () { return *this; }
};
const S& s = S().self(); // s is dangling
Certain functions are safe in this respect โ for example std::use_facet: they take and return a reference, but they don't return one of its arguments, which can fool the warning. Such functions can be excluded 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 that contains the call to std::minmax.
This warning is enabled by -Wextra. ๐
-Wdelete-non-virtual-dtor(C++ and Objective-C++ only) โ warns whendeleteis used to destroy an instance of a class that has virtual functions and 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 does not 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. 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 when the usual arithmetic conversions are 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 when the usual arithmetic conversions are 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 too. For example:
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) โ okay so this one says do not warn about uses ofstd::initializer_listthat are likely to result in dangling pointers. Since the underlying array for aninitializer_listis handled like a normal C++ temporary object, it's easy to inadvertently 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 localinitializer_listvariable, 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 theinitializer_listin the heap has a dangling pointer. - When an
initializer_listvariable 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 theinitializer_listvariable 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
beginpointer from theinitializer_listargument, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporaryinitializer_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 everyconstexprfunction 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 this restriction (slay, I guess โจ), so it's possible to have a function or a function template markedconstexprfor which no invocation satisfies the requirements of a core constant expression.
This warning is enabled as a pedantic warning by default in C++20 and earlier. In C++23, -Winvalid-constexpr can be turned on, in which case it will be an ordinary warning. For 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 all imported macro definitions are valid at the end of compilation. This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros. ๐ง-Wno-literal-suffix(C++ and Objective-C++ only) โ do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility 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);
}
okay so real talk โ notice how "PRId64" here is treated as a separate preprocessing token ๐ it is not glued onto the string literal, even though it looks like it wants to be. that's just how it is bestie.
This option ALSO handles your warnings when a user-defined literal operator gets declared with a literal suffix identifier that doesn't begin with an underscore. and why do we care? because literal suffix identifiers that don't start with an underscore are reserved for future standardization ๐ so like, hands off, that's the committee's lane.
These warnings are enabled by default. slay ๐
-Wno-narrowing(C++ and Objective-C++ only) โ for C++11 and later standards, narrowing conversions are diagnosed by default, because the standard said so. a narrowing conversion from a constant? that's an error. from a non-constant? that's a warning. but-Wno-narrowingjust suppresses the whole diagnostic. heads up tho: this does NOT change the meaning of well-formed code โ narrowing conversions are still considered ill-formed in SFINAE contexts, no cap.
With -Wnarrowing in C++98, it warns when a narrowing conversion prohibited by C++11 happens inside { }, like:
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) โ warns when anoexcept-expression evaluates tofalsebecause 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 audacity, honestly ๐ญ-Wnoexcept-type(C++ and Objective-C++ only) โ warns if the C++17 feature that makes"noexcept"part of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat.
for 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>". iconic behavior shift โจ
-Wclass-memaccess(C++ and Objective-C++ only) โ warns 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's 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.
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) โ warns 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. ๐ฏ-Wregister(C++ and Objective-C++ only) โ warns 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 a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with-std=c++17.-Wreorder(C++ and Objective-C++ only) โ warns when the order of member initializers given in the code doesn't 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 u, but i'm telling everyone" ๐ญ
-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.
struct T {
...
};
T fn()
{
T t;
...
return std::move (t);
}
But in this example, the "std::move" call prevents copy elision. so you slowed your own code down, bestie ๐
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. ๐ญ brutal.
This warning is enabled by -Wall. periodt.
-Wredundant-tags(C++ and Objective-C++ only) โ warns 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
see? context is everything, iykyk ๐
-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.-Weffc++(C++ and Objective-C++ only) โ warns 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 a virtual destructor in accessible non-polymorphic base 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. yeah. the stdlib said "not my problem" ๐ซ
-Wno-exceptions(C++ and Objective-C++ only) โ disables the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. order matters, bestie!! ๐-Wstrict-null-sentinel(C++ and Objective-C++ only) โ warns 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. so like, cute for GCC, tragic everywhere else ๐
-Wno-non-template-friend(C++ and Objective-C++ only) โ shuts off the warning that fires when non-template friend functions get declared inside a template. Ok so storytime: in very old versions of GCC (like, before the ISO standard was implemented), stuff likefriend int foo(int), where the friend's name is an unqualified-id, could get read as a specific specialization of a template function ๐ญ. The warning exists purely to catch those compatibility problems, and bestie it's on by default.-Wold-style-cast(C++ and Objective-C++ only) โ yells at you if you use an old-style (C-style) cast to a non-void type inside a C++ program. The new-style casts (dynamic_cast,static_cast,reinterpret_cast,const_cast) are way less prone to unintended effects and so much easier to grep for. it's giving glow-up for a reason โจ-Woverloaded-virtual(C++ and Objective-C++ only)-Woverloaded-virtual=nโ warns when a function declaration hides virtual functions from a base class. Example time, watch this:
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();
straight-up fails to compile ๐
When 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". chef's kiss.
The optional level suffix controls the behavior when all the declarations in the derived class override virtual functions in the base class, even if not all of the 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've decided the base class semantics for some overloads are fine.
At level 1, this case does not warn; at level 2, it does. -Woverloaded-virtual by itself selects level 2. Level 1 is included in -Wall. ๐ซถ
-Wno-pmf-conversions(C++ and Objective-C++ only) โ turns off the diagnostic for converting a bound pointer to member function into a plain pointer.-Wsign-promo(C++ and Objective-C++ only) โ warns when overload resolution picks 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. not G++ being messy, it's the standard, ok ๐-Wtemplates(C++ and Objective-C++ only) โ warns when a primary template declaration shows up. Some coding rules disallow templates entirely, and this is how you enforce that rule. The warning is inactive inside a system header file (like the STL), so you can still use the STL. You can also instantiate or specialize templates. balances out ๐-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, plus 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 gets 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 doesn't match either the definition or the first declaration if no definition is provided.
For example, the declaration of struct Object in the argument list of draw triggers the warning. To dodge it, either remove the redundant class-key struct or swap it for class to 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 here to help you achieve a consistent style of class declarations. In code meant 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 together with -Wredundant-tags. ๐ธ
-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 is how you enforce that rule. The warning is inactive inside a system header file (like the STL), so you can still use the STL. You can also define classes that indirectly use multiple inheritance, no cap.-Wvirtual-inheritanceโ warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this is how you enforce that rule. The warning is inactive inside a system header file (like the STL), so you can still use the STL. You can also define classes that indirectly use virtual inheritance.-Wno-virtual-move-assignโ suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. > This is dangerous bestie, because if the virtual base is reachable along more than one path, it gets 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.-Wnamespacesโ warns when a namespace definition is opened. Some coding rules disallow namespaces, and this is how you enforce that rule. The warning is inactive inside a system header file (like the STL), so you can still use the STL. You may also use using directives and qualified names. โจ-Wno-terminate(C++ and Objective-C++ only) โ disables the warning about a throw-expression that will immediately result in a call toterminate.-Wno-vexing-parse(C++ and Objective-C++ only) โ warns about the most vexing parse syntactic ambiguity ๐. This fires 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 for 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. ๐
-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. literally never getting called, why would it ๐ซ-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.
-Wzero-as-null-pointer-constant(C++ and Objective-C++ only) โ warns when a literal 0 is used as a null pointer constant. Super useful for facilitating the conversion tonullptrin C++11. glow-up arc ๐-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=all also warns about class member allocation functions. ๐
-Wno-placement-new-Wplacement-new=nโ warns about placement new expressions with undefined behavior, like constructing an object in a buffer smaller than the type of the object. For example, the placement new expression below gets diagnosed because it tries to construct an array of 64 integers in a buffer only 64 bytes large. math isn't mathing ๐ญ
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โ ok so level two, bestie ๐ on top of diagnosing every single thing level 1 already clocks, this one also clocks placement new expressions that construct an object in the last member of a structure whose type is an array of a single element, and whose size is less than the size of the object being constructed. So yeah, the example right above? diagnosed. But this next construct uses the flexible member array extension to vibe around the level-2 warning completely:
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, sorry not sorry ๐ This one yells about catch handlers that don't catch via reference. With-Wcatch-value=1(or just-Wcatch-valuefor short) it warns about polymorphic class types that are caught by value. With-Wcatch-value=2it warns about all class types that are caught by value. With-Wcatch-value=3it warns about all types that are not caught by reference. And-Wcatch-valueis enabled by-Wall. ๐-Wconditionally-supportedโ C++ and Objective-C++ only. Warns for conditionally-supported constructs, i.e. the ones in(C++11 [intro.defs]). ๐-Wno-delete-incompleteโ C++ and Objective-C++ only. Do not warn when deleting a pointer to an incomplete type, which may cause undefined behavior at runtime. ๐ซฃ This warning is enabled by default, because deleting incomplete types is genuinely a little cursed.-Wextra-semiโ C++, Objective-C++ only. Warns about redundant semicolons after in-class function definitions. Yes bestie, the extra;๐ญ-Wno-inaccessible-baseโ C++, Objective-C++ only. This option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. The warning is enabled by default. Note that the warning for ambiguous virtual bases is enabled by the-Wextraoption. The vibe in question:
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ Suppresses warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor. This warning is on by default, because the ellipsis is not inherited โ fr fr, it just isn't ๐-Wno-invalid-offsetofโ C++ and Objective-C++ only. Suppresses warnings from applying theoffsetofmacro to a non-POD type. According to the 2014 ISO C++ standard, applyingoffsetofto a non-standard-layout type is undefined. In existing C++ implementations, though,offsetoftypically gives meaningful results. This flag is for the users who are fully aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it. Iconic. Reckless. Respect. โจ
The restrictions on offsetof may be relaxed in a future version of the C++ standard.
-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 code quality would be improved if the type were declared with the C++11finalspecifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. Heads up: this warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. ๐-Wsuggest-final-methodsโ Warns about virtual methods where code quality would be improved if the method were declared with the C++11finalspecifier, or, if possible, if its type were declared in an anonymous namespace or with thefinalspecifier. Same deal as above: it's more effective with link-time optimization, where the information about the class hierarchy graph is more complete. And the recommended order is: first consider suggestions of-Wsuggest-final-types, then rebuild with new annotations. One at a time, bestie ๐ง-Wsuggest-overrideโ Warns about overriding virtual functions that are not marked with theoverridekeyword. just say override. it's right there. ๐-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 it may yield different results with optimization than without. ๐-Wuse-after-free=1โ At level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call torealloc, regardless of whether or not the call resulted in an actual reallocation of memory. This includes double-freecalls as well as uses in arithmetic and relational expressions. Although 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, in addition to 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, the second call tofreein the following function is 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. All uses of indeterminate pointers are undefined, but equality tests sometimes appear after calls toreallocas an attempt to determine whether the call resulted in relocating the object to a different address. They're diagnosed at a separate level to aid legacy code gradually transition to safe alternatives. For example, the equality test in the function below is diagnosed at this level:
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 avoid the warning at this level, store offsets into allocated memory instead of pointers. This approach obviates needing to adjust the stored pointers after reallocation. ๐
And the plot twist: -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. This warning does not occur when a class object is converted to a non-reference type, because that's a 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. ๐
โจ Options Controlling Objective-C and Objective-C++ Dialects ๐
NOTE: this manual does not describe the Objective-C and Objective-C++ languages themselves. We're just here for the flags, bestie.
This section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs. But don't panic โ you can also use most of the language-independent GNU compiler options. ๐ซถ 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 that 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). Similarly, Objective-C++ compilations may use C++-specific options (e.g., -Wabi). Same energy, different front-end. ๐ฆ
Here's the list of options that are only for compiling Objective-C and Objective-C++ programs:
-fconstant-string-class=class-nameโ Use 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). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption, if also present, overrides the-fconstant-string-classsetting and causes@"..."literals to be laid out as constant CoreFoundation strings. Note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. ๐-fgnu-runtimeโ Generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐-fnext-runtimeโ Generate 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. โญ-fno-nil-receiversโ Assume that all Objective-C message dispatches ([receiver message:arg]) in this translation unit ensure that the receiver is notnil. This allows for more efficient entry points in the runtime to be used. Heads up: this option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. ๐-fobjc-abi-version=nโ bestie, this picks which version n of the Objective-C ABI you're rolling with for the runtime you chose ๐ rn it's only a thing for the NeXT runtime, okay? So like, Version 0 is the OG traditional 32-bit ABI with no support for properties or any of that Objective-C 2.0 goodness. Version 1? That's the traditional 32-bit ABI but with properties and the other 2.0 additions, slay. Version 2 is the modern 64-bit ABI, the glow-up โจ. If you don't specify anything, the default is Version 0 on 32-bit target machines and Version 2 on 64-bit target machines. periodt.-fobjc-call-cxx-cdtorsโ okay so for every Objective-C class, this checks if any of its instance variables is a C++ object with a non-trivial default constructor ๐ and if it is, it synthesizes a special- (id) .cxx_constructinstance method that runs those non-trivial default constructors on those instance variables, in order, then returnsself. And btw it does the 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. no cap.
The - (id) .cxx_construct and - (void) .cxx_destruct methods it generates only touch instance variables declared in the current Objective-C class, not the 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 right after a new object instance is allocated, and the - (void) .cxx_destruct methods get invoked right before the runtime deallocates an object instance. literally.
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking those - (id) .cxx_construct and - (void) .cxx_destruct methods. iykyk.
-fobjc-direct-dispatchโ this lets you do fast jumps to the message dispatcher ๐โโ๏ธ๐จ on Darwin, this gets accomplished via the comm page.-fobjc-exceptionsโ turns on syntactic support for structured exception handling in Objective-C, kinda like what C++ offers ๐ this option is required to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. It's available with both the GNU runtime and the NeXT runtime โ but not in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier, sorry bestie ๐-fobjc-gcโ enables garbage collection (GC) in Objective-C and Objective-C++ programs ๐๏ธโจ this one's only available with the NeXT runtime, since 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, this checks for a nil receiver in method invocations before doing the actual method call ๐ this is the default and you can disable it with-fno-objc-nilcheck. Class methods and super calls are never checked for nil this way no matter what you set this flag to. Currently this flag does absolutely 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 GCC 4.0 doesn't recognize gets rejected. This is 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 running โ no need to restart the program itself, iconic. 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 name of the class 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 allows individual class implementations to 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 ๐ณ this 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. phew ๐-fivar-visibility=[public|protected|private|package]โ sets the default instance variable visibility to the specified option so that instance variables declared outside the scope of any access modifier directives default to the specified visibility ๐-gen-declsโ dumps interface declarations for all classes seen in the source file to a file named sourcename.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 gets 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. slay.-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 is performed on the list of methods in the final stage of compilation. Additionally, 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 aren't 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, bestie. ๐-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 ๐ฉบ
Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (like its width, etc.) ๐ค you can use the options described below to control the formatting algorithm for diagnostic messages โ e.g. how many characters per line, how often source location info should be reported. Note that some language front ends may not honor these options, so like, vibe check before you rely on it. โจ
-fmessage-length=nโ tries 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.
Note โ 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. okay bestie don't get it twisted ๐
-fdiagnostics-plain-outputโ this option requests that diagnostic output look as plain as possible, which may be useful when running dejagnu or 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. no cap. ๐ฅ
-fdiagnostics-show-location=onceโ only does anything when you're in line-wrapping mode, bestie. It tells the diagnostics reporter to spill the source location info once โ so if a message is too long for one physical line and has to wrap, you won't get the source location re-emitted as a prefix over and over again on every continuation line. This is the default behavior, no cap. โจ-fdiagnostics-show-location=every-lineโ also only meaningful in line-wrapping mode. This one makes the diagnostics reporter print the same source location info (as a prefix) on every physical line that comes out of breaking up a message that was too long for a single line. So yeah, the location gets its main character moment on literally every line. ๐-fdiagnostics-color[=WHEN]-fno-diagnostics-colorโ color in your diagnostics!! ๐ WHEN isnever,always, orauto. The default depends on how the compiler was configured when it was built โ it can be any of those WHEN options, or alsoneverif theGCC_COLORSenvironment variable isn't hanging out in the environment, andautootherwise.automakes GCC use color only when standard error is a terminal, and when it's not running inside an emacs shell. And the forms-fdiagnostics-colorand-fno-diagnostics-colorare aliases for-fdiagnostics-color=alwaysand-fdiagnostics-color=never, respectively. Periodt.
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 get interpreted by your terminal or terminal emulator. (Go check the section in your text terminal's documentation for the permitted values and what they mean as character attributes.) These substring values are integers in decimal representation and you can concatenate them with semicolons. Common values you might 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. obsessed.
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. The supported capabilities are as follows, bestie:
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=, like the identifiers of individual events and lines indicating interprocedural calls and returns.range1=โ SGR substring for the first additional range.range2=โ SGR substring for the second additional range.locus=โ SGR substring for location information,file:lineorfile:line:columnetc.quote=โ SGR substring for information printed inside 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]โ uses escape sequences to embed URLs right into your diagnostics ๐ฆ. For example, when-fdiagnostics-show-optionemits text showing the command-line option controlling a diagnostic, it embeds a URL for the documentation of that option. So helpful, honestly.
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when standard error is a terminal, and when it's not executing in an emacs shell or any graphical terminal 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.
But even with -fdiagnostics-urls=always the behavior is 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 the -fdiagnostics-urls=always.
-fno-diagnostics-show-optionโ by default, every diagnostic emitted includes text indicating the command-line option that directly controls that diagnostic (if such an option is known to the diagnostic machinery, anyway). Specifying the-fno-diagnostics-show-optionflag suppresses that behavior. gone, reduced to atoms.-fno-diagnostics-show-caretโ by default, every diagnostic emitted includes the original source line and a caret^showing the column. This option suppresses that info. The source line gets truncated to n characters if the-fmessage-length=noption is given. And when the output goes to the terminal, the width is limited to the width given by theCOLUMNSenvironment variable or, if that's 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, like 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). so long, little vertical bars ๐ญ
-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, like 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. (the margin was NOT making rent, she's gone ๐)-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โ emits 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. iconic. ๐
-fdiagnostics-generate-patchโ prints 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). slay.
-fdiagnostics-show-template-treeโ bestie, listen, C++ template errors are their own โจgenreโจ and this flag is here to make them make sense. So when the C++ frontend prints a diagnostic about mismatching template types, it usually looks like this ๐ญ:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
and with this flag on, instead of that squished-up mess you get a little tree showing which bits are the same and which bits are fighting, like so:
map<
[...],
vector<
[double != float]>>
and the parts that differ get highlighted with color โ <pink>double</pink> and <purple>float</purple> in this case. slay ๐
-fno-elide-typeโ okay so by default, whenever the C++ frontend prints a diagnostic about mismatching template types, it hides the boring matching parts behind[...]so the error stays smol and readable. Like:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
and if you're the type of girl who wants the whole type spelled out, no hiding, no [...], you pass -fno-elide-type and it stops doing that. Periodt. Also heads up: this flag also affects the output of the -fdiagnostics-show-template-tree flag ๐
-fdiagnostics-path-format=KINDโ this one is the boss of how you print out paths of control-flow events for diagnostics that have a path attached. โจ
KIND is one of none, separate-events, or inline-events โ and inline-events is the default ๐
nonemeans: just don't print diagnostic paths at all. bye ๐separate-eventsmeans: print a separatenotediagnostic for every single event inside the diagnostic. Like:
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-eventsmeans: print the events inline inside the source code itself. This view tries to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges within the source. ๐ซถ
For example, those exact same events as above might come out looking like this:
'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 those stack frames nest, get pushed, and get popped. iconic, 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โ extra tea โ when you're printing control-flow paths that come attached to a diagnostic.
If you turn this option on, then the stack depth gets printed for each run of events within -fdiagnostics-path-format=inline-events. And if you use it together with -fdiagnostics-path-format=separate-events, then the stack depth and the function declaration get appended while printing each event. ๐
This one is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. So like โ it's for the girlies building GCC itself, not your everyday vibe. iykyk.
-fno-show-columnโ do not print column numbers in diagnostics. Lowkey necessary if your diagnostics are getting scanned by a program that does not understand column numbers, such asdejagnu. ๐ฆ-fdiagnostics-column-unit=UNITโ picks the units for the column number. This affects traditional diagnostics (i.e. when-fno-show-columnis not in play), and also JSON format diagnostics if you asked for those.
The default UNIT, display, counts the number of display columns each character takes up. Which can be bigger than the number of bytes needed to encode that character โ tab characters, we're looking at you ๐ญ โ or it can be smaller, in the case of multibyte characters. Example time: the character GREEK SMALL LETTER PI (U+03C0) takes up one display column, and its UTF-8 encoding needs two bytes. Meanwhile SLIGHTLY SMILING FACE (U+1F642) occupies two display columns, and its UTF-8 encoding needs four bytes. math queen ๐
Setting UNIT to byte changes the column number to the raw byte count, in all cases, exactly like GCC traditionally output it before version 11.1.0. throwing it back fr.
-fdiagnostics-column-origin=ORIGINโ sets the origin for column numbers, i.e. the column number assigned to the very first column. The default value of1matches traditional GCC behavior and the GNU style guide. Some utilities may vibe better with an origin of0; any non-negative value can be specified. โจ-fdiagnostics-escape-format=FORMATโ so when GCC prints the relevant source lines for a diagnostic, it normally just tries to print the source bytes straight up, no filter. BUT ๐ some diagnostics are about encoding issues in the source file โ malformed UTF-8, Unicode normalization drama, etc. Those diagnostics get flagged, and then GCC will escape the bytes that aren't printable ASCII when it prints 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 get shown as hexadecimal in the form <XX>.
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 you the underlying encoding of non-ASCII Unicode characters. For the example above, you'd get:
before<CF><80><BF>after
-fdiagnostics-format=FORMATโ pick a whole different format for printing diagnostics.FORMATis one oftext,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, without formatting โ the examples below have been formatted for clarity, you're welcome.
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:
[
{
"kind": "warning",
"locations": [
{
"caret": {
"display-column": 3,
"byte-column": 3,
"column": 3,
"file": "misleading-indentation.c",
"line": 15
},
"finish": {
"display-column": 4,
"byte-column": 4,
"column": 4,
"file": "misleading-indentation.c",
"line": 15
}
}
],
"message": "this \u2018if\u2019 clause does not guard...",
"option": "-Wmisleading-indentation",
"option_url": "https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmisleading-indentation",
"children": [
{
"kind": "note",
"locations": [
{
"caret": {
"display-column": 5,
"byte-column": 5,
"column": 5,
"file": "misleading-indentation.c",
"line": 17
}
}
],
"escape-source": false,
"message": "...this statement, but the latter is ..."
}
]
"escape-source": false,
"column-origin": 1,
}
]
where that whole "note" is literally a child of the "warning" โ like, it lives inside it, it's giving family tree energy ๐ณ๐
Okay so every diagnostic has a "kind". If that "kind" is "warning", bestie, then there's an "option" key chillin' right there describing the command-line option that controls the warning. ๐
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 plus optional "start" and "finish" positions. And 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. (Not me being efficient ๐
)
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. So like, it's got receipts โจ 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". ๐ (delete = nothing there, insert = same spot, iconic.)
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 isn't wrong wrong, but it's giving "hmm bestie are you 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 a lil vibe check on the syntax, no building, no nothing. ๐ซถ-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. (So if they beef,-Wfatal-errorswins, no cap. ๐)-wโ Inhibit all warning messages. Like, muted. ๐ Not a peep.-Werrorโ Make all warnings into errors. Every single warning gets promoted to a full-on error, main character energy only. ๐-Werror=โ bestie, this one promotes a specific warning to a full-on error. You just tack the warning's name onto the end, like-Werror=switch, and boom ๐ฅ every warning that-Wswitchcontrols becomes an error instead. It's got a negative form too, so you can yeet-Werrorfor just one warning:-Wno-error=switchmakes the-Wswitchwarnings stay chill little warnings, even when-Werroris running the whole show.
Every controllable warning prints the option that controls it right there in the message, so you can grab that name and feed it straight to -Werror= or -Wno-error= like we just did. (Want the option name gone from the message? -fno-diagnostics-show-option handles that. ๐)
Heads up: writing-Werror=foosecretly also implies-Wfoo, no cap. But-Wno-error=foo? That one implies nothing at all. ๐
-Wfatal-errorsโ the dramatic exit option ๐ . The moment the first error shows up, the compiler just aborts the whole compilation instead of trying to keep going and printing more error messages. One strike and it's done.
okay so you can also just ask for a ton of specific warnings with options that start with -W, like -Wimplicit if you want warnings about implicit declarations. Every single one of those specific warning options has a negative twin starting with -Wno- that turns it off โ say hi to -Wno-implicit ๐ซถ. This manual only ever lists one of the two forms per warning, whichever one is not the default. And for language-specific stuff, go peek at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options too. Oh and psst โ you can unlock even more warnings by enabling the static analyzer โจ
Some options, like -Wall and -Wextra, turn on other options, like -Wunused, which can turn on even more options, like -Wunused-value. It's options all the way down ๐. So here's how the positive and negative forms sort out their drama: more specific options always win over less specific ones, and it does not matter where they sit on the command line. If two options have the same specificity, the last one wins, periodt. And options you enable or disable via pragmas? They act like they got tacked onto the very end of the command line.
Now, when you ask for a warning option nobody recognizes (like, say, -Wunknown-warning), GCC tells you straight up that the option is not recognized. But the -Wno- form is lowkey different: -Wno-unknown-warning produces no diagnostic, unless other diagnostics are being produced anyway. Why? So you can use shiny new -Wno- options with old compilers without everything exploding ๐ง โ but if something goes wrong, the compiler will warn that an unrecognized option is hanging around.
Also real talk: how effective some warnings are depends on optimizations being turned on too. Like, -Wsuggest-final-types hits way harder with link-time optimization, and some instances of other warnings might not even get issued at all unless optimization is enabled. Optimization generally makes control-flow and data-flow sensitive warnings more useful, but in some cases it can also cause false positives. It's giving balanced ๐
-Wpedantic,-pedanticโ this is the strict-mode queen ๐. It issues all the warnings demanded by strict ISO C and ISO C++, rejects every program that uses forbidden extensions, and rejects some other programs that don't follow ISO C and ISO C++ either. For ISO C, it follows whichever version of the ISO C standard your-stdoption picked.
Here's the vibe: valid ISO C and ISO C++ programs should compile just fine with or without this option (though a rare few need -ansi or a -std option with the required version of ISO C spelled out). But without this option, certain GNU extensions and traditional C and C++ features are supported too. Turn this on and all of that gets rejected. ๐
-Wpedantic does not warn when you use the alternate keywords whose names begin and end with __. That same alternate format can disable warnings for non-ISO __intN types โ i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". But listen ๐ซต โ only system header files should use these escape routes. Application programs should avoid them, fr fr.
Some people try to use -Wpedantic to check whether their programs are strict ISO C conformant, and they quickly find out it does not do quite what they want ๐ญ. It catches some non-ISO practices, but not all โ only the ones ISO C requires a diagnostic for, plus some others where diagnostics have been added.
A feature that reports any failure to conform to ISO C could be useful sometimes, but it would take considerable additional work and would be quite different from -Wpedantic. We don't have plans to support such a feature in the near future. Sorry bestie ๐
When the standard you picked with -std is a GNU extended dialect of C, like gnu90 or gnu99, there's a corresponding base standard โ the version of ISO C that the GNU extended dialect is built on. -Wpedantic warnings show up where the base standard requires them. (It wouldn't make sense to only warn about features that aren't in the specified GNU C dialect, because by definition the GNU dialects of C include every feature the compiler supports with that option โ there'd literally be nothing to warn about. ๐คท)
-pedantic-errorsโ throws a full error whenever the base standard (that's the-Wpedanticone) requires a diagnostic, in some cases where there's undefined behavior at compile-time, and in some other cases that don't prevent compilation of programs that are valid according to the standard. And ngl, this is not equivalent to-Werror=pedanticโ there are errors this option enables that the other one doesn't, and vice versa. Different girls, different energies ๐-Wallโ the big one ๐. This enables all the warnings about constructions that some users consider questionable and that are easy to avoid (or easy to tweak so the warning stops), even when macros are in the mix. It also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.
Okay so -Wall turns on the following warning flags, get ready:
-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
Important though: some warning flags are not implied by -Wall ๐ซ. Some of them warn about constructions users generally don't consider questionable but that you might occasionally want to check for. Others warn about constructions that are necessary or hard to avoid in some cases, where there's no simple way to change the code and silence the warning. A few of those get enabled by -Wextra, but many of them you have to enable individually, one by one. ๐
-Wextraโ enables some extra warning flags that-Walldoesn't bother with. (Fun fact: this option used to be called-W. The older name still works, but the newer name is way more descriptive, iykyk โจ)
-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)
And -Wextra also prints warning messages for these special 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 play nice with the vendor-neutral C++ ABI, plus the psABI for the particular target.
Since G++ now defaults to updating the ABI with every major release, normally -Wabi only warns about C++ ABI compatibility problems when a check got added later in a release series for an ABI issue discovered after the initial release. Select an older ABI version (with -fabi-version=n) and -Wabi starts warning about more things. ๐ณ
You can also hand -Wabi an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level โ e.g. -Wabi=2 warns about changes relative to -fabi-version=2.
If you give an explicit version number and you didn't specify -fabi-compat-version, then the version number from this option gets used for compatibility aliases. And if you don't give an explicit version number with this option but you did specify -fabi-compat-version, that version number gets used for the C++ ABI warnings. Balance โจ
but likeโฆ bestie, there's a whole list of these and some of them are so sneaky nobody even warns you about them ๐ญ Yeah, so even though the GCC devs tried their absolute hardest to warn about every single incompatible-code situation, there are probably still some cases that slip through unwarned, even while G++ is out here generating code that just does not play nice. And plot twist ๐ โ sometimes you get warnings even though the code that got generated is perfectly compatible. Rude.
So if the thought of your G++ code not being binary compatible with code from other compilers is keeping you up at night, the move is: rewrite your code so those warnings never happen in the first place. Self-care, honestly. ๐
Here's the tea on the known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9), no cap:
- A template with a non-type template parameter of reference type got mangled incorrectly. It's giving:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}
This got fixed in -fabi-version=3. โจ
- SIMD vector types declared using
"__attribute ((vector_size))"were mangled in a non-standard way that does not allow overloading of functions taking vectors of different sizes. Messy. The mangling got changed in-fabi-version=4. "__attribute ((const))"andnoreturnwere mangled as type qualifiers, and"decltype"of a plain declaration was folded away. These mangling issues were fixed in-fabi-version=5.- Scoped enumerators passed as arguments to a variadic function get promoted like unscoped enumerators, which makes
"va_arg"complain. On most targets this doesn't actually affect the parameter passing ABI, since there's literally no way to pass an argument smaller than"int". 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. All of these got corrected in-fabi-version=6. - Lambdas in default argument scope were mangled incorrectly, and the ABI changed the mangling of
"nullptr_t". 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. Fixed in
-fabi-version=8, the default for GCC 5.1. ๐ decltype(nullptr)incorrectly had an alignment of 1, leading to unaligned accesses. Heads up though โ this did not affect the ABI of a function with a"nullptr_t"parameter, because parameters have a minimum alignment. Fixed in-fabi-version=9, the default for GCC 5.2.- Target-specific attributes that affect the identity of a type โ think ia32 calling conventions on a function type (stdcall, regparm, etc.) โ did not affect the mangled name, which caused name collisions when function pointers were used as template arguments. Fixed in
-fabi-version=10, the default for GCC 6.1. ๐ซถ
This option also turns on warnings about psABI-related changes. The known psABI changes at this point include:
- For SysV/x86-64, unions with
"long double"members are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. Like, for example:
union U {
long double ld;
int i;
};
"union U" is now always passed in memory. Immovable. Periodt.
๐ธ -Wno-changes-meaning (C++ and Objective-C++ only) ๐ธ
C++ requires that unqualified uses of a name within a class have the same meaning across the complete scope of the class, so declaring the name after you already used it is ill-formed, bestie:
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 a straight-up error. Both diagnostics can be disabled with -Wno-changes-meaning. Alternatively, you can downgrade the error case to a warning with -Wno-error=changes-meaning or -fpermissive. ๐ฆ
Both diagnostics are also suppressed by -fms-extensions. Slay.
-Wchar-subscripts
Warn if an array subscript has type "char". This is a super common cause of error, because programmers constantly forget that this type is signed on some machines. This warning is enabled by -Wall. โญ
-Wno-coverage-mismatch
Warn when feedback profiles don't match while you're using the -fprofile-use option. If a source file changes between compiling with -fprofile-generate and compiling with -fprofile-use, then the files with the profile feedback can fail to match the source file, and GCC can't use that profile feedback info. ๐ญ
By default this warning is enabled and treated as an error. -Wno-coverage-mismatch can disable the warning, or -Wno-error=coverage-mismatch can disable just the error. Disabling the error for this warning can result in poorly optimized code, and it's only useful for super minor changes like bug fixes to an existing codebase. Completely disabling the warning is not recommended. Don't do it, bestie.
-Wno-coverage-invalid-line-number
Warn when a function ends earlier than it begins, thanks to an invalid linenum macros. That's giving time-travel but make it broken. ๐ This warning is only emitted with --coverage enabled.
By default, this warning is enabled and treated as an error. -Wno-coverage-invalid-line-number can disable the warning, or -Wno-error=coverage-invalid-line-number can disable the error.
-Wno-cpp (C, Objective-C, C++, Objective-C++ and Fortran only)
Suppress warning messages emitted by "#warning" directives. Shhh. ๐คซ
-Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
Gives you a warning when a value of type "float" gets implicitly promoted to "double". Here's why that matters: CPUs with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate "double" in software. On a machine like that, doing computations with "double" values is way more expensive because of all the overhead that software emulation needs. ๐ธ
And it's genuinely 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 that floating-point literal is a "double". Sneaky!! ๐
-Wduplicate-decl-specifier (C and Objective-C only)
Warn if a declaration has a duplicate "const", "volatile", "restrict" or "_Atomic" specifier. This warning is enabled by -Wall. โ
-Wformat / -Wformat=n
Checks calls to "printf" and "scanf", etc., to make sure the arguments you supplied have types that actually match the format string specified, and that the conversions specified in the format string make sense. This covers standard functions, plus others specified by format attributes, across the "printf", "scanf", "strftime" and "strfmon" families (where "strfmon" is an X/Open extension, not in the C standard) โ or other target-specific families. ๐
Which functions get checked without format attributes having been specified depends on the standard version you selected, and those checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.
Formats are checked against the format features supported by GNU libc version 2.2. That includes all ISO C90 and C99 features, plus features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all of these features, though โ and GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used together with -Wformat, you get warnings about format features that aren't in the selected standard version (just not for "strfmon" formats, since those aren't 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 these options:-Wno-format-contains-nul,-Wno-format-extra-args, and-Wno-format-zero-length. And-Wformatis enabled by-Wall. โจ-Wformat=2โ Enables-Wformatplus extra format checks. Currently equivalent to-Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k. That's the deluxe version, bestie. ๐
-Wno-format-contains-nul
If -Wformat is specified, don't warn about format strings that contain NUL bytes. Containing NULs is giving cursed energy ngl. ๐
-Wno-format-extra-args
If -Wformat is specified, don't warn about excess arguments to a "printf" or "scanf" format function. The C standard says such arguments are simply ignored. Ignored. Periodt.
Where the unused arguments sit between used arguments that are specified with $ operand number specifications, warnings are normally still given, since the implementation couldn't know what type to pass to "va_arg" in order to skip those 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 such unused arguments are allowed. ๐ซถ
-Wformat-overflow / -Wformat-overflow=level
Warn about calls to formatted input/output functions such as "sprintf" and "vsprintf" that might overflow the destination buffer. ๐ฌ When the exact number of bytes written by a format directive can't be determined at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. And while enabling optimization will in most cases improve the accuracy of the warning, it can also result in false positives. Mixed blessing fr fr. โ๏ธ
-Wformat-overflow,-Wformat-overflow=1โ okay so level 1 of-Wformat-overflow, which gets switched on by-Wformat, is the โจcautiousโจ girlie. She only drags a call when it most likely overflows the buffer, no false alarms. At this level the vibes are:- numeric arguments to format directives whose values are unknown? assumed to be
1๐ซถ - strings of unknown length? assumed to be empty
- numeric arguments 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, are assumed to take on the value within the range that results in the most bytes on output (worst-case behaviour, bestie ๐ )
- numeric arguments to format directives whose values are unknown? assumed to be
So like, the call to sprintf 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 lands past its end ๐ญ. Bumping the buffer up by a single byte is enough to dodge the warning โ though ngl that may not be enough to dodge the actual 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 the overachiever ๐ she also warns about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2:- 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 1 character long
- unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than
At level 2, that example call from before is diagnosed 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 regardless of the values of the two variables, the destination buffer has to be grown to at least 34 bytes. GCC lowkey blesses you by including the minimum size of the buffer in an informational note right after the warning ๐
Another option instead of growing the buffer: constrain the range of formatted values. 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 required buffer size. For example, if a and b 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 reduces the maximum required size of the buffer to 24 bytes:
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, do not warn about zero-length formats. The C standard literally says zero-length formats are allowed, so chill ๐ง-Wformat-nonliteralโ if-Wformatis specified, also warn if the format string is not a string literal and therefore cannot be checked โ 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 this warns about calls toprintfandscanffunctions where the format string is not a string literal and there are no format arguments, like inprintf (foo);. That can be a security hole if the format string came from untrusted input and contains%n๐ฑ (this is currently a subset of what-Wformat-nonliteralwarns about, but bestie, in future warnings may be added to-Wformat-securitythat are not included in-Wformat-nonliteral.)-Wformat-signednessโ if-Wformatis specified, also warn if the format string requires an unsigned argument and the argument is signed, and vice versa. Stay consistent babes ๐-Wformat-truncation,-Wformat-truncation=levelโ warns about calls to formatted input/output functions such assnprintfandvsnprintfthat might result in output truncation โ๏ธ. When the exact number of bytes written by a format directive can't be determined at compile-time, it's estimated based on heuristics that depend on the level argument and on optimization. Enabling optimization will in most cases improve the accuracy of the warning, but it may also result in false positives ๐. Except as noted otherwise, this option uses the same logic as-Wformat-overflow.-Wformat-truncation,-Wformat-truncation=1โ level 1 of-Wformat-truncation(switched on by-Wformat) is the conservative girlie: she 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 hi).-Wnonnullโ warn about passing a null pointer for arguments marked as requiring a non-null value by thenonnullfunction attribute. This one is included in-Walland-Wformat, and can be disabled with the-Wno-nonnulloption.-Wnonnull-compareโ warn when comparing an argument marked with thenonnullfunction attribute against null inside the function ๐คจ-Wnonnull-compareis included in-Wall, and 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 option is only active when-fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used.-Winfinite-recursionโ warn about infinitely recursive calls ๐๐. The warning is effective at all optimization levels, but it requires optimization in order to detect infinite recursion in calls between two or more functions.-Winfinite-recursionis included in-Wall.
Compare with -Wanalyzer-infinite-recursion, which provides a similar diagnostic but is implemented in a 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 this option can only be used with the-Wuninitializedoption.
Like, GCC warns about i being uninitialized in the following snippet only when -Winit-self has 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 does not specify a type. This 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. This warning is enabled by default in C99 and later dialects of C, and also by-Wall. The warning is made 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=3and-Wno-implicit-fallthroughis the same as-Wimplicit-fallthrough=0. Periodt ๐-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;
}
This warning does not fire when the last statement of a case cannot fall through, e.g. when there's a return statement or a call to a function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, 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:
...
}
Since there are occasions where a switch case fall through is actually desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that's meant to be used along with a null statement to suppress this warning that would normally occur:
switch (cond)
{
case 1:
bar (0);
__attribute__ ((fallthrough));
default:
...
}
C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14, users can use [[gnu::fallthrough]];, which is a GNU extension. And instead of these attributes, it's also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:
-Wimplicit-fallthrough=0disables the warning altogether.-Wimplicit-fallthrough=1matches".*"regular expression, any comment is used as fallthrough comment.
-Wimplicit-fallthrough=2โ case insensitively matches the".*falls?[ \t-]*thr(ough|u).*"regular expression. slay, flexible ๐-Wimplicit-fallthrough=3โ case sensitively matches ONE of these iconic regular expressions, no more no less:"-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โ also case sensitively matches one of these, but a shorter lil list:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5โ bestie it does NOT 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. like so:
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 get issued at all. these warnings are enabled by default.-Wignored-qualifiers(C and C++ only) โ warns you if a function's return type has a type qualifier like"const". for ISO C that qualifier literally does nothing, since the value returned by a function isn't an lvalue. for C++ the warning only fires for scalar types or"void". and 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 one controls warnings when an attribute is ignored. it's different from the-Wattributesoption because it warns whenever the compiler decides to drop an attribute โ not that the attribute is unknown or used in a wrong place or whatever. enabled by default ๐-Wmainโ warns if the type of"main"is looking suspicious ๐"main"should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. enabled by default in C++, and 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. the audacity ๐ญ
In this 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". */
When it's mixed tabs and spaces, the warning uses the -ftabstop= option to figure out if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic, like this:
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, because that usually means autogenerated code and no assumptions can be made about the layout of the file that the directive references. iykyk.
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, and whose absence may adversely affect the correctness or efficiency of generated code. for example, it fires for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. this is typically 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, double period, iconic typo energy ๐)
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 gets 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 example below, the initializer for"a"is not fully bracketed, but the one for"b"is. fully bracketed bestie ๐
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-Jonly.-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. when that happens, the profile feedback data files don't contain any profile feedback information for the newly added function or file respectively. also, if 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 ๐ฌ-Wno-missing-profilecan be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified.-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 example below,"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 like"if","else","for","switch", or"while"โ but where 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. you can usually fix this 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. we've all been there ๐
Also warns if a comparison like "x<=y<=z" appears โ because that's equivalent to "(x<=y ? 1 : 0) <= z", which is a completely different interpretation from ordinary mathematical notation. ma'am that's not math ๐
Also warns for dangerous uses of the GNU extension to "?:" with an 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);
}
That warning is enabled by -Wall. ๐
-Wno-self-move(C++ and Objective-C++ only) โ bestie this one is so real. It warns when a value gets moved to itself withstd::move. And likeโฆ such astd::movetypically has no effect at all. It's giving "I did something" but it did nothing, iykyk. ๐ซ
struct T {
...
};
void fn()
{
T t;
...
t = std::move (t);
}
This warning is enabled by -Wall. โจ
-Wsequence-pointโ Warns about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards. Yes queen, we're going into the โจtheoryโจ section, stay with me. ๐ง
The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap. ๐
It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that "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.". If a program breaks these rules, the results on any particular implementation are entirely unpredictable. ๐
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 has been found fairly effective at detecting this sort of problem in programs.
The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this option will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++. ๐
The standard is worded confusingly, therefore there is 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. it's giving dangling vibes but okay, your call bestie. ๐-Wreturn-typeโ Warn whenever a function is defined with a return type that defaults toint. Also warns about anyreturnstatement with no return value in a function whose return type is notvoid(falling off the end of the function body is considered returning without a value). ๐ฆ
For C only, warn about a return statement with an expression in a function whose return type is void, unless the expression type is also void. As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used. 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 is 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. ๐
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โ Warn if left shifting a negative value. This warning is enabled by-Wextrain C99 (and newer) and C++11 to C++17 modes. negative shift? not the moment. ๐-Wno-shift-overflow,-Wshift-overflow=nโ These options control warnings about left shift overflows. two levels, pick your fighter:-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โ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration. (The presence of adefaultlabel prevents this warning.)caselabels outside the enumeration range also provoke warnings when this option is used (even if there is adefaultlabel). This warning is enabled by-Wall. ๐-Wswitch-defaultโ Warn whenever aswitchstatement does not have adefaultcase. girl where is your default case ๐ญ-Wswitch-enumโ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration.caselabels outside the enumeration range also provoke warnings when this option is used. The only difference between-Wswitchand this option is that this option gives a warning about an omitted enumeration code even if there is adefaultlabel. ๐-Wno-switch-boolโ Do not warn when aswitchstatement has an index of boolean type and the case values are outside the range of a boolean type. It is possible to suppress this warning by casting the controlling expression to a type other thanbool. For example:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs. ๐
-Wno-switch-outside-rangeโ This option controls warnings when aswitchcase 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 aswitchstatement contains statements between the controlling expression and the first case label, which will never be executed. For example:
switch (cond)
{
i = 15;
...
case 5:
...
}
-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) โ Warn when__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions are used. These functions changed semantics in GCC 4.4. era-defining plot twist tbh. ๐-Wtrivial-auto-var-initโ Warn when-ftrivial-auto-var-initcannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of aswitchstatement. ๐-Wunused-but-set-parameterโ Warn 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โ Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by-Wall. bestie you set it and then ghosted it?? ๐ป
To suppress this warning use the unused attribute. ๐
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-functionโ Warn whenever astaticfunction is declared but not defined or a non-inlinestaticfunction is unused. This warning is enabled by-Wall. ๐ฆ-Wunused-labelโ Warn 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) โ Warn when a typedef locally defined in a function is not used. This warning is enabled by-Wall. ๐-Wunused-parameterโ Warn 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 attributewarn_unused_resultdoes not use its return value. The default is-Wunused-result. ๐-Wunused-variableโ Warn whenever a local orstaticvariable is unused aside from its declaration. This option implies-Wunused-const-variable=1for 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โ ok so this one? It yells at you whenever a constant static variable is just... sitting there, unused, aside from the fact that it got declared. That's it. That's the whole crime. ๐
Little nuance tho, bestie: -Wunused-const-variable=1 is switched on by -Wunused-variable for C, but not for C++. Why the difference? Because in C this actually declares variable storage, whereas in C++ it's not even an error since const variables are just out here doing the job of #defines. ๐
Wanna silence it? Slap the "unused" attribute on the thing.
-Wunused-const-variable=1โ this is the level that-Wunused-variableenables for C. It only warns about unused static const variables defined in the main compilation unit, and stays quiet about static const variables declared in any header that got included. ๐-Wunused-const-variable=2โ this level is extra and also warns about unused constant static variables in headers (system headers excluded, don't worry). This is the level of plain-Wunused-const-variable, and you have to explicitly request it, because in C++ it isn't an error and in C it might be way harder to clean up all the headers you included. ๐ญ
-Wunused-valueโ warns whenever a statement computes a result that is explicitly not used. To shut it up, cast the unused expression to"void". This covers an expression-statement, or the left-hand side of a comma expression, that contains no side effects. For example, an expression like"x[i,j]"triggers a warning, while"x[(void)i,j]"does not. ๐ซถ
This warning is enabled by -Wall.
-Wunusedโ literally all the above-Wunusedoptions combined into one iconic bundle. โจ
Heads up tho: to actually get a warning about an unused function parameter, you gotta either specify -Wextra -Wunused (and yes, -Wall implies -Wunused, iykyk), or go out of your way and separately specify -Wunused-parameter.
-Wuninitializedโ warns if an object with automatic or allocated storage duration gets used without ever having been initialized. ๐ฑ In C++, it also warns if a non-static reference or a non-static"const"member shows up in a class that has no constructors.
And there's more: passing a pointer (or, in C++, a reference) to an uninitialized object into a "const"-qualified argument of a built-in function that's known to read the object also gets diagnosed by this warning. (For ordinary functions, it's -Wmaybe-uninitialized that gets issued instead.)
Wanna catch code that uses the uninitialized value of a variable in its own initializer? That's a whole different option, bestie โ use -Winit-self.
These warnings happen for individual uninitialized elements of structure, union or array variables, and also 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 that get flagged depend on the precise optimization options and the version of GCC you're running. ๐
Also note: there may be no warning at all about a variable that's only used to compute a value that itself is never used, because those computations can get deleted by data flow analysis before the warnings even print. ๐
In C++, this warning also flags 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 the"memory_order"enumeration. For example, since the"__atomic_store"and"__atomic_store_n"built-ins are only defined for the relaxed, release, and sequentially consistent memory orders, this code gets 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's a path from the function entry to a use of the object where it is initialized, but there also exist some other paths where it isn't, the compiler emits a warning if it can't prove that those uninitialized paths never actually get executed at run time. ๐ต๏ธโโ๏ธ
On top of that, passing a pointer (or in C++, a reference) to an uninitialized object into a "const"-qualified function argument also gets diagnosed by this warning. (-Wuninitialized is what gets issued for built-in functions known to read the object.) And if you annotate the function with attribute "access (none)", that tells the compiler the argument isn't used to access the object, which avoids the warning. ๐
These warnings are only possible in optimizing compilation, because otherwise GCC isn't keeping track of the state of variables at all.
And they're made optional because GCC might not be able to figure out when the code is actually correct in spite of it looking like there's an error. Here's one example of how that can go 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 get changed by a call to "longjmp". The compiler only sees the calls to "setjmp", so it literally cannot know where "longjmp" will be called โ and in fact, a signal handler could call it at any point in the code. ๐ณ As a result, you may get a warning even when there is in fact no problem, because "longjmp" can't actually be called at the place that would cause one.
Some spurious warnings can be dodged 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"#pragma"directive gets encountered that GCC doesn't understand. And if this command-line option is the one used, warnings get issued even for unknown pragmas inside 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. The constructor and destructor attributes let you assign a priority to a constructor/destructor to control its order of execution before"main"is called or after it returns. But the priority values must be greater than 100, because the compiler reserves the priority values between 0--100 for the implementation itself. No touching. ๐ โโ๏ธ
-Wstrict-aliasingโ this option is only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules the compiler is using for optimization. Fair warning: the warning does not catch all the cases, but it does try to catch the more common pitfalls. It's included in-Wall. And it's equivalent to-Wstrict-aliasing=3. ๐
-Wstrict-aliasing=nโ same deal: only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules the compiler uses for optimization. Higher levels = higher accuracy (meaning fewer false positives). But higher levels also = more effort, kind of like how-Oworks. And yeah,-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 your 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 (though not as many as level 1), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.
- Level 3 (the 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โ this option is 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. Note that it doesn't warn about all the cases where the code might overflow โ only the cases where the compiler implements some optimization. So yeah, 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 does, in fact, occur. So this warning can easily give a false positive: a warning about code that's not actually a problem. To help you focus on the important stuff, several warning levels are defined. And 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 simplifies"x + 1 > x"to 1. This level of-Wstrict-overflowis enabled by-Wall; higher levels are not enabled by it, and must be explicitly requested.
-Wstrict-overflow=2โ ok so this level ALSO clocks the other cases where a comparison gets squished down to a constant. Likeabs (x) >= 0for example. And the tea here is that this can only ever be simplified when signed integer overflow is undefined, becauseabs (INT_MIN)overflows right back toINT_MIN, which is less than zero. And bestie, heads up:-Wstrict-overflowwith no level at all? Same as-Wstrict-overflow=2. ๐-Wstrict-overflow=3โ now we're also flagging even MORE cases where a comparison gets simplified. Example bestie:x + 1 > 1gets turned intox > 0.-Wstrict-overflow=4โ and at level four we're also warning about all the other simplifications that the levels above didn't already cover. Example:(x * 10) / 5becomesx * 2. Iconic behaviour honestly.-Wstrict-overflow=5โ this is the top one and it also warns when the compiler shrinks the magnitude of a constant involved in a comparison. Example:x + 2 > ygets simplified tox + 1 >= y. โ ๏ธ It's only reported up at the highest warning level because this simplification applies to SO many comparisons that you get an absolutely unhinged number of false positives. Like girl, be prepared.
๐ซถ -Wstring-compare
Warns you about calls to strcmp and strncmp where the result is decided โ zero or non-zero, no in-between โ in those equality tests, just because one argument's length is bigger than the size of the array the other argument lives in (or the bound, in strncmp's case). Basically these calls could be total mistakes. For example, the strcmp call below gets diagnosed because its result is necessarily non-zero, no matter what's chillin' inside the array a:
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");
}
And yeah, -Wstring-compare is enabled by -Wextra. โจ
๐ธ -Wno-stringop-overflow / -Wstringop-overflow / -Wstringop-overflow=type
Warns for calls to string manipulation functions like memcpy and strcpy that get 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. That argument only means anything for functions that work on character arrays โ not for raw memory functions like memcpy, which always use Object Size type-0. This option also warns for calls that specify a size beyond the largest possible object, or at most SIZE_MAX / 2 bytes. It gives its best results with optimization enabled, but it can still catch a small subset of simple buffer overflows even without optimization, in calls to GCC built-in functions like __builtin_memcpy that match up with the standard functions. Either way, it only warns about a subset of the buffer overflows that the corresponding overflow-checking built-ins catch.
For example, the option warns about the strcpy call below because it copies at least 5 characters (the string blue plus the terminating NUL) 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
The -Wstringop-overflow=1 option uses type-zero Object Size Checking to work out the sizes of destination objects. At this setting it does not warn about writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination could be one of several objects, it assumes it's the largest one of them. On Linux systems, with optimization enabled, at this setting the option warns for the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value. ๐ง
-Wstringop-overflow=2
The -Wstringop-overflow=2 option uses type-one Object Size Checking to work out the sizes of destination objects. At this setting it warns about overflows when writing to members of the largest complete objects whose exact size is known. But it does NOT warn about excessive writes to those same members of unknown objects referenced by pointers, because those pointers might point to arrays holding some unknown number of elements. This is the default setting, bestie. ๐
-Wstringop-overflow=3
The -Wstringop-overflow=3 option uses type-two Object Size Checking to work 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 heads up โ it may throw warnings at completely safe code. ๐ญ
-Wstringop-overflow=4
The -Wstringop-overflow=4 option uses type-three Object Size Checking to work out the sizes of destination objects. At this setting 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 warn. Just like -Wstringop-overflow=3, this setting may warn about perfectly benign code. ๐
๐ฆ -Wno-stringop-overread
Warns for calls to string manipulation functions like memchr, or strcpy, that get determined to read past the end of the source sequence.
And yeah โ -Wstringop-overread is enabled by default. โจ
๐ -Wno-stringop-truncation
Don't warn for calls to bounded string manipulation functions like strncat, strncpy, and stpncpy that might either truncate the copied string or leave the destination untouched.
In the example below, the call to strncat specifies a bound that's less than the length of the source string. So the copy of the source gets truncated and the call gets diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound.
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
Another example: the strncpy call below copies to d just the characters before the terminating NUL, without sticking the NUL on the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call gets diagnosed. To avoid the warning when the result isn't expected to be NUL-terminated, call memcpy instead.
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
And one more: the strncpy call below specifies the size of the destination buffer as the bound. If the source string's length is equal to or greater than this size, the result of the copy won't be NUL-terminated. So yes, 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 meant to store a sequence of bytes with no terminating NUL, you can annotate that array with the attribute nonstring to avoid this warning. But lowkey โ 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 the strict_flex_array (level) attribute attached to the trailing array field of a structure if it's available โ otherwise according to the level of the option -fstrict-flex-arrays=level.
This option only does anything when level is bigger than 0. Otherwise it gets ignored, with a warning. ๐
- when level=1, warnings get 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 to level=1, extra warnings get 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 to level=2, extra warnings get 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 a good idea. The attributes currently supported 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 attributes pure, const, noreturn or malloc. The compiler only warns for functions visible in other compilation units, or (in the case of pure and const) if it can't prove that the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis needs the option -fipa-pure-const, which is enabled by default at -O and higher. And higher optimization levels? They improve the accuracy of the analysis. โจ
-Wsuggest-attribute=format,-Wmissing-format-attributeโ okay so this one yells at you about function pointers that might be candidates forformatattributes ๐. And listen โ these are only possible candidates, not absolute ones, so don't come for GCC. Here's the tea: GCC guesses that if a function pointer has aformatattribute and it's used in an assignment, an initialization, a parameter pass, or a return statement, then the resulting type should also have a correspondingformatattribute. Translating that: 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 carry aformatattribute โ otherwise, warning. ๐
GCC also side-eyes function definitions that might be candidates for format attributes. Again โ only possible candidates, bestie. GCC's guess is that format attributes might be appropriate for any function that calls something like vprintf or vscanf, but ngl that's not always the case, and sometimes functions that do deserve a format attribute just don't get detected. It's giving "vibes-based heuristic" ๐ซถ.
-Wsuggest-attribute=coldโ warns about functions that might be candidates for thecoldattribute โ๏ธ. This is based on static detection, and generally it only warns about functions that always lead to a call to anothercoldfunction โ think wrappers around C++throw, or fatal error reporting functions that lead toabort.
-Walloc-zeroโ warns about calls to allocation functions decorated with thealloc_sizeattribute that specify zero bytes ๐ญ, including the built-in forms ofaligned_alloc,alloca,calloc,malloc, andrealloc. Why care? Because the behavior of these functions when called with a zero size differs between implementations โ and in the case ofreallocit's been deprecated, periodt โ so relying on it may result in subtle portability bugs and should be avoided. ๐- *
-Walloc-size-larger-than=byte-size* โ warns about calls to functions decorated with thealloc_sizeattribute that 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 ๐ฆ. Fun fact:-Walloc-size-larger-than=PTRDIFF_MAXis enabled by default. And you can mute the warnings from this option either by specifying a byte-size ofSIZE_MAXor more, or just by using-Wno-alloc-size-larger-than. -Wno-alloc-size-larger-thanโ turns off the-Walloc-size-larger-than=warnings ๐ค. This option is equivalent to-Walloc-size-larger-than=SIZE_MAXor larger.-Wallocaโ warns on all uses ofallocain the source. Every single one. No chill ๐ฅ.-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 listen โ 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 ๐.
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. Like:
void func ()
{
void *p = alloca (n);
f (p);
}
If -Walloca-larger-than=500 were passed, the above would trigger a warning โ this time because of the lack of bounds checking ๐.
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, causing a larger-than-expected argument to be implicitly cast into the alloca call. Sneaky ๐ค.
This option also warns when alloca is used in a loop ๐.
-Walloca-larger-than=PTRDIFF_MAX is enabled by default, but it's usually only effective when -ftree-vrp is active (the default for -O2 and above).
See also -Wvla-larger-than=byte-size.
-Wno-alloca-larger-thanโ disables the-Walloca-larger-than=warnings ๐ธ. Equivalent to-Walloca-larger-than=SIZE_MAXor larger.-Warith-conversionโ this one makes GCC warn about implicit conversions from arithmetic operations even when converting the operands to the same type can't actually change their values. It 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
}
-Warray-bounds, *-Warray-bounds=n* โ warns about out-of-bounds subscripts or offsets into arrays ๐จ. This warning is enabled by-Wall. It's way more effective when-ftree-vrpis active (the default for-O2and above), but a subset of instances get flagged 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's declared as either a flexible array member per C99 standard onwards ([]), a GCC zero-length array extension ([0]), or an 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 a 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 to level=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 bestie: this 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.
-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, which 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.
and the attribute guest list is giving main character energy: alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice. that's the whole lineup bestie ๐
-Wattribute-alias is literally just -Wattribute-alias=1 wearing a different fit โ same thing, and yeah, that's the default. wanna turn these warnings all the way off? either -Wno-attribute-alias or -Wattribute-alias=0 gets it done. your call, no judgment ๐ซถ
-Wbidi-chars=[none|unpaired|any|ucn]โ warns you about possibly-misleading UTF-8 bidirectional control characters hiding in comments, string literals, character constants, and identifiers. these lil guys can flip left-to-right writing direction into right-to-left (and vice versa), which makes the logical order and the visual order disagree with each other. that's actually dangerous โ like, it can look like a chunk of code isn't commented out when it absolutely is. trust issues fr ๐ญ
GCC supports three levels of warning here. the default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the whole warning off. -Wbidi-chars=any warns about any use of bidirectional control characters, periodt.
by default this warning does not warn about UCNs. but you can turn that checking on with -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. and heads up: -Wbidi-chars=ucn is valid, and it's equivalent to -Wbidi-chars=unpaired,ucn, if no previous -Wbidi-chars=any was specified. iykyk ๐
-Wbool-compareโ warns when a boolean expression gets compared with an integer value that isn'ttrue/false. like, this comparison is always false, bestie, it's giving "why would you write this":
int n = 5;
...
if ((n > 1) == 2) { ... }
this warning is enabled by -Wall. โจ
-Wbool-operationโ warns about suspicious operations on expressions of a boolean type. for instance, bitwise negation of a boolean is very likely a bug in the program. for C, this warning also warns 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 identical branches. it catches cases like:
if (p != NULL)
return 0;
else
return 0;
it does not warn when both branches contain just a null statement. and it also warns for conditional operators:
int i = x ? *p : *p;
the way that second *p is just sitting there... ๐
-Wduplicated-condโ warns about duplicated conditions in an if-else-if chain. for instance, warn for this code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
girl, you already asked that ๐ญ
-Wframe-addressโ warns when__builtin_frame_addressor__builtin_return_addressis called with an argument greater than 0. such calls may return indeterminate values or crash the program. the warning is included in-Wall. crash energy is not cute ๐-Wno-discarded-qualifiers(C and Objective-C only) โ do not warn if type qualifiers on pointers are being discarded. typically, the compiler warns if aconst char *variable is passed to a function that takes achar *parameter. this option can be used to suppress such a warning. quiet little icon ๐-Wno-discarded-array-qualifiers(C and Objective-C only) โ do not warn if type qualifiers on arrays which are pointer targets are being discarded. typically, the compiler warns if aconst int (*)[]variable is passed to a function that takes aint (*)[]parameter. this option can be used to suppress such a warning.-Wno-incompatible-pointer-types(C and Objective-C only) โ do not warn when there is a conversion between pointers that have incompatible types. this warning is for cases not covered by-Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness. two different jobs, two different switches, no overlap โจ-Wno-int-conversion(C and Objective-C only) โ do not warn about incompatible integer to pointer and pointer to integer conversions. heads up: this warning is about implicit conversions; for explicit conversions the warnings-Wno-int-to-pointer-castand-Wno-pointer-to-int-castmay be used. don't mix them up bestie ๐-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. undefined behaviour, babes, we do not play ๐
for example, the first two stores in function bad are diagnosed because the array elements overlap the subsequent members b and c. the third store is diagnosed by -Warray-bounds because it is 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
}
and option -Wzero-length-bounds is enabled by -Warray-bounds. chain reaction โจ
-Wno-div-by-zeroโ do not warn about compile-time integer division by zero. floating-point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs. so don't come for it, it's valid ๐-Wsystem-headersโ prints warning messages for constructs found in system header files. warnings from system headers are normally suppressed, on the assumption that they usually don't indicate real problems and would only 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. glow-up for the headers โจ
โ ๏ธ but note: using-Wallin conjunction with this option does not warn about unknown pragmas in system headers โ for that,-Wunknown-pragmasmust also be used. you need both, no shortcuts ๐ซถ
-Wtautological-compareโ warns if a self-comparison always evaluates to true or false. it detects various mistakes such as:
int i = 1;
...
if (i > i) { ... }
this warning also warns about bitwise comparisons that always evaluate to true or false, for instance:
if ((a & 16) == 10) { ... }
which will always be false. bestie that math is not mathing ๐
this warning is enabled by -Wall.
-Wtrampolinesโ warns about trampolines generated for pointers to nested functions. a trampoline is a small piece of data or code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. for some targets, it is made up of data only and thus requires no special treatment. but for most targets, it is made up of code and thus requires the stack to be made executable in order for the program to work properly. executable stack?? okay security girlies, eyes up ๐-Wfloat-equalโ warns if floating-point values are used in equality comparisons.
the idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. if you're doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a different problem). in particular, instead of testing for equality, you should check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken. lowkey a whole philosophy lesson ๐ฆ
-Wtraditional(C and Objective-C only) โ warns about certain constructs that behave differently in traditional C and ISO C. also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. the full tea 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. therefore-Wtraditionalwarns about directives that traditional C understands but ignores because the#does not appear as the first character on the line. it also suggests you hide directives like#pragmanot understood by traditional C by indenting them. some traditional implementations do not 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, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the_MIN/_MAXmacros in<limits.h>. use of 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. - 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 by prototypes between fixed/floating-point values and vice versa. And like... when you're compiling with traditional C and those prototypes aren't there? Serious problems. This is only a subset of the possible conversion warnings, bestie โ for the whole set you want
-Wtraditional-conversion. - Use of ISO C style function definitions. 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 thus not relevant to traditional C compatibility. ๐
-Wtraditional-conversion(C and Objective-C only) โ Warn if a prototype causes a type conversion that's different from what would happen to the same argument if the prototype weren't there. That includes conversions of fixed point to floating and vice versa, plus conversions changing 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) โ Warn when a declaration shows up after a statement in a block. It's a construct you know from C++, it got introduced with ISO C99, and GCC allows it by default. It is not supported by ISO C90. ๐-Wshadowโ Warn 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 gets shadowed. Note that 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 on, it includes all instances of local shadowing too, which means-Wno-shadow=localand-Wno-shadow=compatible-localare 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. simple as that ๐-Wshadow=globalโ Warn for any shadowing. Same as-Wshadow.-Wshadow=localโ Warn when a local variable shadows another local variable or parameter.-Wshadow=compatible-localโ Warn 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 shadowing variable's type can be converted to the shadowed variable's type. The creation of this flag (on top of-Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it's most likely intentional โ not a bug or a typo. Exhibit A, your honor:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
for (int i = 0; i < N; ++i)
{
...
}
...
}
Since those two variables 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 that shadowing const char *i by char *i does not emit a warning.
This warning is also enabled by -Wshadow=local. ๐ฆ
-Wlarger-than=byte-size โ Warn 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.
It 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โ Disable-Wlarger-than=warnings. Equivalent to-Wlarger-than=SIZE_MAXor larger. bye felicia ๐-Wframe-larger-than=byte-size โ Warn if a function frame's size exceeds byte-size. Heads up though: 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 get no warning at all. On top of that, any space allocated viaalloca, variable-length arrays, or related constructs is not included by the compiler when it decides whether to warn you.-Wframe-larger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by the option can be disabled either by specifying a byte-size ofSIZE_MAXor more, or by-Wno-frame-larger-than.-Wno-frame-larger-thanโ Disable-Wframe-larger-than=warnings. Equivalent to-Wframe-larger-than=SIZE_MAXor larger. ๐-Wfree-nonheap-objectโ Warn when you try to deallocate an object that either wasn't allocated on the heap, or that you're pointing at with a pointer that was not returned from a prior call to the corresponding allocation function. Example time: becausestpcpyreturns a pointer to the terminating nul character and not to the beginning of the object, thefreecall below gets diagnosed.
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is included in -Wall. ๐
-Wstack-usage=byte-size โ Warn if a function's stack usage might exceed byte-size. This computation is conservative, and unlike the frame one, any space allocated viaalloca, variable-length arrays, or related constructs is included by the compiler when it decides whether to warn you.
The message matches the output of -fstack-usage:
- If the stack usage is fully static but exceeds the specified amount, it's this:
warning: stack usage is 1120 bytes
- If the stack usage is (partly) dynamic but bounded, it's this:
warning: stack usage might be 1648 bytes
- If the stack usage is (partly) dynamic and not bounded, it's this:
warning: stack usage might be unbounded
-Wstack-usage=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-stack-usage.
-Wno-stack-usageโ Disable-Wstack-usage=warnings. Equivalent to-Wstack-usage=SIZE_MAXor larger. ๐ธ-Wunsafe-loop-optimizationsโ Warn if the loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. And with-funsafe-loop-optimizations, warn if the compiler makes such assumptions. ๐ฅ-Wno-pedantic-ms-format(MinGW targets only) โ When combined with-Wformatand-pedanticwithout GNU extensions, this option disables the warnings about non-ISOprintf/scanfformat width specifiersI32,I64, andIused on Windows targets, which depend on the MS runtime.-Wpointer-arithโ Warn about anything that depends on the "size of" a function type or ofvoid. GNU C assigns these types a size of 1, 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 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โ Warn about unsupported features in ThreadSanitizer. ThreadSanitizer does not supportstd::atomic_thread_fenceand can report false positives. This warning is enabled by default. ๐-Wtype-limitsโ Warn if a comparison is always true or always false due to the limited range of the data type โ but do not warn for constant expressions. For example, warn if an unsigned variable gets compared against zero with<or>=. This warning is also enabled by-Wextra.-Wabsolute-value(C and Objective-C only) โ Warn 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 for 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โ Warn whenever a comment-start sequence/*appears in a/*comment, or whenever a backslash-newline appears in a//comment. This warning is enabled by-Wall.-Wcommentsโ same vibe, same flag, iconic duo ๐ซถ-Wtrigraphsโ Warn if any trigraphs are encountered that might change the meaning of the program. Trigraphs inside comments are not warned about, except the ones 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โ Warn if an undefined identifier is evaluated in an#ifdirective. Those identifiers get replaced with zero, so like... yeah. โญ-Wexpansion-to-definedโ Warn 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โ Warn 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's redefined or undefined. ๐
Built-in macros, macros you defined on the command line, and macros that came from include files? Not warned about, bestie. They're safe. โจ
Heads up though ๐: if a macro is actually used, but only inside skipped conditional blocks, the preprocessor will still clock it as unused. To dodge that warning, you can level up the scope of the macro's definition โ like moving it into the first skipped block, iykyk. Or you could just give it a fake little cameo, something like:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsโ stoppp don't warn me when an#elseor an#endifis followed by text ๐. This used to happen all the time in older programs, code that looks like this:
#if FOO
...
#else FOO
...
#endif FOO
That second and third FOO? Should've been in comments, fr. This warning is on by default.
-Wbad-function-cast(C and Objective-C only) โ warns when you cast a function call to a type that doesn't match. Like if a function returning an integer type gets cast to a pointer type โ that's giving chaos and GCC will call it out. ๐-Wc90-c99-compat(C and Objective-C only) โ snitches on features that aren't in ISO C90 but are in ISO C99. Think variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, all of it. This option doesn't care what standards mode you're in โ it's independent. And the warnings go quiet inside the expression that follows__extension__. ๐ฆ-Wc99-c11-compat(C and Objective-C only) โ same energy, one era over: flags features not in ISO C99 but present in ISO C11. We're talking anonymous structures and unions, the_Atomictype qualifier, the_Thread_localstorage-class specifier, the_Alignasspecifier, theAlignofoperator, the_Generickeyword, and so on. Still independent of the standards mode, still silenced inside the expression after__extension__. โจ-Wc11-c2x-compat(C and Objective-C only) โ the glow-up check: warns about features not in ISO C11 but present in ISO C2X. For instance omitting the string in_Static_assert, using[[]]syntax for attributes, using decimal floating-point types, you get it. Independent of standards mode, and 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. asking for an implicit conversion fromvoid *to a pointer to a non-voidtype. Not the vibe for portable code. ๐-Wc++11-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning shifted between ISO C++ 1998 and ISO C++ 2011, e.g. identifiers that were fine in ISO C++ 1998 but became 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 when you're compiling code with an older C++ standard. And even without this option, some C++11 constructs only get diagnosed if you're using-Wpedantic. ๐ซถ-Wno-c++14-extensions(C++ and Objective-C++ only) โ don't warn about C++14 constructs in code compiled under an older C++ standard. Same deal: even without this option, some C++14 constructs are only diagnosed with-Wpedantic. ๐-Wno-c++17-extensions(C++ and Objective-C++ only) โ no warnings for C++17 constructs under an older C++ standard. And yeah, without this option some C++17 constructs still only get diagnosed if-Wpedanticis used. ๐ง-Wno-c++20-extensions(C++ and Objective-C++ only) โ hush on C++20 constructs in older-standard code. Even without it, some C++20 constructs are only diagnosed when-Wpedanticis in the chat. ๐-Wno-c++23-extensions(C++ and Objective-C++ only) โ no warning about C++23 constructs when compiling with an older C++ standard. And, you guessed it, some C++23 constructs only get diagnosed if-Wpedanticis used. ๐-Wcast-qualโ warns whenever you cast a pointer in a way that strips a type qualifier off the target type. Like casting aconst char *to a plain oldchar *? Warned. ๐ญ
It also warns when a cast introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, bestie, watch:
/* 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';
-Wcast-alignโ warns when a pointer cast raises the required alignment of the target. Like casting achar *to anint *on machines where integers can only be accessed at two- or four-byte boundaries. Aligned or it didn't happen. ๐-Wcast-align=strictโ the strict version, periodt: warns whenever a pointer cast increases the required alignment of the target. Same example โchar *cast to anint *โ except this one doesn't care what the target machine is. ๐ฅ-Wcast-function-typeโ warns when a function pointer gets cast to an incompatible function pointer. Details, because details matter: if the cast involves function types with a variable argument list, only the types of the initial arguments that are provided get considered. Any parameter of pointer-type matches any other pointer-type. Benign differences in integral types are ignored, likeintvs.longon ILP32 targets. Type qualifiers get ignored too. And the function typevoid (*) (void)is special โ it matches everything, which you can use to suppress this warning. If the cast involves pointer to member types, this warning fires whenever the type cast changes the pointer to member type. Enabled by-Wextra. โจ-Wwrite-stringsโ in C, this gives string constants the typeconst char[length], so copying the address of one into a non-constchar *pointer throws a warning. These warnings help you catch, at compile time, code that might try to write into a string constant โ but only if you've been extremely careful about usingconstin your declarations and prototypes. Otherwise it's just a nuisance, which is exactly why-Walldoes not request these warnings. ๐ซ
In C++, it warns about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs.
-Wclobberedโ warns about variables that might get changed bylongjmporvfork. 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. You can turn that off with-Wno-complain-wrong-lang, which is mostly useful when you're invoking a single compiler driver on multiple source files written in different languages. Example time:
$ 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. That latter front end diagnoses f951: Warning: command-line option '-fno-rtti' is valid for C++/D/ObjC++ but not for Fortran โ which you can disable with -Wno-complain-wrong-lang. ๐
-Wconversionโ warns for implicit conversions that might 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). It does not warn for explicit casts likeabs ((int) x)andui = (unsigned) -1, or when the value isn't changed by the conversion, like inabs (2.0). Warnings about conversions between signed and unsigned integers can be switched off with-Wno-sign-conversion. ๐
For C++, it also warns for confusing overload resolution for user-defined conversions, and for 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.
And lowkey important: 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 it's confusing whichifstatement anelsebranch belongs to. Here's a classic offender:
{
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). That's often not what the programmer expected โ as the indentation in the example above reveals. When there's potential for this confusion, GCC issues a warning if this flag is specified. Want it gone? Add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. The fixed-up code looks like this:
{
if (a)
{
if (b)
foo ();
else
bar ();
}
}
This warning is enabled by -Wparentheses. ๐
-Wdangling-pointer,-Wdangling-pointer=nโ ok bestie, this one is giving pointer afterlife realness ๐. It warns about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. That includes local variables declared in nested blocks, compound literals and other unnamed temporary objects. Plus, it warns about storing the address of such objects in escaped pointers. The warning is enabled at all optimization levels but may yield different results with optimization than without. No cap.-Wdangling-pointer=1โ At level 1, the warning diagnoses only unconditional uses of dangling pointers. 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';
}
In the following function, the store of the address of the local variable "x" in 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โ At level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of dangling pointers. For example, because the arrayain the following function is out of scope when the pointersthat was set to point is 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");
...
}
And just so you know, -Wdangling-pointer=2 is included in -Wall. Periodt. ๐
-Wdate-timeโ Warn when macros"__TIME__","__DATE__"or"__TIMESTAMP__"are encountered as they might prevent bit-wise-identical reproducible compilations. So if you're trying to get that reproducible build, this warning is like "girl, those macros are gonna mess you up." ๐ฐ๏ธ-Wempty-bodyโ Warn if an empty body occurs in an"if","else"or"do while"statement. This warning is also enabled by-Wextra. Empty body? That's a no from me. ๐ โโ๏ธ-Wno-endif-labelsโ Do not warn about stray tokens after"#else"and"#endif". So if you've got random stuff after those preprocessor directives, this shuts up the warning. Silence is golden. โจ-Wenum-compareโ Warn about a comparison between values of different enumerated types. In C++ enumerated type mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by-Wall. Comparing different enums is like comparing your ex to your current boo โ not the vibe. ๐ซ-Wenum-conversionโ Warn when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by-Wextrain C. Implicit enum conversion? That's a sneaky link. ๐ต๏ธโโ๏ธ-Wenum-int-mismatch(C and Objective-C only) โ Warn about mismatches between an enumerated type and an integer type in declarations. 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. However, since the choice of the underlying type of an enumerated type is implementation-defined, such mismatches may cause portability issues. In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat. So like, keep your enums and ints separated in declarations, bestie. It's giving portability drama. ๐
-Wjump-misses-init(C, Objective-C only) โ Warn if a"goto"statement or a"switch"statement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option. So jumping over initializations? Not today, Satan. ๐ฆ
-Wsign-compareโ Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. In C++, this warning is also enabled by-Wall. In C, it is also enabled by-Wextra. Signed vs unsigned comparisons are a classic trap, and this warning is your friend. ๐ฏโโ๏ธ-Wsign-conversionโ Warn 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. In C, this option is enabled also by-Wconversion. So if you're flipping signs without telling anyone, it'll call you out. ๐จ-Wfloat-conversionโ Warn for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by-Wconversion. Losing precision? That's a red flag. ๐ฉ-Wno-scalar-storage-orderโ Do not warn on suspicious constructs involving reverse scalar storage order. So if you're doing byte-order weirdness, this silences the warning. ๐ค-Wsizeof-array-divโ Warn about divisions of two sizeof operators when the first one is applied to an array and the divisor does not equal the size of the array element. In such a case, the computation will not yield the number of elements in the array, which is likely what the user intended. This warning warns e.g. about:
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall. So if you're dividing sizeofs wrong, it'll catch that. โ
-Wsizeof-pointer-divโ Warn for suspicious divisions of two sizeof expressions that divide the pointer size by the element size, which is the usual way to compute the array size but won't work out correctly with pointers. This warning warns e.g. about"sizeof (ptr) / sizeof (ptr[0])"if"ptr"is not an array, but a pointer. This warning is enabled by-Wall. Pointer math gone wrong? It's on it. ๐งฎ-Wsizeof-pointer-memaccessโ Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses"sizeof". This warning triggers for example for"memset (ptr, 0, sizeof (ptr));"if"ptr"is not an array, but a pointer, and suggests a possible fix, or about"memcpy (&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. So using sizeof on pointers for mem functions? Big yikes. ๐ฌ
-Wno-sizeof-array-argumentโ Do not warn when the"sizeof"operator 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. So if you're doing that, you can silence it. ๐-Wmemset-elt-sizeโ Warn for suspicious calls to the"memset"built-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. This indicates that the user has omitted a multiplication by the element size. This warning is enabled by-Wall. Forgot to multiply? It'll remind you. ๐ง-Wmemset-transposed-argsโ Warn for suspicious calls to the"memset"built-in function where the second argument is not zero and the third argument is zero. For example, the call"memset (buf, sizeof buf, 0)"is diagnosed because"memset (buf, 0, sizeof buf)"was meant instead. The diagnostic is only emitted if the third argument is a literal zero. Otherwise, if it is an expression that is folded to zero, or a cast of zero to some type, it is far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by-Wall. Swapped args in memset? Caught. ๐-Waddressโ Warn 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. So address shenanigans? It'll warn. ๐
-Wno-address-of-packed-memberโ Do not warn when the address of packed member of struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default. So if you're doing that, you can silence it. ๐ฆ-Wlogical-opโ Warn 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. Also warns when the operands of a logical operator are the same:
extern int a;
if (a < 0 && a < 0) { ... }
So logical ops being weird? It'll tell you. ๐ค
-Wlogical-not-parenthesesโ Warn 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) { ... }
So if you put ! in a weird place, it'll warn. ๐คจ
okay so you can mute this one โ just wrap the LHS in parentheses and the compiler chills out:
if ((!a) > 1) { ... }
and fyi, -Wall is the one that turns this warning on in the first place โจ
-Waggregate-returnโ yells at you if any function that returns a struct or a union gets defined or called. (And in languages where returning an array is a thing, that triggers the warning too.) structs coming back out of functions? it's giving suspicious ๐-Wno-aggressive-loop-optimizationsโ warns when you've got a loop with a constant number of iterations and the compiler catches some undefined behavior happening in a statement during one or more of those iterations. undefined behavior in a fixed-count loop?? bestie the compiler noticed ๐ญ-Wno-attributesโ stops the warning for an unexpected__attribute__, like attributes nobody recognizes, or function attributes slapped onto variables, etc. Important: this does not stop errors for incorrect use of attributes that are supported. errors still error, it's not a free pass ๐
Also, with -Wno-attributes=, you can squash warnings about unknown scoped attributes (in C++11 and C2X). For example, -Wno-attributes=vendor::attr disables the warning about this declaration:
[[vendor::attr]] void f();
And you can turn off warnings for every attribute in a namespace with -Wno-attributes=vendor::, which prevents warnings about both of these:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Heads up though:-Wno-attributes=does not imply-Wno-attributes. Two separate vibes, no cap.
-Wno-builtin-declaration-mismatchโ warns if a built-in function is declared with a signature that doesn't match, or declared as a non-function, or when a built-in declared with a type that has no prototype gets called with arguments whose promoted types don't line up with what the function expects. When-Wextrais on, it also warns when a built-in that takes arguments is declared without a prototype.-Wbuiltin-declaration-mismatchis enabled by default. To dodge the warning, just include the right header so the built-in prototypes are in scope. ๐ซถ
Like, the memset call below gets flagged, because the function wants a value of type size_t and the type of 32 is int. With -Wextra, the declaration of the function gets flagged too:
extern void* memset ();
void f (void *d)
{
memset (d, '\0', 32);
}
-Wno-builtin-macro-redefinedโ do not warn if certain built-in macros get redefined. This suppresses redefinition warnings for__TIMESTAMP__,__TIME__,__DATE__,__FILE__, and__BASE_FILE__. builtin macros stay iconic, don't touch them โญ-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 allowed to slide without a warning if there's a declaration before it that specifies the argument types.)-Wold-style-declaration(C and Objective-C only) โ warns about obsolescent usages in a declaration, per the C Standard. Like, warn if storage-class specifiers such asstaticaren't the first things in a declaration. This warning is also enabled by-Wextra. put yourstaticfirst bestie it's the law now-Wold-style-definition(C and Objective-C only) โ warns if an old-style function definition is used. You get the warning even if there's a previous prototype. A definition using()is not considered old-style in C2X mode, because there it's equivalent to(void)โ but for older standards it totally counts as old-style. ๐-Wmissing-parameter-type(C and Objective-C only) โ fires when 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. Yes, even if the definition itself provides a prototype. Use this option to sniff out global functions that don't have a matching prototype declaration in a header file. Not valid for C++, because in C++ all function declarations provide prototypes, and a non-matching declaration declares an overload instead of clashing with an earlier declaration. For C++, use-Wmissing-declarationsto catch missing declarations. wrong tool for the C++ job, iykyk-Wmissing-declarationsโ warns if a global function is defined without a previous declaration, even if the definition itself provides a prototype. Use it to find global functions that aren't declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations โ use-Wmissing-prototypesto catch those 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 struct's initializer is missing some fields. For example, this code triggers it, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so this tweak doesn't trigger it:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
In C, this option doesn't warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
Same energy in C++: this option doesn't warn about the empty { } initializer, like:
struct s { int f, g, h; };
s x = { };
This warning is included in -Wextra. And if you want the other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers. ๐
-Wno-missing-requiresโ by default, the compiler warns about a concept-id showing up 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 you meant to write:
bool satisfied = requires { requires C<T> };
so that satisfied is only true if concept C is satisfied for type T. This warning can be disabled with -Wno-missing-requires. that missing requires is the whole plot twist ๐ญ
-Wno-missing-template-keywordโ the member access tokens.,->and::must be followed by thetemplatekeyword 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 you can get false positives. To silence those, wrap the expression in parentheses. For example, this next one 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 these are a typo in your code โ they have implementation-defined values and should never be in portable code. please don't ship'FOOF'fr fr ๐-Wnormalized=[none|id|nfc|nfkc]โ in ISO C and ISO C++, two identifiers are different if they're different sequences of characters. But sometimes, when characters outside the basic ASCII set get used, you can end up with two different character sequences that look identical. To avoid confusion, the ISO 10646 standard lays out normalization rules which, when applied, ensure two sequences that look the same get turned into the same sequence. GCC can warn you when you're using identifiers that haven't been normalized โ this option controls that warning. ๐ฆ
GCC supports four levels of warning. The default is -Wnormalized=nfc, which warns about any identifier that isn't 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. Basically 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. The hope is that future versions of the standards involved will fix 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're using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. invisible bugs are not the vibe ๐
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 exactly like a regular n that's been put in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all of these into a standard form too, and GCC warns if your code isn't in NFKC when you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier containing the letter O because it might get confused with the digit 0 โ so it's not the default, but it may be useful as a local coding convention if your programming environment can't be fixed to display these characters distinctly.
-Wno-attribute-warningโ do not warn about usage of functions declared with thewarningattribute. 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 compiling with the-Werrorflag. โจ-Wno-deprecatedโ do not warn about usage of deprecated features. living in the past, but make it silent-Wno-deprecated-declarationsโ do not warn about uses of functions, variables, and types marked as deprecated by using thedeprecatedattribute.-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. On by default, so it's already watching ๐-Wopenacc-parallelismโ yells at you when your OpenACC parallelism choices are likeโฆ potentially suboptimal. not a vibe, but it's informative โจ-Wopenmp-simdโ warns you when the vectorizer cost model straight-up overrides the OpenMP simd directive you set, king. if you wanna relax that cost model, hit up-fsimd-cost-model=unlimited๐ซถ-Woverride-init(C and Objective-C only) โ if you used designated initializers and an initialized field with no side effects gets overridden, it says something. this one is bundled inside-Wextra, and if you want all the other-Wextrawarnings without this one, you do-Wextra -Wno-override-init. iykyk ๐-Wno-override-init-side-effects(C and Objective-C only) โ the opposite energy: do NOT warn when an initialized field with side effects gets overridden via designated initializers. Enabled by default.-Wpackedโ warns when a struct gets the packed attribute but packing does literally nothing to its layout or size. like, such structures can be mis-aligned for basically zero benefit ๐ญ example: here the variablef.xinstruct baris misaligned even thoughstruct baritself isn't packed:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compatโ lore time ๐ง the GCC 4.1, 4.2 and 4.3 series justโฆ ignored thepackedattribute on bit-fields of typechar. fixed in GCC 4.4, but that fix can change your structure layout. so GCC tells you when the offset of such a field changed in 4.4. for example there's no longer a 4-bit padding between fieldaandbin this bad boy:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. use -Wno-packed-bitfield-compat to turn it off ๐
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warns when a struct field with explicitly specified alignment, sitting inside a packed struct or union, ends up misaligned. like forstruct Syou'd get a warning that goeswarning: alignment 1 of 'struct S' is less than 8, in this code:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
struct S8 s8;
};
this one is turned on by -Wall โจ
-Wpaddedโ warns if padding snuck into a structure, whether it's to align one element or to align the whole thing. sometimes you can shuffle the fields around to cut the padding and make the structure smaller, and that's a lil glow-up ๐ธ-Wredundant-declsโ warns if literally anything is declared more than once in the same scope. even when the multiple declaration is technically valid and changes absolutely nothing. yeah, it's that strict ๐-Wrestrictโ warns when an object referenced by arestrict-qualified parameter (or, in C++, a__restrict-qualified parameter) gets aliased by another argument, or when copies between such objects overlap. example: thestrcpycall below is trying to truncate the string by replacing its leading characters with the last four โ but the call writes the terminating NUL intoa[4], so the copies overlap and boom, diagnosed:
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
-Wrestrict catches some simple overlap cases even with zero optimization, but it's at its best at -O2 and above. included in -Wall ๐
-Wnested-externs(C and Objective-C only) โ warns if anexterndeclaration shows up inside a function. nested?? in this economy?? ๐-Winlineโ warns if a function declared as inline is, in fact, not inlined. sorry bestie. even with this option on, the compiler stays quiet about failures to inline functions declared in system headers, so don't come for it about those.
the compiler uses a whole pile of heuristics to decide whether to inline โ for example it weighs the size of the function being inlined and how much inlining has already happened in the current function. so seemingly tiny changes in your source can make -Winline warnings appear or completely vanish. chaotic, but that's the game ๐ฆ
-Winterference-sizeโ warns about using C++17std::hardware_destructive_interference_sizewithout setting its value via--param destructive-interference-size. it also warns about questionable values for that option.
this variable is meant for controlling class layout, to dodge 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 storing to one won't force accesses to the other to reload the cache line.
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).
if ABI stability matters to you โ say, the use is in a header for a library โ you should probably not use the hardware interference size variables at all. alternative: force a particular value with --param.
if you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can silence the warning with -Wno-interference-size ๐
-Wint-in-bool-contextโ warns on suspicious integer values hanging out where booleans are expected. like conditional expressions (?:) using non-boolean integer constants in boolean context, e.g.if (a <= b ? 2 : 3). or left shifting signed integers in boolean context, likefor (a = 0; 1 << a; a++);. same deal for every kind of multiplication regardless of data type. 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.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.-Winvalid-pchโ warns if a precompiled header is chilling in the search path but cannot be used. so close yet so far ๐ญ-Winvalid-utf8โ warns if an invalid UTF-8 character is found. this one is on by default for C++23 if-finput-charset=UTF-8is used, and it gets turned into an error with-pedantic-errorsโญ-Wno-unicodeโ doesn't diagnose invalid forms of delimited or named escape sequences which are treated as separate tokens.Wunicodeis enabled by default.-Wlong-longโ warns if thelong longtype is used. enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. to inhibit the warning messages, 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 inhibit the warning 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. a vector operation can be implemented "piecewise" โ meaning the scalar operation is performed on every vector element; "in parallel" โ meaning the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and "as a single scalar" โ meaning 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. bestie behavior honestly ๐ค- *
-Wvla-larger-than=byte-size* โ when this one's on, 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. works similarly to how-Walloca-larger-than=byte-sizeworks, but for variable-length arrays.
heads up: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not even trigger for those ๐
-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-Wvla-larger-than=warnings. the option is equivalent to-Wvla-larger-than=SIZE_MAXor larger. gone, reduced to atoms ๐-Wvla-parameterโ warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and 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. failing to provide arguments of sufficient size, or accessing more than that maximum number of elements, may be diagnosed ๐
Like, say you got the VLA-bound situation: the warning fires on these redeclarations because the first one lets any size of array get passed to f, while the second one says the array argument has at least n elements. And bestie, calling f with the VLA bound parameter bigger than the actual VLA bound? Yeah, also a warning. ๐
void f (int n, int[n]);
// warning: argument 2 previously declared as a VLA
void f (int, int[]);
void g (int n)
{
if (n > 4)
return;
int a[n];
// warning: access to a by f may be out of bounds
f (sizeof a, a);
...
}
-Wvla-parameter comes bundled inside -Wall. And if you're dealing with plain old ordinary array arguments instead, -Warray-parameter will clap about similar problems. ๐
-Wvolatile-register-varโ clocks you if a register variable gets declaredvolatile. Real talk: thevolatilemodifier does not stop all the optimizations that could kill off reads and/or writes to register variables. Being cutesy withvolatiledoesn't save you here. This warning is enabled by-Wall.-Wxor-used-as-pow(C, C++, Objective-C and Objective-C++ only) โ warns about^, the exclusive or operator, in moments where it really looks like you meant exponentiation. Specifically? The warning shows up 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, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. So your brain may be lying to you. ๐ญ
This warning is enabled by default. Want it gone? Convert one of the operands to hexadecimal. poof, silenced. โจ
-Wdisabled-optimizationโ warns you if a requested optimization pass gets disabled. ngl this does not generally mean something is wrong with your code โ it just means GCC's optimizers couldn't handle your code effectively. Usually the problem is your code is too big or too complex; GCC literally refuses to optimize programs when the optimization itself would take inordinate amounts of time. it's not you, it's the vibes being too much.-Wpointer-sign(C and Objective-C only) โ warns for pointer argument passing or assignment where the signedness differs. 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. protect your stack babes ๐-Woverlength-stringsโ warns about string constants longer than the "minimum maximum" length laid out in the C standard. Modern compilers generally allow string constants that are way, way longer than the standard's minimum limit, but if you want very portable programs you 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 got raised to 4095. C++98 does not specify a normative minimum maximum, so we do not 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. Use it together with-Wsystem-headersand it'll warn about such constants in system header files too. Handy when you're prepping 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 coming from different compilation units. Requires-fltoto be enabled. Enabled by default.-Wno-designated-init(C and Objective-C only) โ suppress warnings when a positional initializer is used to initialize a structure that has been marked with thedesignated_initattribute.
๐ต๏ธโ๏ธ Options That Control Static Analysis ๐ต๏ธโ๏ธ
-fanalyzerโ turns on a static analysis of program flow that hunts for "interesting" interprocedural paths through the code, and issues warnings for problems found along them.
Heads up bestie: 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 is a bug-finding tool, rather than a tool for proving program correctness. So don't treat it like a proof, it's more like a friend going "hmm that's suspicious".
The analyzer is only suitable for use on C code in this release.
Enabling this option 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.
-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 reaches an internal limit. The -Wanalyzer-too-complex option warns if this occurs. so like, at least you'd know? ๐
-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, suggesting that the pointer could have been NULL. Such cases suggest that the check for NULL is either redundant, or that it needs to be moved to before the pointer is dereferenced.
This diagnostic 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.
This diagnostic is unlikely to be reported when any level of optimization is enabled, as GCC's optimization logic will typically consider such checks for NULL as being redundant, and optimize them away before the analyzer "sees" them. Hence optimization should be disabled when attempting to trigger this diagnostic.
-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. once is enough bestie ๐ญ
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 (such as writing a password to a log file). not the password in the 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 atrust 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 (such as 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.
This diagnostic also warns for code paths in a which a function with attribute fd_arg_read (N) is called with a file descriptor opened with O_WRONLY at referenced argument N or a function with attribute fd_arg_write (N) is called with a file descriptor opened with O_RDONLY at referenced argument N.
-Wno-analyzer-fd-double-closeโ bestie, this warning needs-fanalyzerto even exist (that's what turns it on), so if you want it gone you hit it with-Wno-analyzer-fd-double-close.
It clocks you closing the same file descriptor more than once on some path through your code. That's a no. ๐
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-fd-leakโ also-fanalyzer-gated, so-Wno-analyzer-fd-leakis your off switch.
This one drags you for paths where an open file descriptor justโฆ leaks. Opened, never closed, left on read forever. ๐
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โ needs-fanalyzer; kill it with-Wno-analyzer-fd-phase-mismatch.
It warns when you try to do an operation in the wrong phase of a file descriptor's whole lifetime arc. The example it gives is calling accept on a stream socket that hasn't had listen successfully called on it yet. Like, babe, that socket isn't ready. ๐ญ
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; disable with-Wno-analyzer-fd-type-mismatch.
This is the vibe check for using the wrong type of file descriptor. For example it'll flag you trying to use socket operations on a file descriptor you got from open, or doing a stream socket operation on a datagram socket. Wrong fit, wrong energy. โจ
-Wno-analyzer-fd-use-after-closeโ needs-fanalyzer; turn it off with-Wno-analyzer-fd-use-after-close.
It warns for paths in your code where a read or a write is called on a closed file descriptor. Ma'am, that door is shut. ๐ช
This diagnostic also warns for paths through code in which a function with attribute fd_arg (N) or 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; disable it with-Wno-analyzer-fd-use-without-check.
Warns for paths through the code where a file descriptor gets used without ever being checked for validity first. No verification, just vibes. Not the move.
This diagnostic also warns for paths through code in which a function with attribute fd_arg (N) or 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โ needs-fanalyzer; silence it with-Wno-analyzer-file-leak.
Warns for paths through your code where a <stdio.h> FILE * stream object gets leaked. Opened a file, forgot the whole thing. ๐
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; disable with-Wno-analyzer-free-of-non-heap.
This diagnostic warns for paths through the code in which free is called on a non-heap pointer โ like an on-stack buffer, or a global. You cannot return that, bestie, it was never heap's to begin with.
See CWE-590: Free of Memory not on the Heap (https://cwe.mitre.org/data/definitions/590.html).
-Wno-analyzer-imprecise-fp-arithmeticโ needs-fanalyzer; off switch is-Wno-analyzer-imprecise-fp-arithmetic.
Warns for paths through the code where floating-point arithmetic is used in locations that genuinely need precise computation. Heads up though: at the moment this diagnostic only warns on use of floating-point operands inside the calculation of an allocation size. That's the one place it's looking. ๐
-Wno-analyzer-infinite-recursionโ requires-fanalyzer; disable it with-Wno-analyzer-infinite-recursion.
This diagnostic warns for paths through the code that appear to lead to infinite recursion. Forever loop, no exit, main character never leaving the building.
To be specific: when the analyzer "sees" a recursive call, it compares the state of memory at the entry to the new frame with that at the entry to the previous frame of that function on the stack. The warning is issued if nothing in memory appears to be changing; any changes observed to parameters or globals are assumed to lead to termination of the recursion, and so they suppress the warning.
Also real talk โ this diagnostic is likely to miss cases of infinite recursion that get converted to iteration by the optimizer before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic. Turn the optimizer off for this one, periodt.
Compare with -Winfinite-recursion, which provides a similar diagnostic, but is implemented in a different way.
-Wno-analyzer-jump-through-nullโ requires-fanalyzer; disable with-Wno-analyzer-jump-through-null.
Warns for paths through the code in which a NULL function pointer is called. Jumping straight through the void. ๐
-Wno-analyzer-malloc-leakโ needs-fanalyzer; silence it with-Wno-analyzer-malloc-leak.
Warns for paths through the code in which a pointer allocated via an allocator is leaked. That's either malloc, or a function marked with attribute malloc. Allocated and abandoned. ๐ซ
See CWE-401: Missing Release of Memory after Effective Lifetime (https://cwe.mitre.org/data/definitions/401.html).
-Wno-analyzer-mismatching-deallocationโ requires-fanalyzer; use-Wno-analyzer-mismatching-deallocationto disable.
This diagnostic warns for paths through the code in which 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 break it, you buy it with the matching function, okay?
See CWE-762: Mismatched Memory Management Routines (https://cwe.mitre.org/data/definitions/762.html).
-Wno-analyzer-out-of-boundsโ needs-fanalyzer; disable with-Wno-analyzer-out-of-bounds.
Warns for paths through the code in which a buffer is definitely read or written out-of-bounds. The diagnostic applies for cases where the analyzer is able to determine a constant offset, and for accesses past the end of a buffer that also has a constant capacity. On top of that, the diagnostic does limited checking for accesses past the end when both the offset and the capacity are 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; disable it with-Wno-analyzer-possible-null-argument.
Warns for paths through the code in which a possibly-NULL value is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. You promised it wouldn't be NULL. ๐ญ
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-possible-null-dereferenceโ needs-fanalyzer; turn it off with-Wno-analyzer-possible-null-dereference.
Warns for paths through the code in which a possibly-NULL value is dereferenced. Might be null, might not โ either way, dereferencing it is a gamble.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-null-argumentโ requires-fanalyzer; disable with-Wno-analyzer-null-argument.
Warns for paths through the code in which a value known to be NULL is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. Not "possibly". Known. You knew. ๐
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-null-dereferenceโ needs-fanalyzer; silence it with-Wno-analyzer-null-dereference.
Warns for paths through the code in which a value known to be NULL is dereferenced. That's a straight-up crash waiting in the wings, bestie.
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-putenv-of-auto-varโ requires-fanalyzer; disable with-Wno-analyzer-putenv-of-auto-var.
This diagnostic warns for paths through the code in which a call to putenv is passed a pointer to an automatic variable or an on-stack buffer. That memory is not sticking around, and putenv is gonna keep the pointer. Nope.
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โ needs-fanalyzer; off switch is-Wno-analyzer-shift-count-negative.
Warns for paths through the code in which 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 version is implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. One caveat though: the analyzer doesn't prioritize detection of such paths, so false negatives are more likely here relative to other warnings. So if it stays quiet, don't assume you're safe. ๐
-Wno-analyzer-shift-count-overflowโ requires-fanalyzer; disable it with-Wno-analyzer-shift-count-overflow.
That's the shift thing, bestie ๐ if a shift gets a count that's greater than or equal to the precision of the operand's type, this diagnostic will call it out. It's basically the cousin of the -Wshift-count-overflow diagnostic over in the C/C++ front ends โ except this one is built on analyzing interprocedural paths instead of just parsing the syntax tree. And real talk: the analyzer does not prioritize hunting these paths, so compared to its other warnings, false negatives are way more likely. ๐
-Wno-analyzer-stale-setjmp-bufferโ heads up, this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-stale-setjmp-bufferto turn it back off.
This diagnostic flags paths through the code where longjmp gets called to rewind to a jmp_buf belonging to a setjmp call in a function that has already returned. ๐ญ
Here's the tea: when setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. 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 no longer exists โ and that probably leads to a crash (or worse). ๐
-Wno-analyzer-tainted-allocation-sizeโ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-allocation-sizeto disable it.
This diagnostic flags paths where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized โ meaning an attacker could inject an excessively large allocation and potentially cause a denial of service attack. ๐ซ
See CWE-789: Memory Allocation with Excessive Size Value (https://cwe.mitre.org/data/definitions/789.html).
-Wno-analyzer-tainted-assertionโ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-assertionto disable it.
This diagnostic flags paths where a value that could be under an attacker's control is used as part of a condition without being sanitized first, and that condition guards a call to a function marked with attribute noreturn (like the function __builtin_unreachable). Those functions typically indicate abnormal termination of the program โ think assertion failure handlers, iykyk. For example:
assert (some_tainted_value < SOME_LIMIT);
In cases like that:
- when assertion-checking is enabled: an attacker could trigger a denial of service by injecting an assertion failure
- when assertion-checking is disabled, such as by defining
NDEBUG, an attacker could inject data that subverts the process, since it presumably violates a precondition that's being assumed by the code. ๐
Note this well though: when assertion-checking is disabled, the assertions are typically 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 the purpose of this warning, any function marked with attribute noreturn counts as a possible assertion failure handler, __builtin_unreachable included. And note that these functions are sometimes removed by the optimizer before the analyzer "sees" them โ so optimization should be disabled when you're trying to trigger this diagnostic. No optimizing your way out of this one bestie.
See CWE-617: Reachable Assertion (https://cwe.mitre.org/data/definitions/617.html).
The warning can also report problematic constructions like this one:
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 not an assertion failure. ๐คท
-Wno-analyzer-tainted-array-indexโ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-array-indexto disable it.
This diagnostic flags paths where a value that could be under an attacker's control is 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โ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-divisorto disable it.
This diagnostic flags paths where a value that could be under an attacker's control is 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โ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-offsetto disable it.
This diagnostic flags paths where a value that could be under an attacker's control is 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โ this one needs both-fanalyzerand-fanalyzer-checker=taintto be enabled; use-Wno-analyzer-tainted-sizeto disable it.
This diagnostic flags paths where a value that could be under an attacker's control is used as the size of an operation such as 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 turn it on (that flag enables it); use-Wno-analyzer-unsafe-call-within-signal-handlerto disable it.
This diagnostic flags paths where a function known to be async-signal-unsafe (such as fprintf) is 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โ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-use-after-freeto disable it.
This diagnostic flags paths where a pointer is used after a deallocator got called on it: either free, or a deallocator referenced by attribute malloc. ๐
See CWE-416: Use After Free (https://cwe.mitre.org/data/definitions/416.html).
-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-use-of-pointer-in-stale-stack-frameto disable it.
This diagnostic flags paths where a pointer that points to a variable in a stale stack frame gets dereferenced. ๐ซฃ
-Wno-analyzer-va-arg-type-mismatchโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-va-arg-type-mismatchto disable it.
This diagnostic flags interprocedural paths where the analyzer catches an attempt to use va_arg to extract a value passed to a variadic call โ but using a type that does not match that of the expression passed to the call. Not the vibe, honestly.
See CWE-686: Function Call With Incorrect Argument Type (https://cwe.mitre.org/data/definitions/686.html).
-Wno-analyzer-va-list-exhaustedโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-va-list-exhaustedto disable it.
This diagnostic flags interprocedural paths where the analyzer catches an attempt to use va_arg to access the next value passed to a variadic call โ except every value in the va_list has already been consumed. ๐ empty. gone. nothing left.
See CWE-685: Function Call With Incorrect Number of Arguments (https://cwe.mitre.org/data/definitions/685.html).
-Wno-analyzer-va-list-leakโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-va-list-leakto disable it.
This diagnostic flags interprocedural paths where the analyzer catches that va_start or va_copy was called on a va_list without a corresponding call to va_end. ๐ฉ
-Wno-analyzer-va-list-use-after-va-endโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-va-list-use-after-va-endto disable it.
This diagnostic flags 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โ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-write-to-constto disable it.
This diagnostic flags paths where the analyzer catches an attempt to write through a pointer to a const object. That said, the analyzer does not prioritize hunting these paths, so false negatives are more likely relative to other warnings. ๐
-Wno-analyzer-write-to-string-literalโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-write-to-string-literalto disable it.
This diagnostic flags paths where the analyzer catches an attempt to write through a pointer to a string literal. Same caveat as above bestie: the analyzer does not prioritize detecting these, so false negatives are more likely relative to other warnings.
-Wno-analyzer-use-of-uninitialized-valueโ this one needs-fanalyzerto turn it on (that flag enables it); use-Wno-analyzer-use-of-uninitialized-valueto disable it.
This diagnostic flags paths where an uninitialized value gets used. โจ it's giving "mystery garbage bytes".
See CWE-457: Use of Uninitialized Variable (https://cwe.mitre.org/data/definitions/457.html).
The analyzer has hardcoded knowledge about the behavior of the following memory-management functions: ๐
okay so the analyzer also has a whole VIP list of functions it lowkey treats specially ๐ First, the memory besties:
alloca- 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 of the following functions for working with file descriptors:
openclosecreatdup,dup2anddup3isattypipe, andpipe2readwritesocket,bind,listen,accept, andconnect
of the following functions for working with <stdio.h> streams:
- 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 of the following functions:
- 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
In addition, various functions with an __analyzer_ prefix have special meaning to the analyzer, described in the GCC Internals manual. ๐
Pertinent parameters for controlling the exploration 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. Buckle up bestie, itโs giving very โdeveloper debug modeโ energy. ๐ข
-fanalyzer-call-summariesโ this one simplifies interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return. no cap.
If 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).
-fanalyzer-checker=nameโ restrict the analyzer to run just the named checker, and enable it.
Some checkers are disabled by default (even with -fanalyzer), like the taint checker that implements -Wanalyzer-tainted-array-index, and this option is required to enable them.
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 option is intended for analyzer developers.
By default the analyzer verifies that there is a feasible control flow path for each diagnostic it emits: that the conditions that hold are not mutually exclusive. Diagnostics for which no feasible path can be found are rejected. This filtering can be suppressed with -fno-analyzer-feasibility, for debugging issues in this code.
-fanalyzer-fine-grainedโ this option is intended 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, each statement gets its own edge.
-fanalyzer-show-duplicate-countโ this option is intended for analyzer developers: if multiple diagnostics have been detected as being duplicates of each other, it emits a note when reporting the best diagnostic, giving the number of additional diagnostics that were suppressed by the deduplication logic.-fno-analyzer-state-mergeโ this option is intended for analyzer developers.
By default the analyzer attempts to simplify analysis by merging sufficiently similar states at each program point as it builds its "exploded graph". With -fno-analyzer-state-merge this merging can be suppressed, for debugging state-handling issues.
-fno-analyzer-state-purgeโ this option is intended for analyzer developers.
By default the analyzer attempts to simplify analysis by purging aspects of state at a program point that appear to no longer be relevant e.g. the values of locals that aren't accessed later in the function and which aren't relevant to leak analysis.
With -fno-analyzer-state-purge this purging of state can be suppressed, for debugging state-handling issues.
-fno-analyzer-suppress-followupsโ this option is intended for analyzer developers.
By default the analyzer will stop exploring an execution path after encountering certain diagnostics, in order to avoid potentially issuing a 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 will continue to explore such paths even after such diagnostics, which may be helpful for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior.
-fanalyzer-transitivityโ this option enables transitivity of constraints within the analyzer.-fno-analyzer-undo-inliningโ this option is intended for analyzer developers.
-fanalyzer runs 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, leading to the interprocedural execution paths emitted by the analyzer containing function frames that don't correspond to those in the original source code.
By default the analyzer attempts to reconstruct the original function frames, and to emit events showing the inlined calls.
With -fno-analyzer-undo-inlining this attempt to reconstruct the original frame information can be be disabled, which may be of help when debugging issues in the analyzer.
-fanalyzer-verbose-edgesโ this option is intended for analyzer developers. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths.-fanalyzer-verbose-state-changesโ this option is intended for analyzer developers. It enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.-fanalyzer-verbosity=levelโ this option controls the complexity of the control flow paths that are 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.
-fdump-analyzerโ dump internal details about what the analyzer is doing tofile.analyzer.txt.-fdump-analyzer-stderroverrides this option.-fdump-analyzer-stderrโ dump internal details about what the analyzer is doing to stderr. This option overrides-fdump-analyzer.-fdump-analyzer-callgraphโ dump a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot.-fdump-analyzer-exploded-graphโ dump 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.-fdump-analyzer-exploded-nodesโ emit diagnostics showing where nodes in the "exploded graph" are in relation to the program source.-fdump-analyzer-exploded-nodes-2โ dump a textual representation of the "exploded graph" tofile.eg.txt.-fdump-analyzer-exploded-nodes-3โ dump a textual representation of the "exploded graph" to one dump file per node, tofile.eg-id.txt. This is typically a large number of dump files.-fdump-analyzer-exploded-pathsโ dump a textual representation of the "exploded path" for each diagnostic tofile.idx.kind.epath.txt.-fdump-analyzer-feasibilityโ dump 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 glow-up of the analyzer's internals intofile.analyzer.json.gz. Heads up bestie: the precise format is subject to change, so don't get attached. ๐-fdump-analyzer-state-purgeโ same energy as-fdump-analyzer-supergraph, it dumps a representation of the "supergraph" that's suitable for viewing with GraphViz, but it also annotates the graph with info on what state will be purged at each node. The graph gets written tofile.state-purge.dot. โจ-fdump-analyzer-supergraphโ dumps representations of the "supergraph" suitable for viewing with GraphViz 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. Obsessed with the drama of it all ๐ซถ-fdump-analyzer-untrackedโ emits custom warnings with internal details intended for analyzer developers. iykyk, it's giving insider info ๐
โจ Options for Debugging Your Program โจ
To tell GCC to emit extra info for use by a debugger, in almost all cases you only need to 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. Slay, coexist ๐
GCC lets you use -g with -O. The shortcuts taken by optimized code may occasionally be surprising: 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, debugging optimized code is a whole vibe.
If you are 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). โ ๏ธ Other debuggers may simply refuse to read your program, fr fr.
-ggdbโ produces debugging information for use by GDB. This means to use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible. GDB stans rise up ๐-gdwarf-gdwarf-versionโ produces debugging information in DWARF format (if that is 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. Names are giving ancient history but the behavior said forward motion, periodt. ๐ฆ
-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. BFFs can share the stage โจ-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 byDEBUGon Alpha/VMS systems. Retro era energy ๐ธ-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. Last one standing wins, that's the rule ๐
-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. Nothing left behind ๐ฅน-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. Size inflation warning, bestie โ factor of two is not a drill.-fno-merge-debug-stringsโ direct 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. Trade-offs, we love to see them ๐-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. Reproducible builds are the moment ๐ซถ-fvar-trackingโ run 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. Autopilot on โจ
-fvar-tracking-assignmentsโ annotate assignments to user variables early in the compilation and attempt 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. Not me carrying these annotations the whole way just to ghost them at the end ๐ญ
-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, the-gdwarf32selects the 32-bit DWARF format and the-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. Smaller but capped vs. bigger but niche โ choose your fighter.-gdescribe-diesโ add description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. Giving the unnamed ones a moment in the spotlight ๐-gpubnamesโ generate DWARF.debug_pubnamesand.debug_pubtypessections. Iconic sections, honestly ๐ฅ-ggnu-pubnamesโ generate.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. Check your linker's vibe first ๐ง-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. So it can be a glow-up or a glow-down, depending on the object โ not all consumers are ready for it yet.-grecord-gcc-switches,-gno-record-gcc-switchesโ bestie, this one yeets 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 โจ. The options get concatenated with spaces chillin' between each other and between them and the compiler version, no cap. It's on by default ๐ . Wanna another way to stash compiler options into the object file? Peep-frecord-gcc-switches.-gstrict-dwarfโ says NO to using extensions from a later DWARF standard version than the one you picked with-gdwarf-version๐ . On most targets, using non-conflicting DWARF extensions from later standard versions is, like, allowed โ but this flag shuts that down.-gno-strict-dwarfโ the chill version: it allows using extensions of a later DWARF standard version than what you selected with-gdwarf-version๐ฆ.-gas-loc-supportโ lets the compiler know the assembler out here supporting".loc"directives ๐. Then it can use them so the assembler itself generates DWARF2+ line number tables. This is generally, like, the desirable vibe, because assembler-generated line-number tables are a whole lot more compact than the ones the compiler makes by itself ๐. It gets enabled by default if, back at GCC configure time, the assembler was found to support these directives.-gno-as-loc-supportโ forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are gonna be generated at all. No assembler help, we do it ourselves ๐ช.-gas-locview-supportโ tells the compiler 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, but only if-gvariable-location-viewswas explicitly requested. iykyk ๐-gcolumn-info,-gno-column-infoโ emits location column info into your DWARF debugging information instead of just file and line โญ. On by default, girlie.-gstatement-frontiers,-gno-statement-frontiersโ this one has GCC making markers in its internal representation at the beginning of statements ๐, then keeping them, like, roughly in place the whole way through compilation, using them to guide the output of"is_stmt"markers in the line number table. It's enabled by default when you're 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 ๐. The whole point? It lets debug information consumers inspect state at certain points of the program, even when there are no instructions associated with the corresponding source locations 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 ๐.
This is 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 will 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 ๐ญ. Yeah. Silently. Mismatching. Be careful.
Now, there's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, and you can enable it with -gvariable-location-views=incompat5. Heads up though: this option may be removed in the future, and it's only provided as a reference implementation of the proposed representation ๐ซฃ. Debug information consumers are not expected to support this extended format, and they would be rendered unable to decode location lists using it ๐.
okay so real talk โ incompat5 is giving "I'm doing science and I might regret it". Don't just casually ship it, bestie.
-ginternal-reset-location-views,-gno-internal-reset-location-viewsโ tries to determine location views that can be omitted from location view lists ๐ง. It 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 information 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 information โจ. You can enable this independently of location views, and in that 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 you're using. 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 gets rejected ๐ซ. Otherwise, if the assembler doesn't support them,-gzis silently ignored when producing object files ๐ซ .-femit-struct-debug-baseonlyโ emits debug information 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 substantially reduces the size of your debugging information โ but at significant potential loss in type information to the debugger ๐ญ. Wanna something less aggressive? See-femit-struct-debug-reduced. Want max detailed control? See-femit-struct-debug-detailed. Oh and heads up: 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 where the type is defined, unless the struct is a template or defined in a system header ๐. This significantly reduces the size of your debugging information, with some potential loss in type information to the debugger. See-femit-struct-debug-baseonlyfor the more aggressive route, and-femit-struct-debug-detailedfor the detailed controls ๐. Works only with DWARF debug output.-femit-struct-debug-detailed[=spec-list]โ lets you specify exactly which struct-like types the compiler generates debug information for ๐. The intent: reduce duplicate struct debug information between different object files within the same program. This option is the detailed version of-femit-struct-debug-reducedand-femit-struct-debug-baseonly, and it serves for most needs.
A specification has the syntax
[dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word limits the spec 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. Example time: struct one direct; struct two * indirect;.
The optional second word limits the spec 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 information ๐. The values none and any have the normal meaning. The value base means that the base of the 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 information 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โ emits DWARF unwind info as a compiler generated".eh_frame"section, instead of using GAS".cfi_*"directives ๐ .-fno-eliminate-unused-debug-typesโ okay so normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are nowhere used in the source file being compiled ๐ . But 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's not actually used in your program (but is declared) ๐ฏ. More often, though, this results in a significant amount of wasted space ๐๏ธ.
๐ Options That Control Optimization ๐
These options control various sorts of optimizations ๐ .
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 ๐ซถ.
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, bestie. It's giving balance.
Okay so real talk bestie, the compiler optimizes based on what it knows about your program. And if you compile multiple files at once into a single output file, it gets to use the info it learns from all of them when it's compiling each one. cross-file gossip but for code โจ
Not every single optimization has a flag though. Only the ones that do get listed here. The rest are just vibing behind the scenes. ๐
Big caveat incoming: most optimizations are completely disabled at -O0, or if you never set an -O level on the command line at all โ even if you explicitly pass individual optimization flags. Wild, I know. And -Og suppresses a bunch of optimization passes too. ๐ญ
Also, depending on your target and how GCC was configured for you, the exact set of optimizations at each -O level might differ slightly from what's written below. Wanna know what you actually got? Run this:
-Q --help=optimizers
Go look at the real list, don't just trust the docs. ๐
-O-O1โ Optimize! Optimizing compilation takes a bit more time and a whole lot more memory for large functions. With-O, the compiler tries to shrink code size and execution time without doing any optimizations that cost a serious amount of compile 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 does nearly all the supported optimizations that don't involve a space-speed tradeoff. Compared to-O, this bumps up both compile time and the performance of the generated code. <fire>glow up fr</fire> ๐ฅ
-O2 turns on all the optimization flags specified by -O1. It also turns on these:
-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
Real heads-up: peep the warning under-fgcseabout running-O2on programs that use computed gotos. Don't skip it, bestie. โ ๏ธ
NOTE: In Ubuntu 8.10 and later versions,-D_FORTIFY_SOURCE=2โ and in Ubuntu 24.04 and later versions,-D_FORTIFY_SOURCE=3โ is set by default, and it activates when-Ois set to 2 or higher. This turns on extra compile-time and run-time checks for several libc functions. Wanna turn it off? 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 every optimization-O2specifies, and also flips on these:
-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 results you expect. This is the default. Chill vibes, no drama.-Osโ Optimize for size.-Osenables all-O2optimizations except the ones that often make code bigger:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, makes the compiler tune for code size instead of execution speed, and performs further optimizations designed to shrink your code. tiny but mighty ๐ง
-Ofastโ Disregard strict standards compliance. ma'am this is not legal in all jurisdictions.-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.-Ogโ Optimize the debugging experience.-Ogshould be your optimization level of choice for the standard edit-compile-debug cycle โ it gives you a reasonable level of optimization while keeping compilation fast and debugging actually good. It's a better pick than-O0for producing debuggable code, because some compiler passes that collect debug information are disabled at-O0. ๐โจ
Just like -O0, -Og completely disables a bunch of optimization passes, so individual options controlling them have no effect. Other than that, -Og enables all -O1 optimization flags except the ones that might 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 can increase the number of instructions executed if those instructions need fewer bytes to encode.-Ozbehaves similarly to-Os, including enabling most-O2optimizations. smol and unbothered ๐ฆ
If you pass multiple -O options, with or without level numbers, the last one wins. Periodt.
Options of the form -fflag specify machine-independent flags. Most flags have both a positive and a negative form โ the negative form of -ffoo is -fno-foo. In the table below only one of the forms is listed: the one you'd typically use. You can figure out the other one by either removing no- or adding it. iykyk ๐
The following options control specific optimizations. They're either activated by -O options or related to ones that are. Reach for these flags in those rare cases when you want to "fine-tune" which optimizations get performed. ๐
-fno-defer-popโ For machines that have to pop arguments after a function call, always pop the arguments as soon as each function returns. At levels-O1and higher,-fdefer-popis the default; that lets the compiler let arguments pile up on the stack across 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 whether the result can be simplified. If loop unrolling is active, two passes are performed, and the second one 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, like forming fused multiply-add operations if the target has native support for them.-ffp-contract=onenables floating-point expression contraction if the language standard allows it โ but heads up, this is currently not implemented and treated the same as-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 that save, set up and restore the frame pointer, and on many targets it also frees up an extra register. ๐
On some targets this flag has no effect, because the standard calling sequence always uses a frame pointer and it can't be omitted.
Note that -fno-omit-frame-pointer does not 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. glow up for your string funcs โจ
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. boundaries, we love to see them ๐
-finline-small-functionsโ Integrate functions into their callers when their body is smaller than the expected function call code (so the overall program size shrinks). The compiler heuristically decides which functions are simple enough to be worth integrating this way. This inlining applies to all functions โ even ones not declaredinline.
Enabled at levels -O2, -O3, -Os.
-findirect-inliningโ Inline indirect calls too, when earlier inlining reveals they're known at compile time. This option only has any effect 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're not declaredinline. The compiler heuristically decides which ones are worth integrating this way.
If all calls to a given function get 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: everystaticfunction that gets called exactly once? Yeah, consider it for inlining into its caller, even if nobody bothered to mark itinline. And once a call to a function gets integrated like that, the function doesn't get spat out as assembler code in its own right anymore. Gone, folded in, slayed. ๐
It's turned on at levels -O1, -O2, -O3 and -Os, but not -Og.
-fearly-inliningโ this one inlines functions markedalways_inline, plus functions whose body looks smaller than the function call overhead would be, and it does it early โ before-fprofile-generateinstrumentation and before the real inlining pass even shows up. The way this makes profiling significantly cheaper and usually makes inlining faster on programs that have big chains of nested wrapper functions?? iconic. ๐ง
Enabled by default. You don't have to do anything. She's just like that.
-fipa-sraโ interprocedural scalar replacement of aggregates โจ plus removing unused parameters, plus swapping parameters that were passed by reference over to being passed by value. Glow-up for your call sites.
Enabled at levels -O2, -O3 and -Os.
-finline-limit=nโ okay so by default GCC limits how big a function can be before it's allowed to get inlined. This flag gives you coarse control over that limit.nis the size of functions that can be inlined, measured in number of pseudo instructions.
Real talk though: inlining is actually controlled by a whole bunch of parameters, and you can set each one individually with --param name=value. What -finline-limit=n does is set some of those parameters for you, like this:
max-inline-insns-singleโ is set ton/2.max-inline-insns-autoโ is set ton/2.
Scroll down (in the original docs) for the documentation of the individual parameters controlling inlining and for the defaults of those parameters. ๐
Note: there may be no value to -finline-limit that results in default behavior. Not one. She said what she said.
Note: "pseudo instruction" here means an abstract measurement of a function's size, in this particular context. It does not represent a count of assembly instructions, like, at all, and its exact meaning might change from one release to another. So don't come for her later. ๐
-fno-keep-inline-dllexportโ this is a more fine-grained version of-fkeep-inline-functions, and it applies only to functions declared using thedllexportattribute or declspec. Niche, but she knows her audience. ๐-fkeep-inline-functionsโ in C, this emitsstaticfunctions that are declaredinlineinto the object file, even if the function got inlined into literally all of its callers. (This switch does not affect functions using theextern inlineextension in GNU C90, fyi.) In C++, it emits any and all inline functions into the object file. No one left behind. ๐ซถ-fkeep-static-functionsโ emitstaticfunctions into the object file, even if the function is never used. She's keeping them anyway. Main character energy for a function 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 or not optimization is turned on, use the -fno-keep-static-consts option instead.
-fmerge-constantsโ attempt to merge identical constants (string constants and floating-point constants) across compilation units. Matchy matchy. ๐
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โ attempt to merge identical constants and identical variables.
This one 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. But bestie, listen: 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 "works until it absolutely doesn't." โ ๏ธ
-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 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: this option is effective only with-fmodulo-schedenabled. They're a package deal. ๐-fno-branch-count-regโ disables the optimization pass that goes hunting for opportunities to use "decrement and branch" instructions on a count register, instead of instruction sequences that decrement a register, compare it against zero, 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: -fno-branch-count-reg doesn't remove the decrement and branch instructions that other optimization passes already shoved into the generated instruction stream. It's not a cleanup crew, it's just a "stop doing that" sign.
The default is -fbranch-count-reg at -O1 and higher, except for -Og.
-fno-function-cseโ don't put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly, right there, in the open.
The result is less efficient code, no cap. But some strange hacks that alter the assembler output may get confused by the optimizations performed when this option is not used. So sometimes you want the messy-but-predictable version. ๐
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, which can save space in the resulting code. That's the default behavior.
This option turns that off, because some programs explicitly rely on variables going to the data section โ e.g. so the resulting executable can find the beginning of that section and/or make assumptions based on that. Respect the weird ones. ๐
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ perform optimizations that check whether a jump branches to a location where another comparison, subsumed by the first one, is found. If so, the first branch gets redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false. Sneaky little shortcut, and honestly? She ate. ๐
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-typesโ when you're using a type that occupies multiple registers, likelong 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, babes. ๐ญ
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. (So don't @ her if nothing happens.)
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 isn't reached by any other path. For example, when CSE encounters anifstatement with anelseclause, CSE follows the jump when the condition tested is false. Following the plot, literally. ๐
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ similar to-fcse-follow-jumps, but this makes CSE follow jumps that conditionally skip over blocks. When CSE encounters a simpleifstatement with no else clause,-fcse-skip-blocksmakes CSE follow the jump around the body of theif. Same vibe, different route. โจ
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-run common subexpression elimination after the loop optimizations are done. Second pass, because she's thorough like that. ๐
Enabled at levels -O2, -O3, -Os.
-fgcseโ perform a global common subexpression elimination pass. This pass also performs global constant and copy propagation. Two for one, we love an overachiever.
Note: when compiling a program using 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.
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 to a load outside the loop, and a copy/store within the loop. Loop glow-up unlocked. ๐ฅ
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.
Not enabled at any optimization level. You have to ask for her. ๐
-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).
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. Tidy up the mess. ๐ง
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. And it 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.
This option is enabled by default. So like, behave. ๐
-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. She's being cautious, and honestly? Valid. ๐-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. No promises, just vibes. ๐
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 don't have instructions to support this. Enabled by default at-O1and higher on architectures that support this. ๐-fdceโ bestie, this one does dead code elimination (DCE) on RTL ๐. Like, code that's literally never gonna run? Gone. Enabled by default at-O1and higher, no notes.-fdseโ dead store elimination (DSE) on RTL. Storing a value nobody ever reads? That's giving pointless, so it gets yeeted โจ. Also enabled by default at-O1and higher.-fif-conversionโ tries to glow-up conditional jumps into branch-less equivalents ๐ฆ. That means conditional moves,min,max, set flags andabsinstructions, plus some lil tricks you can do with standard arithmetics. Whether it uses conditional execution on chips where that exists is controlled by-fif-conversion2.
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fif-conversion2โ uses conditional execution (where available) to turn conditional jumps into branch-less equivalents. Same vibe, different pass ๐ .
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fdeclone-ctor-dtorโ okay so the C++ ABI is dramatic and requires multiple entry points for constructors and destructors: one for a base subobject, one for a complete object, and one for a virtual destructor that callsoperator deleteafterwards ๐ญ. For a hierarchy with virtual bases, the base and complete variants are clones, which literally means two copies of the function. 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 ๐. This option enables simple constant folding optimizations at all optimization levels. On top of that, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; those assume that 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.
But bestie, heads up ๐ โ in some environments this assumption is 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 analysis of the type inheritance graph, it figures out for a given call the set of likely targets. If that set is small โ preferably of size 1 โ it changes the call into a conditional deciding between direct and indirect calls. These speculative calls enable more optimizations, like inlining. And when they seem useless after further optimization, they get converted back into their original form. Iconic behaviour, honestly.-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 is disabled by default.-fexpensive-optimizationsโ performs a number of minor optimizations that are relatively expensive ๐ธ. Worth it though.
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.
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; 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 (like, because youroperator newclears 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=0is equivalent to-fno-lifetime-dse.-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 is 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โ uses 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.
This option is enabled at level -Os for all targets.
-fira-loop-pressureโ uses 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. Same energy, more stack ๐ .-flra-rematโ enables CFG-sensitive rematerialization in LRA โจ. Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it is profitable.
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 caused by 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.
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 from rising 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 ๐. 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. -fsched-stalled-insns-dep,-fsched-stalled-insns-dep=nโ okay so this one sets how many insn groups (aka cycles, bestie, same thing here) get examined when we're looking for a dependency on a stalled insn that's a candidate for getting yeeted early out of the queue of stalled insns. ๐ซ And it's got limits, okay: this only does anything during the second scheduling pass, and only if-fsched-stalled-insnsis actually turned on. Also-fno-sched-stalled-insns-depis literally the same as-fsched-stalled-insns-dep=0, and if you just write-fsched-stalled-insns-depwith no value at all? That's-fsched-stalled-insns-dep=1. slay.-fsched2-use-superblocksโ so when you're scheduling after register allocation, this says use superblock scheduling, which lets motion happen across basic block boundaries โจ and that gives you faster schedules. BUT โ and this is the important part โ this option is experimental, because not every machine description GCC has models the CPU closely enough to dodge unreliable results from the algorithm. ๐ญ So like, it can be messy. And it only even makes sense when 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 enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐-fsched-critical-path-heuristicโ turns on the critical-path heuristic, which favors instructions that are on the critical path (iconic behavior, honestly). Enabled by default when scheduling is enabled โ-fschedule-insnsor-fschedule-insns2or-O2and up.-fsched-spec-insn-heuristicโ turns on the speculative instruction heuristic, and it favors speculative instructions with greater dependency weakness. Enabled by default whenever scheduling is on, i.e.-fschedule-insnsor-fschedule-insns2or-O2or higher.-fsched-rank-heuristicโ turns on the rank heuristic, which favors the instruction belonging to a basic block with greater size or frequency. Enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐-fsched-last-insn-heuristicโ turns on the last-instruction heuristic, which favors the instruction that is less dependent on the last instruction scheduled. Enabled by default when scheduling is on, i.e.-fschedule-insnsor-fschedule-insns2or-O2or higher.-fsched-dep-count-heuristicโ turns on the dependent-count heuristic, which favors the instruction that has more instructions depending on it. Enabled by default when scheduling is enabled, i.e.-fschedule-insnsor-fschedule-insns2or at-O2or higher.-freschedule-modulo-scheduled-loopsโ so here's the tea: modulo scheduling happens before traditional scheduling. So if a loop got modulo scheduled, later scheduling passes might go in and change its schedule ๐ณ and this option is how you control that behavior.-fselective-schedulingโ schedule instructions using the selective scheduling algorithm. Selective scheduling runs instead of the first scheduler pass, fyi.-fselective-scheduling2โ same energy, different slot: schedule instructions using the selective scheduling algorithm, but this time it runs instead of the second scheduler pass.-fsel-sched-pipeliningโ enable software pipelining of innermost loops during selective scheduling. Heads up though โ this option has 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 the outer loops. And again, no effect unless-fsel-sched-pipeliningis turned on.-fsemantic-interpositionโ okay this one's a whole lecture so sit down bestie ๐. 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. Now, this feature is useful โ like for rewriting memory allocation functions with a debugging implementation โ but it is expensive in terms of code quality. So with-fno-semantic-interpositionthe 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 the 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. periodt.-fshrink-wrapโ emit function prologues only before the parts of the function that actually need it, instead of dumping them 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, buuut it has no effect unless-fshrink-wrapis also turned on and the target supports this. ๐-fcaller-savesโ enable allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls. And ngl, that allocation only happens when it looks like it'll result in better code. This option is always enabled by default on certain machines, usually the ones that have 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. When that's the 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 generated code will be instrumented for profiling (-p, or-pg), or if the callee's register usage can't be known exactly (which 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. And 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. It's especially useful as a code size optimization, but it often helps for code speed too ๐. 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โ make 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. So 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 (so clean โจ). 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. Careful though โ 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. The functions called only from cold functions get marked as cold. Also functions executed once (such as"cold","noreturn", static constructors or destructors) get 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 determine 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โ bestie, this one does function cloning so that interprocedural constant propagation hits HARDER ๐ช When it's on, interprocedural constant propagation clones a function whenever an externally visible function can be called with constant arguments. And likeโฆ that's powerful but it can also make multiple copies of functions, so code size might go ๐ significantly (peep--param ipa-cp-unit-growth=valuefor that). It's switched on by default at-O3, and-fprofile-useplus-fauto-profileturn it on too.-fipa-bit-cpโ when enabled, it does interprocedural bitwise constant propagation โจ On by default at-O2, and also switched on by-fprofile-useand-fauto-profile. It needs-fipa-cpto be enabled first tho, that's its whole prerequisite.-fipa-vrpโ when enabled, it propagates value ranges interprocedurally ๐ On by default at-O2. It also requires-fipa-cpto be enabled. Package deal, fr fr.-fipa-icfโ this one performs Identical Code Folding for functions and read-only variables ๐ The optimization shrinks code size, but heads up: it may disturb unwind stacks, because it replaces a function with an equivalent one that has a different name. It works more effectively when link-time optimization is enabled.
So even though the behavior looks like the Gold Linker's ICF optimization, GCC ICF works on different levels, so the optimizations are not the same โ there are equivalences that only GCC finds, and equivalences that only Gold finds. Both iconic, different vibes ๐
Enabled by default at -O2 and -Os.
-flive-patching=levelโ this controls GCC's optimizations so the output is suitable for live-patching ๐ฉน
Okay so the concept: if the compiler's optimization uses a function's body, or info extracted from its body, to optimize or change another function, then that other function is called an impacted function of the former. And if a function gets patched, its impacted functions should be patched too. No skipping, bestie.
The impacted functions get determined by the compiler's interprocedural optimizations. For example, a caller is impacted when a function is inlined into its caller, or when a function is cloned and its caller is changed to call the new clone, or when a function's pureness/constness info is extracted to optimize its direct or indirect callers, etc.
Usually the more IPA optimizations you enable, the bigger the number of impacted functions per function. So to control that count and make computing the list of impacted functions easier, IPA optimizations can be partially enabled at two different levels.
The level argument should be one of these:
inline-cloneโ only enables inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. So when you patch a function, all its callers and its clones' callers are impacted, which means they need patching as well.-flive-patching=inline-clonedisables the following 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-modrefinline-only-staticโ only enables inlining of static functions. So when you patch a static function, all its callers are impacted and need patching as well. On top of all the flags that-flive-patching=inline-clonedisables,-flive-patching=inline-only-staticdisables 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.
ngl this is the important bit:-flive-patchingis not supported with link-time optimization (-flto). Just so you know ๐ซถ
-fisolate-erroneous-paths-dereferenceโ detects paths that trigger erroneous or undefined behavior because of dereferencing a null pointer ๐ญ It isolates those paths from the main control flow and turns the statement with erroneous or 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 areturns_nonnullornonnullattribute ๐ It isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. This is not currently enabled, but it may be enabled by-O2in the future. So likeโฆ watch this space ๐-ftree-sinkโ performs forward store motion on trees ๐ณ Enabled 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 is enabled by default at-O1and higher โ except for-Og, which is the exception, bestie. It requires-ftree-ccpto be enabled.-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees ๐ This pass only operates on local scalar variables and is enabled by default at-O1and higher.-fssa-backpropโ propagates info about uses of a value up the definition chain, so the definitions can be 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โ performs conversion of simple initializations in a switch to initializations from a scalar array ๐ Enabled by default at-O2and higher.-ftree-tail-mergeโ looks for identical code sequences ๐ฏ When it finds them, it replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. Enabled by default at-O2and higher. The compilation time in this pass can be limited using 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 seterrnobut 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 โพ๏ธ This lets the compiler remove loops that otherwise have no side-effects, without counting an eventual endless loop as a side-effect. Enabled by default at-O2for C++ with-std=c++11or higher.-ftree-dominator-optsโ does a whole variety of simple scalar cleanups based on a dominator tree traversal: constant/copy propagation, redundancy elimination, range propagation and expression simplification ๐งน 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 gets overwritten later by another store with no intervening loads. In that case the earlier store can just be deleted. Enabled by default at-O1and higher.-ftree-chโ performs loop header copying on trees ๐ This is beneficial because it increases the effectiveness of code motion optimizations, and it also saves one jump. Enabled by default at-O1and higher. It is 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โ all three of these 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 the GIMPLE -> GRAPHITE -> GIMPLE transformation. Some minimal optimizations are also performed by the code generator isl, like index splitting and dead code elimination in loops.-floop-nest-optimizeโ enables the isl based 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 โ so like, it's giving beta energy ๐-floop-parallelize-allโ uses the Graphite data dependence analysis to identify loops that can be parallelized โก It parallelizes all the loops that can be analyzed to not contain loop carried dependences, without checking that it is profitable to parallelize the loops. So no vibe check on profitability, it just goes.-ftree-coalesce-varsโ while transforming the program out of the SSA representation, it attempts to reduce copying by coalescing versions of different user-defined variables, instead of just compiler temporaries ๐ This may severely limit the ability to debug an optimized program compiled with-fno-var-tracking-assignments. In the negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise.-ftree-loop-if-convertโ attempts to transform conditional jumps in the innermost loops to branch-less equivalents ๐ฆ The intent is to remove control-flow from the innermost loops so the vectorization pass can handle these loops better. Enabled by default if vectorization is enabled.-ftree-loop-distributionโ performs loop distribution ๐ This flag can improve cache performance on big loop bodies and allow 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
...and boom, that loop gets reshaped into:
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
This flag is on by default at -O3. It also gets switched on by -fprofile-use and -fauto-profile. ๐
-ftree-loop-distribute-patternsโ does loop distribution on patterns that can be codegenned as calls into a library ๐ซถ. This bad boy is enabled by default at-O2and higher, plus by-fprofile-useand-fauto-profile.
So like, this pass splits apart the initialization loops and drops in a call to memset zero. For instance, this loop:
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
gets glow-upped into:
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and then that initialization loop becomes a straight-up call to memset zero โจ. Enabled by default at -O3, and also switched on by -fprofile-use and -fauto-profile.
-floop-interchangeโ does loop interchange outside of graphite. Bestie, this can make your cache performance on loop nests way better and unlocks further loop optimizations, like vectorization, to actually happen ๐ฅ. Example time โ this 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];
gets transformed into:
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];
Enabled by default at -O3. Also enabled by -fprofile-use and -fauto-profile. ๐
-floop-unroll-and-jamโ applies unroll-and-jam transformations on loops that are feasible for it. In a loop nest this unrolls the outer loop by some factor and then fuses the resulting multiple inner loops together ๐. Enabled by default at-O3. Also enabled by-fprofile-useand-fauto-profile.-ftree-loop-imโ performs loop invariant motion on trees ๐ณ. This pass only moves invariants that are hard to deal with at the RTL level (think function calls, or operations that expand into nontrivial sequences of insns). With-funswitch-loopsit also hoists the operands of conditions that are invariant right out of the loop, so we can get away with just trivial invariantness analysis in loop unswitching ๐. Bonus: the pass also includes store motion.-ftree-loop-ivcanonโ creates a canonical counter for the number of iterations in loops where figuring out the iteration count needs some complicated analysis ๐. Later optimizations can then determine that number easily. Super useful especially when paired with unrolling.-ftree-scev-cpropโ performs final value replacement ๐. If a variable gets modified inside a loop in a way that its value on exit can be worked out using only its initial value and the number of loop iterations, then uses of the final value get replaced by that computation โ as long as it's cheap enough. This cuts down data dependencies and may unlock further simplifications. Enabled by default at-O1and higher.-fivoptsโ performs induction variable optimizations on trees: strength reduction, induction variable merging, and induction variable elimination. The whole trio ๐.- *
-ftree-parallelize-loops=n*** โ parallelizes loops, aka splits their iteration space so it runs across *n* threads ๐งต. This only works for loops whose iterations are independent and can be reordered however you like. And ngl, the optimization is only worth it on multiprocessor machines, for loops that are CPU-intensive rather than ones constrained by, say, memory bandwidth. Heads up: this option implies-pthread, so it's <red>only supported on targets that have support for-pthread` โ ๏ธ. -ftree-ptaโ performs function-local points-to analysis on trees ๐. Enabled by default at-O1and higher, except for-Og.-ftree-sraโ performs scalar replacement of aggregates. This pass swaps structure references out for scalars so the compiler doesn't commit structures to memory too early ๐. Enabled by default at-O1and higher, except for-Og.-fstore-mergingโ merges narrow stores to consecutive memory addresses. This pass squishes contiguous stores of immediate values that are narrower than a word into fewer, wider stores, so there are fewer instructions overall โจ. Enabled by default at-O2and higher, plus-Os.-ftree-terโ performs temporary expression replacement during the SSAโnormal phase ๐ซ. Single use/single def temporaries get replaced at their use location with their defining expression. The result is non-GIMPLE code, but it hands the expanders way more complex trees to work on, which means better RTL generation. Enabled by default at-O1and higher.-ftree-slsrโ performs straight-line strength reduction on trees ๐ช. It spots related expressions involving multiplications and swaps them for less expensive calculations wherever it can. Enabled by default at-O1and higher.-ftree-vectorizeโ performs vectorization on trees ๐. This flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif they weren't explicitly specified.-ftree-loop-vectorizeโ performs loop vectorization on trees ๐. Enabled by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftree-slp-vectorizeโ performs basic block vectorization on trees ๐งฑ. 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, which bumps up the security and predictability of your program by preventing uninitialized memory disclosure and use ๐. Important though: GCC <italic>still</italic> treats an automatic variable with no explicit initializer as uninitialized โ-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still throw warning messages on those automatic variables, and the compiler optimizes as if the variable were uninitialized. With this option, GCC will also zero out any padding of automatic variables that have structure or union types. <red>But</red> the current implementation cannot initialize automatic variables declared between the controlling expression and the firstcaseof aswitchstatement. Use-Wtrivial-auto-var-init` to get a report of all such cases.
The three values of choice are:
uninitializedโ doesn't initialize any automatic variables. This is C and C++'s default ๐ .patternโ initializes automatic variables with values that will likely turn logic bugs into crashes down the line, that are easily recognized in a crash dump, and that aren't values programmers can rely on for useful program semantics ๐. The current value is a byte-repeatable pattern with byte"0xFE". Heads up: the values used for pattern initialization might change in the future ๐.zeroโ initializes automatic variables with zeroes.
The default is uninitialized.
You can control this behavior for a specific variable by using the variable attribute "uninitialized".
- *
-fvect-cost-model=model*** โ changes up the cost model used for vectorization ๐. The *model* argument should be one ofunlimited,dynamic,cheaporvery-cheap`.- With the
unlimitedmodel, the vectorized code-path is just assumed to be profitable โจ. - With the
dynamicmodel, a runtime check guards the vectorized code-path so it only kicks in for iteration counts that will likely run faster than the original scalar loop would ๐ฅ. - The
cheapmodel disables vectorization of loops where doing so would be cost-prohibitive โ like because of required runtime checks for data dependence or alignment โ but otherwise it's the same as thedynamicmodel. - The
very-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code being vectorized. Like, if each iteration of a vectorized loop could only handle exactly four iterations of the scalar loop, thenvery-cheapwould only allow vectorization if the scalar iteration count is known to be a multiple of four ๐.
- With the
The default cost model depends on your other optimization flags and is either dynamic or cheap.
- *
-fsimd-cost-model=model*** โ changes up the cost model used for vectorization of loops marked with the OpenMPsimddirective ๐ธ. The *model* argument should be one ofunlimited,dynamic,cheap. All values of *model* mean the same thing as described in-fvect-cost-model, and by default a cost model defined with-fvect-cost-model` is used. -ftree-vrpโ performs Value Range Propagation on trees ๐. It's similar to the constant propagation pass, but instead of values, ranges of values get propagated. This lets the optimizers nuke unnecessary range checks, like array bound checks and null pointer checks ๐. Enabled by default at-O2and higher. Oh, and null pointer check elimination is only done if-fdelete-null-pointer-checksis enabled โ iykyk.-fsplit-pathsโ splits paths leading to loop backedges ๐. This can improve dead code elimination and common subexpression elimination. Enabled by default at-O3and above.-fsplit-ivs-in-unrollerโ enables expression of the values of induction variables in later iterations of the unrolled loop using the value in the first iteration ๐ซ. This breaks up long dependency chains, which improves the efficiency of the scheduling passes ๐.
A combo of -fweb and CSE is often enough to get the same effect. BUT that's not reliable when the loop body is more complicated than a single basic block ๐. It also doesn't work at all on some architectures, thanks to restrictions in the CSE pass.
This optimization is enabled by default.
-fvariable-expansion-in-unrollerโ with this option, the compiler makes multiple copies of some local variables when it unrolls a loop, which can result in superior code ๐ .
This optimization is enabled by default for PowerPC targets, but disabled by default everywhere else.
-fpartial-inliningโ Inline parts of functions, not the whole thing. Bestie, this one is a total diva โ it does absolutely nothing unless inlining itself is already switched on by-finline-functionsor-finline-small-functions. ๐
Enabled at levels -O2, -O3, -Os.
-fpredictive-commoningโ Does the predictive commoning optimization, which is a fancy way of saying: reuse computations (especially memory loads and stores) that already happened in previous iterations of loops. It's giving "we've been here before, why do the work twice." ๐
This one is enabled at level -O3. It's also enabled by -fprofile-use and -fauto-profile.
-fprefetch-loop-arraysโ If your target machine supports it, this generates instructions to prefetch memory so that loops accessing big arrays run faster. Manifesting speed. โจ
Heads up though: this option may generate better or worse code โ the results are highly dependent on the structure of the loops inside your source code. It's a vibe check every time. ๐ญ
Disabled at level -Os.
-fno-printf-return-valueโ Say NOT today to substituting constants for the known return value of formatted output functions like"sprintf","snprintf","vsprintf", and"vsnprintf"(but not"printf"of"fprintf"). ๐ซถ
This transformation lets GCC optimize or even 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 determining 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. The -fprintf-return-value option is enabled by default. ๐
-fno-peephole,-fno-peephole2โ Disable any machine-specific peephole optimizations. The difference between-fno-peepholeand-fno-peephole2is in how they are implemented in the compiler; some targets use one, some use the other, a few use both. It's giving "same energy, different plumbing." ๐ธ
-fpeephole is enabled by default. -fpeephole2 enabled at levels -O2, -O3, -Os.
-fno-guess-branch-probabilityโ Do not guess branch probabilities using heuristics. No guessing games today. ๐
GCC uses heuristics to guess branch probabilities if they aren't provided by 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 that the effects of "__builtin_expect" are easier to understand. Lowkey a debugging main character moment.
It is also possible to specify expected probability of the expression with "__builtin_expect_with_probability" built-in function.
The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.
-freorder-blocksโ Reorder basic blocks in the compiled function to reduce the number of taken branches and improve code locality. Getting the most-executed stuff up front so the CPU doesn't have to go on a whole journey. ๐ฆ
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. Roblox character build vs. full gym routine, honestly. โจ
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, fr fr. ๐
This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or target specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that does not support named sections. When -fsplit-stack is used this option is not enabled by default (to avoid linker errors), but may be enabled explicitly (if using a working linker). โ ๏ธ
Enabled for x86 at levels -O2, -O3, -Os.
-freorder-functionsโ Reorder functions in the object file in order to improve code locality. This is implemented by using special subsections.text.hotfor most frequently executed functions and.text.unlikelyfor unlikely executed functions. 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. ๐
This option isn't effective unless you either provide profile feedback (see -fprofile-arcs for details) or manually annotate functions with "hot" or "cold" attributes. No receipts, no results.
Enabled at levels -O2, -O3, -Os.
-fstrict-aliasingโ Allow the compiler to assume the strictest aliasing rules applicable 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 never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an"unsigned int"can alias an"int", but not a"void*"or a"double". A character type may alias any other type. ๐ฅ
Pay special attention to code like this:
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;
}
Bestie, please do not do the undefined-behavior thing. It will not slay. It will just break. ๐ญ
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-fipa-strict-aliasingโ Controls whether the rules of-fstrict-aliasingare 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 โ Align 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. It's giving "line up your functions nicely, periodt." ๐
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, and -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 allows you to 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โ If this option is 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. Reading the room, basically. ๐-falign-labels,-falign-labels=n,-falign-labels=n:m,-falign-labels=n:m:n2,-falign-labels=n:m:n2:m2 โ Align all branch targets to a power-of-two boundary. โจ
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 โ Align 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. The padding pays for itself, bestie. ๐
If -falign-labels is greater than this value, then its value is used instead.
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โ bestie, this one lines up your branch targets on a power-of-two boundary โจ but only for the ones you can only get to by jumping. Which means: no dummy operations have to actually run. Free realignment, we love to see it ๐
Ok so if -falign-labels is greater than this value, then -falign-labels's value gets used instead. That's the rule, no cap.
The parameters here work just like the ones for -falign-functions. And heads up: -fno-align-jumps and -falign-jumps=1 are literally equivalent, and both of them mean loops are not aligned. periodt.
If n isn't specified or it's zero, you get a machine-dependent default. And the max allowed value for n? 65536. That's the ceiling, don't test it ๐ซถ
Enabled at levels -O2, -O3.
-fno-allocation-dceโ do not remove unused C++ allocations during dead code elimination. Like, leave them alone, the compiler thinks they're dead but we said no ๐-fallow-store-data-racesโ this one lets the compiler do optimizations that might introduce brand new data races on stores, without it having to prove the variable can't be touched by other threads at the same time ๐ It does not affect optimization of local data, so locals are chill. And it's safe to use this if you know global data won't be accessed by multiple threads. iykyk.
Examples of optimizations that -fallow-store-data-races turns on include hoisting or if-conversions that may cause a value that was already sitting in memory to be re-written with that same value. Rewriting it is totally safe in a single-threaded context but may be unsafe in a multi-threaded one ๐ Also note: on some processors, if-conversions may actually be required in order to enable vectorization. So it's giving "tradeoffs", bestie.
Enabled at level -Ofast.
-funit-at-a-timeโ this option is just left around for compatibility reasons ๐-funit-at-a-timehas 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 same order they appear in the input file, exactly as given ๐ธ When this option is used, unreferenced static variables are not removed either. This whole option exists to support existing code that relies on a particular ordering. For new code, it's better to use attributes when possible โ like, genuinely, use attributes.
-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Plus, -fno-toplevel-reorder implies -fno-section-anchors.
-funreachable-trapsโ with this, the compiler turns calls to"__builtin_unreachable"into traps instead of using them for optimization ๐ฅ This also affects any such calls that were implicitly generated by the compiler itself. Sneaky ones included.
This option has the same effect as -fsanitize=unreachable -fsanitize-trap=unreachable, but it does not affect the values of those options. And if -fsanitize=unreachable is enabled, that option takes priority over this one. Queen behavior ๐
This option is enabled by default at -O0 and -Og.
-fwebโ constructs webs as commonly used for register allocation purposes, and assigns each web its own individual pseudo register ๐ธ๏ธ This lets the register allocation pass operate on pseudos directly, but it also strengthens several other optimization passes too โ like CSE, the loop optimizer, and the trivial dead code remover. Slay.
It can, however, make debugging impossible ๐ญ because variables no longer stay in a "home register". So, you know, pick your fighter.
Enabled by default with -funroll-loops.
-fwhole-programโ assume that the current compilation unit represents the whole program being compiled. All public functions and variables โ with the exception of"main"and those merged by attribute"externally_visible"โ become static functions, and in effect get optimized way more aggressively by interprocedural optimizers ๐ช
With -flto this option has a 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]โ ok this is a big one, sit down bestie ๐ This option runs the standard link-time optimizer. When it's invoked 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. Iconic.
To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It's recommended that you compile all the files participating in the same link with the same options, and also specify those options at link time. For example:
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, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one โจ This 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.
Another (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 mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step ๐ซถ GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command.
To make whole program optimization effective, it is 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 supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to allow the compiler to make these assumptions, which leads to more aggressive optimization decisions. So it's giving "trust me bro, or use the plugin" ๐
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 that object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster but you cannot perform a regular, non-LTO link on them. Pick your vibe ๐
When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. Therefore, you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing. So organized of it.
Generally, options specified at link time override those specified at compile time, although in some cases GCC attempts to infer link-time options from the settings used to compile the input files. Lowkey mind-reading.
If you do not 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 is generally ineffective to specify an optimization level option only at link time and not at compile time, for two reasons. First, compiling without optimization suppresses compiler passes that gather information needed for effective optimization at link time. Second, some early optimization passes can be performed only at compile time and not at link time. So do both, bestie, fr fr ๐
There are some code generation flags preserved by GCC when generating bytecodes, as 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 the following 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 ignored ๐
โโ๏ธ 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 are 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.
Diagnostic options such as -Wstringop-overflow are passed through to the link stage and their setting matches that of the compile-step at function granularity ๐ฆ Note that this matters only for diagnostics emitted during optimization. Note that code transforms such as inlining can lead to warnings being enabled or disabled for regions of code not consistent with the setting at compile time. So the vibes can shift mid-optimization, 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 ๐
Debug info + LTO is its own lil situation, so listen up ๐
To get debug info generated you have to hand over -g at compile time. And like, if any of the input files at link time were built with debug info generation on, the link turns debug info generation on too. But the fancy debug info settings โ think stuff like the dwarf level -gdwarf-5 โ have to be explicitly repeated on the linker command line, and mixing different settings across different translation units is discouraged. Don't do it, bestie, it's giving chaos ๐
If LTO runs into objects with C linkage declared with incompatible types sitting in separate translation units that are getting linked together (which is undefined behavior according to ISO C99 6.2.7, btw ๐ญ), it may throw a non-fatal diagnostic. And the behavior? Still undefined at run time. Same energy for similar diagnostics in other languages.
Another LTO slay โจ you can apply interprocedural optimizations to 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 the final link is done with g++ so we get the C++ runtime libraries, and -lgfortran got added 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. Consistency is the vibe check ๐ฅ
If object files containing GIMPLE bytecode are parked in a library archive, say libfoo.a, you can extract and use them in an LTO link if you're using a linker with plugin support. To create 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. 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 needed GIMPLE files out of libfoo.a and passes them along to the running GCC so they become part of the aggregated GIMPLE image that's about to get optimized. Ugh, iconic ๐ซถ
If you are 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 as usual โ but they do not participate in the LTO optimization process. To make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects. Bestie, that's the move โจ
Link-time optimizations do not require the presence of the whole program to operate. If your program doesn't need any symbols to be exported, you can combine -flto and -fwhole-program to let the interprocedural optimizers use more aggressive assumptions, which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when the linker plugin is active (see -fuse-linker-plugin).
The current implementation of LTO makes no attempt to generate bytecode that is 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. Yeah. ๐ Keep your versions matched, babes.
Link-time optimization also does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF. Noted ๐
If you specify the optional n, the optimization and code generation done at link time is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used.
You can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. This is 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. This option likely only works if MAKE is GNU make. Even without the option value, GCC tries to automatically detect a running GNU make's job server. She's observant like that ๐
Use -flto=auto to use GNU make's job server, if available, or otherwise fall back to autodetection of the number of CPU threads present in your system.
-flto-partition=algโ picks the partitioning algorithm the link-time optimizer uses. The value is either1to1(partitioning that mirrors the original source files) orbalanced(partitioning into equally sized chunks, whenever possible) ormax(creates a new partition for every symbol where possible). Specifyingnoneas an algorithm disables partitioning and streaming completely. The default value isbalanced. While1to1can be used as a workaround for various code ordering issues, themaxpartitioning is intended for internal testing only. The valueonespecifies that exactly one partition should be used, while the valuenonebypasses partitioning and executes the link-time optimization step directly from the WPA phase.-flto-compression-level=nโ sets the level of compression used for the intermediate language written to LTO object files, and it's only meaningful alongside LTO mode (-flto). GCC currently supports two LTO compression algorithms. For zstd, valid values are0(no compression) to19(maximum compression), while zlib supports values from0to9. Values outside this range get clamped to either the minimum or 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. It improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). The resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. See -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 effective only when compiling with-fltoand is 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. Additionally, 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 usage of 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 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 performs a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy.
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 such inconsistencies. By default, GCC emits an error message when an inconsistent profile is detected. So yeah, this one's your lil fixer-upper ๐
This option is enabled by -fauto-profile.
-fprofile-partial-trainingโ with-fprofile-use, all portions of programs not executed during the train run are optimized aggressively for size rather than speed. In some cases it's not practical to train all possible hot paths in the program. (Like, the program may contain functions specific for a given hardware, and the training may not cover every hardware configuration the program runs on.) With-fprofile-partial-training, profile feedback will be ignored for all functions not executed during the train run, which leads 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 it also leads to significantly bigger code. Pick your fighter โจ-fprofile-use-fprofile-use=pathโ enables profile feedback-directed optimizations, plus the following optimizations, many of which are generally profitable only with profile feedback 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 skipping steps, bestie ๐
Also, real talk: by default GCC throws a whole error at you if your feedback profiles don't match the source code. Like, screaming. You can downgrade that drama to a warning with -Wno-error=coverage-mismatch. โ ๏ธ But bestie, listen โ that may give you poorly optimized code. And heads up, by default GCC also warns you if the feedback profiles straight up don't exist (peep -Wmissing-profile).
If you pass a path, GCC goes looking in that path for the profile feedback data files. See -fprofile-dir. ๐ซถ
-fauto-profile,-fauto-profile=pathโ turns on sampling-based feedback-directed optimizations, plus this whole roster of optimizations below. (Lowkey most of these are only actually worth it when you've got profile feedback lying around.) โจ
Here's the squad it drags in with it:
-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
So, path is the name of a file holding AutoFDO profile info. Skip it and it defaults to fbdata.afdo in the current directory. ๐
To actually make an AutoFDO profile data file you gotta run your program with the perf utility on a supported GNU/Linux target system. More deets here: https://perf.wiki.kernel.org/ ๐
Like, for example:
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then you use the create_gcov tool to convert that raw profile data into a format GCC can actually vibe with. You also must hand this tool the unstripped binary for your program. Check https://github.com/google/autofdo ๐
Example time:
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
Okay switching gears โจ the next batch of options controls how the compiler behaves around floating-point arithmetic. These are all about trading off between speed and correctness, and ngl you have to specifically turn every single one of them on yourself.
-ffloat-storeโ do not store floating-point variables in registers, and also shut down any other option that could change whether a floating-point value comes from a register or from memory.
This one stops that annoying excess precision on machines like the 68000, where the floating registers (of the 68881) keep more precision than a "double" is supposed to have. Same deal on the x86 architecture. For most programs that extra precision does only good, but a few programs are out here relying on the precise definition of IEEE floating point. For those ones, use -ffloat-store โ but only after you've modified them to store all pertinent intermediate computations into variables. ๐งฎ
-fexcess-precision=styleโ gives you finer 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=fastis what's in effect, which means operations may be carried out in a wider precision than the types in your source if that gets you faster code โ and honestly it's unpredictable when rounding down to the source-specified types even happens. When you're compiling C or C++, if you say-fexcess-precision=standardthen excess precision follows the rules from ISO C99 or C++; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas-ffloat-storeonly touches assignments). This one's on by default for C or C++ if you're using a strict conformance option like-std=c99or-std=c++17. And-ffast-mathenables-fexcess-precision=fastby default whether or not you've got a strict conformance option going. ๐
K so-fexcess-precision=standardis not implemented for languages other than C or C++. And on the x86, it has no effect if-mfpmath=sseor-mfpmath=sse+387is specified โ in the first case, IEEE semantics apply with no excess precision, and in the second, 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.
This option causes the preprocessor macro __FAST_MATH__ to be defined. ๐
No -O option turns this on besides -Ofast, because it can produce incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. That said, it may give you faster code for programs that don't need those guarantees. โก
-fno-math-errnoโ do not seterrnoafter calling math functions that execute with a single instruction, e.g.sqrt. If your program relies on IEEE exceptions for math error handling, you might want this flag for speed while keeping IEEE arithmetic compatibility.
No -O option turns this on, since it can result in incorrect output for programs depending 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 those guarantees. ๐โโ๏ธ
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 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. ๐ฌ
No -O option turns this on, 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 those guarantees. It 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, ignore NaNs, and inhibit or create underflow or overflow โ so it absolutely cannot be used on code that relies on rounding behavior like (x + 2**52) - 2**52. It may also reorder floating-point comparisons, so it can't be used when ordered comparisons are required. ๐จ
This option requires that both -fno-signed-zeros and -fno-trapping-math be in effect. Also, 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 that value if it enables optimizations. For examplex / ycan be replaced withx * (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 arguments and results are not NaNs or +-Infs.
No -O option turns this on, 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 those guarantees. ๐ฅ
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 distinct behavior for+0.0and-0.0values, and that then prohibits simplification of expressions likex+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 floating-point operations can't generate user-visible traps. Those traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that-fno-signaling-nansbe in effect. Setting this may allow faster code if you're relying 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.
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. That's round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. Specify this 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 when sign-dependent rounding modes are around. ๐๏ธ
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations 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โ bestie, this is the "trust the sNaN" mode ๐ compile your code assuming that IEEE signaling NaNs might throw user-visible traps mid-floating-point-operation. Turning this on disables the optimizations that could change how many exceptions are visible when signaling NaNs are around. It also implies-ftrapping-math.
It's giving macro-defining energy too: this option makes the preprocessor macro __SUPPORT_SNAN__ get defined.
The default is -fno-signaling-nans.
Fair warning, bestie ๐จ this option is experimental and it does not currently guarantee that it disables every single GCC optimization that affects signaling NaN behavior. It's trying its best, okay ๐ญ
-fno-fp-int-builtin-inexactโ don't let the built-in functionsceil,floor,round, andtrunc(plus theirfloatandlong doublevariants, of course ๐) generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 actually allow these functions to raise thatinexactexception, but ISO/IEC TS 18661-1:2014 โ the C bindings to IEEE 754-2008, as integrated into ISO C2X โ says nope, they can't do that.
The default is -ffp-int-builtin-inexact, which allows the exception to be raised, unless C2X or a later C standard is selected. Also this option literally does nothing unless -ftrapping-math is in effect. ๐ซถ
And even if you use -fno-fp-int-builtin-inexact, if the functions generate a call to a library function, then the inexact exception may still be raised if the library implementation doesn't follow TS 18661. Sneaky little exception ๐ญ
-fsingle-precision-constantโ treat floating-point constants as single precision instead of the usual implicit glow-up into double-precision constants. โจ-fcx-limited-rangeโ when this is enabled, you're basically stating that a range reduction step is not needed when doing complex division. Also, there's no checking whether the result of a complex multiplication or division isNaN + I*NaN, and no 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. But bestie, it applies to all languages anyway. ๐
-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's no check on whether the result of a complex multiplication or division isNaN + I*NaN, and no attempt to rescue that situation either.
The default is -fno-cx-fortran-rules.
The following options control optimizations that may improve performance, but are not enabled by any -O options. Heads up bestie ๐จ this section includes experimental options that may produce broken code. Not me warning you twice ๐
-fbranch-probabilitiesโ after you run 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 every source file. The info in that data file is super dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations ๐ซถ (details about the file naming live in-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. Iconic tbh ๐
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 to gather info about values of expressions.
With -fbranch-probabilities, it reads back the gathered data and actually performs the optimizations based on them. Currently those 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. But depending on the debug info format your target adopted, 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 when they're adjacent 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, letting other optimizations 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,-fweb, and-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 info 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. 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 particularly 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, bestie ๐ซถ 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 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 it goes and calculates the addresses of all three variables, but if you compile it with -fsection-anchors, it just grabs the variables from one common anchor point instead โจ The vibe is basically this pseudocode right here (and bestie, this is not valid C, ok, it's just a vibe):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
Not all targets support this option, so don't come crying to me if yours is like "nope ๐"
-fzero-call-used-regs=choiceโ this one zeroes out the call-used registers when a function returns, which makes your program more secure ๐ก๏ธ It either mitigates Return-Oriented Programming (ROP) attacks or stops info from leaking through registers. The possible values of choice are exactly the same as for the"zero_call_used_regs"attribute. Default isskip. And if you wanna control this for just one specific function, use the function attribute"zero_call_used_regs"๐--param name=valueโ so sometimes GCC uses a bunch of constants to control how much optimization it does. Like, GCC won't inline functions that have more than a certain number of instructions. And you can control some of these constants straight from the command line with--param๐
The parameter names and what their values actually mean are tied to the compiler's internals, so heads up โ they can legitimately change without any notice in future releases ๐
Wanna know the minimal, maximal and default values of a parameter? Use the --help=param -Q options, bestie.
In every case the value is an integer. These are the *name*s that are recognized for all targets:
predictable-branch-outcomeโ if a branch is predicted as taken with a probability lower than this threshold (in percent), then it's considered well predictable.max-rtl-if-conversion-insnsโ RTL if-conversion tries to yeet the conditional branches around a block and swap them for conditionally executed instructions. This param is the max number of instructions in a block that should be considered for if-conversion. The compiler also uses other heuristics to figure out whether if-conversion is actually gonna be profitable.max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove the conditional branches around a block and replace them with conditionally executed instructions. These parameters give the max permissible cost for the sequence that if-conversion would generate, depending on whether the branch is statically determined to be predictable or not. Units here are the same as GCC's internalseq_costmetric. The compiler tries to give a reasonable default using theBRANCH_COSTtarget macro.max-crossjump-edgesโ the max number of incoming edges to consider for cross-jumping. The algorithm-fcrossjumpinguses is O(N^2) in the number of edges coming into each block. Bigger values = more aggressive optimization, so compile time goes up with probably just a tiny improvement in executable size.min-crossjump-insnsโ the min number of instructions that have to match at the end of two blocks before cross-jumping even happens on them. This value gets ignored when all the instructions in the block being cross-jumped from are matched.max-grow-copy-bb-insnsโ the max code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.max-goto-duplication-insnsโ the max number of instructions to duplicate to a block that jumps to a computed goto. To dodge O(N^2) behavior in a bunch of passes, GCC factors computed gotos early in compilation and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more thanmax-goto-duplication-insnsget unfactored.max-delay-slot-insn-searchโ the max number of instructions to consider when it's hunting for an instruction to fill a delay slot. If it searches more than this arbitrary number of instructions, the time savings from filling the delay slot are minimal, so it just stops. Bigger values = more aggressive optimization, compile time goes up, probably small improvement in execution time.max-delay-slot-live-searchโ when trying to fill delay slots, this is the max number of instructions to consider when searching for a block with valid live register info. Increasing this (arbitrarily chosen, ngl) value means more aggressive optimization and more compile time. This parameter should be removed when the delay slot code gets rewritten to maintain the control-flow graph.max-gcse-memoryโ the approximate max amount of memory inkBthat can be allocated to do the global common subexpression elimination optimization. If more memory than specified is needed, the optimization just doesn't happen.max-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is bigger 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 max number of pending dependencies scheduling allows before it flushes the current state and starts over. Big functions with few branches or calls can create excessively large lists that needlessly eat memory and resources ๐ญmax-modulo-backtrack-attemptsโ the max number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compile time ๐max-inline-functions-called-once-loop-depthโ max loop depth of a call considered by inline heuristics that tries to inline all functions called once.max-inline-functions-called-once-insnsโ max estimated size of functions produced while inlining functions called once.max-inline-insns-singleโ several parameters control the tree inliner used in GCC. This number sets the max number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declaredinlineand 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 normally wouldn't be considered for inlining get investigated. For 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 considered relevant with-finline-small-functions.max-inline-insns-sizeโ this is the bound applied to calls that are optimized for size. Small growth may be desirable to anticipate optimization oppurtunities exposed by inlining. (yes that typo is literally in the source, iykyk ๐)uninlined-function-insnsโ number of instructions accounted by the inliner for function overhead, like function prologue and epilogue.uninlined-function-timeโ extra time accounted by the inliner for function overhead, like the time needed to execute the function prologue and epilogue.inline-heuristics-hint-percentโ the scale (in percents) applied toinline-insns-single,inline-insns-single-O2,inline-insns-autowhen inline heuristics hints that inlining is very profitable (aka it'll enable later optimizations ๐ฅ).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.large-function-insnsโ the limit specifying really large functions. For functions bigger than this limit after inlining, inlining is constrained by--param large-function-growth. This parameter is useful primarily to avoid extreme compile time caused by non-linear algorithms used by the back end.large-function-growthโ specifies the max growth of a large function caused by inlining, in percents. For example, a parameter value of100limits large function growth to 2.0 times the original size.large-unit-insnsโ the limit specifying a large translation unit. Growth caused by inlining units bigger than this limit is limited by--param inline-unit-growth. For small units this might be too tight. Like, consider a unit consisting of function A that's 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. But for very large units made of small inlineable functions, the overall unit growth limit is needed to avoid exponential explosion of code size. So 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 the max overall growth of the compilation unit caused by inlining. For example, a parameter value of20limits 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.ipa-cp-unit-growthโ specifies the max overall growth of the compilation unit caused by interprocedural constant propagation. For example, a parameter value of10limits 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 straight up considers large. ๐large-stack-frameโ the limit that defines what counts as a large stack frame. When inlining is happening, the algorithm is actively trying not to blow past this limit too much. ๐ซถlarge-stack-frame-growthโ the max growth (in percents, bestie) that large stack frames are allowed to gain from inlining. Like, parameter value1000caps large stack frame growth at11times the original size. ๐ธmax-inline-insns-recursive,max-inline-insns-recursive-autoโ the biggest number of instructions an out-of-line copy of a self-recursive inline function can grow into from doing recursive inlining. ๐
--param max-inline-insns-recursive is the one for functions declared inline. For functions that aren't 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. no cap.
max-inline-recursive-depth,max-inline-recursive-depth-autoโ the maximum recursion depth used when doing recursive inlining. ๐ณ๏ธ
--param max-inline-recursive-depth handles functions declared inline. For functions not declared inline, recursive inlining only kicks in 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 that have deep recursion on average, and it can actually hurt functions with little recursion depth by fattening up the prologue size or making the function body more complex for 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 via a given call expression. This parameter limits inlining to only those call expressions whose probability exceeds the given threshold (in percents).
early-inlining-insnsโ specifies the growth the early inliner is allowed to make. Basically it increases how much inlining happens for code that's carrying a big abstraction penalty. โจmax-early-inliner-iterationsโ the iteration limit of the early inliner. This is basically the bound on how many nested indirect calls the early inliner can resolve. Deeper chains still get handled by late inlining, so don't even worry. ๐ฅcomdat-sharing-probabilityโ the probability (in percent) that C++ inline functions with comdat visibility get shared across multiple compilation units. ๐modref-max-bases,modref-max-refs,modref-max-accessesโ specify the max number of base pointers, references, and accesses stored for a single function by the mod/ref analysis. ๐modref-max-testsโ specifies the maxmal number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter ought to be bigger than--param modref-max-basesand--param modref-max-refs.modref-max-depthโ specifies the maximum depth of the DFS walk used by modref escape analysis. Setting it to0disables the analysis completely. ๐modref-max-escape-pointsโ specifies the maximum number of escape points tracked by modref per SSA-name.modref-max-adjustmentsโ specifies the maximum number the access range gets enlarged during modref dataflow analysis. ๐ฆprofile-func-internal-idโ a parameter controlling whether to use the function internal id in profile database lookup. If the value is0, the compiler uses an id based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. ๐min-vect-loop-boundโ the minimum number of iterations under which loops are not vectorized when-ftree-vectorizeis used. After vectorization, the number of iterations needs to be greater than the value specified by this option for vectorization to be allowed. โญgcse-cost-distance-ratioโ the scaling factor in the calculation of 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 is with simple expressions โ i.e. those expressions that cost less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions entirely. ๐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. Currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying0lets all expressions travel unrestricted distances. ๐max-hoist-depthโ the depth of 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, but it may slow down compilation of huge functions. ๐ฎโ๐จmax-tail-merge-comparisonsโ the maximum amount of similar bbs to compare a bb against. This is used to avoid quadratic behavior in tree tail merging.max-tail-merge-iterationsโ the maximum amount of iterations of the pass over the function. Used to limit 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 in the attemt to 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. If a loop is 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โ a bound on the number of candidates for induction variables, below which all candidates get considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones get considered, 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 aPHIsupported by TREE if conversion, unless the loop is marked with a simd pragma. ๐vect-max-layout-candidatesโ the maximum number of possible vector layouts (such as 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. Value-1means no limit. โพ๏ธmax-iterations-to-trackโ this is the ceiling on how many loop iterations the brute-force algorithm will actually bother evaluating when it's trying to figure out how many times a loop runs. Basically: bestie, we're not counting to infinity ๐hot-bb-count-fractionโ the denominator n of the fraction 1/n of the biggest execution count any basic block gets in the whole program. A basic block has to hit at least that much to be crowned hot ๐. Default is10000, so a block is hot if its execution count is bigger than 1/10000 of the max execution count.0means it's never considered hot. Used in non-LTO mode.hot-bb-count-ws-permilleโ the number of most-executed permilles, ranging from0to1000, of the profiled execution of the entire program that a basic block's execution count has to be part of to be considered hot. Default is990, which means a basic block is hot if its execution count lands in the upper 990 permilles โ that's 99.0% โ of the profiled execution of the whole program.0means it's never considered hot. Used in LTO mode.hot-bb-frequency-fractionโ the denominator n of the fraction 1/n of the execution frequency of a function's entry block. A basic block in that function needs at least that much to be considered hot. Default is1000, so a block is hot in a function if it's executed more often than 1/1000 of the entry block's frequency.0means it's never considered hot.unlikely-bb-count-fractionโ the denominator n of the fraction 1/n of the number of profiled runs of the entire program. A basic block's execution count has to be below that for the block to be considered unlikely executed. Default is20, so a block is "unlikely executed" if it runs in fewer than 1/20 โ 5% โ of the program's runs.0means it's always considered unlikely executed ๐.max-predicted-iterationsโ the max number of loop iterations we predict statically. Super handy when a function has one loop with a known bound and another loop with an unknown bound: the known iteration count gets predicted correctly, while the unknown one averages out to roughly10. Which means the unbounded loop looks artificially cold next to the other one ๐ฅถ.builtin-expect-probabilityโ controls the probability of the expression having the value you specified. Takes a percentage, i.e.0 ... 100.builtin-string-cmp-inline-lengthโ the maximum length of a constant string for a builtin string cmp call to still be eligible for inlining.align-thresholdโ picks the fraction of the maximal execution frequency of a basic block in a function, used to decide whether 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. It's the little leash that keeps unnecessary code size expansion from running wild.
The tracer-dynamic-coverage-feedback parameter is only used when profile feedback is available. The real profiles (as opposed to the statically estimated ones) are way less balanced, which lets the threshold be a larger value.
tracer-max-code-growthโ stop tail duplication once code growth hits the given percentage. It's a pretty artificial limit, because most of the duplicates get eliminated later during cross jumping, so you can set it to much higher values than the code growth you actually want.tracer-min-branch-ratioโ stop reverse growth when the reverse probability of the best edge is less than this threshold (in percent).tracer-min-branch-probability,tracer-min-branch-probability-feedbackโ stop forward growth if the best edge has a probability lower than this threshold.
Just like with tracer-dynamic-coverage, there are two parameters here. tracer-min-branch-probability-feedback is used when compiling with profile feedback, tracer-min-branch-probability when compiling without. The value for compiling with profile feedback needs to be more conservative (higher) for the tracer to actually do its thing.
stack-clash-protection-guard-sizeโ specifies the size of the operating system provided stack guard as2raised 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 ๐จ. No cap, do not do that.stack-clash-protection-probe-intervalโ stack clash protection means probing stack space as it's allocated. This param controls the maximum distance between probes into the stack as2raised 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 ๐จ. Same energy, same warning.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โ GCC uses a garbage collector to manage its own memory allocation, iconic behaviour honestly. This parameter specifies the minimum percentage by which the garbage collector's heap should be allowed to expand between collections. Tuning this may improve compilation speed; it has no effect on code generation.
The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If getrlimit is available, the notion of "RAM" is the smallest of actual RAM and RLIMIT_DATA or RLIMIT_AS. If GCC isn't able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity โ which is extremely slow, but can be useful for debugging ๐.
ggc-min-heapsizeโ the minimum size of the garbage collector's heap before it even 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 of RAM/8, RLIMIT_RSS, or a limit that tries to make sure RLIMIT_DATA or RLIMIT_AS aren't exceeded โ but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (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. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.
max-reload-search-insnsโ the maximum number of instructions reload should look backward for an equivalent register. Increasing values mean more aggressive optimization, making compilation time go up with probably slightly better performance. Trade-offs, bestie ๐max-cselib-memory-locationsโ the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making compilation time increase 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 the CFG to extend regions. A value of0disables region extensions.max-sched-insn-conflict-delayโ the maximum conflict delay for an insn to even be considered for speculative motion.sched-spec-prob-cutoffโ the minimal probability of speculation success (in percents) for speculative insns to actually get scheduled.sched-state-edge-prob-cutoffโ the minimum probability an edge has to 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 that target 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 that an instruction gets scheduled during selective scheduling. This is 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 are considered for renaming in the selective scheduler.sms-min-scโ the minimum value of stage count that the swing modulo scheduler generates.max-last-value-rtlโ the biggest size, measured in actual number of RTLs, that can get recorded in an expression inside the combiner when it's tracking a pseudo register's last known value. โจmax-combine-insnsโ the max number of instructions the RTL combiner will even try to combine. It's giving "know your limits, bestie". ๐integer-share-limitโ okay so small integer constants can share a data structure, which is literally such a slay move: it cuts the compiler's memory usage AND speeds it up. This param sets the maximum value of a shared integer constant. ๐ssp-buffer-sizeโ the minimum size of buffers (aka arrays, hi) that get stack smashing protection when-fstack-protectoris doing its thing. Funnily enough, the default before Ubuntu 10.10 was"8", but currently it's"4"โ because that way more functions get protected by the stack protector. iconic honestly. ๐ก๏ธmin-size-for-stack-sharingโ the minimum size of variables that get to participate in stack slot sharing when not optimizing. lowkey exclusive club. ๐max-jump-thread-duplication-stmtsโ maximum number of statements allowed in a block that needs to be duplicated when threading jumps. ๐max-jump-thread-pathsโ the max number of paths to consider when it's out here searching for jump threading opportunities. When arriving 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 doesn't exhaust the specified maximum number of paths to consider. math is mathing. ๐ฅmax-fields-for-field-sensitiveโ maximum number of fields in a struct that get treated in a field sensitive manner during pointer analysis. no cap.prefetch-latencyโ the estimate of the average number of instructions executed before a prefetch finishes. The distance prefetched ahead is proportional to this constant. Heads up though: bumping this number up may also lead to less streams being prefetched (seesimultaneous-prefetches). trade-offs, bestie. ๐ญsimultaneous-prefetchesโ the maximum number of prefetches that can run at the same time. main character energy only. โญl1-cache-line-sizeโ the size of a cache line in the L1 data cache, in bytes.l1-cache-sizeโ the size of the L1 data cache, in kilobytes.l2-cache-sizeโ the size of the L2 data cache, in kilobytes.prefetch-dynamic-stridesโ whether the loop array prefetch pass should issue software prefetch hints for strides that are non-constant. In some cases this may be 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 1 if prefetch hints should be issued for non-constant strides. Set it to 0 if prefetch hints should be issued only for strides that are known to be constant and belowprefetch-minimum-stride. ๐ฆprefetch-minimum-strideโ 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. This setting is useful for processors that have hardware prefetchers, in which case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, it should be used here to improve the use of software prefetchers. A value of-1means we don't have a threshold, and therefore prefetch hints can be issued for any constant stride. Just know this setting is only useful for strides that are known and constant. periodt. โจdestructive-interference-sizeconstructive-interference-sizeโ these two are the values for the C++17 variablesstd::hardware_destructive_interference_sizeandstd::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 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 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 it is used in that context, users can stabilize the value using this option. The constructive interference size is less sensitive, as it's typically only used in astatic_assertto 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 that's up to be interchanged.loop-interchange-stride-ratioโ the minimum ratio between the stride of two loops for interchange to actually be profitable. ๐ซถmin-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches 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 to enable prefetching in a loop.use-canonical-typesโ whether the compiler should use the "canonical" type system. Should always be 1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. However, if bugs in the canonical type system are causing compilation failures, set this value to 0 to disable canonical types. known bug behavior, not me making it up. ๐switch-conversion-max-branch-ratioโ switch initialization conversion refuses to create arrays that are bigger thanswitch-conversion-max-branch-ratiotimes the number of branches in the switch. hard boundaries, slay. ๐max-partial-antic-lengthโ maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at-O3and above. For some sorts of source code, the enhanced partial redundancy elimination optimization can literally run away and consume 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 the runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length. be careful bestie. ๐ญrpo-vn-max-loop-depthโ the maximum loop depth that gets value-numbered optimistically. When the limit hits, the innermostrpo-vn-max-loop-depthloops and the outermost loop in the loop nest are value-numbered optimistically, and the remaining ones are not. yes, it's giving "the famous ones get VIP, the rest wait outside". ๐sccvn-max-alias-queries-per-accessโ the maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit is hit, the search is aborted and the load or store is not considered redundant. 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. popular loops stay winning. ๐ira-max-conflict-table-sizeโ okay so although 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. speed over quality, we've all been there. โญ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. Default of the parameter is the best found from numerous experiments. science ate. ๐ฅira-consider-dup-in-all-altsโ makes IRA consider the matching constraint (duplicated operand number) heavily in all available alternatives for 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 preferred register class even if it has found some choice with an appropriate register class, and respect the found qualified matching constraint. thorough queen. ๐ธira-simple-lra-insn-thresholdโ approximate function insn number, in 1K units, that triggers simple local RA.lra-inheritance-ebb-probability-cutoffโ LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance. EBB is used as a region to do this optimization. The parameter defines a minimal fall-through edge probability in percentage used to add BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64, so like, trust the data. ๐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 bestie, you're too big. ๐ฆ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 no handled by the optimizations using loop data dependencies. (yes that typo is canon, it's in the manpage, iykyk.) ๐max-vartrack-sizeโ caps how many hash table slots the variable tracking dataflow analysis gets to use on any one function. If you blow past that limit and variable tracking at assignments is on, the analysis for that function gets retried without it โ after literally stripping every debug insn out of the function. If you still exceed the limit even with the debug insns gone, var tracking analysis is just fully switched off for that function, periodt. Setting the parameter to zero = no limit at all, go wild. ๐max-vartrack-expr-depthโ the max number of recursion levels it'll go when trying to map variable names or debug temporaries onto value expressions. It's a trade: compilation time vs. more complete debug info. Set it too low and value expressions that are available and could show up in debug info might just... not get used ๐ญ. Crank it up and the compiler might find more complex debug expressions, but compile time and memory use can grow too.max-debug-marker-countโ sets a threshold on how many debug markers (likebegin stmtmarkers) are allowed, so we don't get a complexity explosion when inlining or expanding to RTL. If a function has more such gimple stmts than the limit, those stmts get dropped from the inlined copy of the function โ and from its RTL expansion too. โจmin-nondebug-insn-uidโ nondebug insns start their uids at this parameter. Everything below it is reserved exclusively for debug insns created by-fvar-tracking-assignments, but debug insns can still get (non-overlapping) uids above it if that reserved range runs out. ๐ipa-sra-deref-prob-thresholdโ IPA-SRA will only swap out a pointer that's known to not be NULL for one or more new parameters if the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter. No cap. ๐ipa-sra-ptr-growth-factorโ IPA-SRA only replaces a pointer to an aggregate with one or more new parameters when their cumulative size is less than or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter.ipa-sra-ptrwrap-growth-factorโ the additional allowed growth of the total size of new parameters thatipa-srareplaces a pointer to an aggregate with, when that pointer points to a local variable the caller only writes to and passes as an argument to other functions. yes this is a very specific vibe, we love specificity ๐ฆipa-sra-max-replacementsโ the maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it's also the maximum number of replacements of a formal parameter.sra-max-scalarization-size-Ospeedandsra-max-scalarization-size-Osizeโ okay so the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) both aim to replace scalar parts of aggregates with uses of independent scalar variables. These two parameters control the max size, in storage units, of the aggregate that's considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or for 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, so that copy propagation is easier.tm-max-aggregate-sizeโ when copying thread-local variables inside a transaction, this parameter sets the size in bytes after which variables get saved with the logging functions instead of save/restore code sequence pairs. Only applies when you're using-fgnu-tm.graphite-max-nb-scop-paramsโ to keep the Graphite loop transforms from going exponential, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero lifts the bound entirely. Oh and PSA: a variable whose value is unknown at compile time and defined outside a SCoP counts as a parameter of the SCoP. ๐loop-block-tile-sizeโ loop blocking or strip mining transforms, which you enable with-floop-blockor-floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. You change the strip length with theloop-block-tile-sizeparameter.ipa-jump-function-lookupsโ specifies how many statements get visited during jump function offset discovery.ipa-cp-value-list-sizeโ IPA-CP tries to track all possible values and types passed to a function's parameter so it can propagate them and do devirtualization.ipa-cp-value-list-sizeis the max number of values and types it stores per one formal parameter of a function.ipa-cp-eval-thresholdโ IPA-CP calculates its own score using cloning profitability heuristics, and it'll do the cloning opportunities whose scores exceedipa-cp-eval-threshold.ipa-cp-max-recursive-depthโ maximum depth of recursive cloning for a self-recursive function.ipa-cp-min-recursive-probabilityโ recursive cloning happens only when the probability of the call actually being executed exceeds this parameter.ipa-cp-profile-count-baseโ when you're using the-fprofile-useoption, IPA-CP takes 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โ the percentage penalty that recursive functions receive when they're being evaluated for cloning.ipa-cp-single-call-penaltyโ the percentage penalty that functions containing a single call to another function receive when they're being evaluated for cloning.ipa-max-agg-itemsโ IPA-CP can also propagate a number of scalar values passed inside an aggregate.ipa-max-agg-itemscontrols the max number of such values per one parameter.ipa-cp-loop-hint-bonusโ when IPA-CP figures out 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 that candidate. little treat for the good 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โ while analyzing function bodies, IPA-CP pulls in alias analysis to track the values pointed to by function parameters. To avoid spending way too much time on huge functions, it gives up and considers all memory clobbered once it's examinedipa-max-aa-stepsstatements that modify memory. ๐ipa-max-switch-predicate-boundsโ the maximal number of boundary endpoints of case ranges of aswitchstatement. For aswitchthat exceeds this limit, IPA-CP won't construct the cloning cost predicate โ which is what's used to estimate cloning benefit โ for the default case of the switch.ipa-max-param-expr-opsโ IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit of cloning upon a certain constant value. But if the number of operations in a parameter expression exceedsipa-max-param-expr-ops, the expression is treated as a complicated one and just isn't handled by IPA analysis.lto-partitionsโ specify the desired number of partitions produced during WHOPR compilation. The number of partitions should exceed the number of CPUs used for compilation. ๐ฅ๏ธlto-min-partitionโ the size of the minimal partition for WHOPR (in estimated instructions). This stops you from wasting effort splitting very small programs into way too many partitions.lto-max-partitionโ the size of the max partition for WHOPR (in estimated instructions), to give an upper bound for the individual size of a partition. Meant to be used only with balanced partitioning.lto-max-streaming-parallelismโ the 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. it's the compiler being like "did you meanโฆ" ๐ซถsink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block, which is what allows statement sinking of a statement. Bigger numbers = more aggressive statement sinking. A small positive adjustment gets applied for statements with memory operands, since those are even more profitable to sink.max-stores-to-sinkโ the maximum number of conditional store pairs that can be sunk. Set it 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's 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). This 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). This parameter is used when optimizing for speed.tree-reassoc-widthโ sets the maximum number of instructions executed in parallel in a reassociated tree. This parameter overrides the target-dependent heuristics used by default if it has a non-zero value. ๐ฅsched-pressure-algorithmโ okay so there are two whole implementations of-fsched-pressureand you get to pick, bestie. Algorithm 1 is the OG โ the original โ and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was literally designed as the compromise between algorithm 1's relatively conservative approach and the default scheduler's rather aggressive approach. It leans way harder on the target having a regular register file and accurate register pressure classes. If you want the whole lore, go readhaifa-sched.ccin the GCC sources ๐ The default choice here? Depends on the target, so vibe check your arch first.max-slsr-cand-scanโ sets the max number of existing candidates considered while hunting for a basis for a new straight-line strength reduction candidate. That's it, that's the knob โจasan-globalsโ turns on buffer overflow detection for global objects. This protection is on by default when you're using-fsanitize=address. Wanna turn that global-objects protection off? Use--param asan-globals=0.asan-stackโ turns on buffer overflow detection for stack objects. On by default when using-fsanitize=address. To kill the stack protection, use--param asan-stack=0๐ซถasan-instrument-readsโ buffer overflow detection for memory reads. On by default with-fsanitize=address. To disable memory reads protection, use--param asan-instrument-reads=0.asan-instrument-writesโ buffer overflow detection for memory writes. On by default with-fsanitize=address. To disable memory writes protection, use--param asan-instrument-writes=0โจasan-memintrinโ enables detection for built-in functions. On by default with-fsanitize=address. To disable built-in functions protection, use--param asan-memintrin=0.asan-use-after-returnโ enables detection of use-after-return. On by default with the-fsanitize=addressoption. To disable it, use--param asan-use-after-return=0.
๐จ Note, bestie: by default the check is disabled at run time. To actually turn it on, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS. The parameter alone is not the whole story, iykyk.
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. E.g. 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โ enables hwasan instrumentation of statically sized stack-allocated variables. On by default with-fsanitize=hwaddress, and off by default with-fsanitize=kernel-hwaddress. Disable stack instrumentation with--param hwasan-instrument-stack=0, enable it with--param hwasan-instrument-stack=1.hwasan-random-frame-tagโ when stack instrumentation is in play, this decides tags for stack variables using a deterministic sequence that begins at a random tag for each frame. With this parameter unset, tags get chosen using the same sequence but starting from1. It's enabled by default for-fsanitize=hwaddressand unavailable for-fsanitize=kernel-hwaddress. To disable it, use--param hwasan-random-frame-tag=0.hwasan-instrument-allocasโ enables hwasan instrumentation of dynamically sized stack-allocated variables. On by default with-fsanitize=hwaddress, off by default with-fsanitize=kernel-hwaddress. To disable instrumentation of such variables, use--param hwasan-instrument-allocas=0, and to enable it, use--param hwasan-instrument-allocas=1๐hwasan-instrument-readsโ enables hwasan checks on memory reads. Instrumentation of reads is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To stop checking memory reads, use--param hwasan-instrument-reads=0.hwasan-instrument-writesโ enables hwasan checks on memory writes. Instrumentation of writes is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To stop checking memory writes, use--param hwasan-instrument-writes=0.hwasan-instrument-mem-intrinsicsโ enables 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 a local variable's size in bytes is smaller than or equal to this number, directly poison (or unpoison) shadow memory instead of going through run-time callbacks ๐ธtsan-distinguish-volatileโ emit special instrumentation for accesses to volatiles. That's the vibe โจtsan-instrument-func-entry-exitโ emit instrumentation calls to__tsan_func_entry()and__tsan_func_exit().max-fsm-thread-path-insnsโ maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path. Fr fr, that's the cap ๐งthreader-debugโthreader-debug=[none|all]enables verbose dumping of the threader solver. Picknoneorall, no in-between.parloops-chunk-sizeโ chunk size of omp schedule for loops parallelized by parloops.parloops-scheduleโ 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: for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread istwo๐max-ssa-name-query-depthโ maximum depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion = following a use-def chain, so yeah, that's one hop down the chain ๐max-speculative-devirt-maydefsโ the maximum number of may-defs we analyze when we're looking for a must-def that specifies the dynamic type of an object invoking a virtual call we might be able to devirtualize speculatively. Long sentence, iconic parameter.evrp-sparse-thresholdโ maximum 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 maximum number of switch cases before EVRP ignores a switch. Bye girl ๐unroll-jam-min-percentโ the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to even be considered profitable.unroll-jam-max-unrollโ the maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.max-rtl-if-conversion-unpredictable-costโ maximum 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, this is the maximum number of times an individual variable will be expanded during loop unrolling ๐partial-inlining-entry-probabilityโ maximum probability of the entry BB of a split region (in percent relative to the entry BB of the function) for partial inlining to actually happen.max-tracked-strlensโ maximum 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 permit performing redundancy elimination after reload.max-loop-header-insnsโ the maximum number of insns in a loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enable 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 maximum 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โ enable loop vectorization of floating point inductions ๐avoid-fma-max-bitsโ maximum 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 swing modulo scheduler uses for scheduling a loop ๐ฅlra-max-considered-reload-pseudosโ the max number of reload pseudos that get considered while we're spilling a non-reload pseudo ๐งmax-pow-sqrt-depthโ maximum depth of sqrt chains we'll use when synthesizing exponentiation by a real constant.max-dse-active-local-storesโ max number of active local stores allowed in RTL dead store elimination.asan-instrument-allocasโ turns on asan allocas/VLAs protection โจmax-iterations-computation-costโ the bound on how expensive an expression can be to compute the number of iterations.max-isl-operationsโ max number of isl operations;0means unlimited ๐graphite-max-arrays-per-scopโ maximum number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of a 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 against--param=max-jump-thread-duplication-stmts.uninit-control-dep-attemptsโ max number of nested calls made while searching for control dependencies during uninitialized variable analysis.uninit-max-chain-lenโ maximum number of predicates anded for each predicate ored in the normalized predicate chain.uninit-max-num-chainsโ 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 simply too big to copy.loop-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 when figuring out 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 issues any diagnostics.store-merging-max-sizeโ maximum size, in bytes, of a single store merging region.hash-table-verification-limitโ the number of elements for which hash table verification is performed, 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 max number of exploded nodes per program point inside the analyzer, before it gives up and terminates analysis of that point.analyzer-max-constraintsโ the maximum number of constraints per state.analyzer-min-snodes-for-call-summaryโ the minimum number of supernodes inside a function for the analyzer to 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 it switches 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 terminates analysis of a call that would recurse any deeper.analyzer-max-svalue-depthโ the maximum depth of a symbolic value, before it 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 that 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 analysis gets terminated.ranger-logical-depthโ maximum depth of logical expression evaluation that 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 OpenACCkernelsconstruct 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 ๐ง With--param=openacc-kernels=parloops, OpenACCkernelsconstructs are handled by the parloops pass, en bloc. That one 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.
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 means storing smaller elements in larger containers and accessing elements with extending loads and truncating stores.
aarch64-float-recp-precisionโ the number of Newton iterations used to calculate the reciprocal for the 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 used to calculate the reciprocal for the double type. The precision of division is proportional to this param when division approximation is enabled. The default value is2.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 the available tuning information to figure out whether unrolling the main vectorized loop would be beneficial, and by how much. This parameter sets the upper bound on how much the vectorizer will unroll the main loop. The default value isfour.
The following choices of name are available on i386 and x86_64 targets: ๐ฆ
x86-stlf-window-ninsnsโ the instruction count 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 gets aborted.
๐งช Program Instrumentation Options ๐งช
GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates, and honestly? it's giving science experiment ๐ฌโจ
One purpose of instrumentation is collecting profiling statistics โ so you can find program hot spots, do code coverage analysis, or run profile-guided optimizations. Another class of program instrumentation is adding run-time checking to catch programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks like stack smashing or C++ vtable hijacking. 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. Very versatile, very main character ๐
-p,-pgโ generate extra code that writes 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. Both times, bestie, or it simply won't work ๐ญ
You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.
-fprofile-arcsโ adds code so that program flow arcs are 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.
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).
๐ก heads up bestie: if a command line directly links source files, the matching.gcdafiles get prefixed with the unsuffixed name of the output file. So like,gcc a.c b.c -o binarywould spit outbinary-a.gcdaandbinary-b.gcda. noted ๐
--coverageโ the โจcompile-and-link-for-coverage-analysisโจ option. It's literally a synonym for-fprofile-arcs+-ftest-coverage(when you're compiling) and-lgcov(when you're linking). Peep the docs for those options for the deets.
Here's the whole pipeline, step by step, no skips:
- Compile the source files with
-fprofile-arcsplus your optimization and code generation options. For test coverage analysis specifically, tack on-ftest-coveragetoo. Ngl you do not need to profile every single source file in a program. ๐ - Also compile the source files with
-fprofile-abs-pathso the.gcnofiles get absolute path names. That's what letsgcovfind the right sources in projects where compilations happen with different working directories. - Link your object files with
-lgcovor-fprofile-arcs(the second one implies the first, slay). - Run the program on a representative workload to generate the arc profile info. You can repeat this any number of times. Concurrent instances of your program? Totally fine โ as long as the file system supports locking, the data files get correctly updated. And unless a strict ISO C dialect option is in effect,
forkcalls are detected and handled correctly without double counting. ๐
Also: an object file can be recompiled multiple times and the corresponding .gcda file 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 info from the.gcnoand.gcdafiles. Go read thegcovdocumentation for more.
With -fprofile-arcs, for each function of your program, GCC creates a program flow graph, then finds a spanning tree for the graph. Only the arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count how many times those arcs get executed. When an arc is the only exit or only entrance to a block, the instrumentation code can just be added to the block; otherwise a new basic block has to be created to hold the instrumentation code. the way that works is so iconic fr fr ๐ธ
-ftest-coverageโ produce 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 whatauxnamemeans and how to generate test coverage data.) Hot tip: coverage data matches the source files more closely if you don't optimize. โจ-fprofile-abs-pathโ automatically convert relative source file names to absolute path names in the.gcnofiles. Again, this is the thing that letsgcovfind the correct sources in projects where compilations occur with different working directories. ๐ฆ-fprofile-dir=pathโ set the directory to search for the profile data files in to path. This option only affects 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 shows up in the same directory as the object file. To prevent 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 file naming under-fprofile-arcs. Also see the similar option-fprofile-note.)
When an executable is run in a massive parallel environment, it's recommended to save the 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 variableVAR.
-fprofile-generate,-fprofile-generate=pathโ enable the options usually used for instrumenting an application to produce profile data that's useful for later recompilation with profile feedback based optimization. You must use-fprofile-generateboth when compiling and when linking your program. ๐
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โ register the profile information in the specified section instead of using a constructor/destructor. The section name is name if it's specified, otherwise the section name defaults to.gcov_info. A pointer to the profile information generated by-fprofile-arcsgets 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. And listen โ 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 that don't 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 the.gcnofile into the path location. If you combine the option with multiple source files, the.gcnofile will be overwritten. ๐ (rip to your previous notes)-fprofile-prefix-path=pathโ this one can be used in combination withprofile-generate=profile_dirandprofile-use=profile_dirto inform GCC where the base directory of the built source tree is. By defaultprofile_dirwill contain files with mangled absolute paths of all object files in the built project. That's 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 won't 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. Also peep-ffile-prefix-mapand-fcanon-prefix-map. โจ-fprofile-update=methodโ alter 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 a detached thread), a profile file can still be 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. ๐ฅ
-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'. ๐ง
-fprofile-exclude-files=regexโ instrument only functions from files whose name does not match any of the regular expressions (separated by semi-colons).
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 controls how reproducible the profile is that-fprofile-generategathers โจ and the whole point is that you can rebuild a program and get the exact same outcome โ which is, like, the dream scenario for distribution packages ๐
With -fprofile-reproducible=serial the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded, and profile data streaming is always done in the same order. And bestie, heads up: profile streaming happens at the end of the program run but ALSO before the fork function is invoked ๐
Also also โ it's quite common that execution counts of some part of programs depend on, for example, the length of temporary file names or memory space randomization (which may affect hash-table collision rate ๐). Such non-reproducible parts of programs may be annotated by the no_instrument_function function attribute. And gcov-dump with -l can be used to dump the gathered data and verify that it's actually reproducible ๐
With -fprofile-reproducible=parallel-runs the collected profile stays reproducible regardless of the order of streaming of the data into gcda files. This setting makes it possible to run multiple instances of the instrumented program in parallel (such as with make -j) ๐ฅ This reduces the quality of gathered data, in particular of indirect call profiling. Tradeoffs, we hate to see it ๐ญ
-fsanitize=addressโ turns on AddressSanitizer, a fast memory error detector ๐ต๏ธ๐ Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables-fsanitize-address-use-after-scope. See https://github.com/google/sanitizers/wiki/AddressSanitizer for more details. The run-time behavior can be influenced using theASAN_OPTIONSenvironment variable. When set tohelp=1, the available options are shown at startup of the instrumented program. See https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags for a list of supported options. The option cannot be combined with-fsanitize=threador-fsanitize=hwaddress๐ซ Note that the only targets-fsanitize=hwaddressis currently supported on are x86-64 (only with-mlam=u48or-mlam=u57options) and AArch64, in both cases only in ABIs with 64-bit pointers.
To get more accurate stack traces, it's possible to use options such as -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which prevents optimizing sibling and tail recursive calls; this option is implicit for -O0, -O1, or -Og), or -fno-ipa-icf (which disables Identical Code Folding for functions). Since multiple runs of the program may yield backtraces with different addresses due to ASLR (Address Space Layout Randomization), it may be desirable to turn ASLR off. On Linux, this can be achieved with setarch uname -m -R ./prog ๐
-fsanitize=kernel-addressโ enables AddressSanitizer for the Linux kernel ๐ง See https://github.com/google/kernel-sanitizers for more details.-fsanitize=hwaddressโ enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer to allow the detection of memory errors with a low memory overhead โจ Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables-fsanitize-address-use-after-scope. See https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html for more details. The run-time behavior can be influenced using theHWASAN_OPTIONSenvironment variable. When set tohelp=1, the available options are shown at startup of the instrumented program. The option cannot be combined with-fsanitize=threador-fsanitize=address, and is currently only available on AArch64 ๐-fsanitize=kernel-hwaddressโ enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel ๐งโจ Similar to-fsanitize=kernel-addressbut using an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences necessary for compiling the Linux kernel. These differences are 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 to the -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default but are still possible by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively. Using a random frame tag is not implemented for kernel instrumentation ๐
-fsanitize=pointer-compareโ instruments comparison operations (<,<=,>,>=) with pointer operands ๐ซถ The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread. Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1detects invalid operation only when both pointers are non-null ๐-fsanitize=pointer-subtractโ instruments subtraction with pointer operands ๐ The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread. Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1detects invalid operation only when both pointers are non-null โจ-fsanitize=shadow-call-stackโ enables ShadowCallStack, a security enhancement mechanism used to protect programs against return address overwrites (e.g. stack buffer overflows) ๐ It works by saving a function's return address to a separately allocated shadow call stack in the function prologue and restoring the return address from the shadow call stack in the function epilogue. Instrumentation only occurs in functions that need to save the return address to the stack.
Currently it only supports the aarch64 platform. It is 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 ๐ญ Users who want to use this feature in user space need to provide their own support for the runtime. It should be noted that this may cause the ABI rules to be broken โ ๏ธ
On aarch64, the instrumentation makes use of the platform register x18. This generally means that 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 so 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 ๐ซ
See https://clang.llvm.org/docs/ShadowCallStack.html for more details.
-fsanitize=threadโ enables ThreadSanitizer, a fast data race detector ๐ Memory access instructions are instrumented to detect data race bugs. See https://github.com/google/sanitizers/wiki#threadsanitizer for more details. The run-time behavior can be influenced using theTSAN_OPTIONSenvironment variable; see https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags for a list of supported options. The option cannot be combined with-fsanitize=address,-fsanitize=leak๐ซ
Note that 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 option only matters for linking of executables. The executable is linked against a library that overridesmallocand other allocator functions. See https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer for more details. The run-time behavior can be influenced using theLSAN_OPTIONSenvironment variable. The option cannot be combined with-fsanitize=thread๐ซ-fsanitize=undefinedโ enables UndefinedBehaviorSanitizer, a fast undefined behavior detector ๐จ Various computations are instrumented to detect undefined behavior at runtime. See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for more details. The run-time behavior can be influenced using theUBSAN_OPTIONSenvironment variable. Current suboptions are:-fsanitize=shiftโ this option enables checking that the result of a 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. This option has two suboptions,-fsanitize=shift-baseand-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 a 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_unreachablecall into a diagnostics message call instead. When reaching the__builtin_unreachablecall, 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, the 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 by a NULL pointer ๐ซ ๐ฅ
-fsanitize=returnโ bestie this one checks yourreturnstatements ๐. Build with it on and any time you hit the end of a non-voidfunction without actually returning a value, you get an error message. C++ only tho, no cap.-fsanitize=signed-integer-overflowโ turns on signed integer overflow checking โจ. It checks that the result of+,*, and both unary and binary-doesn't overflow in signed arithmetic. It also catchesINT_MIN / -1signed division. Note tho โ integer promotion rules have to be taken into account, meaning this next thing is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ instruments array bounds ๐ฆ. Lots of out-of-bounds accesses get detected. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented โ except for flexible array member-like arrays where-fstrict-flex-arraysor-fstrict-flex-arrays=options orstrict_flex_arrayattributes say they shouldn't be treated like flexible array member-like arrays.-fsanitize=bounds-strictโ the strict version, obviously ๐ . Most out-of-bounds accesses get detected, flexible array member-like arrays included. Initializers of variables with static storage are still not instrumented.-fsanitize=alignmentโ checks alignment of pointers when they get 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โ instruments memory references using the__builtin_dynamic_object_sizefunction ๐. Various out-of-bounds pointer accesses get detected.-fsanitize=float-divide-by-zeroโ detects floating-point division by zero. And like, unlike the other similar options,-fsanitize=float-divide-by-zerois not enabled by-fsanitize=undefined, because floating-point division by zero can legitimately be how you get infinities and NaNs ๐ฅ.-fsanitize=float-cast-overflowโ enables floating-point type to integer conversion checking ๐. It checks that the result of the conversion doesn't overflow. Unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Also this one does not work well withFE_INVALIDexceptions enabled, just so you know.-fsanitize=nonnull-attributeโ instruments calls, checking whether null values get 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 ๐.-fsanitize=boolโ instruments loads from bool ๐. If a value other than 0/1 gets loaded, run-time error, boom.-fsanitize=enumโ instruments loads from an enum type ๐. Load a value outside the range of values for the enum type and you get a run-time error.-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 ๐ .-fsanitize=pointer-overflowโ instruments pointer arithmetic โญ. If the pointer arithmetic overflows, run-time error gets issued.-fsanitize=builtinโ instruments arguments to selected builtin functions ๐ง. Pass an invalid value to such arguments and you get a run-time error. E.g. passing 0 as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and this option diagnoses it.
Heads up bestie: sanitizers tend to increase the rate of false positive warnings, most notably the ones around-Wmaybe-uninitialized. We recommend against combining-Werrorand [the use of] sanitizers. fr fr, don't do it to yourself ๐
Also, while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives you a diagnostic message instead. This currently works only for the C family of languages.
-fno-sanitize=allโ disables all previously enabled sanitizers ๐ซถ. And no,-fsanitize=allis not allowed, because some sanitizers cannot be used together. It's giving exclusivity.-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,...โ sanitizes global variables in selected user-defined sections ๐. Each si may contain wildcards.-fsanitize-recover[=opts]โ-fsanitize-recover=controls error recovery mode for the sanitizers listed in the comma-separated list opts ๐ธ. Turn it on for a sanitizer component and it will attempt to keep 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 changes 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 are also accepted โ the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it ๐
.
Even if recovery mode is turned on the compiler side, it also needs to be 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 by setting the halt_on_error flag in the corresponding environment variable.
Syntax without an explicit opts parameter is deprecated ๐. It's equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scopeโ enables sanitization of local variables to detect use-after-scope bugs ๐ฆ. The option sets-fstack-reusetonone.-fsanitize-trap[=opts]โ this one tells the compiler to report undefined behavior for the sanitizers in the comma-separated list opts using__builtin_traprather than alibubsanlibrary routine ๐ฅ. If it's enabled for a certain sanitizer, it takes precedence over-fsanitizer-recover=for that sanitizer โ__builtin_trapwill be emitted and be fatal regardless of whether recovery is enabled or disabled via-fsanitize-recover=.
The advantage? The libubsan library isn't needed and isn't 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 also be 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, since the instrumentation always needs libubsan support โ -fsanitize-trap=vptr is not allowed ๐ซ.
-fsanitize-undefined-trap-on-errorโ this is the deprecated equivalent of-fsanitize-trap=all๐.-fsanitize-coverage=trace-pcโ enables coverage-guided fuzzing code instrumentation โจ. Inserts a call to__sanitizer_cov_trace_pcinto every basic block.-fsanitize-coverage=trace-cmpโ enables 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 ๐.-fcf-protection=[full|branch|return|none|check]โ enables code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (like 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 threats like Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP). Iconic security behavior honestly.
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 ๐.
The value "check" is what you want for that final link when you're doing link-time optimization (LTO), bestie. If your LTO object files got compiled with different -fcf-protection values, it throws an error at you. And heads up: the "check" value is straight-up ignored at compile time. ๐
The macro "__CET__" gets defined whenever you use -fcf-protection. The first bit of "__CET__" is set to 1 when the value is "branch", and the second bit of "__CET__" is set to 1 for "return".
You can also flex the "nocf_check" attribute to flag which functions and calls should be skipped from instrumentation. โจ
Right now, the x86 GNU/Linux target is the one serving an implementation based on Intel Control-flow Enforcement Technology (CET), and it works for i686 processors or newer. ๐
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
Okay so for every logical test that survives gimple optimizations and is not the condition in a conditional branch โ like conditions tested for conditional moves, or ones you're storing into boolean variables โ it emits extra code to compute and verify the reversed condition, and to call "__builtin_trap" if the results don't match. Want full coverage of all your conditionals? Use it together with -fharden-conditional-branches. ๐ธ
๐ -fharden-conditional-branches
For every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and to call "__builtin_trap" if the result is unexpected. Team it up with -fharden-compares to cover all conditionals. ๐ฆ
๐ -fstack-protector
Emit extra code to check for buffer overflows, like stack smashing attacks. How? By adding a guard variable to functions with vulnerable objects. That includes functions that call "alloca", and 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. If a guard check fails, an error message prints and the program exits. Only variables that are actually allocated on the stack count โ optimized away variables or variables allocated in registers don't. ๐
๐ -fstack-protector-all
Same vibe as -fstack-protector except that all functions are protected. ๐ก๏ธ
๐ -fstack-protector-strong
Like -fstack-protector but it includes additional functions to be protected โ specifically those that have local array definitions, or have references to local frame addresses. Only variables that are 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-protector but it only protects those functions which have the "stack_protect" attribute. That's it, that's the whole thing. ๐
๐ -fstack-check
Generate code to verify that you don't go beyond the boundary of the stack. You should specify this flag if you're running in an environment with multiple threads, but you only rarely need it in a single-threaded environment, since stack overflow is automatically detected on nearly all systems when there's only one stack.
Note that this switch does not actually cause checking to be done โ the operating system or the language runtime has to do that. The switch causes generation of code to ensure that they see the stack being extended. ๐
You can additionally pass a string parameter:
nomeans no checkinggenericmeans force the use of old-style checkingspecificmeans use the best checking method and is equivalent to a bare-fstack-check
Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie, it comes with these drawbacks:
- Modified allocation strategy for large objects: they are always allocated dynamically if their size exceeds a fixed threshold. Note 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.
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. It is not generally sufficient to protect against stack-clash attacks. To protect against those you want -fstack-clash-protection. ๐
๐ -fstack-clash-protection
Generate 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 is accessed immediately after allocation. So it prevents allocations from jumping over any stack guard page provided by the operating system. ๐ฅ
Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. -fstack-clash-protection 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
Generate code to ensure that the stack does not grow beyond a certain value โ either the value of a register or the address of a symbol. If a larger stack is required, 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. โญ
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
Generate code to automatically split 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. This is currently 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. If compiling all code, including library code, with -fsplit-stack is not 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]
This option is only available when compiling C++ code, so if that's not you, scroll on. 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 has not 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, which are used for verifying the vtable pointers. The options std and preinit control the timing of when these data structures are 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 appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std. ๐
๐ -fvtv-debug
When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called. This flag also causes the compiler to log information about which vtable pointers it finds for each class. This info is written to a file named vtv_set_ptr_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is 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. ๐๏ธ
๐ -fvtv-counts
This is a debugging flag. When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, it causes the compiler to 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 named vtv_count_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class, and writes this info to vtv_class_set_sizes.log in 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โ okay bestie, this one gets spicy. It generates instrumentation calls for entry to and exit from functions. Right after a function entry and right before it exits, these profiling functions get called with the address of the current function and its call site. Quick heads up though: on some platforms__builtin_return_addressdoesn't work beyond the current function, so the call site info might not reach your profiling functions at all.
void __cyg_profile_func_enter (void *this_fn,
void *call_site);
void __cyg_profile_func_exit (void *this_fn,
void *call_site);
The first argument is the address of the start of the current function, and that one you can look up exactly in the symbol table. <sparkle>slay.</sparkle>
This instrumentation also happens for functions expanded inline in other functions โ the profiling calls show you where, conceptually, the inline function gets entered and exited. Which means addressable versions of such functions have to exist. If literally every use of a function is expanded inline, this can mean extra code size. And if you're out here using extern inline in your C code, an addressable version of such functions must be provided. (Normally that's the case anyway, but if you get lucky and the optimizer always inlines them, you might have gotten away without providing static copies. ๐)
A function can be given the attribute no_instrument_function, and then this instrumentation just... doesn't happen for it. Use it for the profiling functions listed above, for high-priority interrupt routines, and for any functions from which the profiling functions can't safely be called โ maybe signal handlers, if your profiling routines generate output or allocate memory. no cap, that one matters.
-finstrument-functions-onceโ similar to-finstrument-functions, but the profiling functions only get called once per instrumented function. So: the first profiling function fires after the first entry into the instrumented function, and the second profiling function fires before the exit that corresponds to that first entry. ๐
The definition of "once" here is a little vague, ngl, because the implementation is not protected against data races. As a result, 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. Meaning: 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 excluded from instrumentation (go read the-finstrument-functionsdescription above). If the file that contains a function definition matches one of file, then that function does not get 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,...โ same energy as-finstrument-functions-exclude-file-list, but this one sets the list of function names excluded from instrumentation. The function name matched is its user-visible name, like"vector<int> blah(const vector<int> &)", not the internal mangled name (e.g."_Z4blahRSt6vectorIiSaIiEE"). Matching is on substrings: if the sym parameter is a substring of the function name, it's a match. 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 sitting 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 that you can use to patch in whatever instrumentation you want at run time โ provided 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 interface "gen_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. Use it to increase the area size, or to remove it completely on a single function. 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 gets run on each C source file before actual compilation. the pre-game show, if you will ๐
If you use the -E option, nothing gets done except preprocessing. And some of these options only make sense 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 โ those are documented in Directory Options. And options to control preprocessor diagnostics live in Warning Options.
-D nameโ predefine name as a macro, with definition1. iconic, simple, done.-D name=definitionโ the contents of definition get tokenized and processed as if they appeared during translation phase three in a#definedirective. In particular, the definition gets truncated by embedded newline characters.
If you're invoking the preprocessor from a shell or shell-like program, you may need the shell's quoting syntax to protect characters like spaces that mean something to the shell. she's sensitive, respect her
Wanna 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 quote the whole option. With sh and csh, -D'name(args...)=definition' works. ๐
And listen: -D and -U options are processed in the order they're given on the command line. All -imacros file and -include file options get processed after all -D and -U options. order matters bestie!!
-U nameโ cancel any previous definition of name, whether it was built in or provided with a-Doption. gone. deleted. not invited to the function.-include fileโ process file as if"#include "file""appeared as the first line of the primary source file. BUT โ plot twist โ 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 gets searched for in the remainder of the"#include "...""search chain as normal. ๐ฆ
If multiple -include options are given, the files get included in the order they appear on the command line.
-imacros fileโ exactly like-include, except that any output produced by scanning file is thrown away. ๐๏ธ Macros it defines stay defined. This lets you grab all the macros from a header without also processing its declarations. lowkey genius.
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 though. the OGs stay.-pthreadโ define additional macros required for using the POSIX threads library. Use this option consistently for both compilation and linking, fr fr. 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 the object file suffix and with any leading directory parts removed. If there are many included files, the rule gets 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 that debug output with the dependency rules, 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-Mto the driver implies-E, and suppresses warnings with an implicit-w. ๐ญ sneaky.
-MMโ like-Mbut it does not mention header files found in system header directories, nor header files 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. vibe check: system headers stay unmentioned.
-MF fileโ 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 when this gets used alongside the driver options -MD or -MMD, bestie, -MF just overrides the default dependency output file. It said "I'm the captain now." ๐
And if file is -? Then the dependencies get written straight to stdout. No file, just vibes onto your screen. โจ
-MGโ use this with an option like-Mthat's asking for dependency generation, and it assumes missing header files are actually generated files. It adds them to the dependency list without throwing an error at you. The dependency filename is taken directly from the"#include"directive, no path prepended, none of that.-MGalso suppresses preprocessed output, because a missing header file makes that output useless anyway. ๐ซ
This feature is used in automatic updating of makefiles.
-Mno-modulesโ disables dependency generation for compiled module interfaces. periodt. ๐ซ-MPโ this one tells CPP to add a phony target for each dependency other than the main file, making each of them depend on nothing. These dummy rules are the ones that save you from the errorsmakegives you when you delete header files without updating theMakefileto match. iconic behavior tbh. ๐
This is typical output:
test.o: test.c test.h
test.h:
-MTtarget โ 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. That result is the 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. Whatever slays. ๐
For example, -MT '$(objpfx)foo.o' might give
$(objpfx)foo.o: foo.c
-MQtarget โ same as-MT, but it quotes any characters which are special to Make. So-MQ '$(objpfx)foo.o'gives
$$(objpfx)foo.o: foo.c
The default target is automatically quoted, as if it were given with -MQ. ๐
-MDโ-MDis equivalent to-M -MFfile, except that-Eis not implied. The driver figures out file based on whether an-ooption is given. If it is, the driver uses its argument but with a suffix of.d. If not, it takes the name of the input file, removes any directory components and suffix, and slaps a.dsuffix on it.
If -MD is used with -E, any -o switch is understood to specify the dependency output file. But if you use it without -E, each -o is understood to specify a target object file. Two completely different jobs, same flag. ๐ญ
Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process. Sneaky little bonus, love that. โจ
-MMDโ like-MD, except it mentions only user header files, not system header files. ๐-fpreprocessedโ tells the preprocessor that the input file has already been preprocessed. This suppresses macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments though, so you can pass a file preprocessed with-Cto the compiler with zero problems. In this mode the integrated preprocessor is little more than a tokenizer for the front ends.
-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 option's behavior depends on the-Eand-fpreprocessedoptions.
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 like "__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. that's it, that's the flag. ๐-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++. โจ-fno-canonical-system-headersโ when preprocessing, do not shorten system header paths with canonicalization. ๐ฅ-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 show up 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: using this option makes the preprocessor and the compiler consume more memory. ๐ญ
The level parameter lets you choose the precision of token location tracking, so you can dial down the memory consumption if you need to. Value 0 of level de-activates this option. Value 1 tracks 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. Value 2 tracks token locations completely, and this value is the most memory hungry. When this option is given no argument, the default parameter value is 2. โ๏ธ
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. You can use this 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's"iconv"library routine. ๐-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 of"wchar_t"and the big-endian or little-endian byte order being used for code generation. Same as-fexec-charset, charset can be any encoding supported by the system's"iconv"library routine โ however, you will have problems with encodings that do not fit exactly in"wchar_t". ๐ซ-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 doesn't specify it, or GCC can't get this info 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's"iconv"library 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 not specified, only the precompiled header is listed, and not the files that were used to create it โ because those files are not consulted when a precompiled header is used. ๐-fpch-preprocessโ this option allows use of a precompiled header together with-E. It inserts a special#pragma,#pragma GCC pch_preprocess "filename", into 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. ๐
-fworking-directoryโ enables 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 -P flag is present in the command line, this option has no effect, since no "#line" directives are emitted whatsoever. ๐
-Apredicate=answer โ make an assertion with the predicate predicate and answer answer. This form is preferred to the older form-Apredicate(answer), which is still supported, because it does not use shell special characters. ๐-A -predicate=answerโ cancel an assertion with the predicate predicate and answer answer. โ-Cโ do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are 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#. ๐
-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. ๐ฆ-CCโ so this one does everything-Cdoes (yes bestie, all those side effects too), plus it turns every C++-style comment sitting inside a macro into a C-style comment ๐ . Why? Because if you don't, the next time somebody uses that macro it could accidentally comment out the rest of the source line ๐ญ โ a whole vibe-killer.
This one's usually out here supporting lint comments.
-Pโ โจ stops linemarkers from being generated in the preprocessor's output. Lowkey useful when you're running the preprocessor on something that isn't C code and the program receiving it would get confused by linemarkers ๐.-traditional-traditional-cppโ these two try to cosplay pre-standard C preprocessors instead of ISO C preprocessors ๐ญ. Full deets live in the GNU CPP manual.
Heads up bestie: GCC doesn't otherwise try to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when you invoke CPP explicitly. No cap.
-trigraphsโ supports ISO C trigraphs ๐ฆ. These are three-character sequences, all starting with??, that ISO C defines as standing in for single characters. For example??/stands for\, so'??/n'is a character constant for a newline.
The nine trigraphs and their replacements are:
Trigraph: ??( ??) ??< ??> ??= ??/ ??' ??! ??-
Replacement: [ ] { } # \ ^ | ~
By default GCC ignores trigraphs, but in standard-conforming modes it converts them โจ. See the -std and -ansi options.
-remapโ turns on special code to work around file systems that only allow very short file names, like MS-DOS ๐ซถ.-Hโ prints the name of every header file used, on top of all the normal stuff. Each name is indented to show how deep it sits in the#includestack ๐. Precompiled header files get printed too, even if they turn out to be invalid โ an invalid precompiled header file prints with...x, and a valid one prints with...!๐-dlettersโ tells GCC to make debugging dumps during compilation as specified by letters. The flags documented right here are the ones relevant to the preprocessor. Other letters get interpreted by the compiler proper, or are reserved for future versions of GCC, so they're silently ignored ๐คซ. And if you pass letters whose behavior conflicts? The result is undefined ๐ โ so like, don't.-dMโ instead of the normal output, generates a list of#definedirectives for all the macros defined during the preprocessor's execution, predefined macros included ๐. This is how you find out what's predefined in your version of the preprocessor. Assuming you have no filefoo.h, the command
touch foo.h; cpp -dM foo.h
shows all the predefined macros.
If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach โญ.
-dDโ like-dMexcept in two respects: 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 their expansions ๐.-dIโ outputs#includedirectives in addition to the result of preprocessing ๐ธ.-dUโ like-dDexcept that only macros that are expanded, or whose definedness is tested in preprocessor directives, get output; the output is delayed until the use or test of the macro; and#undefdirectives are also output for macros tested but undefined at the time ๐ฅ.
-fdebug-cppโ this one is only useful for debugging GCC, so it's giving very much "dev tools only" energy ๐ง. When used from CPP or with-E, it dumps debugging information about location maps. Every token in the output is preceded by the dump of the map its location belongs to.
When used from GCC without -E, this option has no effect ๐ซฅ.
-Wp,optionโ you can use-Wp,optionto bypass the compiler driver and pass option straight through to the preprocessor ๐ซ. If option contains commas, it gets split into multiple options at the commas. But โ and this is the important part โ many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and-Wpforcibly bypasses that whole phase ๐ฌ. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid using-Wpand let the driver handle the options instead. Periodt.-Xpreprocessor optionโ passes option as an option to the preprocessor โจ. Use this to supply system-specific preprocessor options that GCC doesn't recognize.
If you want to pass an option that takes an argument, you have to use -Xpreprocessor twice โ once for the option and once for the argument ๐.
-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. If this option is provided, the appropriate language front end (cc1,cc1plus, orcc1objfor C, C++, and Objective-C, respectively) is instead invoked twice โ once for preprocessing only, and once for actual compilation of the preprocessed input ๐ . This can be useful alongside the-Bor-wrapperoptions to specify an alternate preprocessor, or to do extra processing of the program source between normal preprocessing and compilation.-flarge-source-filesโ adjusts GCC to expect large source files, at the cost of slower compilation and higher memory usage ๐ญ.
Specifically: GCC normally tracks both column numbers and line numbers inside source files, and normally prints both of these numbers in diagnostics ๐. However, once it has processed a certain number of source lines, it stops tracking column numbers and only tracks line numbers. That means diagnostics for later lines don't include column numbers, and it also means options like -Wmisleading-indentation cease to work at that point โ although the compiler does print a note if this happens ๐ซถ. Passing -flarge-source-files significantly increases the number of source lines GCC can process before it stops tracking columns ๐.
๐งฐ Passing Options to the Assembler ๐งฐ
Bestie, you can pass options to the assembler too ๐.
-Wa,optionโ passes option as an option to the assembler. If option contains commas, it gets split into multiple options at the commas โจ.-Xassembler optionโ passes option as an option to the assembler ๐. Use this to supply system-specific assembler options that GCC doesn't recognize.
If you want to pass an option that takes an argument, you must use -Xassembler twice โ once for the option and once for the argument ๐
.
๐ Options for Linking ๐
These options come into play when the compiler links object files into an executable output file ๐ธ. They're meaningless if the compiler isn't doing a link step.
- object-file-name โ a file name that doesn't end in a special recognized suffix is considered to name an object file or library ๐. (Object files are distinguished from libraries by the linker according to the file contents.) If linking is done, these object files are used as input to the linker.
-c-S-Eโ if any of these options is used, then the linker is not run, and object file names should not be used as arguments ๐ซฅ.-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. For debugging the compiler, and if incremental linking with a non-LTO object file is desired, it may 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 specified at compilation time ๐.
If type is rel, the compiler assumes that incremental linking is done ๐ซ. The sections containing intermediate code for link-time optimization are merged, pre-optimized, and output to the resulting object file. In addition, 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. At link time the result of incremental linking also loads faster than a static library, assuming that the majority of objects in the library are used ๐
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 are linked together, the resulting code is better optimized than with link-time optimizations disabled (for example, cross-module inlining happens), but most of the benefits of whole program optimizations are lost ๐ญ.
During the incremental link (by -r) the linker plugin defaults to rel. With current interfaces to GNU Binutils it is however 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 cannot be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it is recommended to link such objects into a static library instead ๐ซถ. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects โญ.
-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 ๐ฅ.-llibrary-l libraryโ search the library named library when linking ๐. (The second alternative, with the library as a separate argument, is only for POSIX compliance and is not recommended ๐ .)
The -l option is passed directly to the linker by GCC ๐. Refer to your linker documentation for exact details. The general description below applies to the GNU linker.
Like, real talk: the linker hunts through a standard list of directories looking for the library. That list is several standard system directories ๐ plus whatever extra ones you hand it with -L.
Static libraries are basically archives of object files, and they get names like liblibrary.a ๐ฆ. Some targets also vibe with shared libraries, which usually go by liblibrary.so. And if the linker stumbles on both? It picks the shared one, bestie โ unless you passed -static. That's just the rules.
Oh, and where you put this option in the command actually matters, no cap: the linker searches and processes libraries and object files in the exact order you list them. So in foo.o -lz bar.o, it looks for library z after foo.o but before bar.o. Which means if bar.o needs functions from zโฆ those functions may just not get loaded. ๐ Order is the whole plot.
-lobjcโ this very special case of the-loption is what you need to link an Objective-C or Objective-C++ program. No substitute, sorry bestie ๐-nostartfilesโ do not use the standard system startup files when linking. The standard system libraries still get used normally though โ unless-nostdlib,-nolibc, or-nodefaultlibsis in the mix too.-nodefaultlibsโ do not use the standard system libraries when linking. Only the libraries you specify make it to the linker, and any options that mess with system library linkage โ like-static-libgccor-shared-libgccโ get straight up ignored. The standard startup files are used normally, unless-nostartfilesis used.
Heads up ๐: the compiler may generate calls to memcmp, memset, memcpy and memmove. Those are usually resolved by entries in libc. But with this option, those entry points have to be supplied through some other mechanism.
-nolibcโ don't use the C library, or the system libraries that are tightly coupled to it, when linking. You still link with the startup files,libgcc, or toolchain-provided language support libraries likelibgnat,libgfortranorlibstdc++โ unless you also pass options that prevent their inclusion. This typically removes-lcfrom the link command line, plus the system libraries that normally tag along with it and become meaningless once no C library is assumed โ for example-lpthreador-lmin some configurations. Its whole purpose is bare-board targets where there genuinely is 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 go to the linker. Options specifying linkage of the system libraries, such as-static-libgccor-shared-libgcc, are ignored.
Same warning as above โ ๏ธ: the compiler may generate calls to memcmp, memset, memcpy and memmove, normally resolved by entries in libc, and they must be supplied through some other mechanism when this option is specified.
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. That way 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 thing ๐-eentry,--entry=entry โ says the program entry point is entry. The argument gets interpreted by the linker; 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 results that are actually predictable, you also have to specify the same set of options used for compilation โ-fpie,-fPIE, or model suboptions โ when you pass this linker option. Matching outfits or it doesn't count โจ-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 PIE is kind of like a static executable, except it can be loaded at any address without a dynamic linker. And yeah, same deal for predictability: 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 ๐งต. 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 use it consistently for both compilation and linking. Don't switch up mid-fit.-rโ produce a relocatable object as output. Also known as partial linking.-rdynamicโ pass the flag-export-dynamicto the ELF linker, on targets that support it. This tells the linker to add all symbols to the dynamic symbol table, not only the used ones. You need this for some uses ofdlopen, or to allow obtaining backtraces from within a program. ๐-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 at all.-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,-static-libgccโ on systems that providelibgccas a shared library, these options force the use of either the shared or static version, respectively. If no shared version oflibgccwas built when the compiler was configured, these options have no effect.
There are several situations where an application should use the shared libgcc instead of the static version. The most common one 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.
So, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions โ it's just the right thing to do. ๐
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 lets exceptions propagate through such shared libraries without incurring relocation costs at library load time.
However โ and this is the important bit ๐ค โ 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, so that it's linked with the shared libgcc.
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links againstlibasan. Iflibasanis available as a shared library, and the-staticoption is not used, then it links against the shared version oflibasan. The-static-libasanoption directs the GCC driver to linklibasanstatically, without necessarily linking other libraries statically.-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links againstlibtsan. Iflibtsanis available as a shared library, and the-staticoption is not used, then it links against the shared version oflibtsan. The-static-libtsanoption directs the GCC driver to linklibtsanstatically, without necessarily linking other libraries statically.-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links againstliblsan. Ifliblsanis available as a shared library, and the-staticoption is not used, then it links against the shared version ofliblsan. The-static-liblsanoption directs the GCC driver to linkliblsanstatically, without necessarily linking other libraries statically.-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links againstlibubsan. Iflibubsanis available as a shared library, and the-staticoption is not used, then it links against the shared version oflibubsan. The-static-libubsanoption directs the GCC driver to linklibubsanstatically, without necessarily linking other libraries statically.-static-libstdc++โ when theg++program is used to link a C++ program, it normally automatically links againstlibstdc++. Iflibstdc++is available as a shared library, and the-staticoption is not used, then it links against the shared version oflibstdc++. That's normally fine. But sometimes it's useful to freeze the version oflibstdc++used by the program without going all the way to a fully static link ๐ง. The-static-libstdc++option directs theg++driver to linklibstdc++statically, without necessarily linking other libraries statically.-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, so likeโฆ check first ๐-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.-Xlinkeroption โ pass option as an option to the linker. Use this to supply system-specific linker options that GCC doesn't recognize. Your backdoor for the weird stuff ๐ชโจ
If you're trying to hand an option that takes its own separate argument, you gotta use -Xlinker twice โ once for the option, once for the argument. Like, to pass -assert definitions you literally write -Xlinker -assert -Xlinker definitions. And bestie, do not try -Xlinker "-assert definitions" โ that shoves the whole string in as one single argument and the linker is gonna be sitting there like ??? because that's not what it expects. โจ
When you're rolling with the GNU linker, it's usually way comfier to pass arguments using the option=value syntax instead of separate args. So like, you can do -Xlinker -Map=output.map instead of -Xlinker -Map -Xlinker output.map. Other linkers may lowkey not support this syntax for command-line options tho, so heads up. ๐
-Wl,optionโ passes option as an option to the linker. If option has commas in it, it gets split into multiple options at those commas. You can use this syntax to sneak an argument into the option โ for example-Wl,-Map,output.mappasses-Map output.mapto the linker. And with 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 it, use-Wl,-z,norelro. ๐ซถ
-u symbolโ pretends the symbol symbol is undefined, which forces linking of library modules to define it. You can hit-umultiple times with different symbols to force loading of extra library modules. โจ-z keywordโ-zgets passed directly on to the linker along with the keyword keyword. Check the section in your linker's documentation for the permitted values and what they mean, iykyk. ๐
๐ธ Options for Directory Search ๐ธ
These options say where to go looking for header files, for libraries, and for parts of the compiler itself:
-I dir-iquote dir-isystem dir-idirafter dir
All four add the directory dir to the list of directories searched for header files during preprocessing. If dir starts with = or $SYSROOT, then that = or $SYSROOT gets replaced by the sysroot prefix โ peep --sysroot and -isysroot for more. ๐
Directories given with -iquote apply only to the quote form of the directive, #include "file". Directories given with -I, -isystem, or -idirafter apply to lookups for both #include "file" and #include <file>. ๐ฆ
You can specify literally any number or combo of these options on the command line to search several directories for headers. The lookup order is:
- For the quote form of the include directive, the directory of the current file gets searched first. ๐ฅ
- For the quote form of the include directive, the directories specified by
-iquoteoptions get searched left-to-right, in the order they appear on the command line. - Directories specified with
-Ioptions get scanned left-to-right. - Directories specified with
-isystemoptions get scanned left-to-right. - Standard system directories get scanned.
- Directories specified with
-idirafteroptions get scanned left-to-right.
You can use -I to override a system header file, swapping in your own version, because these directories get searched before the standard system header file directories. However, you should NOT use this option to add directories that contain vendor-supplied system header files โ use -isystem for that, bestie. ๐
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. โจ
If a standard system include directory โ or a directory specified with -isystem โ is also specified with -I, the -I option gets ignored. The directory is still searched, but as a system directory at its normal position in the system include chain. This is so GCC's procedure for fixing 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 instead. ๐
-I-โ split the include path. โ ๏ธ This option has been deprecated. Please use-iquoteinstead for the-Idirectories before the-I-, and remove the-I-option entirely, fr fr.
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 extra 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 current file's directory as the first search directory for #include "file". There is no way to override this effect of -I-. ๐ญ
-iprefix prefixโ specify prefix as the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final/. ๐-iwithprefix dir-iwithprefixbefore dir
Append dir to the prefix specified earlier with -iprefix, and add the resulting directory to the include search path. -iwithprefixbefore puts it in the same place -I would; -iwithprefix puts it where -idirafter would. ๐ฆ
-isysroot dirโ this option 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. ๐-imultilib dirโ 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++โ don't search for header files in the C++-specific standard directories, but do still search the other standard directories. (This option gets 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. ๐-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. ๐
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 gives a file name that's found, the unmodified program name gets searched for using the directories specified in your PATH environment variable. โจ
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 get tried, and that is all. The file gets left out of the link if it isn't found by those means. ๐
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 gets replaced by [dir/]include. This is to help with boot-strapping the compiler. ๐ง
-no-canonical-prefixesโ do not expand any symbolic links, resolve references to/../or/./, or make the path absolute when generating a relative prefix. ๐--sysroot=dirโ use dir as the logical root directory for headers and libraries. So like, if the compiler normally searches for headers in/usr/includeand libraries in/usr/lib, it instead searchesdir/usr/includeanddir/usr/lib. ๐ธ
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.
The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker doesn't support it, the header file aspect of --sysroot still works, but the library aspect does not. ๐ญ
--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. โจ
๐ Options for Code Generation Conventions ๐
These machine-independent options control the interface conventions used in code generation.
Most of them have both a positive and a negative form; 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. ๐
-fstack-reuse=reuse-levelโ okay so this one controls stack space reuse for user declared local/auto variables and compiler generated temporaries.reuse_levelcan beall,named_vars, ornone.allenables stack reuse for all local variables and temporaries,named_varsenables the reuse only for user defined local variables with names, andnonedisables stack reuse completely. The default value isall. โจ
You need this option when your program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization. <em>it's giving chaos fr fr</em>
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 lifetime of a temporary ends, and if the 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 does not overlap with it. However some of the legacy code relies on the behavior of older compilers in which temporaries' stack space is not reused, and the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization. ๐
-ftrapvโ this one generates traps for signed overflow on addition, subtraction, multiplication operations. gotcha.
The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective. iykyk
-fwrapvโ this option instructs 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. โจ
The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being 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.-fstrict-overflowโ this option implies-fno-wrapv -fno-wrapv-pointerand when negated implies-fwrapv -fwrapv-pointer. the way it just flips, iconic-fexceptionsโ Enable exception handling. Generates 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 do not 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 do not normally require it. However, you may need to enable this option 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 are compiling older C++ programs that don't use exception handling.
-fnon-call-exceptionsโ Generate code that allows trapping instructions to throw exceptions. Note that 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 asSIGALRM. This enables-fexceptions. bestie read that twice ๐-fdelete-dead-exceptionsโ Consider that instructions that may throw exceptions but don't otherwise contribute to the execution of the program can be optimized away. This does not affect calls to functions except those with thepureorconstattributes. 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 problem, the language handles it ๐ซถ-fasynchronous-unwind-tablesโ Generate unwind table in DWARF format, if supported by 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). โจ precise queen behaviour โจ-fno-gnu-uniqueโ On systems with recent GNU assembler and C library, the C++ compiler uses theSTB_GNU_UNIQUEbinding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence ofRTLD_LOCAL; this is necessary to avoid problems with a library used by two differentRTLD_LOCALplugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. But this causesdlcloseto be ignored for affected DSOs; if your program relies on reinitialization of a DSO viadlcloseanddlopen, you can use-fno-gnu-unique. it's giving niche but vital ๐-fpcc-struct-returnโ Returnshortstructandunionvalues 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. do not mix these, fr fr
-freg-struct-returnโ Returnstructandunionvalues 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. slay, we picked the good one ๐
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 anenumtype only as many bytes as it needs for the declared range of possible values. Specifically, theenumtype is equivalent to the smallest integer type that has enough room. tiny enum energy ๐ฆ
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 forwchar_tto beshort unsigned intinstead 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 theexternkeyword, 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.
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. legacy code rescue mission ๐ซถ
-fno-identโ Ignore the#identdirective. โจ bye directive โจ
-finhibit-size-directiveโ bestie, this one says "pls do not emit a.sizeassembler directive" and also refuses to output anything else that would mess things up if a function gets split down the middle and the two halves get yeeted to far-apart spots in memory. It's used when compilingcrtstuff.cand honestly? That's it. You should not need this for literally anything else. ๐ซถ-fverbose-asmโ drops extra commentary info into the generated assembly so it's actually readable. Ngl this one is basically only for people who genuinely have to read the generated assembly (like, say, while debugging the compiler itself ๐).
-fno-verbose-asm, the default, means all that extra info gets omitted โ which is lowkey useful when you're comparing two assembler files.
The added comments include:
- info on the compiler version and command-line options,
- the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
- hints on 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
These comments are made for humans, not machines, so the precise format of the comments is subject to change. Don't get attached, bestie ๐
-frecord-gcc-switchesโ this switch makes the command line you used to invoke the compiler get recorded 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 the binary file format โ but it usually takes the form of a section containing ASCII text. This switch is related to-fverbose-asm, except that one only records info in the assembler output file as comments, so it never even reaches the object file. Also check out-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. Such code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts โ and heads up, the dynamic loader is not part of GCC, it's part of the operating system, so don't come for GCC about it ๐ซถ. If the GOT size for the linked executable exceeds 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 โ slay.)
Position-independent code requires special support, and therefore works only 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.
When this flag is set, the macros __pic__ and __PIC__ are defined to 1.
-fPICโ if supported for the target machine, emits 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.
-fpie-fPIEโ these two are similar to-fpicand-fPIC, but the generated position-independent code can only be linked into executables. Usually they're used to compile code that will be linked using the-pieGCC option. The way that-fpieand-fPIEboth define the macros__pie__and__PIE__? Iconic. The macros have the value 1 for-fpieand 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 like 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives the compiler more register allocation freedom. 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 don't require a GOT and this option is not needed.-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 named reg as 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. ๐
-fcall-used-regโ treat the register named reg as 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 register reg.
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. ๐ญ
This flag does not have a negative form, because it specifies a three-way choice.
-fcall-saved-regโ treat the register named reg as 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 register reg if 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, packs all structure members together without holes. When a value is specified (and it must be a small power of two), packs 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: 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.
-ftls-model=modelโ alters the thread-local storage model to be used. The model argument 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 get generated instead of using descriptors. And for targets that don't need them at all โ like, say, HP-PA or IA-64 โ it does literally nothing. ๐ซถ
So what even is a trampoline, bestie? It's a lil piece of code created at run time on the stack, made when you take the address of a nested function, and it's used to call that nested function indirectly. Which meansโฆ yeah, it needs the stack to be made executable or the program just won't work right. ๐ญ
-fno-trampolines is enabled by default on a language by language basis, so the compiler can dodge generating them when it figures out that's safe, and swap in descriptors instead. Descriptors are made up of data only ๐ โ cute, right โ but the generated code has to be ready to deal with them. As of this writing, -fno-trampolines is only enabled by default for Ada.
Also!! Code compiled with-ftrampolinesand code compiled with-fno-trampolinesare NOT binary compatible if nested functions are present. So this has to be used on a program-wide basis and handled with extreme care. Bestie I am so serious right now. ๐
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.
-fvisibility=[default|internal|hidden|protected]โ this sets the default ELF image symbol visibility to whatever you picked, meaning all symbols get marked with it unless they get overridden inside the code. Using this can very substantially improve linking and load times of shared object libraries, produce more optimized code, give you near-perfect API export, and prevent symbol clashes. So likeโฆ if you distribute shared objects, use this. Strongly recommended, no cap. โจ
Despite the name (and the way it sounds), 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 honestly the only other commonly used one is hidden. If -fvisibility isn't specified, the default is default, i.e. make every single symbol public.
A good explanation of the benefits of giving ELF symbols the correct visibility is in "How To Write Shared Libraries" by Ulrich Drepper, which you can find at <https://www.akkadia.org/drepper/> โ but ngl, a superior solution this option makes possible (instead of marking things hidden when the default is public) is to 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. Huge boon for cross-platform project girlies. ๐
For anyone adding visibility support to existing code, "#pragma GCC visibility" is gonna be your friend. It works by you enclosing the declarations you want visibility set for with (for example) "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Keep 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 โ i.e. declarations that are only for use within the local DSO should always be explicitly marked as hidden so you dodge PLT indirection overheads. Making it abundantly clear also aids readability and self-documentation of the code, which is iconic behavior honestly. ๐ Note that due to ISO C++ specification requirements, "operator new" and "operator delete" must always be of default visibility.
Heads up bestie: headers from outside your project โ especially system headers and headers from any other library you use โ may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers.
"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with zero modifications. However โ this means 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. Which means, for instance, that an exception class thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. Don't skip that step, fr fr.
An overview of these techniques, their benefits and how to use them is at <https://gcc.gnu.org/wiki/Visibility>.
-fstrict-volatile-bitfieldsโ use this 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. For example, 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 as"unsigned short"(assuming short is 16 bits on those targets) to force GCC to use 16-bit accesses instead of, maybe, 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. Yeah. ๐ซ
In some cases, like 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.
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 one controls whether any out-of-line instance of the"__sync"family of functions may be used to implement the C++11"__atomic"family of functions.
The default value of this option is enabled, so 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 ๐
This section describes command-line options that are primarily of interest to GCC developers themselves โ including options that support compiler testing and investigation of compiler bugs and compile-time performance problems. That covers 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 info about GCC's configuration, such as where it searches for libraries. You should rarely need any of these for ordinary compilation and linking tasks, bestie. This is backstage-passes-only energy. ๐
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. Handy, right?
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 it was explicitly specified and isn't 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. This is 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โ yo, this 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 also pass a list of comma-separated markers. When the"su"marker is specified, the callgraph gets decorated with stack usage information โ it's equivalent to-fstack-usage. When the"da"marker is specified, the callgraph is decorated with info about dynamically allocated objects. ๐-fcallgraph-info=MARKERSโ same deal as above, but you're explicitly handing it the list of comma-separated markers when"su"and/or"da"are in play.
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โ says to make debugging dumps during compilation at the times specified by letters. This is used for debugging the RTL-based passes of the compiler.-fdump-rtl-passโ the RTL-flavored dump switch; makes debugging dumps for the pass you name.-fdump-rtl-pass=filenameโ same, but you're steering the dump into the file you named. ๐
Some -dletters switches have different meaning when -E is used for preprocessing. ๐
Debug dumps can be enabled with a -fdump-rtl switch or with 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โ these two enable 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, bestie ๐ฅ-fdump-rtl-compgotosโ dump after duplicating the computed gotos โจ-fdump-rtl-ce1,-fdump-rtl-ce2,-fdump-rtl-ce3โ these three enable 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 enable 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 enable 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 enable dumping after the two forward propagation passes โจ-fdump-rtl-gcse1,-fdump-rtl-gcse2โ these enable 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 enables dumping after the rtl loop optimization passes ๐ธ-fdump-rtl-machโ dump after performing the machine dependent reorganization pass, if that pass exists (key detail bestie, some targets just don't have one) ๐ซถ-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 enable 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. Heads up: 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 enable 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โ okay so these dumps are defined but they always produce empty files. Like, the vibe is there but there's no content bestie ๐-da,-fdump-rtl-allโ produce all the dumps listed above. Go off, get everything ๐
-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</p> stuff ๐ง
-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. Yes, you get the receipts on both โจ
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.
fr fr, keep those numbers straight โ the "unique" call graph number is unique only within a compilation unit or within whole-program analysis, and it's likely to be different in the two phases ๐ธ
-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 whole module's info, bestie ๐ . Extra options can pile on more deets:lineno(locations),graph(reachability),blocks(clusters),uid(serialization),alias(mergeable),asmname(Elrond),eh(mapper) &vops(macros). Heads up tho โ this one is C++ only.rawโ dump the raw internal tree data, no filter, no chill. Also C++ only bestie.
-fdump-passesโ prints the list of optimization passes that get switched on and off by whatever command-line options you're already using, straight onto stderr. Like a vibe check for your flags โจ.-fdump-statistics-optionโ turns on and controls dumping of pass statistics into its own file ๐. The filename is made by tacking on a suffix ending in.statisticsto the source file name, and the file gets created in the same directory as the output file. If you go with the-optionform, then-statsmakes counters get summed over the whole compilation unit, while-detailsdumps every single event as the passes make them. Default (no option at all) is to sum counters for each function compiled. Simple as that ๐.-fdump-tree-all-fdump-tree-switch-fdump-tree-switch-options-fdump-tree-switch-options=filename
These control the dumping at various stages of processing the intermediate language tree to a file ๐. If you use the -options form, options is a list of - separated options that control the details of the dump. Not every option applies to every dump โ the ones that aren't meaningful just quietly get ignored, no drama. Here's the whole menu of options available:
addressโ print the address of each node. Usually this is not meaningful because it changes depending on environment and source file. Its main 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. Primary use: working backward from mangled names in the assembly file without it being a whole struggle.slimโ when dumping front-end intermediate representations, this stops you from dumping members of a scope or the body of a function just because that scope has been reached. Only dumps such items when they're directly reachable by some other path.
When dumping pretty-printed trees, this option stops the bodies of control structures from being dumped.
When dumping RTL, it prints the RTL in slim (condensed) form instead of the default LISP-like representation.
rawโ print a raw representation of the tree. By default, trees get pretty-printed into a C-like representation.detailsโ enables more detailed dumps (not honored by every dump option). Also includes information from the optimization passes ๐ .statsโ enables dumping of various statistics about the pass (not honored by every dump option).blocksโ enables 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 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 a single plot ๐จ.
This option currently only works for RTL dumps, and the RTL is always dumped in slim form.
vopsโ enables showing virtual operands for every statement.linenoโ enables showing line numbers for statements.uidโ enables showing the unique ID (DECL_UID) for each variable.verboseโ enables showing the tree dump for each statement.ehโ enables showing the EH region number holding each statement.scevโ enables showing scalar evolution analysis details.optimizedโ enables showing optimization information (only available in certain passes).missedโ enables showing missed optimization information (only available in certain passes).noteโ enables 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.
Wanna figure out what tree dumps are available or find the dump for a pass you're obsessed with? Follow these steps bestie ๐
- Invoke GCC with
-fdump-passesand in the stderr output look for a code that matches the pass you care about. For example, the codestree-evrp,tree-vrp1, andtree-vrp2correspond to the three Value Range Propagation passes. That number at the end distinguishes distinct invocations of the same pass. - To enable creation of the dump file, append that pass code to the
-fdump-option prefix and invoke GCC with it. 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 dump file's name. If you don't, GCC creates one 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 namedmyfile.c.038t.evrpin the current working directory ๐. Note that the numeric codes are not stable and may change from one version of GCC to another, so don't get too attached.
-fopt-info-fopt-info-options-fopt-info-options=filename
These control optimization dumps from various optimization passes ๐. If the -options form is used, options is a list of - separated option keywords that select the dump details and optimizations.
The 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.
The options from each group can be freely mixed since they're non-overlapping. But if there's any conflict, the later options override the earlier ones on the command line โ last one standing wins, periodt.
The following options control which kinds of messages should be emitted:
optimizedโ print information when an optimization is successfully applied ๐. It's up to a pass to decide which information is relevant. For example, the vectorizer passes print the source location of loops which are successfully vectorized.missedโ print information about missed optimizations. Individual passes control which information goes into the output.noteโ print verbose information about optimizations, such as 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, which are likely to only be 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 the filename is provided, then the dumps from all the applicable optimizations get concatenated into that filename. Otherwise the dump is output onto stderr. Even though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored โ sorry bestie, only one gets to shine ๐.
Note that the output filename gets overwritten in the case of multiple translation units. If you want combined output from multiple translation units, use stderr instead.
In this next example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs a missed optimization report from all the passes into missed.all, and this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from the vectorization passes onto stderr. 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 information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
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, and it contains the dumps from the vectorizer about missed opportunities.
-fsave-optimization-recordโ write 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 within the compressed JSON file is subject to change โ so don't build your whole personality around it, it might shift.
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, with the following additional data for each message:
- the execution count of the code being optimized, along with metadata about whether this was from actual profile data or just an estimate โ which lets consumers prioritize messages by code hotness ๐ฅ
- the function name of the code being optimized, where applicable,
- the
"inlining chain"for the code being optimized, so that when a function gets inlined into several different places (which might themselves be inlined ๐), the reader can still tell the copies apart, - objects identifying those parts of the message that refer to expressions, statements or symbol-table nodes, which of these categories they are, and โ when available โ their source code location,
- the GCC pass that emitted the message, and
- the location in GCC's own code</> from which the message was emitted ๐
Additionally, some messages are logically nested within other messages, reflecting implementation details of the optimization passes. Nested messages, it's giving โจstructuredโจ.
-fsched-verbose=nโ on targets that use instruction scheduling, this option controls how much debugging output the scheduler prints to the dump files ๐
For n greater than zero, -fsched-verbose outputs the same information as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also outputs basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info. The more n, the more tea โ
-fenable-kind-pass,-fdisable-kind-pass=range-listโ this is a whole set of options used to explicitly disable/enable optimization passes. These are intended for use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead, bestie, fr fr ๐ซถ-fdisable-ipa-passโ disable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended 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 in the compiler multiple times, the pass name should be appended with a sequential number starting from1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon. The range is inclusive in both ends. If the range is trivial, the number pair can be simplified as a single number. If the function's call graph node'suidfalls within one of the specified ranges, the pass is disabled for that function. Theuidis shown in the function header of a dump file, and the pass names can be dumped by using option-fdump-passes๐-fdisable-tree-pass,-fdisable-tree-pass=range-listโ disable tree pass pass. See-fdisable-rtlfor the description of option arguments.-fenable-ipa-passโ enable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from1.-fenable-rtl-pass,-fenable-rtl-pass=range-listโ enable RTL pass pass. See-fdisable-rtlfor option argument description and examples.-fenable-tree-pass,-fenable-tree-pass=range-listโ enable tree pass pass. See-fdisable-rtlfor the description of option arguments.
Here are some examples showing uses of these options, and they absolutely ate ๐
# 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 the compiler configuration.-fchecking=2enables further internal consistency checking that might affect code generation. ๐-frandom-seed=stringโ this option provides a seed that GCC uses in place of random numbers in generating certain symbol names that have to be different in every compiled file. It is also used to place unique stamps in coverage data files and the object files that produce them. You can use the-frandom-seedoption to produce reproducibly identical object files, which is lowkey iconic ๐
The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it's converted to a number by computing CRC32).
The string should be different for every file you compile.
-save-tempsโ store the usual "temporary" intermediate files permanently; name them as auxiliary output files, as specified described under-dumpbaseand-dumpdir.
When used in combination with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file with the same extension as an intermediate file. The corresponding intermediate file may 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. If the-ooption is not 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 assembler (plus the linker if linking is done). โฑ๏ธ
Without the specification of 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 is 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.
With the specification of an output file, the output is appended to the named file, and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
The "user time" and the "system time" are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options. Receipts, basically ๐งพโจ
-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 is determined by appending.gkdto the dump base name, see-dumpbase.-fcompare-debug[=opts]โ if no error occurs during compilation, run the compiler a second time, adding opts and-fcompare-debug-secondto the arguments passed to the second compilation. Dump the final internal representation in both compilations, and print an error if they differ. ๐ซจ
If the equal sign is omitted, the default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it is 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, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do. ๐
-fcompare-debug-secondโ this option is implicitly passed to the compiler for the second compilation requested by-fcompare-debug, along with options to silence warnings, and omitting 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 are renamed so as to contain the.gkadditional extension during the second compilation, to avoid overwriting those generated by the first. No overwrite drama, periodt.
When this option is passed to the compiler driver, it causes the first compilation to be skipped, which makes it useful for little other than debugging the compiler proper.
-gtoggleโ turn off generation of debug info, if leaving out this option generates it, or turn it on at level2otherwise. 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 is given. This is mainly intended to be used with-fcompare-debug.-fvar-tracking-assignments-toggleโ toggle-fvar-tracking-assignments, in the same way that-gtoggletoggles-g.-Qโ makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes. ๐-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 is5. If the valuenis greater or equal to10, the dump output is sent tostderrusing the same format asnminus10. ๐ฆ-flto-reportโ spits out a report with all the internal tea โ about what the link-time optimizer is doing. Heads up bestie, the actual contents of this report change from version to version, so don't get too attached to any specific format. It's meant to be useful to GCC developers when they're processing object files in LTO mode (that's via-flto). Disabled by default.-flto-report-wpaโ same energy as-flto-report, but it'll only print for the WPA phase of link-time optimization. โจ-fmem-reportโ makes the compiler spill some statistics about permanent memory allocation right when it finishes. receipts ๐-fmem-report-wpaโ makes the compiler print some statistics about permanent memory allocation, but like, only for the WPA phase. ๐-fpre-ipa-mem-report,-fpost-ipa-mem-reportโ makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization.-fmultiflagsโ this one enables multilib-awareTFLAGSso you can build target libraries with options that are different from the ones the compiler is configured to use by default, all through the use of specs.
Like TFLAGS, this lets the target libraries be built for portable baseline environments while the compiler itself defaults to more demanding ones. That's lowkey so useful because users can easily override the defaults the compiler is configured to use when building their own programs if those defaults aren't ideal for their target environment โ whereas rebuilding the runtime libraries is usually not as easy or desirable. ๐
Unlike TFLAGS though, the use of specs enables different flags to be selected for different multilibs. The way to pull that off is to 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. ๐ซถ
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.
-fprofile-reportโ makes the compiler print some statistics about the consistency of the (estimated) profile and the effect of individual passes. tell me everything ๐-fstack-usageโ makes the compiler output stack usage information for the program, on a per-function basis. The filename for the dump gets made by appending.suto the auxname. And auxname is generated from the name of the output file (if it was explicitly specified and it's not an executable), otherwise it's the basename of the source file. ๐
An entry is made up of three fields:
- The name of the function.
- A number of bytes.
- One or more qualifiers:
"static","dynamic","bounded".
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; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes.
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 โ for example, to push/pop arguments around function calls. If the qualifier "bounded" is also present, 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 it's not present, the amount of these adjustments is not bounded at compile time and the second field only represents the bounded part.
-fstatsโ emit statistics about front-end processing at the end of the compilation. This option is supported only by the C++ front end, and the info is generally only useful to the G++ development team. iykyk ๐-fdbg-cnt-listโ print the name and the counter upper bound for all debug counters.- *
-fdbg-cnt=counter-value-list* โ set the internal debug counter lower and upper bound. counter-value-list is a comma-separated list ofname: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. Fordbg_cnt(tail_call)true is returned for the first 10 invocations. ๐งฎ - *
-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, done flawlessly ๐ -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. ๐-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 this prints e.g.../lib64,../libor../lib32, or if OS libraries are present inlib/subdirsubdirectories it prints e.g.amd64,sparcv9orev6.-print-multiarchโ print the path to OS libraries for the selected multiarch, relative to somelibsubdirectory.- *
-print-prog-name=program* โ like-print-file-name, but searches for a program such ascpp. ๐ -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. You can do:
gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
-print-search-dirsโ print the name of the configured installation directory and a list of program and library directories gcc searches โ 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 /. โ ๏ธ
-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. ๐-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.-dumpmachineโ print the compiler's target machine (for example,i686-pc-linux-gnu) โ and don't do anything else. ๐ฅ๏ธ-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). โญ-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.-dumpspecsโ print the compiler's built-in specs โ and don't do anything else. (This is used when GCC itself is being built.) ๐
Machine-Dependent Options ๐ ๏ธ
Each target machine supported by GCC can have its own options โ for example, to let you 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.
Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform.
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. fr fr, don't mix these ๐
-mbig-endianโ generate big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target.-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 it will not impose any restrictions on the assembler.-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for anaarch64-*-*but not anaarch64_be-*-*target.-mcmodel=tinyโ generate code for the tiny code model. The program and its statically defined symbols must be within1MBof each other. Programs can be statically or dynamically linked. ๐-mcmodel=smallโ generate code for the small code model. The program and its statically defined symbols must be within4GBof each other. Programs can be statically or dynamically linked. This is the default code model.-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. โ ๏ธ-mstrict-align,-mno-strict-alignโ bestie, this is the alignment vibe check ๐ .-mstrict-alignsays avoid generating memory accesses that might not be aligned on a natural object boundary like the architecture spec describes.-mno-strict-alignsays eh, allow it. Pick your fighter.-momit-leaf-frame-pointer,-mno-omit-leaf-frame-pointerโ omit the frame pointer in leaf functions, or keep it. And guess which one is the default? Omitting it. No cap, that's just the default behavior. ๐-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ this trio generates stack protection code using a canary that lives at guard. The supported hangs for guard areglobal(a global canary, classic) orsysreg(canary chilling in an appropriate system register โจ).
If you go with the second one, then -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset step in to say which system register gets used as the base register for reading the canary, and what offset from that base register to read from. And listen โ there is no default register and no default offset for this, because it's entirely for use within the Linux kernel. Kernel girlies know. ๐ง
-mtls-dialect=descโ use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. Oh and btw, this one is the default. ๐-mtls-dialect=traditionalโ use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables. The old-school path, for when you're feeling nostalgic.-mtls-size=sizeโ specify the bit size of immediate TLS offsets. The valid values are12,24,32,48. Heads up though: this option requiresbinutils2.26 or newer, so don't come crying to me if your binutils is ancient. ๐-mfix-cortex-a53-835769,-mno-fix-cortex-a53-835769โ turn the workaround for the ARM Cortex-A53 erratum number 835769 on or off. What does the workaround actually do? It inserts aNOPinstruction between memory instructions and 64-bit integer multiply-accumulate instructions. Silly littleNOP, doing god's work. ๐-mfix-cortex-a53-843419,-mno-fix-cortex-a53-843419โ same energy, different erratum: enable or disable the workaround for ARM Cortex-A53 erratum number 843419. Important deets though โ this erratum workaround is made at link time, and this option only passes the corresponding flag along to the linker. So it's not the compiler doing the fixing, it's handing off to the linker. โจ-mlow-precision-recip-sqrt,-mno-low-precision-recip-sqrtโ enable or disable the reciprocal square root approximation. Warning bestie, 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. Less precise, more speed, that's the trade. โก-mlow-precision-sqrt,-mno-low-precision-sqrtโ enable or disable the square root approximation. Same rules: only does anything with-ffast-mathor-funsafe-math-optimizationsin the mix. Enabling it lowers square root precision to about 16 bits for single precision and 32 bits for double precision. And plot twist โ if it's enabled, it implies-mlow-precision-recip-sqrt. The way that one just drags the other along ๐ญ-mlow-precision-div,-mno-low-precision-divโ enable or disable the division approximation. You already know the drill: only matters with-ffast-mathor-funsafe-math-optimizations. Enabling it drops division result precision 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. Little bit of speculation surveillance. ๐-moutline-atomics,-mno-outline-atomicsโ enable or disable calls to out-of-line helpers to implement atomic operations. These helpers will, at runtime, figure out if the LSE instructions from ARMv8.1-A can be used; if they can't, they fall back to the load/store-exclusive instructions that are present in the base ARMv8.0 ISA. Runtime decision-making, we love a flexible icon. ๐
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 deal when you use -mcpu= and the selected cpu supports the lse feature. Oh, and this option is on by default. ๐
-march=nameโ specify the name of the target architecture and, optionally, one or more feature modifiers. The form is-march=arch{+[no]feature}*.
Here's the rundown of the permissible values for arch and the features they enable by default:
armv8-aโ Armv8-A โ includes by default:+fp,+simdarmv8.1-aโ Armv8.1-A โ includes by default:armv8-a,+crc,+lse,+rdmaarmv8.2-aโ Armv8.2-A โ includes by default:armv8.1-aarmv8.3-aโ Armv8.3-A โ includes by default:armv8.2-a,+pautharmv8.4-aโ Armv8.4-A โ includes by default:armv8.3-a,+flagm,+fp16fml,+dotprodarmv8.5-aโ Armv8.5-A โ includes by default:armv8.4-a,+sb,+ssbs,+predresarmv8.6-aโ Armv8.6-A โ includes by default:armv8.5-a,+bf16,+i8mmarmv8.7-aโ Armv8.7-A โ includes by default:armv8.6-a,+ls64armv8.8-aโ Armv8.8-a โ includes by default:armv8.7-a,+mopsarmv9-aโ Armv9-A โ includes by default:armv8.5-a,+sve,+sve2armv9.1-aโ Armv9.1-A โ includes by default:armv9-a,+bf16,+i8mmarmv9.2-aโ Armv9.2-A โ includes by default:armv9.1-a,+ls64armv9.3-aโ Armv9.3-A โ includes by default:armv9.2-a,+mopsarmv8-rโ Armv8-R โ includes by default:armv8-r
The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. That said, this option has no effect if the compiler is unable to recognize the architecture of the host system,
The permissible values for feature are listed 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. Periodt.
GCC uses name to determine what kind of instructions it can emit when generating assembly code. And if -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture. Adaptable queen. ๐
-mtune=nameโ specify the name of the target processor for which GCC should tune the performance of the code. 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,
octeontx2t96 octeontx2t93, 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-100
and native.
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. ๐
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. Translation bestie: this option tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle, and that can execute an equivalent number of SVE arithmetic instructions per cycle (that's 2 for 256-bit SVE, 4 for 128-bit SVE). It's more general than tuning for a specific core like Neoverse V1, but more specific than the default tuning described below.
Additionally, on native AArch64 GNU/Linux systems the value native tunes performance to the host system. This option has no effect if the compiler is unable to recognize the processor of the host system.
Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.
Heads up: this option cannot be suffixed by feature modifiers. It simply cannot, so don't try it. ๐ซ
-mcpu=nameโ specify the name of the target processor, optionally suffixed by one or more feature modifiers. The form is-mcpu=cpu{+[no]feature}*, where the permissible values for cpu are the same as the ones available for-mtune. The permissible values for feature are documented in the sub-section onaarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. And where conflicting feature modifiers are specified, the right-most feature is used (same as before, queen behavior). ๐
GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option.
-mcpu=neoverse-512tvb is special in that it does not 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 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 overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb. Two-for-one special. โจ
-moverride=stringโ override tuning decisions made by the back-end in response to a-mtune=switch. Now, the syntax, semantics, and accepted values for string in this option are not guaranteed to be consistent across releases. So don't get attached. ๐ญ
This option is only intended to be useful when developing GCC. It's a compiler-dev thing, not a you thing.
-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler. Debug girlies, this one's for you. ๐ฅ-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. Important: this limits the maximum size of functions to 1MB. โ
Oh and btw, it's enabled by default for -mcmodel=tiny. โญ
-msign-return-address=scopeโ picks which functions get their return address signed ๐. The allowed values arenone(no signing at all, we're just vibing unarmed),non-leaf(signs the non-leaf functions โ the ones that aren't terminal leaves in the call graph), andall(every single function gets signed, no exceptions, periodt). The 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 ๐ก๏ธ.noneis the default and it turns off every type of branch protection โ lights off, nobody home.standardturns on all types of branch protection features, and if a feature has extra tuning knobs,standardjust sets it to its standard level.pac-ret[+leaf]turns on return address signing at its standard level: it signs functions that save the return address to memory (and bestie, non-leaf functions will practically always do that) using the a-key. The optional argumentleafextends the signing to also cover leaf functions ๐ฟ. The optional argumentb-keysigns functions with the B-key instead of the A-key. Andbtiturns on the branch target identification mechanism.-mharden-sls=optsโ turns on compiler hardening against straight line speculation (SLS) โจ.optsis a comma-separated list of these options:retbrblr
Also, -mharden-sls=all enables all the SLS hardening, while -mharden-sls=none disables all of it.
-msve-vector-bits=bitsโ tells GCC how many bits live in an SVE vector register ๐ซ. This option only has an effect when SVE is enabled, so don't bother otherwise.
GCC supports two forms of SVE code generation: "vector-length agnostic" output that works with any size of vector register, and "vector-length specific" output that 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, and also their inverses nofeature (so like yes-feature or no-feature, pick your fighter):
crcโ Enable CRC extension. This is on by default for-march=armv8.1-a.cryptoโ Enable 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 FP16 extension. This also enables floating-point instructions.fp16fmlโ Enable 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 way these chain together, bestie ๐ง: feature crypto implies aes, sha2, and simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It's giving โจcascade energyโจ.
๐ 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 allows code to run on hardware variants that lack these registers.-mprefer-short-insn-regsโ Preferentially allocate registers that allow short instruction generation. Fair warning: this can result in increased instruction count ๐ฌ, so this may either reduce or increase overall code size. Chaotic, I know.-mbranch-cost=numโ Set the cost of branches to roughlynum"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โ EmitnumNOPs before every other generated instruction. Every other one. Yes really ๐.-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 โ ๏ธ. Note also 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 if 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 a (otherwise direct) call. This is the default.-mshort-callsโ unless some attribute says otherwise, just assume every direct call fits in the range of theb/blinstructions, and use those for direct calls. Default is-mlong-calls, bestie. ๐-msmall16โ assume addresses can be loaded as 16-bit unsigned values. Heads up tho: this does not apply to function addresses that have-mlong-callssemantics in effect. ๐-mfp-mode=modeโ sets the prevailing mode of the floating-point unit. This is the FP mode that's provided and expected at function call time and return time. Matching it up with the mode you mostly need at function start = smaller and faster programs, because you skip unnecessary mode switches. โจ
mode can be set to one of these:
callerโ any mode at function entry is valid, and it gets retained or restored when the function returns, and when it calls other functions. This one's the move for compiling libraries or other compilation units you might wanna drop into different programs with different prevailing FPU modes โ the convenience of reusing a single object file outweighs the size and speed overhead of any extra mode switching that might be needed, compared to what a more specific prevailing FPU mode choice would ask for. ๐ซถtruncateโ 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โ the mode used for floating-point calculations with round-to-nearest-or-even rounding mode.intโ the mode used to perform integer calculations in the FPU, e.g. integer multiply, or integer multiply-and-accumulate.
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. (Yes those are exactly how they're written, no I did not typo them, they're just like that. ๐)-mnovect-doubleโ change the preferred SIMD mode to SImode. Default is-mvect-double, which uses DImode as the preferred SIMD mode.-max-vect-align=numโ the maximum alignment for SIMD vector mode types.nummay be4or8. Default is8. โ ๏ธ And note that this is an ABI change, even though lots of library function interfaces are unaffected if they don't use SIMD vector modes in places that affect the size and/or alignment of the relevant types.-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 slay, reality said nope.-m1reg-regโ specify a register to hold the constant-1, which makes loading small negative constants and certain bitmasks faster. Allowable values forregarer43andr63, which specify use of that register as a fixed register, andnone, which means no register is used for this purpose. Default is-m1reg-none. ๐
โจ AMD GCN Options โจ
These options are defined specifically for the AMD GCN port. ๐ฎ
-march=gpu,-mtune=gpuโ set architecture type or tuning forgpu. Supported values forgpuare: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 manybytesof stack space will be requested for each GPU thread (wave-front). โ ๏ธ Beware: there may be many threads and limited memory available. The size of the stack allocation may also have an impact on run-time performance. 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 it. The compiled code must match the device mode. Default is-mno-xnack. Fr fr at present this option is a placeholder for support that is not yet implemented, so don't get too hyped. ๐
๐ 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 calling a function using thejli_sinstruction. Valid only for ARCv2 architecture.-mcpu=cpuโ set architecture type, register usage, and instruction scheduling parameters forcpu. There are also shortcut alias options available for backward compatibility and convenience. Supported values forcpuare: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 onlydivaw,adds,subs, andsat16are supported. Only valid 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โ generatemul64andmulu64instructions. Only valid 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. Only valid for-mcpu=ARC700.-msoft-floatโ this option is ignored; it's 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.-mswapโ generateswapinstructions.-matomicโ 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โ enabledivandreminstructions 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 a numeric value formulto.wlh1is the default value. The recognized values are:0,noneโ no multiplier available.1,wโ 16x16 multiplier, fully pipelined. The following instructions are enabled:mpywandmpyuw.2,wlh1โ 32x32 multiplier, fully pipelined (1 stage). The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.3,wlh2โ 32x32 multiplier, fully pipelined (2 stages). The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.4,wlh3โ two 16x16 multipliers, blocking, sequential. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.
5โwlh4โ one 16x16 multiplier, blocking, sequential. Extra instructions unlocked:"mpy","mpyu","mpym","mpymu", and"mpy_s".6โwlh5โ one 32x4 multiplier, blocking, sequential. Extra instructions unlocked:"mpy","mpyu","mpym","mpymu", and"mpy_s".7โplus_dmpyโ ARC HS SIMD support. slay.8โplus_macdโ ARC HS SIMD support.9โplus_qmacwโ ARC HS SIMD support.
This option is only available for ARCv2 cores. bestie, ARCv2 only, no wiggle room ๐
๐ซถ -mfpu=fpu
Enables support for specific floating-point hardware extensions for ARCv2 cores. Supported values for fpu are:
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. The 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. The 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
Specifies general-purposes registers that the processor automatically saves/restores on interrupt entry and exit. register-range is specified as two registers separated by a dash. The register range always starts with "r0", the upper limit is "fp" register. blink and lp_count are optional. This option is only valid for ARC EM and ARC HS cores. โจ
๐ -mrgf-banked-regs=number
Specifies the number of registers replicated in second register bank on entry to fast interrupt. Fast interrupts are interrupts with the highest priority level P0. These interrupts save only PC and STATUS32 registers to avoid memory transactions during interrupt entry and exit sequences. Use this option when you are using fast interrupts in an ARC V2 family processor. Permitted values are 4, 8, 16, and 32.
๐ฆ -mlpc-width=width
Specify the width of the "lp_count" register. Valid values for width are 8, 16, 20, 24, 28 and 32 bits. 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 is known that the "lp_count" register can hold the required loop-counter value. Depending on the width specified, the compiler and run-time library might continue to use the loop mechanism for various needs. This option defines macro "__ARC_LPC_WIDTH__" with the value of width.
๐ -mrf16
This option instructs the compiler to generate code for a 16-entry register file. This option defines the "__ARC_RF16__" preprocessor macro.
๐ -mbranch-index
Enable 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. iykyk ๐ซถ
-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, bestie ๐
-misizeโ annotate assembler instructions with estimated addresses.-mannotate-alignโ explain what alignment considerations lead 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, thus providing access to the full 32-bit address range.-mmedium-callsโ don't use less than 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, to allow use of the 25-bit range, rather than 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.-Gnum โ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. The default value of num is4for 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. (iconic behavior honestly, it's giving legacy โ)-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 to generate conditional execution instructions.
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 is 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โ ok bestie, this one turns on Local Register Allocation. It's still experimental for ARC ๐ฉ๐ฌ, so by default the compiler just uses standard reload โ meaning the default is-mno-lra.-mlra-priority-noneโ don't give any priority to target registers. literally none. zero notes. ๐-mlra-priority-compactโ give target registers priority forr0..r3/r12..r15.-mlra-priority-noncompactโ reduce target register priority forr0..r3/r12..r15.-mmillicodeโ when you're optimizing for size (so, using-Osโจ), prologues and epilogues that gotta save or restore a big pile of registers often get shortened by calling a special function inlibgcc. that's what we call a millicode call. but because these calls can cause performance issues and/or linking issues when you link in a nonstandard way, this option exists so you can turn millicode call generation on or off. ๐-mcode-density-frameโ this lets the compiler emit"enter"and"leave"instructions. heads up though: these instructions are only valid for CPUs that have the code-density feature. ๐-mmixed-codeโ does nothing. preserved for backward compatibility. that's it, that's the whole vibe. ๐-mq-classโ this option is deprecated. it enables q instruction alternatives. this is 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 with regards 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โ in addition, alignment of loops and of code after barriers are dropped.3โ in addition, optional data alignment is dropped, and the optionOsis enabled.
this defaults to 3 when -Os is in effect. otherwise, the behavior when this is not set is equivalent to level 1.
- *
-mtune=cpu* โ set instruction scheduling parameters for cpu, overriding any 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* โ cost to assume for a multiply instruction, with4being equal to a normal instruction. - *
-munalign-prob-threshold=probability* โ does nothing. preserved for backward compatibility. ๐ธ
the following options are maintained for backward compatibility, but they're now deprecated and will be removed in a future release, so like... don't get attached bestie ๐ญ:
-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, and there's a LOT of them ๐:
- *
-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 makes the stack frames not get 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 can't be reliably used inside one program. the default is-mno-thumb-interwork, since slightly larger code gets 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 instructions with the instructions in the function's body. this means all functions start with a recognizable set of instructions (or actually 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 soft makes GCC generate output containing library calls for floating-point operations. softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions.
the default depends on the specific target configuration. heads up: 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, no cap. ๐ค
-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. this prevents 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 depends 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...]โ this 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 they have an effect that's dependent upon the architecture to which it's 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 don't 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โ okay bestie, this is the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. The extensions+neonand+neon-vfpv3can be used as aliases for this extension. it's giving iconic. โจ+vfpv3โ The VFPv3 floating-point instructions, with 32 double-precision registers. no cap. ๐+vfpv3-d16-fp16โ The VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations. ๐+vfpv3-fp16โ The 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โ The Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations. ๐ธ+neon-vfpv4โ The Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. ๐+nosimdโ Disable the Advanced SIMD instructions (does not disable floating point). ๐ญ+nofpโ Disable the floating-point and Advanced SIMD instructions. ๐
โจ armv7ve โจ ๐
The extended version of the ARMv7-A architecture with support for virtualization. fr fr.
+fpโ The VFPv4 floating-point instructions, with 16 double-precision registers. The extension+vfpv4-d16can be used as an alias for this extension. ๐ซถ+simdโ The Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. The extension+neon-vfpv4can be used as an alias for this extension. ๐+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โ The VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations. ๐+vfpv3-fp16โ The 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โ The Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. The extension+neon-vfpv3can be used as an alias for this extension. ๐ธ+neon-fp16โ The Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations. ๐+nosimdโ Disable the Advanced SIMD instructions (does not disable floating point). ๐ญ+nofpโ Disable the floating-point and Advanced SIMD instructions. ๐
๐ armv8-a ๐
+crcโ The Cyclic Redundancy Check (CRC) 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. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐
๐ armv8.1-a ๐
+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โ Disable the cryptographic instructions. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐
๐ฆ armv8.2-a and armv8.3-a ๐ฆ
+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โ Enable the Dot Product extension. This also enables Advanced SIMD instructions. ๐งฎ+nocryptoโ Disable the cryptographic extension. ๐ซ+nofpโ Disable 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 ๐ฅ
+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โ Disable the cryptographic extension. ๐ซ+nofpโ Disable 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 ๐
+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โ Disable the cryptographic extension. ๐ซ+nofpโ Disable 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 ๐
+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โ Disable the cryptographic extension. ๐ซ+nofpโ Disable 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 ๐ง
+fp.spโ The single-precision VFPv3 floating-point instructions. The extension+vfpv3xdcan be used as an alias for this extension. ๐ฆ+fpโ The VFPv3 floating-point instructions with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension. ๐+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โ Disable the floating-point extension. ๐+idivโ The ARM-state integer division instructions. โ+noidivโ disables the ARM-state integer division extension. sorry babe, no dividing ๐ซโarmv7e-mโ the extension menu for this one goes:+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โ kills the floating-point extensions.
armv8.1-m.mainโ okay so:+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โ disables the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ enables the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options, in the range 0 to 7.+pacbtiโ enables the Pointer Authentication and Branch Target Identification Extension.
armv8-m.mainโ same energy, different list:+dspโ the DSP instructions.+nodspโ disables the DSP extension.+fpโ the single-precision floating-point instructions.+fp.dpโ the single- and double-precision floating-point instructions.+nofpโ disables the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ enables the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options, in the range 0 to 7.
armv8-rโ and for this queen:+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โ disables the cryptographic instructions.+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions. girl's got range ๐
-march=native hits different because it makes the compiler auto-detect the architecture of the build computer itself. Important caveat tho: 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. lowkey just vibes at that point ๐ญ
-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.
And bestie, that's not even it โ this option can also specify that GCC should tune the performance of the code for a big.LITTLE system. Permissible names for that 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.
So -mtune=generic-arch specifies that GCC should tune the performance for a blend of processors within architecture arch. The whole goal is to generate code that runs well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range and avoiding performance pitfalls of other CPUs. Heads up: the effects of this option may change in future GCC versions as CPU models come and go. iconic but evolving ๐ซ
-mtune permits the same extension options as -mcpu, but โ plot twist โ the extension options do not affect the tuning of the generated code. ๐ซถ
-mtune=native makes the compiler 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. same energy as -march=native, fr fr.
-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 -march or -mtune, those options take precedence over the appropriate part of this option. so basically whoever's most specific wins, periodt โจ
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. choose ur fighter ๐
Permissible names for this option are the same as those for -mtune.
The following extension options are common to the listed CPUs:
+nodspโ disables the DSP instructions oncortex-m33,cortex-m35p,cortex-m55andcortex-m85. Also disables the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85.+nopacbtiโ disables the Pointer Authentication and Branch Target Identification Extension oncortex-m85.+nomveโ disables the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85.+nomve.fpโ disables the M-Profile Vector Extension (MVE) single precision floating-point instructions oncortex-m55andcortex-m85.+cdecp0,+cdecp1, ... ,+cdecp7โ enables 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. iykyk ๐ฆ
-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-armv8 and crypto-neon-fp-armv8. Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2. cute little nicknames, obsessed ๐
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 so real talk about NEON ๐ฆ โ if the floating-point hardware you picked has the NEON extension (like, say, -mfpu=neon), just know that GCC's auto-vectorization pass will not generate floating-point operations for you unless -funsafe-math-optimizations is also in the mix. Why? Because NEON hardware doesn't fully implement the IEEE 754 standard for floating-point arithmetic (denormal values straight up get treated as zero, bestie ๐ญ), 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. Slay, per-function control. โจ
-mfp16-format=nameโ sets the format of the__fp16half-precision floating-point type. The permissible names arenone,ieee, andalternative, and the default isnone, in which case the__fp16type literally isn't 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 you set here. The 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 โ that's the tea. โ
This option is deprecated. ๐ซ
-mabort-on-noreturnโ generates a call to the functionabortat the end of anoreturnfunction. It gets executed if the function tries to return. Like, "you said you'd never come back, so we're making sure." ๐-mlong-calls-mno-long-callsโ tells the compiler to do 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 the 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. Exceptions to the exceptions, iykyk. ๐ซถ
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 the one responsible for initializing this register with an appropriate value before execution begins. Teamwork, fr fr. ๐ค-mpic-register=regโ specify the register to be used for PIC addressing. For the standard PIC base case, the default is any suitable register determined by the compiler. For the single PIC base case, the default isR9if the 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. Sneaky default behavior but okay ๐-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). Forensics era ๐โจ
-mthumb-marmโ pick 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. Per-function mode switches, we love to see it. ๐
-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. It's a test-only diva, don't put it in your real builds. ๐ง-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. Small price to pay tbh ๐ธ-mtp=nameโ specify the access model for the thread local storage pointer. The valid models are:soft, which generates calls to__aeabi_read_tpcp15, which fetches the thread pointer fromcp15directly (supported in the arm6k architecture)auto, which uses the best available method for the selected processor
The default setting is auto. Let the compiler cook ๐ฉโ๐ณ
-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. Two-for-one deal ๐
-mneon-for-64bitsโ this option is deprecated and has no effect. It's giving ghost ๐ป-mslow-flash-dataโ assume loading data from flash is slower than fetching instructions. Therefore literal load is minimized for better performance. This option is only supported when compiling for ARMv7 M-profile and is 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 a comment in the 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โ turns on verbose cost model dumping inside the debug dump files โจ. Lowkey this one exists purely so you can debug the compiler itself, bestie โ it's not for normal human code.-mpure-codeโ says nope, no constant data living in code sections ๐ โโ๏ธ. And bonus: when you're compiling for the ELF object format, it hands every text section the ELF processor-specific section attribute"SHF_ARM_PURECODE". Heads up tho โ this option only exists when you're generating non-pic code for M-profile targets ๐ .-mcmseโ generates secure code exactly as laid out in the"ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification", which lives over at <https://developer.arm.com/documentation/ecm0359818/latest/> ๐-mfix-cmse-cve-2021-35465โ mitigates a potential security issue with the"VLLDM"instruction in some M-profile devices when you're using CMSE (CVE-2021-365465) ๐ญ. It's on by default whenever you use the-mcpu=option with"cortex-m33","cortex-m35p","cortex-m55","cortex-m85"or"star-mc1". Wanna turn the mitigation off? Use-mno-fix-cmse-cve-2021-35465๐ซถ-mstack-protector-guard=guard</italic> and-mstack-protector-guard-offset=offset</italic> โ generates stack protection code with the canary sitting at guard ๐ค. Supported locations areglobalfor a global canary, ortlsfor a canary you reach via the TLS register. Fair warning:-mstack-protector-guard-offset=is meant to go with-fstack-protector-guard=tlsand not for use in user-land code ๐ซ-mfdpic/-mno-fdpicโ selects the FDPIC ABI, which reps pointers to functions using 64-bit function descriptors ๐ฆ. When the compiler is configured for"arm-*-uclinuxfdpiceabi"targets, this option is on by default and implies-fPIEif you didn't hand it any of the PIC/PIE-related options. On other targets it only switches on the FDPIC-specific code generation features, and you the user have to explicitly provide the PIC/PIE-related options yourself as needed, fr fr.
Heads up: static linking is not supported here, because it would still involve the dynamic linker when the program self-relocates ๐. If that behavior is acceptable to you, use-staticand-Wl,-dynamic-linker.
The opposite, -mno-fdpic, is useful โ and actually required โ to build the Linux kernel with the same ("arm-*-uclinuxfdpiceabi") toolchain you used to build the userland programs ๐
-mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]]โ enables branch protection features (armv8.1-m.main only) ๐ก๏ธnoneโ generate code without branch protection or return address signing.standard[+leaf]โ generate code with all branch protection features enabled at their standard level.pac-ret[+leaf]โ generate code with return address signing set to its standard level, which means signing all functions that save the return address to memory.leafโ when return address signing is enabled, also sign leaf functions even if they don't write the return address to memory ๐+btiโ add landing-pad instructions at the permitted targets of indirect branch instructions.
If the +pacbti architecture extension isn't enabled, then every branch protection and return address signing operation is constrained to use only the instructions defined in the architectural-NOP space โจ. The generated code stays backwards-compatible with earlier versions of the architecture, but you can switch the extra security on 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 โ ๏ธ
Any setting other than none is supported only on armv8-m.main or later, no cap.
The default is to generate code without branch protection or return address signing ๐
๐ธ AVR Options ๐ธ
These options are defined for AVR implementations ๐:
-mmcu=mcu</italic> โ specify the AVR instruction set architecture (ISA) or device type ๐. The default for this option is"avr2".
The following AVR devices and ISAs are supported โญ. Note: 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 (https://gcc.gnu.org/wiki/avr-gcc#spec-files) file specs-mcu. Only the latter is provided by the compiler according to the supported *mcu*s below ๐. The rest is supported by AVR-LibC (https://www.nongnu.org/avr-libc/), or by means of atpack (https://gcc.gnu.org/wiki/avr-gcc#atpack) files from the hardware manufacturer ๐ฆ
"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 the"MOVW"instruction. 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 the"MOVW"instruction. 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"."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
"XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space. โจ
mcu = "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".
๐ธ 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. Big girl RAM energy ngl.
mcu = "atxmega64a1", "atxmega64a1u".
๐ง 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. the way that these have bothโฆ iconic.
mcu = "atxmega128a1", "atxmega128a1u", "atxmega128a4u".
๐ avrtiny
"TINY" Tiny core devices with 512 B up to 4 KiB of program memory. tiny but mighty fr fr. ๐ฃ
mcu = "attiny4", "attiny5", "attiny9", "attiny10",
"attiny102", "attiny104", "attiny20", "attiny40".
โญ avr1
This ISA is implemented by the minimal AVR core and supported for assembler only. periodt.
mcu = "attiny11", "attiny12", "attiny15",
"attiny28", "at90s1200".
-mabsdataโ bestie, this says: assume that all data in static storage can be accessed byLDS/STSinstructions. It only does anything on reduced Tiny devices like ATtiny40. There's also theabsdataAVR Variable Attributes variable attribute, go look at that too. ๐-maccumulate-argsโ accumulate outgoing function arguments, and acquire/release the stack space they need once, up in the function prologue/epilogue. If you don't turn this on, outgoing arguments get pushed before the call and popped after it. ๐ฎโ๐จ
Popping arguments after the function call can be spendy on AVR, so accumulating the stack space might give you smaller executables, because those arguments don't need to be removed from the stack after such a function call. lowkey a glow-up for your binary size.
This option can reduce code size for functions that make 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 get expanded as calls to the appropriate subroutines. Code size is smaller. โจ-mdouble=bits-mlong-double=bits โ set the size (in bits) of thedoubleorlong doubletype, respectively. The possible values for bits are32and64. Whether a specific value for bits is even allowed depends on the--with-double=and--with-long-double=configure options (https://gcc.gnu.org/install/configure.html#avr), and the exact same thing applies to the default values of these options. iykyk.-mgas-isr-prologuesโ interrupt service routines (ISRs) may use the__gcc_isrpseudo instruction that GNU Binutils supports. If this option is on, you can still disable the feature for individual ISRs using the AVR Function Attributesno_gccisrfunction 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โ assumeintis an 8-bit integer. This affects the sizes of all types: acharis 1 byte, anintis 1 byte, alongis 2 bytes, andlong longis 4 bytes. โ ๏ธ Heads up: this option does not conform to the C standards, but it does give you smaller code size.-mmain-is-OS_taskโ do not save registers inmain. The effect is the same as attaching the AVR Function AttributesOS_taskattribute tomain. It's activated per default if optimization is on. ๐-mno-interruptsโ generated code is not compatible with hardware interrupts. Code size is smaller. pick your fighter, bestie.-mrelaxโ try to replaceCALL(resp.JMP) instructions with the shorterRCALL(resp.RJMP) instruction 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 aren't known before the code is located. So the assembler code the compiler generates is the same, but the instructions in the executable may differ from the instructions in the assembler code. sneaky but correct.
Relaxing must be turned on if linker stubs are needed โ see the section on EIND and linker stubs below. ๐
-mstrict-Xโ use address registerXthe way the hardware proposes. That meansXis only used in indirect, post-increment or pre-decrement addressing.
Without this option, the X register may be used the same way as Y or Z, which then gets 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. just the bottom bits, bestie. ๐-mfract-convert-truncateโ allow using 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 (compiler proper, assembler, linker) with appropriate command line options. This means the user has to supply her own private device specs file via-specs=path-to-specs-file. There's no more need for the-mmcu=mcu option.
This option can also serve as a replacement for the older way of specifying custom device-specs files, which needed -B some-path to point to a directory containing a folder named device-specs, which contains a specs file named specs-mcu, where mcu was specified by -mmcu=mcu. history lesson, but make it functional. ๐
-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 the__vectorprefix. Enabled by default. ๐ (we all been there)
๐ EIND and Devices with More Than 128 Ki Bytes of Flash
Okay so pointers in the implementation are 16 bits wide. The address of a function or label is represented as a 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's a special function register called EIND that serves as the most significant part of the target address whenever the EICALL or EIJMP instructions get used. main character register fr.
Indirect jumps and calls on these devices are handled as follows by the compiler, and they are subject to some limitations. โ ๏ธ
- The compiler never sets
EIND. - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions, or it 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. do not touch it, bestie. ๐ - For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads, sometimes also called trampolines. So 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. ๐ no cap. - 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.
lowkey this whole section is the "please read before you @ me about your indirect calls not working" bit. ๐ซถ
- The startup code from libgcc never sets
EIND. Bestie, notice that startup code is a blend of code from libgcc and AVR-LibC. For the impact of AVR-LibC onEIND, see the AVR-LibC user manual (https://www.nongnu.org/avr-libc/user-manual/). - It is legitimate for user-specific startup code to set up
EINDearly, like by means of initialization code located in section.init3. Such code runs prior to general startup code that initializes RAM and calls constructors, but after the bit of startup code from AVR-LibC that setsEINDto the segment where the vector table is located.
#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. โจ
- Stubs are generated automatically by the linker if these two conditions are met:
- The address of a label is taken by means of the
gsmodifier (short for generate stubs), 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 such
gsmodifiers for code labels in these situations:- 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. If you do not want such dispatch tables you can specify the
-fno-jump-tablescommand-line option. - C and C++ constructors/destructors called during startup/shutdown.
- If the tools hit a
gs()modifier explained above.
- Jumping to non-symbolic addresses like so is not supported:
int main (void)
{
/* Call function at word address 0x2 */
return ((int(*)(void)) 0x2)();
}
Instead, a stub has to be set up, i.e. 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 the application be linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script. ๐
Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers
Some AVR devices support memories larger than the 64 KiB range that can be accessed with 16-bit pointers. To access memory locations outside this 64 KiB range, the content of a RAMP register is used as the high part of the address: the X, Y, Z address register is concatenated with the RAMPX, RAMPY, RAMPZ special function register, respectively, to get a wide address. Similarly, RAMPD is used together with direct addressing. Big memory energy. ๐
- The startup code initializes the
RAMPspecial function registers with zero. - If a 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.
โ ๏ธ That last one is a real you must, bestie. No skipping.
AVR Built-in Macros
GCC defines several built-in macros so that the user code can test 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, 6for mcu=avr2,avr25,avr3,avr31,avr35,avr4,avr5,avr51,avr6, respectively, and100, 102, 103, 104, 105, 106, 107for 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=atmega8the 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=deviceis 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_*. ๐ฆ__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 to 2 or 3.__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
Okay so first up, bestie, a little heads-up from the source: 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 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're documented for completeness, and in order to get a better understanding of device specs (https://gcc.gnu.org/wiki/avr-gcc#spec-files) files.
-mn-flash=numโ Assume that the flash memory has a size of num times 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.
-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. (Register real estate, we love to see it ๐ )-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. Iconic behavior honestly ๐ฅ-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. (Speed over strictness, it's giving reckless โจ)-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 ofBF561when 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 ofBF561when 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. Periodt.
-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.-mtune=architecture-typeโ tune everything about the generated code to architecture-type and honestly it's giving glow-up, except for the ABI and the set of available instructions, which stay exactly as they were. The choices for architecture-type are the same as for-march=architecture-type. ๐-mmax-stack-frame=nโ yell at you (a warning) when a function's stack frame goes over n bytes. ๐ซถ-metrax4โ-metrax100โ ok so these two are literally just synonyms, bestie:-metrax4means-march=v3and-metrax100means-march=v8. Same thing, different name, iconic behavior. โจ-mmul-bug-workaroundโ-mno-mul-bug-workaroundโ vibe-checks and works around a bug in themulsandmuluinstructions, but only for the CPU models where that bug actually applies. Disabled by default, no cap. ๐-mpdebugโ turns on CRIS-specific verbose debug-related info in the assembly code. Also (sneaky) it turns off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file. ๐-mcc-initโ do not reuse condition-code results left over from a previous instruction; always emit compare and test instructions before condition codes get used. Fresh start every time, periodt. ๐ธ-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 un-arrange, for the no- versions) for the stack frame, individual data and constants to be aligned for the maximum single data access size of the chosen CPU model. Default is to arrange for 32-bit alignment. And bestie, ABI details like structure layout are not affected by any of these. ๐-m32-bitโ-m16-bitโ-m8-bitโ similar to the stack-, data- and const-align options up there โ, these ones arrange for the stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned respectively. Default is 32-bit alignment. ๐ฅ-mno-prologue-epilogueโ-mprologue-epilogueโ with-mno-prologue-epiloguethe normal function prologue and epilogue that set up the stack frame are justโฆ omitted, and no return instructions or return sequences get generated in the code. Use this only while you're visually inspecting the compiled code with your own eyeballs, ok?
No warnings, no errors. Nothing. If call-saved registers need saving, or storage for locals needs allocating, the compiler will not tell you. You've been warned. ๐
-melfโ legacy no-op option. It does nothing, it's just here, it's a legacy icon. ๐-simโ arranges to link with input-output functions from a simulator library. Code, initialized data and zero-initialized data all get 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. Yes, the whole vibe is C-SKY V2, and we ate. ๐
-march=archโ specify the C-SKY target architecture. Valid values for arch are:ck801,ck802,ck803,ck807, andck810. The default isck810. โญ-mcpu=cpuโ specify the C-SKY target processor. Valid values for cpu are a whole long list, so here it is, verbatim, no skipping, bestie:
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, and ck810ftv. ๐ญ (the naming scheme is giving lore, iykyk)
-mbig-endianโ-EBโ-mlittle-endianโ-ELโ select big- or little-endian code. The default is little-endian. ๐ฆ-mfloat-abi=nameโ specifies which floating-point ABI to use. Permissible values are:soft,softfpandhard.softmakes GCC 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.
The default depends on the specific target configuration. And heads up, bestie:
Thehard-float andsoft-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, no matching, no exceptions. ๐
-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, this enables generation of double-precision float instructions. That's the default โ except when you're compiling forCK803. ๐ธ-mfdivduโ-mno-fdivduโ when-mhard-floatis in effect, enable generation offrecipd,fsqrtd, andfdivdinstructions. Default, except when compiling forCK803. โจ-mfpu=fpuโ select the floating-point processor. Can only be used together with-mhard-float. Values for fpu are:fpv2_sfโ equivalent to-mno-double-float -mno-fdivdufpv2โ-mdouble-float -mno-divdufpv2_divdโ-mdouble-float -mdivdu
-melrwโ-mno-elrwโ enable the extendedlrwinstruction. Defaults to on forCK801and off everywhere else. ๐-mistackโ-mno-istackโ enable interrupt stack instructions; the default is off.
The-mistackoption is required to handle theinterruptandisrfunction attributes. Don't skip it if you need those. ๐ซถ
-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 manpage says coprocessor here too โ we're keeping it exactly as written, no fixing, periodt ๐)-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 default to off. ๐ฅ-mdivโ-mno-divโ generate divide instructions. Default is off.-msmartโ-mno-smartโ generate code for Smart Mode, using only registers numbered0-7so that 16-bit instructions can be used. This option is ignored forCK801, where that's the required behavior anyway, and it defaults to on forCK802. For other targets, the default is off. ๐ง-mhigh-registersโ-mno-high-registersโ generate code using the high registers numbered16-31. Not supported onCK801,CK802, orCK803, and enabled by default for the other processors. ๐-manchorโ-mno-anchorโ generate code using global anchor symbol addresses.-mpushpopโ-mno-pushpopโ generate code usingpushandpopinstructions. Defaults to on. ๐-mmultiple-stldโ-mstmโ-mno-multiple-stldโ-mno-stmโ generate code usingstmandldminstructions. Isn't supported onCK801, but it's enabled by default on other processors.-mconstpoolโ-mno-constpoolโ create constant pools in the compiler instead of deferring that whole job to the assembler. This option is the default and required for correct code generation onCK801andCK802, and it's optional on other processors. ๐-mstack-sizeโ-mno-stack-sizeโ emit.stack_sizedirectives for each function in the assembly output. Defaults to off.-mccrtโ-mno-ccrtโ generate code for the C-SKY compiler runtime instead oflibgcc. 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.
Doing this can result in code that is not compliant with the C-SKY V2 ABI prologue requirements, and that cannot be debugged or backtraced. It's disabled by default for a reason, 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. Group effort, slay. ๐ซถ
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 that 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, and honestly, the drama:
- 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 appc750object 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 appc970object file in appc7400library). ๐ - The linker for executables,
ld, quietly gives the executable the most restrictive subtype of any of its input files. No announcement, just vibes. -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. ๐ฆ
A framework directory is just a directory with frameworks chillin' inside it. And what's a framework, bestie? It's a directory that ends in .framework and has a Headers and/or PrivateHeaders directory right there in it. โจ The framework's name is the directory name minus the .framework. Headers live in one of those two dirs, and Headers gets searched first, no cap.
A subframework is a framework directory sitting inside a framework's Frameworks directory. Includes of subframework headers are only allowed in a header of the framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they're in the same framework, fr fr. A subframework shouldn't have the same name as a framework โ you get a warning if you do that ๐. Currently a subframework can't have subframeworks; maybe in the future the mechanism gets extended to support it. The standard frameworks live in /System/Library/Frameworks and /Library/Frameworks. An example include looks like #include <Framework/header.h>, where Framework is the framework's name and header.h is found in the PrivateHeaders or Headers directory. ๐
-iframeworkdirโ Like-Fexcept the directory is treated as a system directory. The big difference between-iframeworkand-Fis that with-iframeworkthe compiler doesn't warn about constructs inside header files found via dir. This option is valid only for the C family of languages, bestie.-gusedโ Emit debugging info for symbols that are used. For the stabs debugging format, this enables-feliminate-unused-debug-symbols. This is ON by default. ๐-gfullโ Emit debugging info for all symbols and types. Everything. The whole buffet.-fconstant-cfstringsโ This one is literally just an alias for-mconstant-cfstrings.-mconstant-cfstringsโ When the NeXT runtime is being used (which is the default on these systems), this overrides any-fconstant-string-classsetting and causes@"..."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 the compiler is running on. Otherwise the default is to make choices compatible with as many systems and code bases as possible. ๐ซถ
-mkernelโ Enable kernel development mode, main character energy for kernel devs. 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 forboolso thatsizeof(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, like letting GDB 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 info.-arch_errors_fatalโ Cause the errors having to do with files that have the wrong architecture to be fatal. No mercy. ๐-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 info.-bundle_loaderexecutable โ This option specifies the executable that will load the build output file being linked. Seeman ld(1)for more info.-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.-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โ These options are passed to the Darwin linker. The Darwin linker man page describes them in detail. (Yeah, a couple of them show up twice up in that list โ that's just how it is. ๐คท)
๐ฆ 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're 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're 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. Yeah, even the ones with no FP ops gotta have the 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 isn't 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. No mixing, bestie. ๐
A typical use of this option is building a kernel that doesn't use, and hence need not save and restore, any floating-point registers. Vibe check: kernel edition.
-mieeeโ The Alpha architecture implements floating-point hardware optimized for maximum performance. It's mostly compliant with the IEEE floating-point standard. But for full compliance, software assistance is required. This option generates code that's fully IEEE-compliant except that the inexact-flag is not maintained (see below). If this option is turned on, the preprocessor macro_IEEE_FPis defined during compilation. The resulting code is less efficient but is able to correctly support denormalized numbers and exceptional IEEE values like 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. ๐ So like, yeah, keep it on.
-mieee-with-inexactโ This is like-mieeeexcept the generated code also maintains the IEEE inexact-flag. Turning this on causes the generated code to implement fully-compliant IEEE math. In addition to_IEEE_FP,_IEEE_FP_EXACTis defined as a preprocessor macro. On some Alpha implementations the resulting code may execute significantly slower than the code generated by default. Since there's 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 the 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. A field in the floating-point control register (fpcr, see Alpha architecture reference manual) controls the rounding mode in effect. The C library initializes this register for rounding towards plus infinity. So unless your program modifies thefpcr,dcorresponds to round towards plus infinity. ๐-mtrap-precision=trap-precisionโ In the Alpha architecture, floating-point traps are imprecise. That means without software assistance it is impossible to recover from a floating trap and program execution normally needs to be terminated. GCC can generate code that can assist operating system trap handlers in determining the exact location that caused a floating-point trap. Depending on the requirements of an application, different levels of precision can be selected:pโ Program precision. This option is the default and means a trap handler can only identify which program caused a floating-point exception.fโ Function precision. The trap handler can determine the function that caused a floating-point exception.iโ Instruction precision. The trap handler can determine the exact instruction that caused a floating-point exception. Other Alpha compilers provide the equivalent options called-scope_safeand-resumption_safe. ๐ซถ
-mieee-conformantโ This option marks the generated code as IEEE conformant. You must 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. โ ๏ธ-mbuild-constantsโ Normally GCC examines a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it cannot, it outputs the constant as a literal and generates code to load it from the data segment at run time. Use this option to require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six). You typically use this option to build a shared library dynamic loader. Itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment. โจ-mbwx,-mno-bwx,-mcix,-mno-cix,-mfix,-mno-fix,-mmax,-mno-maxโ Indicate whether GCC should generate code to use the optional BWX, CIX, FIX and MAX instruction sets. The default is to use the instruction sets supported by the CPU type specified via-mcpu=option or that of the CPU on which GCC was built if none is specified. ๐-mfloat-vax,-mfloat-ieeeโ Generate code that uses (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 provided no way to generate symbol relocations except via assembler macros. Use of these macros does not allow optimal instruction scheduling. GNU binutils as of version 2.12 supports a new syntax that allows the compiler to explicitly mark which relocations should apply to which instructions. This option is mostly useful for debugging, as GCC detects the capabilities of the assembler when it is built and sets the default accordingly. ๐-msmall-data,-mlarge-dataโ When-mexplicit-relocsis in effect, static data is accessed via gp-relative relocations. When-msmall-datais used, objects 8 bytes long or smaller are placed in a small data area (the.sdataand.sbsssections) and are accessed via 16-bit relocations off of the$gpregister. This limits the size of the small data area to 64KB, but allows the variables to be directly accessed via a single instruction. The default is-mlarge-data. With this option the data area is limited to just below 2GB. Programs that require more than 2GB of data must usemallocormmapto allocate the data in the heap instead of in the program's data segment. When generating code for shared libraries,-fpicimplies-msmall-dataand-fPICimplies-mlarge-data. ๐ฆ-msmall-text,-mlarge-textโ When-msmall-textis used, the compiler assumes that the code of the entire program (or shared library) fits in 4MB, and is thus reachable with a branch instruction. When-msmall-datais used, the compiler can assume that all local symbols share the same$gpvalue, and thus reduce the number of instructions required for a function call from 4 to 1. The default is-mlarge-text. ๐-mcpu=cpu_typeโ Set the instruction set and 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 chooses the default values for the instruction set from the processor you specify. If you do not specify a processor type, GCC defaults to the processor on which the compiler was built. Supported values for cpu_type are:ev4,ev45,21064โ Schedules as an EV4 and has no instruction set extensions. ๐ev5,21164โ Schedules as an EV5 and has no instruction set extensions.ev56,21164aโ Schedules as an EV5 and supports the BWX extension.pca56,21164pc,21164PCโ Schedules as an EV5 and supports the BWX and MAX extensions.ev6,21264โ Schedules as an EV6 and supports the BWX, FIX, and MAX extensions.ev67,21264aโ Schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions. Native toolchains also support the valuenative, which selects the best architecture option for the host processor.-mcpu=nativehas no effect if GCC does not recognize the processor. ๐
-mtune=cpu_typeโ Set only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed. Native toolchains also support the valuenative, which selects the best architecture option for the host processor.-mtune=nativehas 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. Valid options for time are:numberโ A decimal number representing clock cycles.L1,L2,L3,mainโ 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 thatL3is 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. โจ-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 of v2, 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. โจ-mno-lsimโ Assume that runtime support has been provided and so there is 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. ๐ง-mnodivโ Do not use div and mod instructions. ๐-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 touch the first 32 floating-point registers, bestie. That's the whole vibe.-mfpr-64โ okay now we're using ALL 64 floating-point registers. go big ๐-mhard-floatโ floating-point math goes to actual hardware instructions. fast, real, iconic.-msoft-floatโ floating-point math goes through library routines instead. no hardware, just vibes and function calls.-malloc-ccโ dynamically allocate condition code registers.-mfixed-ccโ do not try to dynamically allocate condition code registers; only useicc0andfcc0. that's it. that's the whole roster.-mdwordโ changes the ABI to use double word instructions.-mno-dwordโ no double word instructions. not today.-mno-doubleโ no floating-point double instructions.-mdoubleโ yes floating-point double instructions โจ-mmediaโ use media instructions.-mno-mediaโ do not use media instructions.-mmuladdโ use multiply and add/subtract instructions.-mno-muladdโ do not use multiply and add/subtract instructions.-mfdpicโ picks the FDPIC ABI, which represents pointers to functions using function descriptors. With no PIC/PIE-related options at all, it implies-fPIE. Give it-fpicor-fpieand it assumes GOT entries and small data live within a 12-bit range from the GOT base address; give it-fPICor-fPIEand GOT offsets get computed with 32 bits. And if the target isbfin-elf, this option implies-msim.-minline-pltโ turns on inlining of PLT entries in function calls to functions that aren't known to bind locally. Heads up though: it does nothing without-mfdpic. It's on by default when you're optimizing for speed and compiling for shared libraries (so,-fPICor-fpic), or when an optimization option like-O3or above is sitting in the command line.-mTLSโ assume there's a large TLS segment when generating thread-local code.-mtlsโ do not assume a large TLS segment when generating thread-local code.-mgprel-roโ enables usingGPRELrelocations in the FDPIC ABI for data known to be in read-only sections. It's on by default, except for-fpicor-fpie: even though it might shrink the global offset table, it trades 1 instruction for 4. ๐ญ With-fPICor-fPIEit trades 3 instructions for 4 โ one of which might be shared by multiple symbols โ and it skips needing a GOT entry for the referenced symbol, so it's way more likely to be a win. If it isn't?-mno-gprel-rodisables it.-multilib-library-picโ link with the (library, not FD) pic libraries. It's implied by-mlibrary-pic, and also by-fPICand-fpicwithout-mfdpic. Real talk: you should never have to use it explicitly.-mlinked-fpโ follows the EABI requirement of always creating a frame pointer whenever a stack frame is allocated. It's enabled by default, and you can turn it off with-mno-linked-fp.-mlong-callsโ uses indirect addressing to call functions outside the current compilation unit. This lets those functions live anywhere within the 32-bit address space. so much room ๐-malign-labelsโ tries to align labels to an 8-byte boundary by inserting NOPs into the previous packet. Only does anything when VLIW packing is enabled. And it does not create new packets โ it just adds NOPs to existing ones. lowkey polite of it.-mlibrary-picโ generate position-independent EABI code.-macc-4โ use only the first four media accumulator registers.-macc-8โ use all eight media accumulator registers. full squad ๐ซถ-mpackโ pack VLIW instructions.-mno-packโ do not pack VLIW instructions.-mno-eflagsโ do not mark ABI switches ine_flags.-mcond-moveโ enable the use of conditional-move instructions (this is the default).
This switch is mainly for debugging the compiler and will likely be removed in a future version.
-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.
-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.
-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.
-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.
-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.
-mvliw-branchโ runs 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.
-mno-vliw-branchโ does 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.
-mmulti-cond-execโ enables optimization of&&and||in conditional execution (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version.
-mno-multi-cond-execโ disables optimization of&&and||in conditional execution.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
-mnested-cond-execโ enables nested conditional execution optimizations (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version.
-mno-nested-cond-execโ disables nested conditional execution optimizations.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
-moptimize-membarโ this switch removes redundantmembarinstructions from the compiler-generated code. It's enabled by default.-mno-optimize-membarโ this switch disables the automatic removal of redundantmembarinstructions from the generated code.-mtomcat-statsโ causesgasto print out tomcat statistics. ๐ฑ iconic honestly- *
-mcpu=cpu* โ pick the processor type you're generating code for. The possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple.
๐ง 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.-muclibcโ use the uClibc C library. This is the default on*-*-linux-*uclibc*targets.-mmuslโ use the musl C library. This is the default on*-*-linux-*musl*targets.-mbionicโ use the Bionic C library. This is the default on*-*-linux-*android*targets.-mandroidโ compile code compatible with the 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. And finally, this option causes the preprocessor macro __ANDROID__ to be defined. main character energy fr ๐
-tno-android-ccโ disable the compilation effects of-mandroid, i.e. don't enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default.-tno-android-ldโ disable the linking effects of-mandroid, i.e. pass standard Linux linking options to the linker.
๐ H8/300 Options ๐
These -m options are defined for the H8/300 implementations:
-mrelaxโ shorten some address references at link time when possible; it uses the linker option-relax.-mhโ generate code for the H8/300H.-msโ generate code for the H8S.-mnโ generate code for the H8S and H8/300H in the normal mode. This switch must be used either with-mhor-ms.-ms2600โ generate code for the H8S/2600. This switch must be used with-ms.-mexrโ extended registers are stored on the stack before execution of a function with the monitor attribute. Default option is-mexr. This option is valid only for H8S targets.-mno-exrโ extended registers are not stored on the stack before execution of a function with the monitor attribute. Default option is-mno-exr. This option is valid only for H8S targets.-mint32โ makeintdata 32 bits by default.-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-300makes them align on 2-byte boundaries instead. This option does nothing at all on the H8/300. zero effect, we love a harmless flag ๐
๐ 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. Go check/usr/lib/sched.modelson an HP-UX system to figure out the proper architecture option for your machine. Also super important: code compiled for lower numbered architectures runs on higher numbered architectures, but **not the other way around. no cap.-mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0โ these are synonyms for-march=1.0,-march=1.1, and-march=2.0respectively.-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. Because of that, 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. So basically all atomic support is implemented using sync and atomic libcalls. Sync libcall support lives in libgcc.a. Atomic libcall support lives in libatomic.
This option generates __atomic_exchange calls for atomic stores. It also provides special handling for atomic DImode accesses on 32-bit targets.
-mbig-switchโ does nothing. It's preserved for backward compatibility. the way that it literally just exists to not break things ๐ญ iconic-mcaller-copiesโ the caller is the one copying function arguments that got passed by hidden reference ๐ซถ. Use this one with care, bestie, because it's not compatible with the default 32-bit runtime. But plot twist: only aggregates bigger than eight bytes get passed by hidden reference, and this option gives you better compatibility with OpenMP.-mcoherent-ldcwโ use theldcw/ldcdcoherent cache-control hint โจ.-mdisable-fpregsโ floating-point registers? Cut off. Big "no fpregs" energy. Equivalent to-msoft-float.-mdisable-indexingโ stops the compiler from using indexing address modes ๐. This dodges some really obscure problems when you're compiling MIG generated code under MACH. iykyk.-mfast-indirect-callsโ generates code that assumes calls never cross space boundaries, so GCC can emit indirect calls that go zoom ๐จ.
Heads up though: this does not work if you've got shared libraries or nested functions in the mix. No cap.
-mfixed-range=register-rangeโ generates code treating the given register range as fixed registers ๐ . A fixed register is one the register allocator literally cannot use. Super handy when you're compiling kernel code ๐. A register range is written as two registers separated by a dash, and you can stack multiple ranges by separating them with a comma.-mgasโ turns on the use of assembler directives that only GAS understands.-mgnu-ldโ use the options that are specific to GNUld๐. This passes-sharedtoldwhen you're building a shared library. It's the default when GCC is configured โ explicitly or implicitly โ with the GNU linker. Important: this option does not change whichldgets called, only what parameters get handed to it ๐. Whichldis called comes down to, in order: the--with-ldconfigure option, GCC's program search path, and finally the user'sPATH. You can print the linker GCC uses with whichgcc -print-prog-name=ld. Also, this option is only available on the 64-bit HP-UX GCC, i.e. one configured withhppa*64*-*-hpux*.-mhp-ldโ use the 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 before: this option does not affect whichldis called, only which parameters get passed to it. Whichldis called is determined by the--with-ldconfigure option, GCC's program search path, and finally the user'sPATH. The linker GCC uses can be printed with whichgcc -print-prog-name=ld. And once again, it's only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*.-mlinker-optโ enables the optimization pass inside the HP-UX linker ๐ฅ. Note that this makes symbolic debugging impossible ๐ญ. It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers where they spit out bogus error messages when linking some programs ๐.-mlong-callsโ generates code that uses long call sequences ๐. This guarantees a call can always reach linker generated stubs. The default behavior is to generate long calls only when the distance from the call site to the beginning of the function or translation unit (whichever applies) goes past a predefined limit set by the branch type being used. The limits for normal calls are7,600,000and240,000bytes, respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at240,000bytes.
Distances are measured from the beginning of functions when you use the -ffunction-sections option, or when you use the -mgas and -mno-portable-runtime options 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, particularly when partial linking is used to build the application โจ.
Which types of long calls get used depends on what the assembler and linker can do, plus the type of code being generated. The impact on systems that support long absolute calls, and long pic symbol-difference or pc-relative calls, should be relatively small. But on 32-bit ELF systems in pic code, an indirect call gets used โ and it is quite long ๐ฎโ๐จ.
-mlong-load-storeโ generates 3-instruction load and store sequences, which the HP-UX 10 linker sometimes needs ๐. This is equivalent to the+koption to the HP compilers.-mjump-in-delayโ this option is ignored and exists purely for compatibility purposes only ๐.-mno-space-regsโ generates code that assumes the target has no space registers ๐ฆ. This 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 are not needed โ .-mportable-runtimeโ use the portable calling conventions that HP proposed 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 peek at/usr/lib/sched.modelson an HP-UX system to figure out the right scheduling option for your machine ๐. The default scheduling is8000.-msioโ generates the predefine_SIOfor server IO ๐ธ. The default is-mwsio. That one generates the predefines__hp9000s700,__hp9000s700__and_WSIO, for workstation IO ๐ป. These options are available under HP-UX and HI-UX.-msoft-floatโ generates output that contains 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 are used, but you can't do that directly in cross-compilation. You have to make your own arrangements to provide suitable library functions for cross-compilation.
-msoft-float changes the calling convention in the output file, so it's 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 for this to actually work.
-msoft-multโ use software integer multiplication โ๏ธ. This disables the use of thexmpyuinstruction.-munix=unix-stdโ generate compiler predefines and pick 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.98is 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 is 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, fr fr.
Library code that's intended to work 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 that searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later ๐.-staticโ the HP-UX implementation ofsetlocaleinlibchas a dependency onlibdld.sl๐. There is no archive version oflibdld.sl. So when the-staticoption is specified, special link options are needed to resolve this dependency.
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when -static is specified. This 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 ๐.
-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. Yeah. Don't.-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 can make assembler output more readable ๐.-mno-sdata,-msdataโ disable (or enable) optimizations that use the small data section ๐. This can be useful for working around optimizer bugs ๐.-mconstant-gpโ generate code that uses a single constant global pointer value ๐ฏ. This is useful when compiling kernel code ๐.-mauto-picโ generate code that is self-relocatable ๐. This implies-mconstant-gp. Useful when you're 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 generates code for inline square roots using the minimum latency algorithm. Speed demon behavior ๐-minline-sqrt-max-throughputโ same vibes but the other direction: generate code for inline square roots using the maximum throughput algorithm. Volume up ๐ฅ-mno-inline-sqrtโ do not generate inline code forsqrt. Stay out of it fr fr.-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, periodt.-mno-dwarf2-asm,-mdwarf2-asmโ don't (or do) generate assembler code for the DWARF line number debugging info. This may be useful when you're not using the GNU assembler. iykyk โจ-mearly-stop-bits,-mno-early-stop-bitsโ allow stop bits to 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 ๐ญ- *
-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. Multi-range? She's flexible ๐ - *
-mtls-size=tls-size* โ specify bit size of immediate TLS offsets. Valid values are14,22, and64. - *
-mtune=cpu-type* โ tune the instruction scheduling for a particular CPU. Valid values areitanium,itanium1,merced,itanium2, andmckinley. Pick your fighter ๐ -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, so likeโฆ context matters ๐ซถ-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. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is enabled.-mno-sched-control-spec,-msched-control-specโ (dis/en)able control speculative scheduling. This feature is available only during region scheduling (i.e. before reload). This 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 are dependent on the data speculative loads before reload. This is effective only 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 are dependent on the data speculative loads after reload. This is effective only 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 are dependent on the control speculative loads. This is effective only 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 chosen for schedule only if there are no other choices at the moment. This makes the use of the data speculation much 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 chosen for schedule only if there are no other choices at the moment. This makes the use of the 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 are considered during computation of the instructions priorities. This makes the use of the speculation a 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 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, giving lower priority to subsequent memory insns attempting to schedule in the same instruction group. Frequently useful to prevent cache bank conflicts. The default value is1. -msched-max-memory-insns-hard-limitโ makes the limit specified bymsched-max-memory-insnsa hard limit, disallowing more than that number in an instruction group. Otherwise, the limit is "soft", meaning that non-memory operations are preferred when the limit is reached, but memory operations may still be scheduled. Soft launch vs hard launch, we love a metaphor ๐
LM32 Options ๐ธ
These -m options are defined for the LatticeMico32 architecture:
-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. Main character energy, honestly ๐
LoongArch Options ๐ฆ
These command-line options are defined for LoongArch targets:
-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. No cap, this is the commitment one ๐ค
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. She's local, she's loyal ๐loongarch64โ a generic CPU with 64-bit extensions.la464โ LoongArch LA464 CPU with LBT, LSX, LASX, LVZ. Look at all those letters, slay โจ
- *
-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. This option may change the target ABI. Heads up bestie, ABI shifts are not a vibe check you skip โ ๏ธ-msingle-floatโ force-mfpu=32and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI.-mdouble-floatโ force-mfpu=64and allow the use of 32/64-bit floating-point registers for parameter passing. This option may change the target ABI.- *
-mbranch-cost=n* โ set the cost of branches to roughly n instructions. -mcheck-zero-division,-mno-check-zero-divisonโ trap (do not trap) on integer division by zero. The default is-mcheck-zero-divisionfor-O0or-Og, and-mno-check-zero-divisionfor other optimization levels. (Yes, the second one is spelleddivisonin the original โ we copy it exact, character for character, no fixing ๐)-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 (do not force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. Setting optimization level to-Osalso forces the use ofmemcpy, but-mno-memcpymay override this behavior if explicitly specified, regardless of the order these options on the command line. Order? Irrelevant. She said what she said ๐-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.
Not me dropping a whole architecture's worth of flags in one part ๐ญ but every single one of them is here, bestie, nothing skipped, nothing skimmed. ๐ซถ
-mcmodel=code-modelโ sets the code model, and code-model has to be one of these besties:tiny-staticโ 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โ the text segment and the data segment both have to be within a 2GB addressing space.largeโ not implemented yet ๐extremeโ this mode does not limit the size of the code segment and data segment at all. But heads up:-mcmodel=extremeis incompatible with-fpltand-mno-explicit-relocs๐ซ
The default code model is "normal". periodt ๐
-mexplicit-relocs,-mno-explicit-relocsโ use, or do not use, assembler relocation operators when you're dealing with symbolic addresses. The alternative is using assembler macros instead, which can limit instruction scheduling but lets linker relaxation happen. The default for this option gets figured out from the assembler capability that was detected when GCC was built, plus whatever-mrelaxis set to: if the assembler supports relocation operators but-mrelaxis not enabled you get-mexplicit-relocs, and otherwise you get-mno-explicit-relocs. 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 gets used for external symbols with default visibility, but it is not used for other external symbols.
With -mdirect-extern-access, GOT is not used at all and every external symbol is PC-relatively addressed. This is only suitable for environments where no dynamic link is performed, like firmwares, OS kernels, executables linked with -static or -static-pie. And no cap: -mdirect-extern-access is not compatible with -fPIC or -fpic. ๐ซถ
-mrelax,-mno-relaxโ take (or do not take) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option also gets passed along to the assembler. The default is decided at GCC build-time by detecting the corresponding assembler support: you get-mrelaxif the assembler supports both the-mrelaxoption and conditional branch relaxation, and-mno-relaxotherwise. And bestie, that conditional branch relaxation support is required โ without it, the.aligndirectives and conditional branch instructions in the assembly code that GCC outputs 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 through to the assembler. The default is decided at GCC build-time by detecting the corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption, and-mno-pass-mrelax-to-asotherwise. This one is mostly useful for debugging, or for interoperating with assemblers that aren't the build-time one. ๐ง
๐ธ M32C Options ๐ธ
-mcpu=nameโ pick the CPU you're generating code for. name can ber8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series. ๐-msimโ says the program is gonna run on the simulator. This makes an alternate runtime library get linked in, one that supports stuff like file I/O for example. > You must not use this option when you're generating programs that will run on real hardware โ you have to provide your own runtime library for whatever I/O functions you need. no exceptions bestie ๐-memregs=numberโ sets 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 the 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 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โ turn off use of the small data area. Variables go into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default.
The small data area consists of the sections .sdata and .sbss. Objects can 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 don't 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 that are 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 incorrect code is not generated. ๐
-mdebugโ makes the M32R-specific code in the compiler display some statistics that might help when you're 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 for flushing the cache. The default is12. Valid numbers are between0and15inclusive.-mno-flush-trapโ specifies that the cache can't 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 isn't available.-mno-flush-funcโ says there's 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. The permissible values of arch for M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures get selected according to Freescale's ISA classification, and the permissible values are:isaa,isaaplus,isabandisac.
GCC defines a macro __mcfarch__ whenever it's generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When they're used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for one 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 : -mcpu arguments
51 : 51 51ac 51ag 51cn 51em 51je 51jf 51jg 51jm 51mm 51qe 51qm
5206 : 5202 5204 5206
5206e : 5206e
5208 : 5207 5208
5211a : 5210a 5211a
5213 : 5211 5212 5213
5216 : 5214 5216
52235 : 52230 52231 52232 52233 52234 52235
5225 : 5224 5225
52259 : 52252 52254 52255 52256 52258 52259
5235 : 5232 5233 5234 5235 523x
5249 : 5249
5250 : 5250
5271 : 5270 5271
5272 : 5272
5275 : 5274 5275
5282 : 5280 5281 5282 528x
53017 : 53011 53012 53013 53014 53015 53016 53017
5307 : 5307
5329 : 5327 5328 5329 532x
5373 : 5372 5373 537x
5407 : 5407
5475 : 5470 5471 5472 5473 5474 5475 547x 5480 5481 5482 5483 5484
5485
-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Any other combination of -mcpu and -march gets rejected. ๐ซ
GCC defines the macro __mcf_cpu_cpu when the 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 whatever constraints-marchand-mcpuhave set. 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 it's tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. And if GCC is tuning for a range of architectures, like the ones selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range. ๐
GCC also drops the macro __muarch__ when it's tuning for the ColdFire microarchitecture uarch, where uarch is literally one of the arguments listed just up above. ๐
-m68000,-mc68000โ spit out output for a 68000. This is the default when the compiler was configured for 68000-based systems, and it's equivalent to-march=68000.
Reach for this one on microcontrollers rockin' a 68000 or EC000 core, so like 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 bestie: this one blocks the use of 68881/68882 instructions that have to be emulated in software on the 68040. So use it if your 68040 has no code to emulate those instructions. ๐
-m68060โ output for a 68060. Default when the compiler is configured for 68060-based systems. Equivalent to-march=68060.
Same energy here: it blocks the use of 68020 and 68881/68882 instructions that have to be emulated in software on the 68060. Use it if your 68060 doesn't have code to emulate those. ๐ญ
-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 is 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. Equivalent to-mcpu=5206, and it's now deprecated in favor of that option.
Use it for a microcontroller with a 5200 core, so the MCF5202, MCF5203, MCF5204 and MCF5206. ๐ฆ
-m5206eโ output for a 5206e ColdFire CPU. This option is now deprecated in favor of the equivalent-mcpu=5206e.-m528xโ output for a member of the ColdFire 528X family. Now deprecated in favor of the equivalent-mcpu=528x.-m5307โ output for a ColdFire 5307 CPU. Now deprecated in favor of the equivalent-mcpu=5307.-m5407โ output for a ColdFire 5407 CPU. Now deprecated in favor of the equivalent-mcpu=5407.-mcfv4eโ output for a ColdFire V4e family CPU (like547x/548x). This includes use of hardware floating-point instructions. It's equivalent to-mcpu=547x, and it's 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 runs relatively efficiently on either a 68020/68881, a 68030, or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.
This 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, a 68030, or a 68040. And yep, the generated code does use the 68881 instructions that are emulated on the 68060.
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 is"on"for ColdFire architectures and"off"for M680x0 architectures. Otherwise the default comes from the target CPU (either the default CPU, or the one you gave with-mcpu). For example, the default is"off"for-mcpu=5206and"on"for-mcpu=5206e.
GCC defines the macro __mcfhwdiv__ when this option is enabled. โญ
-mshortโ treat the typeintas 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โ don't treatintas 16 bits wide. This is the default.-mnobitfield,-mno-bitfieldโ don't 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, where functions taking a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. 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 gets generated for calls to those functions.
Also also: 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 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โ don't (or do) assume that unaligned memory references are handled by the system.-msep-dataโ generate code that lets the data segment sit 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 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 it's no more space- or time-efficient than just 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 isn't needed;-fPICsuffices.
GCC normally uses a single instruction to load values from the GOT. While that's relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger makes the linker report an error like:
relocation truncated to fit: R_68K_GOT16O foobar
If that 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. ๐
-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โ bestie, this one just says: emit callgraph information. That's it, that's the whole vibe ๐-mslow-bytes,-mno-slow-bytesโ makes it prefer word access when it's reading byte quantities ๐ฆ-mlittle-endian,-mbig-endianโ generate code for a little-endian target โจ-m210,-m340โ generate code for the 210 processor ๐-mno-lsimโ assume that runtime support has been provided, so omit the simulator library (libsim.a) from the linker command line. no cap, that's the whole thing ๐ซถ-mstack-increment=sizeโ sets the max amount for a single stack increment operation. Big values can make programs faster when they've got functions that need a large amount of stack spaceโฆ but they can also trigger a segmentation fault if the stack gets extended too much ๐ญ The default value is0x1000.
๐ธ MicroBlaze Options ๐ธ
-msoft-floatโ use software emulation for floating point (this is the default) ๐ง-mhard-floatโ use hardware floating-point instructions, we love a glow-up โจ-mmemcpyโ do not optimize block moves, just usememcpy.-mno-clearbssโ okay so, this option is deprecated ๐ use-fno-zero-initialized-in-bssinstead.-mcpu=cpu-typeโ use features of, and schedule code for, the given CPU. Supported values are in the formatvX.YY.Z, whereXis a major version,YYis the minor version, andZis compatibility code. Example values arev3.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 ๐ฅ-mxl-pattern-compareโ use pattern compare instructions ๐ฆ-msmall-dividesโ use table lookup optimization for small signed integer divisions โจ-mxl-stack-checkโ deprecated, bestie ๐ use-fstack-checkinstead.-mxl-gp-optโ use GP-relative.sdata/.sbsssections ๐-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โ pick your 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 calledxmdstub. 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.
Heads up bestie: the option-xl-mode-app-modelis a deprecated alias for-mxl-mode-app-model๐
-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, mips64r5 and mips64r6.
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, xlr and xlp.
The special value from-abi selects the most compatible architecture for the selected ABI (that is, mips1 for 32-bit ABIs and mips3 for 64-bit ABIs) โจ
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 ๐ฆ
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 the 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's possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family ๐
-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 (do not 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. So likeโฆ testing only, bestie ๐-minterlink-compressed,-mno-interlink-compressedโ require (do not 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 ๐ซถ-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 ๐
Two more o32 ABI variants exist so we can transition from 32-bit to 64-bit registers, bestie. They're FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). FPXX says all code MUST run correctly whether it's using 32-bit or 64-bit registers, and it can interlink with either FP32 or FP64 โ but like, not both, that's giving messy. FP64A is basically FP64's cousin except it forbids odd-numbered single-precision registers. Slay for using it 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 touching FPU modes. ๐
-mabicalls,-mno-abicallsโ generate (or don't generate) code that's suitable for SVR4-style dynamic objects.-mabicallsis the default for SVR4-based systems.-mshared,-mno-sharedโ generate (or don't generate) code that's fully position-independent, so it can be linked into shared libraries. This only affects-mabicalls.
Okay so all -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. But as a lil 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 mode is selected by -mno-shared.
-mno-shared needs binutils 2.16 or higher and produces objects that can only be linked by the GNU linker. BUT it doesn't affect the ABI of the final executable, only the ABI of relocatable objects, no cap. Using -mno-shared generally makes executables smaller and quicker, we love that. โจ
-mshared is the default.
-mplt,-mno-pltโ assume (or don't assume) that the static and dynamic linkers support PLTs and copy relocations. This only affects-mno-shared -mabicalls. For the n64 ABI, this does nothing without-msym32.
Bestie, you can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.
-mxgot,-mno-xgotโ lift (or don't lift) the usual restrictions on the size of the global offset table.
GCC normally uses a single instruction to load values from the GOT. Efficient? Yes. But it only works if the GOT is smaller than about 64k. Anything bigger and the linker reports an error like:
relocation truncated to fit: R_MIPS_GOT16 foobar
If that happens, recompile your code with -mxgot. This works with very large GOTs, though the code is also less efficient, since it takes three instructions to fetch the value of a global symbol. ๐ข
Note that some linkers can create multiple GOTs. If you have such a linker, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do.
These options have no effect unless GCC is generating position independent code.
-mgp32โ assume that general-purpose registers are 32 bits wide.-mgp64โ assume that general-purpose registers are 64 bits wide.-mfp32โ assume that floating-point registers are 32 bits wide.-mfp64โ assume that floating-point registers are 64 bits wide.-mfpxxโ do not assume the width of floating-point registers.-mhard-floatโ use floating-point coprocessor instructions.-msoft-floatโ don't use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.-mno-floatโ same as-msoft-float, but it ALSO asserts that the program being compiled doesn't perform any floating-point operations. 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-floataccidentally contains floating-point operations, it is likely to suffer a link-time or run-time failure.-msingle-floatโ assume that the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ assume that 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 known to support these registers. When using the o32 FPXX ABI,-mno-odd-spregis set by default.-mabs=2008,-mabs=legacyโ these options control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with theabs.fmtandneg.fmtmachine instructions.
By default, or when -mabs=legacy is used, the legacy treatment is selected. In this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead unless the -ffinite-math-only option has also been specified.
The -mabs=2008 option selects the IEEE 754-2008 treatment. In this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. These instructions are therefore always used for the respective operations. ๐
-mnan=2008,-mnan=legacyโ these options control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.
The -mnan=legacy option 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.
The -mnan=2008 option 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. Yes it's literally the opposite, iconic. ๐
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_revto 1.-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_revto 2.-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. The option-mips3dimplies-mpaired-single. ๐-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โ forcelongtypes to be 64 bits wide. See-mlong32for an explanation of the default and the way that the pointer size is determined.-mlong32โ forcelong,int, and pointer types to be 32 bits wide.
The default size of ints, longs and pointers depends on the ABI. All the supported ABIs use 32-bit ints. The n64 ABI uses 64-bit longs, as does the 64-bit EABI; the others use 32-bit longs. Pointers are the same size as longs, 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. ๐๏ธ-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. ๐
If the linker is out here complaining that an app is using way too much small data, bestie, you might wanna try rebuilding the less performance-critical parts with -mno-local-sdata. And like, you might also wanna build big libraries with -mno-local-sdata too, so those libraries leave more room for the main program. Teamwork, y'know? ๐ซถ
-mextern-sdata,-mno-extern-sdataโ Assume (or do not assume, bestie) that externally-defined data lives in a small data section if its size fits within the-Glimit.-mextern-sdatais the default for all configurations. ๐
Okay so here's the tea: 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 Var is placed in a small data section. If Var is defined by another module, you gotta either compile that module with a high-enough -G setting or slap a "section" attribute onto Var's definition. And if Var is common? You must link the application with a high-enough -G setting. No skipping this, it's giving strict. ๐ค
The easiest way to satisfy all these restrictions is to compile and link every module with the same -G option. Simple. Clean. Iconic. โจ But say you wanna build a library that supports several different small data limits โ you can do that 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. Look at you, flexible queen. ๐
-mgpopt,-mno-gpoptโ Use (or don't use) GP-relative accesses for symbols that are known to be in a small data section; peep-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations, periodt.
-mno-gpopt comes in clutch for cases where the $gp register might not hold the value of "_gp". Like, 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 those situations, the boot monitor itself is usually compiled with -G0.) Lowkey chaotic but okay.
Heads up: -mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. It's a whole package deal. ๐
-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. Trade-offs, bestie, we love a trade-off. ๐ฆ-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ Put uninitialized"const"variables in the read-only data section. This option is only meaningful in conjunction with-membedded-data. Only. Meaningful. Together. Iykyk. ๐-mcode-readable=setting โ Specify whether GCC may generate code that reads from executable sections. There are three possible settings, and honestly? Pick your fighter:-mcode-readable=yesโ Instructions may freely access executable sections. This is the default setting. Freedom, baby! ๐-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. Niche but slay. โจ-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. It's giving legacy, respect the elders. ๐-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. Macro glow-up. ๐
-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 do not trap) on integer division by zero. Dividing by zero is not the vibe, bestie. ๐ญ
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, 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. Turning off safety? Bold choice, but okay. ๐
-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 it only takes effect when the selected architecture is known to support bonding. Conditional queen. ๐-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. Kernel said "not today." ๐ญ-mmemcpy,-mno-memcpyโ Force (or do not force) the use of"memcpy"for non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. Inlining is the moment. โจ-mlong-calls,-mno-long-callsโ Disable (or do not disable) use of the"jal"instruction. Calling functions using"jal"is more efficient but requires the caller and callee to be in the same 256 megabyte segment. Proximity matters, bestie. ๐ซถ
This option has no effect on abicalls code. The default is -mno-long-calls.
-mmad,-mno-madโ Enable (or disable) use of the"mad","madu"and"mul"instructions, as provided by the R4650 ISA.-mimadd,-mno-imaddโ Enable (or disable) use of the"madd"and"msub"integer instructions. The default is-mimaddon architectures that support"madd"and"msub"โ except for the 74k architecture, where it was found to generate slower code. 74k said "not me" and honestly, valid. ๐-mfused-madd,-mno-fused-maddโ Enable (or disable) use of the floating-point multiply-accumulate instructions, when they're available. The default is-mfused-madd.
Now listen, this part is important: 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. Science, bestie. ๐ง
-nocppโ Tell the MIPS assembler to not run its preprocessor over user assembler files (with a.ssuffix) when assembling them. Preprocessor said "I'm out." ๐ช-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. Not GCC's problem, the assembler handles it. ๐ ๏ธ-mfix-r4000,-mno-fix-r4000โ Work around certain R4000 CPU errata:- 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.
Three whole bugs. R4000 was going through it. ๐ญ
-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.
Just the one bug for this one. Small mercies. ๐
-mfix-r10000,-mno-fix-r10000โ Work around certain R10000 errata:"ll"/"sc"sequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier. Deadlock!! Scary!! ๐
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 a"nop"instruction 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. Six instructions or fewer, okay, noted. ๐-mfix-rm7000,-mno-fix-rm7000โ Work around the RM7000"dmult"/"dmultu"errata. The workarounds are implemented by the assembler rather than by GCC.-mfix-vr4120,-mno-fix-vr4120โ Work around certain VR4120 errata:"dmultu"does not always produce the correct result."div"and"ddiv"do 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.
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. Division errors? Can't relate, but glad we're fixing it. ๐
-mfix-vr4130โ Work around the VR4130"mflo"/"mfhi"errata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids using"mflo"and"mfhi"if the VR4130"macc","macchi","dmacc"and"dmacchi"instructions are available instead. See? Adaptation. Main character energy. ๐-mfix-sb1,-mno-fix-sb1โ Work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2"F1"and"F2"floating-point errata.) Parenthetical tea. โ-mr10k-cache-barrier=setting โ Specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors.
Bestie, we are deep in the MIPS lore right now and honestly? It's giving encyclopedic. Keep scrolling, there's more. ๐
Okay so picture this: the R10K is out here doing the same thing as lots of other processors โ it tries to predict which way a conditional branch is gonna go, then speculatively runs instructions from the "taken" branch. Later? It aborts those instructions if the predicted outcome is wrong. But plot twist, bestie: on the R10K, even aborted instructions can have side effects. ๐
This problem only affects kernel stores and, depending on the system, kernel loads. Example time: a speculatively-executed store may load the target memory into cache and mark the cache line as dirty, even if the store itself is later aborted. If a DMA operation writes to the same area of memory before the "dirty" line is flushed, the cached data overwrites the DMA-ed data. See the R10K processor manual for a full description, including other potential problems. ๐
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 the following regions does 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. ๐
If the input program contains a function declaration such as:
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 (such as hand-written assembly code) 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. If 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). The default depends on the target GCC was configured for, but commonly is either"_flush_func"or"__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. 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 the default for the selected architecture. By default, Branch Likely instructions may be generated if they are supported by the selected architecture. An exception is for the MIPS32 and MIPS64 architectures and processors that implement those architectures; for those, Branch Likely instructions are not generated by default because the MIPS32 and MIPS64 architectures specifically deprecate their use.
These options control which form of branches will be generated. The default is -mcompact-branches=optimal.
-mcompact-branches=neverโ ensures that compact branch instructions will never be generated.-mcompact-branches=alwaysโ ensures that a compact branch instruction will be generated if available for MIPS Release 6 onwards. If a compact branch instruction is not available (or pre-R6), a delay slot form of the branch will be used instead. If it is used for MIPS16/microMIPS targets, it will be just ignored now. The behaviour for MIPS16/microMIPS may change in future, since they do have some compact branch instructions.-mcompact-branches=optimalโ 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 is not filled, a compact branch will be chosen if one is available.-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 are 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 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 is enabled by default at optimization level -O3.
-msynci,-mno-synciโ Enable (disable) generation of"synci"instructions on architectures that support it. The"synci"instructions (if enabled) are generated when"__builtin___clear_cache"is 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 is generally safe to use "synci". However, on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior. โ ๏ธ
-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-calls is the default if GCC was configured to use an assembler and a linker that support the ".reloc" assembly directive and -mexplicit-relocs is in effect. With -mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone without help from the compiler.
-mmcount-ra-address,-mno-mcount-ra-addressโ Emit (do not emit) code that allows"_mcount"to modify the calling function's return address. When enabled, this option extends the usual"_mcount"interface with a new ra-address parameter, which has type"intptr_t *"and is passed in register$12."_mcount"can 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", if ra-address is 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 is unused.
This optimization is off by default at all optimization levels.
-mlxc1-sxc1,-mno-lxc1-sxc1โ When applicable, enable (disable) the generation of"lwxc1","swxc1","ldxc1","sdxc1"instructions. Enabled by default.-mmadd4,-mno-madd4โ When applicable, enable (disable) the generation of 4-operand"madd.s","madd.d"and 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 the"rE"epsilon 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 the"PREFIX"assembly 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 range 0 to 255 from the value held in the register. This 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โ make the compiler dodge the multiply-instruction bugs on MN10300 processors. This is the default, bestie, so it's just... already happening. ๐-mno-mult-bugโ okay so do NOT generate the bug-avoiding code for those MN10300 multiply instructions. You're on your own with the silicon, no cap. ๐-mam33โ generate code using features that are specific to the AM33 processor. Slay. โจ-mno-am33โ don't use those AM33-specific features. This is the default. Lowkey the chill option.-mam33-2โ generate code using features specific to the AM33/2.0 processor. Leveled up. ๐ฆ-mam34โ generate code using features specific to the AM34 processor. Main character processor energy. ๐-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's just vibes for scheduling. The CPU type has to be one ofmn10300,am33,am33-2oram34. Periodt.-mreturn-pointer-on-d0โ when the compiler generates a function that returns a pointer, return that pointer in botha0andd0. Otherwise the pointer comes back only ina0, and trying to call such functions without a prototype gives you errors. Heads up: this option is on by default, so use-mno-return-pointer-on-d0to turn it off. ๐ซถ-mno-crt0โ do not link in the C run-time initialization object file. Bye, startup code. ๐ญ-mrelaxโ tell the linker it should do a relaxation optimization pass to shorten branches, calls and absolute memory addresses. Fr fr this one only does anything when you use it on the command line for the final link step.
โ ๏ธ This option makes symbolic debugging impossible. Like, completely. Choose wisely bestie. ๐
-mliwโ let the compiler generate Long Instruction Word instructions if the target is AM33 or later. This is the default. Also it defines the preprocessor macro__LIW__. ๐-mno-liwโ don't allow Long Instruction Word instructions. This one defines the preprocessor macro__NO_LIW__.-msetlbโ allow the compiler to generateSETLBandLccinstructions if the target is AM33 or later. Default! And it defines the preprocessor macro__SETLB__. โจ-mno-setlbโ don't allowSETLBorLccinstructions. Defines the preprocessor macro__NO_SETLB__.
๐ Moxie Options ๐
-mebโ generate big-endian code. This is the default formoxie-*-*configurations. ๐-melโ generate little-endian code. Flip it, reverse it. ๐ฆ-mmul.xโ generatemul.xandumul.xinstructions. This is the default formoxiebox-*-*configurations.-mno-crt0โ do not link in the C run-time initialization object file.
๐ MSP430 Options ๐
Okay these ones are defined for the MSP430, let's get into it:
-masm-hexโ force assembly output to always use hex constants. Normally these constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. (Aesthetic purposes!! iconic. ๐ )-mmcu=โ pick the MCU to target. It's used to create a C preprocessor symbol based on the MCU name, converted to upper case and pre- and post-fixed with__. That symbol then gets used by themsp430.hheader file to pick an MCU-specific supplementary header file.
This option also sets the ISA to use. If the MCU name is one that's known to only support the 430 ISA, then that's the one selected โ otherwise the 430X ISA gets selected. The generic MCU name msp430 also selects the 430 ISA. Similarly, the generic msp430x MCU name selects the 430X ISA. ๐ธ
On top of that, an MCU-specific linker script gets added to the linker command line. The script's name is the name of the MCU with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and makes the linker go look 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. โจ
GCC searches for the devices.csv file using these methods in this exact precedence order, where the first method takes precedence over the second, which takes precedence over the third:
- Include path specified with
-Iand-Lโdevices.csvgets 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โ define the value of the global environment variableMSP430_GCC_INCLUDE_DIRto the full path to the directory containingdevices.csv, and GCC will search this directory fordevices.csv. Ifdevices.csvis found, this directory will also get registered as an include path and linker library path. So header files and linker scripts in this directory can be used without manually specifying-Iand-Lon the command line. Convenient bestie. ๐ - The
msp430-elf{,bare}/include/devicesdirectory โ finally, GCC will look atmsp430-elf{,bare}/include/devicesfrom the toolchain root directory. This directory does not exist in a default installation, but if you made it and copieddevices.csvthere, then the MCU data will be read. Same as above, this directory also gets registered as an include path and linker library path.
If none of those search methods find devices.csv, then the hard-coded MCU data is used. ๐
-mwarn-mcu/-mno-warn-mcuโ enables or disables warnings about conflicts between the MCU name given by-mmcuand the ISA set by-mcpuand/or the hardware multiply support set by-mhwmult. It also toggles warnings about unrecognized MCU names. This option is on by default.-mcpu=โ specifies the ISA to use. Accepted values aremsp430,msp430xandmsp430xv2.
๐จ This option is deprecated. Use the -mmcu= option to select the ISA instead. Okay? Okay. ๐ญ
-msimโ link to the simulator runtime libraries and linker script. This overrides any scripts that-mmcu=would have picked.-mlargeโ use large-model addressing (20-bit pointers, 20-bitsize_t). Big brain mode. ๐ง-msmallโ use small-model addressing (16-bit pointers, 16-bitsize_t). Cutie compact mode. ๐-mrelaxโ this one gets passed to the assembler and linker, and lets the linker perform certain optimizations that can't happen until the final link.mhwmult=โ describes the type of hardware multiply supported by the target. Accepted values:noneโ for no hardware multiply16bitโ for the original 16-bit-only multiply supported by early MCUs32bitโ for the 16/32-bit multiply supported by later MCUsf5seriesโ for the 16/32-bit multiply supported by F5-series MCUsautoโ also acceptable, and this tells GCC to deduce the hardware multiply support based on the MCU name given by-mmcu. If no-mmcuoption is specified, or the MCU name isn't recognized, then no hardware multiply support is assumed.
auto is the default setting. ๐
Hardware multiplies are normally performed by calling a library routine, which saves space in the generated code. But when you're compiling at -O3 or higher, the hardware multiplier is invoked inline instead โ bigger code, but faster. ๐ฅ
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 and in normal code. Slay for safety. โจ
-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.
โ ๏ธ The tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications. Be careful bestie. ๐
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 between0and64inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When this value needs to be exceeded, anmspabihelper function gets 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 the resulting value is used instead. Math!! โจ
-mcode-region=/-mdata-region=โ these 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=โ passes on a request to the assembler to enable the fixes for the named silicon errata. Fixing the silicon's mistakes, we love to see it. ๐-msilicon-errata-warn=โ 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 if there are problems 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. Zoom zoom. ๐ฅ-mno-ext-perfโ do not generate performance extension instructions.-mext-perf2โ okay bestie, this one generates performance extension 2 instructions. โจ-mno-ext-perf2โ and this one says do not generate performance extension 2 instructions. ๐ซ-mext-stringโ generates string extension instructions. ๐งต-mno-ext-stringโ do not generate string extension instructions. ๐-mv3pushโ generates v3 push25/pop25 instructions. ๐-mno-v3pushโ do not generate v3 push25/pop25 instructions. ๐-m16-bitโ generates 16-bit instructions. ๐-mno-16-bitโ do not generate 16-bit instructions. ๐ซ-misr-vector-size=numโ sets the size of each interrupt vector, and it literally has to be4or16, no other vibe checks accepted. ๐-mcache-block-size=numโ sets the size of each cache block, which must be a power of 2 between4and512. โจ-march=archโ specifies the name of the target architecture. ๐๏ธ-mcmodel=code-modelโ sets the code model to one of these, bestie:smallโ all the data and read-only data segments must be within512KBaddressing space. The text segment must be within16MBaddressing space.mediumโ the data segment must be within512KBwhile the read-only data segment can be within4GBaddressing space. The text segment should be still within16MBaddressing space.largeโ all the text and data segments can be within4GBaddressing space.
-mctor-dtorโ enables the constructor/destructor feature. ๐ ๏ธ-mrelaxโ guides the linker to relax instructions. ๐
Nios II Options โจ๐ง
These are the options defined for the Altera Nios II processor. ๐๐ซถ
-G numโ puts global and static objects less than or equal tonumbytes into the small data or BSS sections instead of the normal data or BSS sections. The default value ofnumis8. ๐-mgpopt=option,-mgpopt,-mno-gpoptโ generate (do not generate) GP-relative accesses. The following option names are recognized, no cap:noneโ do not generate GP-relative accesses.localโ generate 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.globalโ as 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. โ ๏ธdataโ generate 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. ๐ฆallโ generate 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. ๐ซถ
-mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none. ๐
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. ๐ญ
-mgprel-sec=regexpโ 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. Theregexpis 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โ specifies names of sections that can be accessed via a16-bitoffset from"r0"; that is, in the low32Kor high32Kof the32-bitaddress space. It is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. Theregexpis 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. ๐
-mel,-mebโ generate little-endian (default) or big-endian (experimental) code, respectively. ๐-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=Noption enables use of a custom instruction with encodingNwhen generating code that usesinsn. 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_lroundf"function 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. 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. ๐ง
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.
okay so before we get into the named FPU configs, quick lil reminder โ you can snag way 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. ๐
-mcustom-fpu-cfg=nameโ this flips on a predefined, named set of custom instruction encodings (peep-mcustom-insnabove for the whole vibe). Right now, these are the sets 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
important!! Custom instruction assignments handed over by individual-mcustom-insn=options override whatever-mcustom-fpu-cfg=said. Doesn't matter what order they show up in on the command line โ the individual one wins. periodt. ๐
and again, for more local control over picking a FPU config, there's the target("custom-fpu-cfg=name") function attribute or pragma. ๐ธ
The name fph2 is short for Nios II Floating Point Hardware 2 Component. Now listen โ the custom instructions enabled by -mcustom-fmins=233 and -mcustom-fmaxs=234 only get generated if -ffinite-math-only is specified. And the custom instruction enabled by -mcustom-round=248 only gets generated if -fno-math-errno is specified. Also, unlike every other config, -fsingle-precision-constant is not set here. ๐ซถ
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 point at the location of the alternate startup code that the HAL BSP hands you. ๐-msmallcโ link with a limited version of the C library,-lsmallc, instead of Newlib. ๐-msys-crt0=startfileโ startfile is the file name of the startfile (crt0) to use when linking. This option is only useful alongside-mhal. ๐ซ-msys-lib=systemlibโ systemlib is the library name of the library that provides the low-level system calls the C library needs, e.g."read"and"write". This option is typically used to link with a library provided by a HAL BSP. ๐
โจ Nvidia PTX Options โจ
These options are defined for Nvidia PTX:
-m64โ ignored, but preserved for backward compatibility. Only the 64-bit ABI is supported. ๐-march=architecture-stringโ generate code for the specified PTX ISA target architecture (e.g.sm_35). 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, forsm_35, it has the value350. ๐-misa=architecture-stringโ alias of-march=.-march-map=architecture-stringโ select the closest available-march=value that is not more capable. Like, 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, for3.1the macros have the values3and1respectively. ๐-mmainkernelโ link in code for a__mainkernel. This is for stand-alone instead of offloading execution. ๐ง-moptimizeโ apply partitioned execution optimizations. This is the default when any level of optimization is selected. ๐ฅ-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, it 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 allows all threads in each warp to execute, 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. ๐-mgompโ generate code for use in OpenMP offloading: enables-msoft-stackand-muniform-simtoptions, and selects the corresponding multilib variant. ๐
๐ 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 is for compatibility purposes only. This used to select linker and preprocessor options for use with newlib. ๐-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. Beware!! 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. ๐ญ-mmcu=mcuโ tells GCC which PRU MCU variant you're building for. Wanna know the exact list of supported MCUs? Go check Newlib, bestie, it's all there.-mno-relaxโ makes GCC pass--no-relaxto the linker instead of--relax. That's it, that's the whole vibe.-mloopโ lets GCC use the LOOP instruction (or not, depending on which version you pick). Your call ๐-mabi=variantโ picks which ABI variant your output code targets.-mabi=ti= the unmodified TI ABI.-mabi=gnu= a GNU variant that copes more naturally with certain GCC assumptions. Here's the tea on the differences:
Function Pointer Size โ TI ABI says function (code) pointers are 16-bit, but GNU only supports 32-bit data and code pointers. So that's a whole thing.
Optional Return Value Pointer โ if a function returns something bigger than 64 bits, it gets passed using a hidden pointer as the first argument. But TI ABI mandates that pointer can be NULL when the caller isn't even using the returned value ๐. GNU always passes and expects a valid return value pointer, no exceptions.
The current -mabi=ti implementation just straight up raises a compile error when it detects any of the above code constructs. And as a consequence, the standard C library can't be built and gets omitted when you link with -mabi=ti. Iconic behavior honestly ๐
Relaxation is a GNU feature and for safety reasons it's disabled when you use -mabi=ti. The TI toolchain doesn't emit relocations for QBBx instructions, so the GNU linker can't adjust them when shortening adjacent LDI32 pseudo instructions. No cap. โจ
๐ 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. An ABI-string has two parts: the size of integer types, and the registers used for floating-point types. For example-march=rv64ifd -mabi=lp64dmeans long and pointers are 64-bit (which implicitly defines int as 32-bit), and floating-point values up to 64 bits wide get passed in F registers. 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 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, specify one explicitly bestie. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. 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, so likeโฆ be aware.
-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 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. Examples includerv64i,rv32g,rv32e, andrv32imaf.
When -march= is not specified, use the setting from -mcpu.
If both -march and -mcpu= are not specified, the default for this argument is system dependent โ so users who want specific architecture extensions should specify one explicitly. ๐
-mcpu=processor-stringโ use the architecture of, and optimize the output for, the given processor specified by a particular CPU name. 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.-mtune=processor-stringโ optimize the output for the given processor, specified by microarchitecture or particular CPU name. 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= is not specified, use the setting from -mcpu โ and the default is rocket if both are not specified.
The size choice is not intended for use by end-users. It's used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but does not override the pipeline info. This helps reduce code size while still giving good performance. Slay. โจ
-mpreferred-stack-boundary=numโ attempts to keep the stack boundary aligned to a 2 raised to num byte boundary. If-mpreferred-stack-boundaryis not specified, the default is4(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. Like, all of them, no exceptions bestie.
-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 uses library function calls. The default is to use fast inline prologues and epilogues.-minline-atomics-mno-inline-atomicsโ do or don't use smaller but slower subword atomic emulation code that uses libatomic function calls. The default is to use fast inline subword atomics that do not require libatomic ๐ฅ.-mshorten-memrefs-mno-shorten-memrefsโ do or do not attempt to make more use of compressed load/store instructions by replacing a load/store of'base register + large offset'with a new load/store of'new base + small offset'. If the new base gets stored in a compressed register, then the new load/store can 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 GiBand+2 GiB. Programs can be statically or dynamically linked. This is the default code model.-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.
The code generated by the medium-any code model is position-independent, but it's not guaranteed to function correctly when linked into position-independent executables or libraries. ๐
-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.-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 (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32.-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. Supported locations areglobalfor a global canary ortlsfor a per-thread canary in the TLS block.
With the 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 as this is entirely for use within the Linux kernel ๐ธ.
๐ 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 is"none", which uses software for both multiplication and division โ this is the default. The"g13"value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. The"g14"value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The value"rl78"is an alias for"g14"and the value"mg10"is an alias for"none". ๐-mcpu=g10,-mcpu=g13,-mcpu=g14,-mcpu=rl78โ tells GCC which RL78 core you're targeting. Default is the G14 core, aka the S3 core, aka just plain RL78. The G13 (S2) core has no multiply or divide instructions at all โ it outsources those to a hardware peripheral instead. And the G10 (S1) core has no register banks, so it rolls with a whole different calling convention. ๐
Setting this option also picks which flavor of hardware multiply support you get โ unless you explicitly override it with -mmul=none on the command line. So -mcpu=g13 turns on the G13 hardware multiply peripheral, and -mcpu=g10 straight up turns off hardware multiplication entirely, bestie. ๐
Note (important!!) โ even though RL78/G14 is the default target, writing -mcpu=g14 or -mcpu=rl78 on the command line does change how the toolchain behaves, because it also switches on G14 hardware multiply support. If you don't pass those on the command line, software multiplication routines get used even though the code is targeting the RL78 core. That's there for backwards compatibility with older toolchains that had no hardware multiply-and-divide support. ๐ซถ
Also a C preprocessor macro gets defined based on this setting. Possible values: __RL78_G10__, __RL78_G13__ or __RL78_G14__.
-mg10,-mg13,-mg14,-mrl78โ these are just aliases for the matching-mcpu=option. They exist purely for backwards compatibility, no cap. โจ-mallregsโ lets the compiler go ahead and use all the available registers. By defaultr24..r31are reserved for interrupt handlers, but flip this on and those registers can be used in ordinary functions too. ๐ฅ-m64bit-doubles,-m32bit-doublesโ makes thedoubledata type 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles.-msave-mduc-in-interrupts,-mno-save-mduc-in-interruptsโ says that interrupt handler functions should preserve the MDUC registers. You only need this if normal code might be using those MDUC registers, like when it does multiplication and division. The default is to ignore the MDUC registers, because that makes interrupt handlers faster. Heads up though: you need to pass the target option-mg13for this to work, since the feature only exists on the G13 target (S2 core). And the MDUC registers only actually get saved if the interrupt handler does a multiplication or division operation, or calls another function. ๐ง
๐ฆ IBM RS/6000 and PowerPC Options ๐ฆ
These -m options are defined for the IBM RS/6000 and PowerPC, bestie, buckle up:
-mpowerpc-gpopt,-mno-powerpc-gpopt,-mpowerpc-gfxopt,-mno-powerpc-gfxopt,-mpowerpc64,-mno-powerpc64,-mmfcrf,-mno-mfcrf,-mpopcntb,-mno-popcntb,-mpopcntd,-mno-popcntd,-mfprnd,-mno-fprnd,-mcmpb,-mno-cmpb,-mhard-dfp,-mno-hard-dfpโ you use these bad boys to say which instructions are available on the processor you're using. Their default value gets decided when GCC is configured. Specifying-mcpu=cpu_typeoverrides whatever you set with these. And fr fr, the recommendation is to use the-mcpu=cpu_typeoption instead of listing these by hand. ๐ธ
So: -mpowerpc-gpopt lets GCC use the optional PowerPC architecture instructions in the General Purpose group, floating-point square root included. -mpowerpc-gfxopt lets GCC use the optional PowerPC architecture instructions in the Graphics group, floating-point select included.
The -mmfcrf option lets GCC generate the move from condition register field instruction, which is 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 instructions implemented on the POWER5 processor and other processors supporting the PowerPC V2.02 architecture. The -mpopcntd option lets GCC generate the popcount instruction implemented on the POWER7 processor and other processors supporting the PowerPC V2.06 architecture. The -mfprnd option lets GCC generate the FP round to integer instructions implemented on the POWER5+ processor and other processors supporting the PowerPC V2.03 architecture. The -mcmpb option lets GCC generate the compare bytes instruction implemented on the POWER6 processor and other processors supporting the PowerPC V2.05 architecture. 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 extra 64-bit instructions found in the full PowerPC64 architecture, and treat GPRs as 64-bit, doubleword quantities. GCC defaults to -mno-powerpc64.
-mcpu=cpu_typeโ sets the architecture type, register usage, and instruction scheduling parameters for the machine typecpu_type. The supported values forcpu_typeare401,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, andnative. ๐ญ (yeah it's a lot, that's the vibe)
-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endian), 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 corresponds to the host processor of the system doing the compilation. -mcpu=native has no effect if GCC doesn't recognize the processor. ๐
The other options specify a specific processor. Code generated under those options 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 โ it depends on what setting seems to produce optimal code for that CPU, and it doesn't necessarily reflect the actual hardware's capabilities. If you wanna set an individual option to a particular value, you may 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 may still enable or disable them individually if you're sure it'll work in your environment. ๐
-mtune=cpu_typeโ sets the instruction scheduling parameters for the machine typecpu_type, but doesn't set the architecture type or register usage the way-mcpu=cpu_typedoes. The same values forcpu_typeare used for-mtuneas for-mcpu. If you specify both, the generated code uses the architecture and registers set by-mcpu, but the scheduling parameters set by-mtune. โจ-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. Other data and code is only limited by the 64-bit address space.-maltivec,-mno-altivecโ generates code that uses (or 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=altivecto 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. Which is to say: 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. ๐
-mvrsave,-mno-vrsaveโ generates VRSAVE instructions when generating AltiVec code.-msecure-pltโ generates code that allowsldandld.soto build executables and shared libraries with non-executable.pltand.gotsections. This is a PowerPC 32-bit SYSV ABI option.-mbss-pltโ generates code that uses a BSS.pltsection thatld.sofills in, and requires.pltand.gotsections that are both writable and executable. This is a PowerPC 32-bit SYSV ABI option. โ ๏ธ-misel,-mno-iselโ this switch enables or disables the generation of ISEL instructions.-mvsx,-mno-vsxโ generates code that uses (or 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 that were 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 that were added in version 2.07 of the PowerPC ISA.-mpower8-fusion,-mno-power8-fusionโ generates code that keeps (or does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors. ๐-mpower8-vector,-mno-power8-vectorโ turns on (or off, bestie) codegen for the vector and scalar instructions that showed up in version 2.07 of the PowerPC ISA. It also flips on the built-in functions that let you get all up close and personal with those vector instructions. ๐-mquad-memory,-mno-quad-memoryโ generate code that uses (does not use) the non-atomic quad word memory instructions. Heads up:-mquad-memoryrequires 64-bit mode. no exceptions, no cap ๐ซถ-mquad-memory-atomic,-mno-quad-memory-atomicโ same energy but for the atomic quad word memory instructions. And yeah,-mquad-memory-atomicalso requires 64-bit mode. โญ-mfloat128,-mno-float128โ enable/disable the__float128keyword for IEEE 128-bit floating point, and pick whether you get software emulation for IEEE 128-bit floating point or actual hardware instructions. ๐ฆ
The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support. And IEEE 128-bit floating point is only supported on Linux, periodt.
The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on every other system.
If you're using the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, IEEE 128-bit floating point support will also enable generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ if you didn't ask for ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ IEEE 128-bit floating point gets done with software emulation. it's giving patience ๐ญ
-mfloat128-hardware,-mno-float128-hardwareโ enable/disable using ISA 3.0 hardware instructions to back the__float128data type. ๐
The default for -mfloat128-hardware is 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 (GNU/Linux is in that club too ๐). 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, exactly like-mpowerpc64does.-mfull-toc,-mno-fp-in-toc,-mno-sum-in-toc,-mminimal-tocโ these four remix how the TOC (Table Of Contents) gets generated, and the TOC is built for every executable file, so yeah, it matters. ๐ธ
-mfull-toc is the one 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 drops floating-point constants into the TOC. But plot twist: only 16,384 entries are available in the TOC. that's the whole budget bestie ๐
If you get a linker error message saying you've overflowed the available TOC space, you can reduce how much TOC space you're using with -mno-fp-in-toc and -mno-sum-in-toc. -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 may specify one or both of these options. Each one makes GCC produce very slightly slower and larger code, at the expense of conserving TOC space. trade-off queen โจ
If you still run out of space in the TOC even with both of those options specified, pass -mminimal-toc instead. This option makes GCC create only one TOC entry for every file. When you specify it, GCC produces code that is slower and larger but uses โจextremelyโจ little TOC space. You may wish to use this option only on files that contain less frequently-executed code.
-maix64,-maix32โ enable the 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 the AIX-compatible ABI. Pass floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. Do not assume that the most significant double in a 128-bitlong doublevalue is properly rounded when comparing values and converting todouble. Use XL symbol names forlong doublesupport routines.
The AIX calling convention was extended but not initially documented, to handle an obscure K&R C case: 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 only is necessary when calling subroutines compiled by IBM XL compilers without optimization. iykyk ๐ง
-mpeโ support IBM RS/6000 SP Parallel Environment (PE). Links an application written to use message passing with special startup code so the application can actually 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 point at the appropriate directory location. The Parallel Environment does not support threads, so the-mpeoption and the-pthreadoption are incompatible. pick a lane bestie ๐ญ-malign-natural,-malign-powerโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux,-malign-naturaloverrides the ABI-defined alignment of larger types โ floating-point doubles, for example โ on their natural size-based boundary. The-malign-poweroption tells 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 (uses) the floating-point register set. Software floating-point emulation is provided if you use the-msoft-floatoption, and you also need to pass the option to GCC when linking. โจ-mmultiple,-mno-multipleโ generate code that uses (does not 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-mmultipleon little-endian PowerPC systems, since those instructions do not work when the processor is in little-endian mode. The exceptions are PPC740 and PPC750, which permit these instructions in little-endian mode. ๐-mupdate,-mno-updateโ generate code that uses (does not 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 that 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 the fine print, fr fr ๐-mavoid-indexed-addresses,-mno-avoid-indexed-addressesโ generate code that tries to avoid (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 (does not 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 (does not 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 (does not 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 (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. the way it just shrinks?? ๐ญ
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems, do not (do) assume that unaligned memory references are handled by the system.-mrelocatable,-mno-relocatableโ generate code that allows (does not 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, which is a table of 32-bit addresses generated by this option. For this to actually work, all objects linked together must be compiled with-mrelocatableor-mrelocatable-lib. And-mrelocatablecode aligns the stack to an 8-byte boundary. โจ-mrelocatable-lib,-mno-relocatable-libโ like-mrelocatable,-mrelocatable-libgenerates a".fixup"section so static executables can 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. mixing and matching, we love to see it ๐ซถ-mno-toc,-mtocโ on System V.4 and embedded PowerPC systems, do not (do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program. ๐-mlittle,-mlittle-endianโ System V.4 girlies and embedded PowerPC besties, compile for the processor in little-endian mode ๐-mlittle-endianis literally just-mlittle's twin, same vibes, no cap.-mbig,-mbig-endianโ System V.4 and embedded PowerPC, but make it big-endian mode ๐ and yeah,-mbig-endian==-mbig, exactly the same thing, don't overthink it.-mdynamic-no-picโ Darwin and Mac OS X only, babe: compile code so it's not relocatable, but its external references are. The resulting code slays for applications but absolutely cannot be a shared library. It's giving "apps only, no sharing" ๐-msingle-pic-baseโ treat the register used for PIC addressing as read-only instead of reloading it in the prologue of every single function (so extra, honestly). The runtime system is the one responsible for initializing that register with a valid value before execution even starts. Not your job, bestie, that's the runtime's problem โจ-mprioritize-restricted-insns=priority โ this one controls the priority assigned to dispatch-slot restricted instructions during the *second scheduling pass. *priority takes0,1, or2to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions. Pick your fighter ๐- *
-msched-costly-dep=dependence_type* โ controls which dependences the target counts as costly during instruction scheduling. dependence_type can be any of these:noโ no dependence is costly, we're unbothered ๐allโ all dependences are costly, everything is expensive, main character energytrue_store_to_loadโ a true dependence from store to load is costlystore_to_loadโ any dependence from store to load is costly- number โ any dependence whose latency is greater than or equal to number is costly
- *
-minsert-sched-nops=scheme* โ controls which NOP insertion scheme gets used during that second scheduling pass. scheme takes one of these:noโ don't insert NOPs. periodt.padโ pad with NOPs any dispatch group with vacant issue slots, according to the scheduler's groupingregroup_exactโ insert NOPs to force costly dependent insns into separate groups. Insert exactly as many NOPs as needed to force an insn into a new group, per the estimated processor grouping. Precision, bestie ๐- number โ same forcing-costly-dependent-insns-apart thing, but insert number NOPs to shove an insn into a new group
-mcall-sysvโ on System V.4 and embedded PowerPC systems, compile 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. Historical โจ-mcall-sysv-eabi,-mcall-eabiโ specify both-mcall-sysvand-meabioptions. Two for the price of one, we love a combo ๐ซถ-mcall-sysv-noeabiโ specify both-mcall-sysvand-mno-eabioptions. The no-eabi remix of the above ๐-mcall-aixdescโ System V.4 and embedded PowerPC systems: compile code for the AIX operating system.-mcall-linuxโ System V.4 and embedded PowerPC systems: compile code for the Linux-based GNU system ๐ง-mcall-freebsdโ System V.4 and embedded PowerPC systems: compile code for the FreeBSD operating system.-mcall-netbsdโ System V.4 and embedded PowerPC systems: compile code for the NetBSD operating system.-mcall-openbsdโ 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 for traceback_type arefull,part, andno. Three choices, that's the whole menu, iykyk. -maix-struct-returnโ return all structures in memory, as specified by the AIX ABI.-msvr4-struct-returnโ return structures smaller than8bytes in registers, as specified by the SVR4 ABI.- *
-mabi=abi-type* โ extend the current ABI with a particular extension, or remove that extension. Valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default. So many options, so little time ๐ -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. Also not likely to work if your system defaults to IBM extended-precisionlong double๐ If you change thelong doubletype from IBM extended-precision, the compiler issues a warning unless you use-Wno-psabi. Requires-mlong-double-128to be enabled.-mabi=elfv1โ change the current ABI to 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 ๐ฅ dramatic but true, bestie.-mabi=elfv2โ change the current ABI to 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 also likely to fail in spectacular ways ๐ธ same warning, same chaos.-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 has to insert an instruction before every non-prototyped call to set or clear bit6of 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 that bit. Less work, less mess ๐-msimโ on embedded PowerPC systems, assume the startup module is calledsim-crt0.oand the standard C libraries arelibsim.aandlibc.a. This is the default forpowerpc-*-eabisimconfigurations.-mmvmeโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibmvme.aandlibc.a.-madsโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.a.-myellowknifeโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a. Yellowknife is such a name honestly ๐-mvxworksโ on System V.4 and embedded PowerPC systems, specify that you're compiling for a VxWorks system.-membโ on embedded PowerPC systems, set the"PPC_EMB"bit 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 (or do not, respectively) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications. Picking-meabimeans:- the stack is aligned to an
8-byte boundary - a function
"__eabi"is called from"main"to set up the EABI environment - the
-msdataoption can use both"r2"and"r13"to point to two separate small data areas
- the stack is aligned to an
Picking -mno-eabi means:
- the stack is aligned to a
16-byte boundary - no EABI initialization function is called from
"main" - the
-msdataoption only uses"r13"to point to a single small data area
The -meabi option is on by default if you configured GCC using one of the powerpc*-*-eabi* options.
-msdata=eabiโ on System V.4 and embedded PowerPC systems: put small initialized"const"global and static data in the.sdata2section, which is pointed to by register"r2". Put small initialized non-"const"global and static data in the.sdatasection, pointed to by register"r13". Put small uninitialized global and static data in the.sbsssection, which sits adjacent to.sdata. The-msdata=eabioption is incompatible with the-mrelocatableoption ๐ and it also sets the-memboption.-msdata=sysvโ on System V.4 and embedded PowerPC systems: put small global and static data in the.sdatasection, pointed to by register"r13". Put small uninitialized global and static data in the.sbsssection, adjacent to.sdata. The-msdata=sysvoption is incompatible with the-mrelocatableoption too ๐-msdata=default,-msdataโ on System V.4 and embedded PowerPC systems: if-meabiis used, compile the same as-msdata=eabi, otherwise compile the same as-msdata=sysv. Choose-your-own-adventure โจ-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 register"r13"to address small data, though. 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. The basics, nothing fancy ๐-mreadonly-in-sdataโ put read-only objects in the.sdatasection as well. This is the default. Yes bestie, the default is already this ๐-mblock-move-inline-limit=num โ inline all block moves (like calls to"memcpy"or structure copies) that are *less than or equal to *num bytes. The minimum value for num is32bytes on 32-bit targets and64bytes on 64-bit targets. The default value is target-specific.-mblock-compare-inline-limit=num โ generate non-looping inline code for all block compares (like calls to"memcmp"or structure compares) that are *less than or equal to *num bytes. If num is0, 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 to *num bytes, but greater than the limit for non-loop inline block compare expansion. If the block length isn't constant, at most num bytes will be compared before"memcmp"gets called to compare the remainder of the block. The default value is target-specific.-mstring-compare-inline-limit=numโ bestie, this one caps how many string bytes get compared with inline code. So: compare at most num string bytes inline, and if the difference or the end of the string isn't found by the end of that inline compare, a call tostrcmporstrncmphandles the rest of the comparison. Default? 64 bytes. Slay.-G numโ on embedded PowerPC systems, this shoves 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. Default num is 8. Heads up though: the-G numswitch also gets passed to the linker, and all modules should be compiled with the same -G num value. Consistency is the vibe, fr fr.-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, do (or don't) emit register names in the assembly language output using symbolic forms. That's it, that's the whole thing ๐-mlongcall,-mno-longcallโ okay so by default this assumes every call is far away, which means a longer and more expensive calling sequence. Dramatic? Maybe. Necessary? Yes, for calls farther than 32 megabytes (33,554,432 bytes) from the current location. If the compiler knows a call can't be that far away, it generates a short call instead. And you can override this whole setting with theshortcallfunction 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 make slower code โ no cap. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. There's a plan to add this feature to the GNU linker for 32-bit PowerPC systems too, iykyk.
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. Noted ๐
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.
And in the future? GCC may ignore all longcall specifications when the linker is known to generate glue. So... watch this space ๐
-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 indlopen'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 the support is detected when configuring GCC โ and, in the case of 32-bit PowerPC, if GCC is configured with--enable-secureplt.
Real talk:-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together. Do not try it. It's giving undefined behaviour ๐ซ
-mtls-markers,-mno-tls-markersโ mark (or don't mark) calls to__tls_get_addrwith a relocation specifying the function argument. Why do we care? Because the 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. Teamwork makes the dream work ๐ค-mrecip,-mno-recipโ this turns on 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.
Also real talk: while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994) for reciprocal square roots. So basically: fast, but don't @ me about precision ๐ญ
-mrecip=optโ this one controls which reciprocal estimate instructions are allowed to be used. opt is a comma-separated list of options, and any of them may be preceded by a!to invert the option:allโ enable all estimate instructions. Everything. All of it โจdefaultโ enable the default instructions, which is 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 like, 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. Exclusion list energy ๐
-mrecip-precision,-mno-recip-precisionโ assume (or don't assume, bestie, live your truth) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. Selecting-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precision. And note: 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. Low-precision machines stay losing, sorry ๐ฅฒ-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-vectorize and -funsafe-math-optimizations must also be enabled. And the MASS libraries must be specified at link time. So like, three things at once, don't forget any of them ๐ซถ
-mfriz,-mno-frizโ generate (or don't generate) thefrizinstruction when the-funsafe-math-optimizationsoption is used to optimize rounding of floating-point values to 64-bit integer and back to floating point.
Important: the friz instruction does not return the same value if the floating-point number is too large to fit in an integer. So like... be aware ๐
-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 registerr2, and the static chain value to be loaded in registerr11.
-mpointers-to-nested-functions is on by default. And here's the catch: you cannot call through pointers to nested functions, or pointers to functions compiled in other languages that use the static chain, if you use -mno-pointers-to-nested-functions. So like, choose wisely ๐
-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 is not saved in the prologue, it gets saved just before the call through the pointer. The-mno-save-toc-indirectoption is the default. Procrastination but make it assembly โจ-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.
Okay so the lore: 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 corrected in more recent versions of GCC. This option may be used to generate code that is compatible with functions compiled with older versions of GCC. Legacy support era ๐
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 a global canary, ortlsfor a per-thread canary in the TLS block (the default with GNU libc version 2.4 or later).
With the tls 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. Canary but make it symbolic ๐ค
-mpcrel,-mno-pcrelโ generate (or don't generate) pc-relative addressing. Heads up: the-mpcreloption requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled. It's a package deal, no ร la carte ๐ฅ-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. Power10 girlies, this one's for you ๐-mmma,-mno-mmaโ generate (or don't generate) the MMA instructions. The-mmaoption requires that the option-mcpu=power10(or later) is enabled. Same energy as above, fr fr.
-mrop-protect,-mno-rop-protectโ Generate (or don't generate, bestie) ROP protection instructions when the target processor supports them. Currently this option disables the shrink-wrap optimization (-fshrink-wrap). ๐-mprivileged,-mno-privilegedโ Generate (or don't generate) code that will run in privileged state. ๐-mblock-ops-unaligned-vsx,-mno-block-ops-unaligned-vsxโ Generate (or don't generate) unaligned vsx loads and stores for inline expansion ofmemcpyandmemmove. ๐ฆ--param rs6000-vect-unroll-limit=โ The vectorizer will check with target 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 is four. โจ
๐ธ RX Options ๐ธ
okay bestie, these command-line options are defined for RX targets: ๐
-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 RX floating-point hardware only works on 32-bit values, which is 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-doublesoption is used. Note If the-fpuoption is enabled then-funsafe-math-optimizationsis also enabled automatically. This is because the RX FPU instructions are themselves unsafe. ๐ญ-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 theMVTIPLinstruction. The RX200 series does not have a hardware floating-point unit and so-nofpuis 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 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 (-O2etc) 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-mpidoption 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, usuallyr13, 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-limitand/or the-mint-registercommand-line options are enabled. Starting with registerr13and proceeding downwards, registers are allocated first to satisfy the requirements of-mint-register, then-mpidand finally-msmall-data-limit. Thus it is possible for the small data area register to ber8if both-mint-register=4and-mpidare specified on the command line. By default this feature is not enabled. The default can be restored via the-mno-pidcommand-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,SUNTILSWHILEand 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-insnsoption 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. ๐
Note: The generic GCC command-line option-ffixed-reghas special significance to the RX port when used with the"interrupt"function 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. ๐
-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. ๐
like bestie the -mbackchain saga is not over, buckle up ๐
Generally speaking, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain. However โ and this is the tea โ using the backchain for debugging purposes usually requires that the whole binary be built with -mbackchain. Also note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. And if you wanna build a linux kernel, use -msoft-float.
The default is to not maintain the backchain. periodt. โจ
-mpacked-stack,-mno-packed-stackโ use (or don't use) the packed stack layout, bestie. When-mno-packed-stackis specified, the compiler uses all fields of the96/160byte register save area only for their default purpose; unused fields still take up stack space ๐ญ. When-mpacked-stackis specified, register save slots are densely packed at the top of the register save area; unused space gets reused for other purposes, which lets you use the available stack space more efficiently. But โ and there's always a but โ 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. The default is to not use the packed stack layout.
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. ๐ซถ Heads up though: 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 do not generate) code using the"bras"instruction to do subroutine calls. This only works reliably if the total executable size does not exceed64k. The default is to use the"basr"instruction instead, which does not have this limitation. slay โจ-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. Note that-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. On top of 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 do not 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 do not 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 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 (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 (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 (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 is 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). 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 exceeding64k. 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 function label is prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum1000000). After the label,2 * post-halfwordsbytes are appended, using the largest NOP like instructions the architecture allows (maximum1000000).
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, bestie, and there are a lot of them. Buckle up ๐ฆ
-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โ code for the SH4-200, but make it in such a way that no double-precision floating-point operations are used ๐ single precision only bestie, we are NOT doing doubles today.-m4-300โ generate code for the SH4-300. that's it, that's the whole vibe ๐ฆ-m4-300-nofpuโ generate code for the SH4-300 in such a way that the floating-point unit is not used. no FPU, she's on her own ๐ค-m4-300-singleโ code for the SH4-300, in such a way that no double-precision floating-point operations are used โจ-m4-300-single-onlyโ code for the SH4-300, in such a way that no double-precision floating-point operations are used. (yes it's the same as the one above, the SH toolchain said "copy paste is self-care" ๐)-m4-340โ generate code for the SH4-340 (no MMU, no FPU). bare bones, no frills, iconic honestly ๐-m4-500โ generate code for the SH4-500 (no FPU). literally passes-isa=sh4-nofputo the assembler ๐ซถ-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โ code for the SH4a in such a way that no double-precision floating-point operations are used โญ-m4a-singleโ code for the SH4a, assuming the floating-point unit is in single-precision mode by default. princess behaviour ๐-m4aโ generate code for the SH4a. short, sweet, slay ๐-m4alโ same as-m4a-nofpu, except it implicitly passes-dspto the assembler. ngl GCC doesn't generate any DSP instructions at the moment, so don't get your hopes up ๐-mbโ compile code for the processor in big-endian mode.-mlโ compile code for the processor in little-endian mode.-mdalignโ align doubles at 64-bit boundaries. > heads up bestie, this changes the calling conventions, which means some functions from the standard C library will not work unless you recompile it first with-mdalign. no cap, recompile first or suffer ๐-mrelaxโ shorten some address references at link time when possible; it uses the linker option-relax.-mbigtableโ use 32-bit offsets inswitchtables. the default is to use 16-bit offsets, fyi โจ-mbitopsโ enable the use of bit manipulation instructions on SH2A.-mfmovdโ enable the use of the instructionfmovd. check-mdalignfor alignment constraints ๐-mrenesasโ comply with the calling conventions defined by Renesas.-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 ๐-mnomacsaveโ mark theMACregister as call-clobbered, even if-mrenesasis given.-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 then-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๐-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. so likeโฆ be aware ๐ญ-misizeโ dump instruction size and location in the assembly code.-mpadstructโ this option is deprecated. it pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. don't do it bestie ๐-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__atomicBuiltins. 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. no mixing, periodt โ
-mtasโ generate thetas.bopcode for__atomic_test_and_set. > heads up: 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. and on multi-core SH4A processors thetas.binstruction must be used with caution since it can result in data corruption for certain cache configurations. that's not a vibe bestie, be careful ๐ญ-mprefergotโ when generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table.-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 ๐ฆ-multcost=numberโ set the cost to assume for a multiply insn.-mdiv=strategyโ set the division strategy to be used for integer division operations. strategy can 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 divs and divu instructions 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 ๐ซถ-mdivsi3_libfunc=nameโ set the name of the library function used for 32-bit signed division to name. 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.-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 ๐-mbranch-cost=numโ assume num to 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 ๐
okay so we're still deep in OPTIONS and these next ones are giving hyper-specific hardware bestie energy ๐ no cap. Let's go.
-mzdcbranch,-mno-zdcbranchโ Assume (do not assume) that zero displacement conditional branch instructions"bt"and"bf"are fast. If-mzdcbranchis specified, the compiler prefers zero displacement branch code sequences. This is enabled by default when generating code for SH4 and SH4A. It can be explicitly disabled by specifying-mno-zdcbranch. โจ-mcbranch-force-delay-slotโ Force the usage of delay slots for conditional branches, which stuffs the delay slot with a"nop"if a suitable instruction cannot be found. By default this option is disabled. It can be enabled to work around hardware bugs as found in the original SH7055. iykyk ๐-mfused-madd,-mno-fused-maddโ Generate code that uses (does not 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. โจ-mfsca,-mno-fscaโ Allow or disallow the compiler to emit the"fsca"instruction for sine and cosine approximations. The option-mfscamust be used in combination with-funsafe-math-optimizations. It is enabled by default when generating code for SH4A. Using-mno-fscadisables sine and cosine approximations even if-funsafe-math-optimizationsis in effect. ๐-mfsrra,-mno-fsrraโ Allow or disallow the compiler to emit the"fsrra"instruction for reciprocal square root approximations. The option-mfsrramust be used in combination with-funsafe-math-optimizationsand-ffinite-math-only. It is 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. ๐ธ-mpretend-cmoveโ Prefer zero-displacement conditional branches for conditional move instruction patterns. This can result in faster code on the SH4 processor. ๐ฅ-mfdpicโ Generate code using the FDPIC ABI. ๐
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 not supported by the current machine, but check at runtime whether or not to use them. periodt ๐-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.
-mimpure-text suppresses the "relocations remain against allocatable but non-writable sections" linker error message. However, 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 -fpic or -fPIC. โ ๏ธ
These switches are supported in addition to the above on Solaris 2:
-pthreadsโ This is a synonym for-pthread. ๐
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, bestie: 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.
-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. ๐ญ
-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 the"casa"instruction 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 of"ldd"and"std"instructions for copies in structure assignment, in place of twice as many"ld"and"st"pairs. 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. ๐จ-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. ๐-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.
v7 cypress, leon3v7
v8 supersparc, hypersparc, leon, leon3, leon5
sparclite
f930, f934, sparclite86x
sparclet
tsc701
v9 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. ๐
Okay so boom โ more SPARC goodness, bestie, we are STILL in the options, don't panic ๐
- With
-mcpu=v9, GCC spits out code for the V9 flavor of the SPARC architecture ๐ This one is giving 64-bit integer and floating-point move instructions, plus 3 extra floating-point condition code registers, plus conditional move instructions. And then, like, the spicy upgrades:-mcpu=ultrasparcโ the compiler additionally optimizes for the Sun UltraSPARC I/II/IIi chips โจ-mcpu=ultrasparc3โ additionally optimizes for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips ๐-mcpu=niagaraโ additionally optimizes for Sun UltraSPARC T1 chips ๐ฆ-mcpu=niagara2โ additionally optimizes for Sun UltraSPARC T2 chips ๐ฆ-mcpu=niagara3โ additionally optimizes for Sun UltraSPARC T3 chips ๐ฆ-mcpu=niagara4โ additionally optimizes for Sun UltraSPARC T4 chips ๐ฆ-mcpu=niagara7โ additionally optimizes for Oracle SPARC M7 chips ๐ฅ-mcpu=m8โ additionally optimizes for Oracle M8 chips ๐ฅ
-mtune=cpu_typeโ sets the instruction scheduling parameters for machine type cpu_type, but does not set the instruction set or register set like the option-mcpu=cpu_typedoes. Sneaky lil distinction, iykyk.
You can use all the same values for -mtune=cpu_type that you'd use for -mcpu=cpu_type, but lowkey only the ones that select a particular CPU implementation are actually useful. Those are: cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. And with native Solaris and GNU/Linux toolchains, native also works ๐
-mv8plus,-mno-v8plusโ with-mv8plus, GCC generates code for the SPARC-V8+ ABI. The difference from the V8 ABI is that the global and out registers are considered 64 bits wide. This is enabled 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. The default is-mno-vis.-mvis2,-mno-vis2โ with-mvis2, GCC generates code that takes advantage of version 2.0 of the UltraSPARC Visual Instruction Set extensions. The default is-mvis2when targeting a cpu that supports such instructions, such as UltraSPARC-III and later. 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. The default is-mvis3when targeting a cpu that supports such instructions, such as niagara-3 and later. Setting-mvis3also sets-mvis2and-mvisโจ-mvis4,-mno-vis4โ with-mvis4, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. The 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 ๐ซถ The default is-mvis4bwhen targeting a cpu that supports such instructions, such as m8 and later. Setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvisโจ-mcbcond,-mno-cbcondโ with-mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. The 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. The 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. The default is-mfsmuldwhen targeting a CPU supporting the architecture versions V8 or V9 with FPU โ except-mcpu=leon๐ (leon said not today)-mpopc,-mno-popcโ with-mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. The 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. The default is-msubxcwhen targeting a CPU that supports such an instruction, such as Niagara-7 and later.-mfix-at697fโ enables the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). Bugs, bestie. We fix em ๐-mfix-ut699โ enables the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.-mfix-ut700โ enables the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ enables the documented workaround for the back-to-back store errata of the GR712RC processor.
Okay and 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. Not confusing at all, right?? ๐ญ-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 ๐ธ
-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 Order
- pso โ Partial Store Order
- tso โ Total Store Order
- sc โ 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 ๐
-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 additional options are available on System V Release 4, for compatibility with other compilers on those systems ๐ (it's giving legacy, but respectfully):
-Gโ create a shared object. It is recommended that-symbolicor-sharedbe used instead. (so like... do that instead, bestie ๐ซถ)-Qyโ identify the versions of each tool used by the compiler, in a".ident"assembler directive in the output.-Qnโ refrain from adding".ident"directives to the output file (this is the default).-YPdirs โ search the directories dirs, and no others, for libraries specified with-l.-Ymdir โ 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 the"ep"register, and use the shorter"sld"and"sst"instructions. 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 era ๐-mtda=n โ put static or global variables whose size is n bytes or less into the tiny data area that register"ep"points 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 register"gp"points 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 ๐. If you use this one, the preprocessor constants"__v850e1__"and"__v850e__"get defined, periodt.-mv850esโ target processor = V850ES โจ. It's literally just an alias for the-mv850e1option, no cap.-mv850eโ target processor = V850E ๐ธ. Using this one defines the preprocessor constant"__v850e__".
ok so if none of -mv850 or -mv850e or -mv850e1 or -mv850e2 or -mv850e2v3 or -mv850e3v5 are defined, then a default target processor gets chosen and the relevant __v850*__ preprocessor constant is defined ๐ฆ.
Also: the preprocessor constants "__v850" and "__v851__" are always defined, no matter which processor variant is the target. always always. iconic.
-mdisable-callt-mno-disable-callt
This option suppresses 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__" gets defined ๐
-mrelax-mno-relax
Pass on (or do not pass on) the -mrelax command-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 option is only significant when the target architecture is V850E2V3 or higher. 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 e3v5 LOOP instruction ๐ซ. The use of this instruction is not enabled by default when the e3v5 architecture is selected, because its use is still experimental. (experimental = proceed with vibes, bestie ๐)-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-align is in effect the C preprocessor symbol "__V850_8BYTE_ALIGN__" is defined โจ.
-mbig-switchโ generate code suitable for big switch tables ๐ฅ. Use this option only if the assembler/linker complain about out of range branches within a switch table.-mapp-regsโ this option causes r2 and r5 to be used in the code generated by the compiler ๐ . This setting is the default.-mno-app-regsโ this option causes r2 and r5 to 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 ๐.
lowkey important:-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, registers r24 to r31 cannot be accessed in this mode; on the GR6, only registers r29 to r31 are 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-v2x86-64-v3x86-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. rude.)i586pentiumโ 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โ okay so when you use this with-march, it's the Pentium Pro instruction set, so the code runs on all i686 family chips. When you use it with-mtune, it has the same meaning asgeneric. ๐pentium2โ Intel Pentium II CPU, based on Pentium Pro core with MMX and FXSR instruction set support. โจpentium3,pentium3mโ Intel Pentium III CPU, based on Pentium Pro core with MMX, FXSR and SSE instruction set support. ๐ฆpentium-mโ Intel Pentium M; low-power version of Intel Pentium III CPU with MMX, SSE, SSE2 and FXSR instruction set support. Used by Centrino notebooks. ๐ปpentium4,pentium4mโ Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support. ๐ฅprescottโ Improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2, SSE3 and FXSR instruction set support. โจnoconaโ Improved version of Intel Pentium 4 CPU with 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. ๐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 vibes โจ 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. she's serving instruction-set realness ๐tremontโ Intel Tremont, okay bestie she's got 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. glow up fr fr ๐ธsierraforestโ Intel Sierra Forest ๐ฒ 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. that list is giving โจgrandridgeโ Intel Grand Ridge, and ngl the instruction list is the exact same energy assierraforest: 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.knmโ Intel Knights Mill CPU, and yes it also has 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. she said more is more ๐ฆk6โ AMD K6 CPU withMMXinstruction set support. short, sweet, vintage ๐k6-2,k6-3โ glow-up versions of the AMD K6 CPU withMMXand3DNow!instruction set support. throwback era ๐athlon,athlon-tbirdโ AMD Athlon CPU withMMX,3dNOW!, enhanced3DNow!andSSEprefetch instructions support. (yes bestie that's the manpage's own mixed casing, we do not touch it ๐)athlon-4,athlon-xp,athlon-mpโ the improved AMD Athlon CPU withMMX,3DNow!, enhanced3DNow!and the fullSSEinstruction set support. ate ๐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.) she contains multitudes fr fr ๐k8-sse3,opteron-sse3,athlon64-sse3โ improved versions of AMD K8 cores withSSE3instruction set support. upgrade szn โจ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.) theAVX512run is main character energy ๐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.) she keeps adding letters and honestly? periodt ๐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 one 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 asi486with additionalMMXinstruction set support. vintage darling, no notes ๐winchip2โ IDT WinChip 2 CPU, dealt in same way asi486with additionalMMXand3DNow!instruction set support.c3โ VIA C3 CPU withMMXand3DNow!instruction set support. (no scheduling is implemented for this chip.) heads up bestie ๐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.) and that's the whole Nano family, iconic lineup tbh ๐lujiazuiโ ZHAOXIN lujiazui CPU with x86-64, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PCLMUL, RDRND, XSAVE, XSAVEOPT, FSGSBASE, CX16, ABM, BMI, BMI2, FXSR, RDSEED instruction set support. And okay bestie listen, even though these CPUs do support AVX and F16C, those two are not enabled by-march=lujiazuiโ it's for performance reasons apparently ๐ so don't come for me when they don't show up.geodeโ AMD Geode embedded processor with MMX and 3DNow! instruction set support. vintage vibes fr ๐
๐ธ -mtune=cpu-type ๐ธ
Tune to cpu-type ~everything applicable~ about the generated code, except for the ABI and the set of available instructions. So while picking a specific cpu-type schedules things appropriately for that particular chip, the compiler does not generate any code that cannot run on the default machine type โ unless you also use a -march=cpu-type option. For example, if GCC is configured for i686-pc-linux-gnu, then -mtune=pentium4 generates code that is tuned for Pentium 4 but still runs on i686 machines. girl is versatile ๐
The choices for cpu-type are the same as for -march. In addition, -mtune supports 2 extra choices for cpu-type:
genericโ Produce code optimized for the most common IA32/AMD64/EM64T processors. If you know the CPU on which your code will run, then you should use the corresponding-mtuneor-marchoption instead of-mtune=generic. But if you do not know exactly what CPU users of your application will have, then you should use this option.
As new processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the processors that are most common at the time that version of GCC is released. it's giving "we move with the times" โจ
There is no -march=generic option because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized.
intelโ Produce code optimized for the most current Intel processors, which are Haswell and Silvermont for this version of GCC. If you know the CPU on which your code will run, then you should use the corresponding-mtuneor-marchoption instead of-mtune=intel. But if you want your application to perform better on both Haswell and Silvermont, then you should use this option. slay for the multitaskers ๐ซถ
As new Intel processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the most current Intel processors at the time that version of GCC is released.
There is no -march=intel option because -march indicates the instruction set the compiler can use, and there is no common instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized.
๐ฆ -mcpu=cpu-type ๐ฆ
A deprecated synonym for -mtune. it's giving legacy era, we don't rly use it anymore bestie ๐
๐ -mfpmath=unit ๐
Generate floating-point arithmetic for selected unit unit. The choices for unit are:
387โ Use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See-ffloat-storefor more detailed description.
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 supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using 387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too.
For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option effective. For the x86-64 compiler, these extensions are enabled by default. no extra work needed, we love that for us ๐
The resulting code should be considerably faster in the majority of cases and avoid the numerical instability problems of 387 code, but may break some existing code that expects temporaries to be 80 bits. โ ๏ธ heads up bestie
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 the execution resources too. Use this option with care, as it is still experimental, because the GCC register allocator does not model separate functional units well, resulting in unstable performance. not me telling you to be careful ๐ญ it's giving chaos mode fr
๐ -masm=dialect ๐
Output assembly instructions using selected dialect. Also affects which dialect is used for basic asm and extended asm. Supported choices (in dialect order) are att or intel. The default is att. Darwin does not support intel. periodt.
๐ -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. keeping it cute and correct ๐
โญ -m80387 / -mhard-float โญ
Generate output containing 80387 instructions for floating point.
๐ธ -mno-80387 / -msoft-float ๐ธ
Generate output containing library calls for floating point.
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.
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. sneaky little opcodes fr ๐
๐ฆ -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 is that the operating system should emulate an FPU. iconic OS behaviour honestly ๐
The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead.
๐ -mno-fancy-math-387 ๐
Some 387 emulators do not support the sin, cos and sqrt instructions for the 387. Specify this option to avoid generating those instructions. This option is overridden when -march indicates that the target CPU always has an FPU and so the instruction does not need emulation. These instructions are not generated unless you also use the -funsafe-math-optimizations switch. so like... it's a chain of conditions bestie, keep up ๐ซถ
โจ -malign-double / -mno-align-double โจ
Control whether GCC aligns double, long double, and long long variables on a two-word boundary or a one-word boundary. Aligning double variables on a two-word boundary produces code that runs somewhat faster on a Pentium at the expense of more memory. speed vs space, the eternal dilemma ๐
On x86-64, -malign-double is enabled by default.
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. do not mix and match, i'm begging ๐ญ
๐ -m96bit-long-double / -m128bit-long-double ๐
These switches control the size of long double type. The x86-32 application binary interface specifies the size to be 96 bits, so -m96bit-long-double is 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 is not 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.
In the x86-64 compiler, -m128bit-long-double is the default choice as its ABI specifies that long double is aligned on 16-byte boundary.
Notice that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double. just alignment bestie, don't expect magic โจ
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.
๐ -mlong-double-64 / -mlong-double-80 / -mlong-double-128 ๐
These switches control the size of long double type. A size of 64 bits makes the long double type equivalent to the double type. This is the default for 32-bit Bionic C library. A size of 128 bits makes the long double type equivalent to the __float128 type. This is the default for 64-bit Bionic C library.
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 above, don't come crying to me ๐
๐ -malign-data=type ๐
Control how GCC aligns variables. Supported values for type are: compat uses increased alignment value compatible uses GCC 4.8 and earlier, abi uses alignment value as specified by the psABI, and cacheline uses increased alignment value to match the cache line size. compat is the default. cute little trio of choices, pick your fighter ๐
-mlarge-data-threshold=thresholdโ okay so when you've got-mcmodel=mediumturned on, any data object bigger than threshold gets yeeted into the large data section. ๐ Heads up: this value has to be the same across every single object linked into the binary, no exceptions bestie. Defaults to65535.-mrtdโ this one switches to a whole different function-calling convention, where functions that take a fixed number of arguments bail out with theret numinstruction, which pops their arguments on the way out. Saves one instruction in the caller since nobody has to pop the args there. โจ
You can mark an individual function as using this calling sequence with the function attribute stdcall. And you can override -mrtd per-function with the 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, including printf) โ otherwise incorrect code gets 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. Not here, bestie.)
-mregparm=numโ controls how many registers get used to pass integer arguments. By default, no registers are used to pass args, and at most3registers can be used. You can control this for a specific function with the function attributeregparm.
Warning: if you use this switch and num is nonzero, then you have to build all modules with the same value, libraries included. That means the system libraries and startup modules too. No mixing. ๐
-msseregparmโ uses SSE register passing conventions forfloatanddoublearguments and return values. Per-function control is available via the function attributesseregparm. ๐ฆ
Warning: if you use this switch then you must build all modules with the same value, including any libraries. Yep, system libraries and startup modules are in there too.
-mvect8-ret-in-memโ returns 8-byte vectors in memory instead of MMX registers. This is the default on VxWorks, so it matches the ABI of the Sun Studio compilers up to version 12. ๐ Only reach for this option if you genuinely need to stay compatible with existing code produced by those previous compiler versions or older versions of GCC.-mpc32,-mpc64,-mpc80โ sets the 80387 floating-point precision to 32, 64 or 80 bits respectively. ๐ So:-mpc32rounds the significands of results of floating-point operations 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 that extended-precision (80-bit) floating-point operations are enabled by default; routines in those 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 โ and heads up,-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 realigns 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 you can apply to individual functions. โจ-mpreferred-stack-boundary=numโ tries 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 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 (like 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 โ yep, system libraries and startup modules included. ๐
-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-boundarygets used instead.
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. ๐
- big roster of instruction-set switches incoming, hold on tight bestie:
-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. The names can be used in-mtune-ctrl=feature-list. ๐-mtune-ctrl=feature-listโ okay so this is the โจfine grainโจ knob for x86 code generation features.feature-listis a comma-separated list of feature names, bestie, and hey โ check out-mdump-tune-featurestoo. When it's specified, a feature gets turned on unless it's preceded by^, and if it is preceded by^it gets turned off. But listen.-mtune-ctrl=feature-listis intended to be used by GCC developers. Using it may lead to code paths not covered by testing and can potentially result in compiler ICEs or runtime errors. ๐ so like, not a casual Friday vibe.-mno-defaultโ tells GCC to turn off all the tunable features. See also-mtune-ctrl=feature-listand-mdump-tune-features. ๐ซถ-mcldโ this one makes GCC emit a"cld"instruction in the prologue of functions that use string instructions. Here's the tea โ: string instructions depend on the DF flag to pick between autoincrement or autodecrement mode, and while the ABI says the DF flag should be cleared on function entry, some operating systems violate this specification by not clearing the DF flag in their exception dispatchers. So the exception handler can get invoked with the DF flag set, which leads to the wrong direction mode when string instructions are used. ๐ญ This option can be enabled by default on 32-bit x86 targets by configuring GCC with the--enable-cldconfigure option. And generation of"cld"instructions can be suppressed with the-mno-cldcompiler option in that case. periodt.-mvzeroupperโ makes GCC emit a"vzeroupper"instruction before a transfer of control flow out of the function, so we minimize the AVX to SSE transition penalty ๐ and also remove unnecessary"zeroupper"intrinsics. slay.-mprefer-avx128โ tells GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. little-bitty vectors, lowkey iconic.-mprefer-vector-width=optโ use opt-bit vector width in instructions instead of the default on the selected platform.-mmove-max=bitsโ sets the maximum number of bits that can be moved from memory to memory efficiently to bits. The valid bits are128,256and512. no cap.-mstore-max=bitsโ sets the maximum number of bits that can be stored to memory efficiently to bits. Valid bits are128,256and512. matching set, we love consistency ๐noneโ No extra limitations applied to GCC other than defined by the selected platform.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 to implement compare-and-exchange operations on 16-byte aligned 128-bit objects. Super useful for atomic updates of data structures exceeding one machine word in size. ๐ธ The compiler uses this instruction to implement__syncBuiltins. However โ for__atomicBuiltins operating on 128-bit integers, a library call is always used. noted ๐-msahfโ enables generation of"SAHF"instructions in 64-bit code. History moment ๐ฆ: early Intel Pentium 4 CPUs with Intel 64 support, prior to the introduction of Pentium 4 G1 step in December 2005, lacked the"LAHF"and"SAHF"instructions which are supported by AMD64. Those are load and store instructions, respectively, for certain status flags. In 64-bit mode, the"SAHF"instruction is used to optimize"fmod","drem", and"remainder"built-in functions; see Other Builtins for details. ๐-mmovbeโ enables use of the"movbe"instruction to implement__builtin_bswap32and__builtin_bswap64. byte-swap bestie ๐-mshstkโ the-mshstkoption enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). ๐ก๏ธ-mcrc32โ enables built-in functions__builtin_ia32_crc32qi,__builtin_ia32_crc32hi,__builtin_ia32_crc32siand__builtin_ia32_crc32dito generate the"crc32"machine instruction. checksums but make it โจhardwareโจ-mmwaitโ enables built-in functions__builtin_ia32_monitor, and__builtin_ia32_mwaitto generate the"monitor"and"mwait"machine instructions. ๐ฅ-mrecipโ enables use of"RCPSS"and"RSQRTSS"instructions (and their vectorized variants"RCPPS"and"RSQRTPS") with an additional Newton-Raphson step to increase precision instead of"DIVSS"and"SQRTSS"(and their vectorized variants) for single-precision floating-point arguments. ๐งฎ These instructions are generated only when-funsafe-math-optimizationsis enabled together with-ffinite-math-onlyand-fno-trapping-math. Note that while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994). ๐ญ
Note that GCC implements "1.0f/sqrtf(x)" in terms of "RSQRTSS" (or "RSQRTPS") already with -ffast-math (or the above option combination), and doesn't need -mrecip.
Also note that GCC emits the above sequence with 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. double-noted, fr fr ๐๐
-mrecip=optโ controls which reciprocal estimate instructions may 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 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, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations, except for square root. ๐ฏ
-mveclibabi=typeโ specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values for type aresvmlfor 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. ๐
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 corresponding function type when -mveclibabi=svml is used, and "__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. ๐ฎ๐จ that's a lot of names, but we keep every one, periodt.
-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. This is useful when 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. This is useful when used with the option-fcf-protection=branchto control ENDBR insertion at the function entry. ๐-mcet-switchโ 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 does not 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 reachable via any indirect jumps.-mcall-ms2sysv-xloguesโ so due to differences in 64-bit ABIs, any Microsoft ABI function that calls a System V ABI function must consider RSI, RDI and XMM6-15 as clobbered. By default, the code for saving and restoring these registers is emitted inline, resulting in fairly lengthy prologues and epilogues. ๐ฎ๐จ Using-mcall-ms2sysv-xloguesemits prologues and epilogues that use stubs in the static portion of libgcc to perform these saves and restores, thus reducing 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 is 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 is a notable increase in code size. ๐ This switch implies-mno-push-args.-mthreadsโ bestie, this one is all about supporting thread-safe exception handling on MinGW. ๐ If your program relies on thread-safe exception handling, you must compile and link all your code with-mthreads. When you're compiling,-mthreadsdefines-D_MTfor you; when you're linking, it links in a special thread helper library called-lmingwthrd, and that library is the one doing the cleanup of per-thread exception-handling data. ๐งนโจ-mms-bitfields-mno-ms-bitfieldsโ turn bit-field layout that's compatible with the native Microsoft Windows compiler on / off. ๐
So here's the tea โ: if "packed" is used on a structure, or if bit-fields get used at all, it's possible that the Microsoft ABI lays the structure out differently than GCC normally does. And especially when you're moving packed data between functions compiled with GCC and the native Microsoft compiler โ whether that's via a function call or just as data sitting in a file ๐ โ you might need to access either format. It's giving compatibility crisis.
This option is enabled by default for Microsoft Windows targets. You can also control this behavior locally using variable or type attributes. For more info, check out x86 Variable Attributes and x86 Type Attributes. ๐
The Microsoft structure layout algorithm is honestly pretty simple, with the one exception of bit-field packing. The padding and alignment of the members of structures โ and whether a bit-field can straddle a storage-unit boundary โ are determined by these rules:
- Structure members are stored sequentially in the order in which they are declared: the first member has the lowest memory address and the last member the highest. ๐
- Every data object has an alignment requirement. The alignment requirement for all data except structures, unions, and arrays is either the size of the object or the current packing size (specified with either 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. Every object is allocated an offset so that:
offset % alignment_requirement == 0
- Adjacent bit-fields are 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 common alignment requirements of the bit-fields. ๐งฉ
MSVC interprets zero-length bit-fields in the following ways, and this is where it gets spicy ๐ถ๏ธ:
- If a zero-length bit-field is inserted between two bit-fields that are normally coalesced, the bit-fields are not coalesced.
For example:
struct
{
unsigned long bf_1 : 12;
unsigned long : 0;
unsigned long bf_2 : 12;
} t1;
The size of "t1" is 8 bytes with the zero-length bit-field. If the zero-length bit-field were removed, "t1"'s size would be 4 bytes. ๐ญ
- If a zero-length bit-field is inserted after a bit-field,
"foo", and the alignment of the zero-length bit-field is greater than the member that follows it,"bar", then"bar"is aligned as 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" is placed at offset 2, rather than offset 1. Accordingly, the size of "t2" is 4. For "t3", the zero-length bit-field does not affect the alignment of "bar" or, as a result, the size of the structure. ๐ธ
Taking this into account, it's important to note the following:
- If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field may affect the alignment of the structure as a whole. For example,
"t2"has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short. ๐ซถ - Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
{
char foo : 6;
long : 0;
} t4;
Here, "t4" takes up 4 bytes. ๐
- Zero-length bit-fields following non-bit-field members are ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
Here, "t5" takes up 2 bytes. ๐
-mno-align-stringopsโ don't align the destination of inlined string operations. This switch reduces code size and improves performance when the destination is already aligned, but GCC just doesn't know about it. ๐คทโ๏ธ-minline-all-stringopsโ by default GCC inlines string operations only when the destination is known to be aligned to at least a 4-byte boundary. This option enables more inlining and increases code size, but it may improve performance of code that depends on fast"memcpy"and"memset"for short lengths. It also enables inline expansion of"strlen"for all pointer alignments. โก-minline-stringops-dynamicallyโ for string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks. Best of both worlds, lowkey genius. โจ-mstringop-strategy=algโ override the internal decision heuristic for the particular algorithm to use for inlining string operations. The allowed values for alg are:rep_byterep_4byterep_8byteโ expand using 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 to decide if"__builtin_memcpy"should be inlined, and what 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 specifies the max byte size with which inline algorithm alg is allowed. For the last triplet, the max_size must be-1. ๐ The max_size of the triplets in the list must be specified in increasing order. The minimal byte size for alg is0for the first triplet and"max_size + 1"of the preceding range.-mmemset-strategy=strategyโ this one is similar to-mmemcpy-strategy=except that it's there to control"__builtin_memset"expansion. ๐งผ-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 it makes an extra register available in leaf functions. Note that the option-fomit-leaf-frame-pointerremoves the frame pointer for leaf functions, which might make debugging harder. ๐๐-mtls-direct-seg-refs-mno-tls-direct-seg-refsโ controls whether TLS variables may be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer must be added. Whether or not this is valid depends on the operating system, and whether it maps the segment to cover the entire TLS area. ๐
For systems that use the GNU C Library, the default is on. โ
-msse2avx-mno-sse2avxโ specify that the assembler should encode SSE instructions with 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. Note: on x86 architectures the attribute"ms_hook_prologue"isn't possible at the moment for-mfentryand-pg. ๐ง-mrecord-mcount-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection that contains pointers to each profiling call. This is 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. This is useful when they should be patched in later dynamically. This is likely 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, but not sibling calls ending withjump. Valid types arenoneto not instrument,callto generate a call to__return__, ornop5to generate a 5 byte nop. ๐ฏ-mrecord-return-mno-record-returnโ generate a__return_locsection pointing to all return instrumentation code. ๐-mfentry-name=nameโ set the name of the__fentry__symbol called at function entry for-pg -mfentryfunctions. ๐ท๏ธ-mfentry-section=nameโ set the name of the section used to record-mrecord-mcountcalls (default__mcount_loc). ๐ฆ-mskip-rax-setup-mno-skip-rax-setupโ when generating code for the x86-64 architecture with SSE extensions disabled,-mskip-rax-setupcan be used to skip setting up the RAX register when there are no variable arguments passed in vector registers. ๐ โ๏ธ
Warning: since the RAX register is used to avoid 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 don't have those issues, regardless of the RAX register value.
-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 dividend and divisor are within the range of 0 to 255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. ๐งฎโก-mavx256-split-unaligned-load-mavx256-split-unaligned-storeโ split 32-byte AVX unaligned load and store. ๐ช-mstack-protector-guard=guard โ make stack protection code using a canary that lives at guard. The supported spots areglobal(a global canary, bestie) ortls(a per-thread canary in the TLS block, which is the default ๐ ). This one only does anything when-fstack-protectoror-fstack-protector-allis in the mix, no cap.
When you go with that second choice, -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset also tell the compiler which segment register (%fs or %gs) to use as base register for reading the canary, and from what offset off that base register. The default for those is whatever the relevant ABI says, so like, take it up with the ABI โจ
-mgeneral-regs-onlyโ generate code that uses only the general-purpose registers ๐ซถ This stops the compiler from touching floating-point, vector, mask and bound registers. Just the basics, and honestly, slay.-mrelax-cmpxchg-loopโ when it's emitting a compare-and-swap loop for__syncBuiltins and__atomicBuiltins that don't have a native instruction to lean on, this optimizes for the very-contended case ๐ฅ It issues an atomic load before the"CMPXCHG"instruction, and uses the"PAUSE"instruction to save CPU power when restarting the loop.-mindirect-branch=choice โ convert indirect call and jump with choice. Default iskeep, which keeps indirect call and jump unmodified.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 with the function attribute"indirect_branch"๐
Heads up though: -mcmodel=large is incompatible with -mindirect-branch=thunk and -mindirect-branch=thunk-extern, because the thunk function may not even be reachable in the large code model ๐ญ
Also, -mindirect-branch=thunk-extern is compatible with -fcf-protection=branch, since 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 with the function attribute"function_return"๐ธ
Note that -mindirect-return=thunk-extern is compatible with -fcf-protection=branch, because the external thunk can be made to enable control-flow check โจ
Note that -mcmodel=large is incompatible with -mfunction-return=thunk and -mfunction-return=thunk-extern, because 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, bestie, it's giving very direct ๐-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 ๐ฅ-mindirect-branch-cs-prefixโ add CS prefix to call and jmp to indirect thunk with branch target inr8-r15registers, so that the call and jmp instruction length is 6 bytes and they can be replaced withlfence; call *%r8-r15orlfence; jmp *%r8-r15at run-time. Sneaky and iconic ๐
These -m switches are supported in addition to all the above on x86-64 processors in 64-bit environments, bestie ๐
-m32-m64-mx32-m16-miamcu
Generate code for a 16-bit, 32-bit or 64-bit environment.
The -m32 option sets "int", "long", and pointer types to 32 bits, and generates code that runs in 32-bit mode โจ
The -m64 option sets "int" to 32 bits and "long" and pointer types to 64 bits, and generates code for the x86-64 architecture. For Darwin only, the -m64 option also turns off the -fno-pic and -mdynamic-no-pic options ๐
The -mx32 option sets "int", "long", and pointer types to 32 bits, and generates code for the x86-64 architecture.
The -m16 option is the same as -m32, except that it outputs the ".code16gcc" assembly directive at the beginning of the assembly output so the binary can run in 16-bit mode ๐ฆ
The -miamcu option generates code that conforms to Intel MCU psABI. It requires the -m32 option to be turned on. Periodt.
-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 isn't 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 ๐ซ-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 ๐-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 ๐-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-thresholdgo 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. Unbothered, unconstrained, main character energy ๐-maddress-mode=longโ generate code for long address mode. This is 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. This is only supported for 32-bit and x32 environments. It's the default address mode for 32-bit and x32 environments ๐-mneeded-mno-needed
Emit GNU_PROPERTY_X86_ISA_1_NEEDED GNU property for Linux target to indicate the micro-architecture ISA level required to execute the binary ๐
-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 ๐
-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 ๐-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 ๐ฆ
๐ช x86 Windows Options ๐ช
These additional options are available for Microsoft Windows targets, bestie:
-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โ this option is 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โ this option is available for Cygwin and MinGW targets. It specifies that the"dllimport"attribute should be ignored ๐-mthreadsโ this option is available for MinGW targets. It specifies that MinGW-specific thread support is to be used ๐งต-municodeโ this option is available for MinGW-w64 targets. It causes the"UNICODE"preprocessor macro to be predefined, and chooses Unicode-capable runtime startup code ๐-mwin32โ this option is 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 ๐-mwindowsโ this option is 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โ this option is 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โ this option is available for MinGW and Cygwin targets. It specifies that relocated-data in read-only section is put into the".data"section. This is necessary for older runtimes not supporting modification of".rdata"sections for pseudo-relocation โจ-mpe-aligned-commonsโ this option is 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's 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 ๐ฎ
๐ธ Xtensa Options ๐ธ
These options are supported for Xtensa targets:
-mconst16/-mno-const16โ turnsCONST16instructions on/off for loading constant values. Bestie, the tea is:CONST16is not a standard option from Tensilica right now. When you enable it,CONST16instructions are always used in place of the standardL32Rinstructions. And here's the default drama โCONST16is enabled by default only if theL32Rinstruction isn't available. That's it, that's the rule. ๐-mfused-madd/-mno-fused-maddโ enable/disable fused multiply/add and multiply/subtract instructions in the floating-point option. Heads up: this does absolutely nothing if the floating-point option isn't also enabled. Ngl kinda iconic. Turning off fused multiply/add and multiply/subtract forces the compiler to use separate instructions for the multiply and the add/subtract. Why would you want that? Okay so โ some cases where you need strict IEEE 754-compliant results: the fused multiply add/subtract instructions don't round the intermediate result, which means you get results with more bits of precision than the IEEE standard says. Disabling them also makes sure your program's output isn't sensitive to whether the compiler decided to combine multiply and add/subtract ops. Consistency slay. โจ-mserialize-volatile/-mno-serialize-volatileโ when enabled, GCC insertsMEMWinstructions beforevolatilememory references to guarantee sequential consistency. The default is-mserialize-volatile. Use-mno-serialize-volatileif you want thoseMEMWinstructions omitted. Pick your fighter. ๐ซถ-mforce-no-picโ for targets like GNU/Linux where all user-mode Xtensa code has to be position-independent code (PIC), this option disables PIC for compiling kernel code. Kernel girlies, this one's for you. ๐-mtext-section-literals/-mno-text-section-literalsโ these control how literal pools get treated. Default is-mno-text-section-literals, which drops literals into a separate section in the output file. That's the vibe because it lets the literal pool live in a data RAM/ROM, and it also lets the linker merge literal pools from separate object files to delete redundant literals and improve code size (code size glow-up fr). With-mtext-section-literals, the literals are interspersed in the text section so they stay as close as possible to their references. This may be necessary for large assembly files. And the details: literals for each function are placed right before that function. ๐ธ-mauto-litpools/-mno-auto-litpoolsโ also about literal pool treatment (we love a sequel). Default is-mno-auto-litpools, which puts literals in a separate section in the output file unless-mtext-section-literalsis used. With-mauto-litpoolsthe literals get interspersed in the text section by the assembler. The compiler doesn't produce explicit.literaldirectives and instead loads literals into registers withMOVIinstructions rather thanL32R, so the assembler can do relaxation and place literals wherever necessary. This lets the assembler create several literal pools per function and assemble very big functions โ which may not be possible with-mtext-section-literals. Big function energy, honestly. ๐ฅ-mtarget-align/-mno-target-alignโ when this is enabled, GCC tells the assembler to automatically align instructions to reduce branch penalties, at the cost of some code density. The assembler tries 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 happens โ no forcing it, bestie. Default is-mtarget-align. Now, important: 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. That one's not up for negotiation. ๐-mlongcalls/-mno-longcallsโ when enabled, GCC instructs the assembler to translate direct calls into indirect calls unless it can determine that the target of a direct call is within the range the call instruction allows. This translation typically happens for calls to functions in other source files. Specifically: the assembler translates a directCALLinstruction into anL32Rfollowed by aCALLXinstruction. Default is-mno-longcalls. Use this in programs where the call target could potentially be out of range. Footage: this option is implemented in the assembler, not the compiler, so the assembly code GCC generates still shows direct call instructions โ look at the disassembled object code to see the actual instructions. And nota bene: the assembler uses an indirect call for every cross-file call, not just the ones that are really out of range. Overachiever behavior tbh. ๐ญ-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 this is 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 this is enabled, function parameters are passed in registersa10througha15, and the called function rotates the register window by 8 registers on entry so 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. Round trip, iconic. ๐ฆ-mextra-l32r-costs=n โ specify an extra cost of instruction RAM/ROM access forL32Rinstructions, measured in clock cycles. When optimizing for speed, this affects whether loading a constant from the literal pool usingL32Rhappens, or whether the constant gets synthesized from a small one with a couple of arithmetic instructions. The default value is0. โญ
zSeries Options ๐
These are listed under
โจ ENVIRONMENT โจ
okay bestie, this section is the whole tea on the environment variables that change how GCC does its thing ๐ some of them work by handing GCC directories or prefixes so it knows where to go hunting for certain kinds of files, and some of them just straight-up tweak other parts of your compile vibe.
and listen โ you can also tell GCC where to look with options like -B, -I and -L. those come first, always. it's options โก๏ธ env vars โก๏ธ whatever GCC was configured with, in that exact order of who's the boss. periodt. ๐
LANG,LC_CTYPE,LC_MESSAGES,LC_ALLโ these control how GCC uses localization info so it can hang with different national conventions. GCC peeks at the locale categoriesLC_CTYPEandLC_MESSAGESif it was configured to do so, and those categories can be set to literally any value your installation supports. a super typical one isen_GB.UTF-8for English in the United Kingdom encoded in UTF-8, iykyk ๐ฌ๐ง
LC_CTYPE says what character classification is. GCC uses it to figure out character boundaries in a string โ which is needed for some multibyte encodings that contain quote and escape characters that would otherwise get read as a string end or an escape ๐ญ
LC_MESSAGES says which language the diagnostic messages should be in.
if LC_ALL is set, it overrides the value of LC_CTYPE and LC_MESSAGES; otherwise LC_CTYPE and LC_MESSAGES default to the value of LANG. if none of these are set at all, GCC defaults to traditional C English behavior. no drama, just English ๐
TMPDIRโ if it's set, it picks the directory for temporary files. GCC uses temp files to hold the output of one stage of compilation that's gonna be the input for the next stage โ for instance, the output of the preprocessor, which is exactly 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. go read that option's docs for the full spiel.GCC_EXEC_PREFIXโ if it's set, it gives a prefix for the names of the subprograms the compiler runs. no slash gets added when this prefix gets combined with the subprogram name, but bestie you can absolutely specify a prefix that already ends with a slash if you're feeling it.
if GCC_EXEC_PREFIX isn't set, GCC tries to figure out an appropriate prefix based on the pathname it was invoked with.
if GCC can't find the subprogram using the prefix you gave, it goes looking in the usual places instead.
the default value is prefix/lib/gcc/ where prefix is the prefix to the installed compiler. in many cases prefix is the value of "prefix" from 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 also โ plot twist โ the prefix is used in a very unusual way when finding directories to search for header files. for each of the standard directories whose name normally starts with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries swapping that beginning out for the specified prefix to make an alternate directory name. so like, with -Bfoo/, GCC searches foo/bar right before it searches the standard directory /usr/local/lib/bar. and if a standard directory begins with the configured prefix, then the value of prefix gets replaced by GCC_EXEC_PREFIX when looking for header files. iconic behavior, honestly ๐
COMPILER_PATHโ its value is a colon-separated list of directories, much likePATH. GCC tries those directories when hunting for subprograms if it can't find them usingGCC_EXEC_PREFIX. bestie fandom of fallback options โจLIBRARY_PATHโ same deal, a colon-separated list of directories much likePATH. when GCC is configured as a native compiler it tries those directories when searching for special linker files, if it can't find them viaGCC_EXEC_PREFIX. and linking with GCC also uses these directories when looking for ordinary libraries for the-loption โ but directories given with-Lcome first, no cap.LANGโ this one passes locale info to the compiler. one way it gets used is to decide the character set used when character literals, string literals and comments get parsed in C and C++. when the compiler is configured to allow multibyte characters, these values forLANGare recognized:C-JISโ recognize JIS characters.C-SJISโ recognize SJIS characters.C-EUCJPโ recognize EUCJP characters.
if LANG isn't defined, or it's set to some other value, then the compiler falls back on mblen and mbtowc as defined by the default locale to recognize and translate multibyte characters. it's giving plan B ๐
GCC_EXTRA_DIAGNOSTIC_OUTPUTโ if it's set to one of the following values, extra text gets emitted to stderr whenever fix-it hints are emitted.-fdiagnostics-parseable-fixitsand-fno-diagnostics-parseable-fixitstake precedence over this environment variable, jsyk.fixits-v1โ emit parseable fix-it hints, equivalent to-fdiagnostics-parseable-fixits. specifically, 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.
and some additional environment variables affect how the preprocessor behaves ๐
CPATH,C_INCLUDE_PATH,CPLUS_INCLUDE_PATH,OBJC_INCLUDE_PATHโ each of these variables holds a list of directories separated by a special character, much likePATH, and that's where headers get searched for. that special character,PATH_SEPARATOR, is target-dependent and decided when GCC is built. 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 to search as if you'd passed -I, but after any paths given with -I options on the command line. this variable gets used no matter which language is being preprocessed.
the remaining ones only apply when preprocessing the particular language they name. each one gives a list of directories to search as if specified with -isystem, but after any paths given with -isystem options on the command line.
and in all of 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 CPATH is :/special/include, that does the exact same thing as -I. -I/special/include. slay ๐ธ
DEPENDENCIES_OUTPUTโ if this is set, its value says how to output dependencies for Make based on the non-system header files the compiler processed. system header files are ignored in that dependency output, sorry babes. ๐ซ
the value can be just a file name, and then the Make rules get written to that file, with the target name guessed from the source file name. or the value can be in the form file target, and then the rules get written to file using target as the target name.
in other words, this environment variable is equivalent to combining the options -MM and -MF, with an optional -MT switch thrown in too. combo meal ๐
SUNPRO_DEPENDENCIESโ same asDEPENDENCIES_OUTPUT(see above), except 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 it's set, its value gives a UNIX timestamp to be used in place of the current date and time in the__DATE__and__TIME__macros, so the embedded timestamps become reproducible. ๐ฐ๏ธโจ
the value must be a UNIX timestamp โ the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00, represented in ASCII, 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. don't be out here making up numbers, bestie.
๐ BUGS ๐
for instructions on reporting bugs, see https://gcc.gnu.org/bugs/. go tell them everything, they wanna know ๐ซถ
๐ 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. supplying them in cases where they aren't necessary is innocuous, though, so no stress. also-sharedsuppresses the addition of startup code that alters 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.
๐ AUTHOR ๐
see the Info entry for gcc, or https://gcc.gnu.org/onlinedocs/gcc/Contributors.html, for contributors to GCC. legends, every single one ๐ญ
โญ 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.
aaaand that's a wrap bestie, the whole page is done ๐ this was gcc-13, dated 2026-09-10, living in section GCC(1) of your manual โ now go forth and compile something iconic, you absolute main character ๐โจ
๐ฆ where this page comes from
- ubuntu stonking: gcc-13-offload-nvptx 13.5.0-1ubuntu1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms