GCC(1)
gcc(1) โ that's the manual name right there, section 1, straight out of the GNU manual. Buckle up bestie, this is the big one ๐
๐ NAME ๐
gcc โ GNU project C and C++ compiler. That's her. That's the whole girl. โจ
๐ฆ SYNOPSIS ๐ฆ
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Okay so lowkey that's only the most useful options โ the rest of them are down below, keep scrolling, they're all there I promise. And g++? She accepts mostly the same options as gcc. Twins fr. ๐
๐ DESCRIPTION ๐
When you invoke GCC, she normally does preprocessing, compilation, assembly and linking. All four. In that order. Main character energy honestly. The "overall options" let you stop this whole process at an intermediate stage โ like, -c says don't run the linker, and then the output consists of object files output by the assembler. Slay.
Other options get passed on to one or more stages of processing. Some of them control the preprocessor, others control the compiler itself. And yet others control the assembler and the linker โ but most of those aren't documented here, because bestie, you rarely need to use 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, no games. And if the description for a particular option doesn't mention a source language at all? Then 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 you're cross-compiling, or machine-gcc-version to run one specific version of GCC. And when you compile C++ programs, you should invoke GCC as g++ instead. The name is not a vibe, it's a decision โจ
The gcc program accepts options and file names as operands. Many options have multi-letter names, and therefore multiple single-letter options may not be grouped together: -dv is very different from -d -v. Do not smush them. I am 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. Read the room, basically.
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 a positive and a negative form โ the negative form of -ffoo is -fno-foo. This manual documents only one of those two forms: whichever one is not the default. Efficient of her.
Some options take one or more arguments, typically separated from the option name by either a space or by the equals sign (=). 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. For the full listing and explanation of the binary and decimal byte size prefixes, refer to the NIST, IEC, and other relevant national and international standards. ๐
๐ OPTIONS ๐
โจ Option Summary โจ
Here is a summary of all the options, grouped by type. The actual explanations live in the sections that come after this one, so hold that thought ๐ซถ
๐ธ Overall Options ๐ธ
-c -S -E -o file -dumpbase dumpbase -dumpbase-ext auxdropsuf
-dumpdir dumppfx -x language -v -### --help[=class[,...]]
--target-help --version -pass-exit-codes -pipe -specs=file
-wrapper @file -ffile-prefix-map=old=new -fcanon-prefix-map
-fplugin=file -fplugin-arg-name=arg -fdump-ada-spec[-slim]
-fada-spec-parent=unit -fdump-go-spec=file
๐ C Language Options ๐
-ansi -std=standard -aux-info filename -fno-asm -fno-builtin
-fno-builtin-function -fcond-mismatch -ffreestanding -fgimple
-fgnu-tm -fgnu89-inline -fhosted -flax-vector-conversions
-fms-extensions -foffload=arg -foffload-options=arg -fopenacc
-fopenacc-dim=geom -fopenmp -fopenmp-simd
-fopenmp-target-simd-clone[=device-type]
-fpermitted-flt-eval-methods=standard -fplan9-extensions
-fsigned-bitfields -funsigned-bitfields -fsigned-char
-funsigned-char -fstrict-flex-arrays[=n] -fsso-struct=endianness
๐ฆ C++ Language Options ๐ฆ
-fabi-version=n -fno-access-control -faligned-new=n
-fargs-in-order=n -fchar8_t -fcheck-new -fconstexpr-depth=n
-fconstexpr-cache-depth=n -fconstexpr-loop-limit=n
-fconstexpr-ops-limit=n -fno-elide-constructors
-fno-enforce-eh-specs -fno-gnu-keywords -fno-implicit-templates
-fno-implicit-inline-templates -fno-implement-inlines
-fmodule-header[=kind] -fmodule-only -fmodules-ts
-fmodule-implicit-inline -fno-module-lazy
-fmodule-mapper=specification -fmodule-version-ignore
-fms-extensions -fnew-inheriting-ctors -fnew-ttp-matching
-fno-nonansi-builtins -fnothrow-opt -fno-operator-names
-fno-optional-diags -fpermissive -fno-pretty-templates -fno-rtti
-fsized-deallocation -ftemplate-backtrace-limit=n -ftemplate-depth=n
-fno-threadsafe-statics -fuse-cxa-atexit -fno-weak -nostdinc++
-fvisibility-inlines-hidden -fvisibility-ms-compat
-fext-numeric-literals -flang-info-include-translate[=header]
-flang-info-include-translate-not -flang-info-module-cmi[=module]
-stdlib=libstdc++,libc++ -Wabi-tag -Wcatch-value -Wcatch-value=n
-Wno-class-conversion -Wclass-memaccess -Wcomma-subscript
-Wconditionally-supported -Wno-conversion-null
-Wctad-maybe-unsupported -Wctor-dtor-privacy -Wdangling-reference
-Wno-delete-incomplete -Wdelete-non-virtual-dtor
-Wno-deprecated-array-compare -Wdeprecated-copy
-Wdeprecated-copy-dtor -Wno-deprecated-enum-enum-conversion
-Wno-deprecated-enum-float-conversion -Weffc++ -Wno-exceptions
-Wextra-semi -Wno-inaccessible-base -Wno-inherited-variadic-ctor
-Wno-init-list-lifetime -Winvalid-constexpr
-Winvalid-imported-macros -Wno-invalid-offsetof -Wno-literal-suffix
-Wmismatched-new-delete -Wmismatched-tags -Wmultiple-inheritance
-Wnamespaces -Wnarrowing -Wnoexcept -Wnoexcept-type
-Wnon-virtual-dtor -Wpessimizing-move -Wno-placement-new
-Wplacement-new=n -Wrange-loop-construct -Wredundant-move
-Wredundant-tags -Wreorder -Wregister -Wstrict-null-sentinel
-Wno-subobject-linkage -Wtemplates -Wno-non-template-friend
-Wold-style-cast -Woverloaded-virtual -Wno-pmf-conversions
-Wself-move -Wsign-promo -Wsized-deallocation
-Wsuggest-final-methods -Wsuggest-final-types -Wsuggest-override
-Wno-terminate -Wuseless-cast -Wno-vexing-parse
-Wvirtual-inheritance -Wno-virtual-move-assign -Wvolatile
-Wzero-as-null-pointer-constant
๐ Objective-C and Objective-C++ Language Options ๐
-fconstant-string-class=class-name -fgnu-runtime -fnext-runtime
-fno-nil-receivers -fobjc-abi-version=n -fobjc-call-cxx-cdtors
-fobjc-direct-dispatch -fobjc-exceptions -fobjc-gc -fobjc-nilcheck
-fobjc-std=objc1 -fno-local-ivars
-fivar-visibility=[public|protected|private|package]
-freplace-objc-classes -fzero-link -gen-decls -Wassign-intercept
-Wno-property-assign-default -Wno-protocol -Wobjc-root-class
-Wselector -Wstrict-selector-match -Wundeclared-selector
๐ง Diagnostic Message Formatting Options ๐ง
-fmessage-length=n -fdiagnostics-plain-output
-fdiagnostics-show-location=[once|every-line]
-fdiagnostics-color=[auto|never|always]
-fdiagnostics-urls=[auto|never|always]
-fdiagnostics-format=[text|sarif-stderr|sarif-file|json|json-
stderr|json-file] -fno-diagnostics-show-option
-fno-diagnostics-show-caret -fno-diagnostics-show-labels
-fno-diagnostics-show-line-numbers -fno-diagnostics-show-cwe
-fno-diagnostics-show-rule -fdiagnostics-minimum-margin-width=width
-fdiagnostics-parseable-fixits -fdiagnostics-generate-patch
-fdiagnostics-show-template-tree -fno-elide-type
-fdiagnostics-path-format=[none|separate-events|inline-events]
-fdiagnostics-show-path-depths -fno-show-column
-fdiagnostics-column-unit=[display|byte]
-fdiagnostics-column-origin=origin
-fdiagnostics-escape-format=[unicode|bytes]
And that's the whole summary, bestie โ every single one of them, no skips. Now we get into what they actually do ๐
โ ๏ธ Warning Options โ ๏ธ
okay so buckle up bestie, this is the warning-flag roster and it is a lot ๐ every single one of these is in the summary list, and i'm putting every single one here because we do not skip. we do not abbreviate. we do not do that thing where someone's like "oh and there's a bunch of -W flags" โ no ma'am. โจ
heads up: these are listed exactly as they show up in the option summary, capital letters,=ns, the whole thing. don't come for me if-Wno-is in there, that's just how she is. ๐
-fsyntax-only-fmax-errors=n-Wpedantic-pedantic-errors-w-Wextra-Wall๐-Wabi=n-Waddress-Wno-address-of-packed-member-Waggregate-return-Walloc-size-larger-than=byte-size-Walloc-zero-Walloca-Walloca-larger-than=byte-size-Wno-aggressive-loop-optimizations-Warith-conversion-Warray-bounds-Warray-bounds=n-Warray-compare-Wno-attributes-Wattribute-alias=n-Wno-attribute-alias-Wno-attribute-warning-Wbidi-chars=[none|unpaired|any|ucn]๐ฆ-Wbool-compare-Wbool-operation-Wno-builtin-declaration-mismatch-Wno-builtin-macro-redefined-Wc90-c99-compat-Wc99-c11-compat-Wc11-c2x-compat-Wc++-compat-Wc++11-compat-Wc++14-compat-Wc++17-compat-Wc++20-compat-Wno-c++11-extensions-Wno-c++14-extensions-Wno-c++17-extensions-Wno-c++20-extensions-Wno-c++23-extensions-Wcast-align-Wcast-align=strict-Wcast-function-type-Wcast-qual-Wchar-subscripts-Wclobbered-Wcomment-Wno-complain-wrong-lang-Wconversion-Wno-coverage-mismatch-Wno-cpp-Wdangling-else-Wdangling-pointer-Wdangling-pointer=n-Wdate-time-Wno-deprecated-Wno-deprecated-declarations-Wno-designated-init-Wdisabled-optimization-Wno-discarded-array-qualifiers-Wno-discarded-qualifiers-Wno-div-by-zero-Wdouble-promotion-Wduplicated-branches-Wduplicated-cond-Wempty-body-Wno-endif-labels-Wenum-compare-Wenum-conversion-Wenum-int-mismatch-Werror๐-Werror=*๐ฅ-Wexpansion-to-defined-Wfatal-errors-Wfloat-conversion-Wfloat-equal-Wformat-Wformat=2-Wno-format-contains-nul-Wno-format-extra-args-Wformat-nonliteral-Wformat-overflow=n-Wformat-security-Wformat-signedness-Wformat-truncation=n-Wformat-y2k-Wframe-address-Wframe-larger-than=byte-size-Wno-free-nonheap-object-Wno-if-not-aligned-Wno-ignored-attributes-Wignored-qualifiers-Wno-incompatible-pointer-types-Wimplicit-Wimplicit-fallthrough-Wimplicit-fallthrough=n-Wno-implicit-function-declaration-Wno-implicit-int-Winfinite-recursion-Winit-self-Winline-Wno-int-conversion-Wint-in-bool-context-Wno-int-to-pointer-cast-Wno-invalid-memory-model-Winvalid-pch-Winvalid-utf8-Wno-unicode-Wjump-misses-init-Wlarger-than=byte-size-Wlogical-not-parentheses-Wlogical-op-Wlong-long-Wno-lto-type-mismatch-Wmain-Wmaybe-uninitialized-Wmemset-elt-size-Wmemset-transposed-args-Wmisleading-indentation-Wmissing-attributes-Wmissing-braces-Wmissing-field-initializers-Wmissing-format-attribute-Wmissing-include-dirs-Wmissing-noreturn-Wno-missing-profile-Wno-multichar-Wmultistatement-macros-Wnonnull-Wnonnull-compare-Wnormalized=[none|id|nfc|nfkc]๐ธ-Wnull-dereference-Wno-odr-Wopenacc-parallelism-Wopenmp-simd-Wno-overflow-Woverlength-strings-Wno-override-init-side-effects-Wpacked-Wno-packed-bitfield-compat-Wpacked-not-aligned-Wpadded-Wparentheses-Wno-pedantic-ms-format-Wpointer-arith-Wno-pointer-compare-Wno-pointer-to-int-cast-Wno-pragmas-Wno-prio-ctor-dtor-Wredundant-decls-Wrestrict-Wno-return-local-addr-Wreturn-type-Wno-scalar-storage-order-Wsequence-point-Wshadow-Wshadow=global-Wshadow=local-Wshadow=compatible-local-Wno-shadow-ivar-Wno-shift-count-negative-Wno-shift-count-overflow-Wshift-negative-value-Wno-shift-overflow-Wshift-overflow=n-Wsign-compare-Wsign-conversion-Wno-sizeof-array-argument-Wsizeof-array-div-Wsizeof-pointer-div-Wsizeof-pointer-memaccess-Wstack-protector-Wstack-usage=byte-size-Wstrict-aliasing-Wstrict-aliasing=n-Wstrict-overflow-Wstrict-overflow=n-Wstring-compare-Wno-stringop-overflow-Wno-stringop-overread-Wno-stringop-truncation-Wstrict-flex-arrays-Wsuggest-attribute=[pure|const|noreturn|format|malloc]โจ-Wswitch-Wno-switch-bool-Wswitch-default-Wswitch-enum-Wno-switch-outside-range-Wno-switch-unreachable-Wsync-nand-Wsystem-headers-Wtautological-compare-Wtrampolines-Wtrigraphs-Wtrivial-auto-var-init-Wtsan-Wtype-limits-Wundef-Wuninitialized-Wunknown-pragmas-Wunsuffixed-float-constants-Wunused-Wunused-but-set-parameter-Wunused-but-set-variable-Wunused-const-variable-Wunused-const-variable=n-Wunused-function-Wunused-label-Wunused-local-typedefs-Wunused-macros-Wunused-parameter-Wno-unused-result-Wunused-value-Wunused-variable-Wno-varargs-Wvariadic-macros-Wvector-operation-performance-Wvla-Wvla-larger-than=byte-size-Wno-vla-larger-than-Wvolatile-register-var-Wwrite-strings-Wxor-used-as-pow-Wzero-length-bounds
like. that's the list. that's all of them. if you read every one out loud you deserve a lil treat ๐
๐ Static Analyzer Options ๐
okay so the static analyzer is the part of gcc that's like... a little detective ๐ต๏ธ and these are her flags. same deal as before โ full list, nothing skipped, i love you, here we go. ๐
-fanalyzer-fanalyzer-call-summaries-fanalyzer-checker=name-fno-analyzer-feasibility-fanalyzer-fine-grained-fno-analyzer-state-merge-fno-analyzer-state-purge-fno-analyzer-suppress-followups-fanalyzer-transitivity-fno-analyzer-undo-inlining-fanalyzer-verbose-edges-fanalyzer-verbose-state-changes-fanalyzer-verbosity=level-fdump-analyzer-fdump-analyzer-callgraph-fdump-analyzer-exploded-graph-fdump-analyzer-exploded-nodes-fdump-analyzer-exploded-nodes-2-fdump-analyzer-exploded-nodes-3-fdump-analyzer-exploded-paths-fdump-analyzer-feasibility-fdump-analyzer-json-fdump-analyzer-state-purge-fdump-analyzer-stderr-fdump-analyzer-supergraph-fdump-analyzer-untracked-Wno-analyzer-double-fclose-Wno-analyzer-double-free-Wno-analyzer-exposure-through-output-file-Wno-analyzer-exposure-through-uninit-copy-Wno-analyzer-fd-access-mode-mismatch-Wno-analyzer-fd-double-close-Wno-analyzer-fd-leak-Wno-analyzer-fd-phase-mismatch-Wno-analyzer-fd-type-mismatch-Wno-analyzer-fd-use-after-close-Wno-analyzer-fd-use-without-check-Wno-analyzer-file-leak-Wno-analyzer-free-of-non-heap-Wno-analyzer-imprecise-fp-arithmetic-Wno-analyzer-infinite-recursion-Wno-analyzer-jump-through-null-Wno-analyzer-malloc-leak-Wno-analyzer-mismatching-deallocation-Wno-analyzer-null-argument-Wno-analyzer-null-dereference-Wno-analyzer-out-of-bounds-Wno-analyzer-possible-null-argument-Wno-analyzer-possible-null-dereference-Wno-analyzer-putenv-of-auto-var-Wno-analyzer-shift-count-negative-Wno-analyzer-shift-count-overflow-Wno-analyzer-stale-setjmp-buffer-Wno-analyzer-tainted-allocation-size-Wno-analyzer-tainted-assertion-Wno-analyzer-tainted-array-index-Wno-analyzer-tainted-divisor-Wno-analyzer-tainted-offset-Wno-analyzer-tainted-size-Wanalyzer-too-complex-Wno-analyzer-unsafe-call-within-signal-handler-Wno-analyzer-use-after-free-Wno-analyzer-use-of-pointer-in-stale-stack-frame-Wno-analyzer-use-of-uninitialized-value-Wno-analyzer-va-arg-type-mismatch-Wno-analyzer-va-list-exhausted-Wno-analyzer-va-list-leak-Wno-analyzer-va-list-use-after-va-end-Wno-analyzer-write-to-const-Wno-analyzer-write-to-string-literal
the -Wno-analyzer- girlies really said "we contain multitudes" and honestly? they do. ๐
๐ C and Objective-C-only Warning Options ๐
these ones are strictly for the C and Objective-C girlies โ she's specialized. ๐
-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 ๐
last group for this part!! these are the debug-info girlies and they're so important when you're sitting there at 2am going "why is it doing that". ๐ญ
-g๐ซถ-glevel-gdwarf-gdwarf-version-gbtf-gctf-gctflevel-ggdb-grecord-gcc-switches-gno-record-gcc-switches-gstrict-dwarf-gno-strict-dwarf-gas-loc-support-gno-as-loc-support-gas-locview-support-gno-as-locview-support-gcolumn-info-gno-column-info-gdwarf32-gdwarf64-gstatement-frontiers-gno-statement-frontiers-gvariable-location-views-gno-variable-location-views-ginternal-reset-location-views-gno-internal-reset-location-views-ginline-points-gno-inline-points-gvms-gz[=type]-gsplit-dwarf-gdescribe-dies-gno-describe-dies-fdebug-prefix-map=old=new-fdebug-types-section-fno-eliminate-unused-debug-types-femit-struct-debug-baseonly-femit-struct-debug-reduced-femit-struct-debug-detailed[=spec-list]โจ-fno-eliminate-unused-debug-symbols-femit-class-debug-always-fno-merge-debug-strings-fno-dwarf2-cfi-asm-fvar-tracking-fvar-tracking-assignments
and that's a wrap on this chunk โ more coming, bestie, don't go anywhere ๐
๐ Optimization Options ๐
okay bestie, deep breath. this is THE list. every optimization flag GCC has, alphabetically yeeted at you, no cap. i'm not gonna gatekeep a single one:
-faggressive-loop-optimizations-falign-functions[=n[:m:[n2[:m2]]]]-falign-jumps[=n[:m:[n2[:m2]]]]-falign-labels[=n[:m:[n2[:m2]]]]-falign-loops[=n[:m:[n2[:m2]]]]-fno-allocation-dce-fallow-store-data-races-fassociative-math-fauto-profile-fauto-profile[=path]-fauto-inc-dec-fbranch-probabilities-fcaller-saves-fcombine-stack-adjustments-fconserve-stack-fcompare-elim-fcprop-registers-fcrossjumping-fcse-follow-jumps-fcse-skip-blocks-fcx-fortran-rules-fcx-limited-range-fdata-sections-fdce-fdelayed-branch-fdelete-null-pointer-checks-fdevirtualize-fdevirtualize-speculatively-fdevirtualize-at-ltrans-fdse-fearly-inlining-fipa-sra-fexpensive-optimizations-ffat-lto-objects-ffast-math-ffinite-math-only-ffloat-store-fexcess-precision=style-ffinite-loops-fforward-propagate-ffp-contract=style-ffunction-sections-fgcse-fgcse-after-reload-fgcse-las-fgcse-lm-fgraphite-identity-fgcse-sm-fhoist-adjacent-loads-fif-conversion-fif-conversion2-findirect-inlining-finline-functions-finline-functions-called-once-finline-limit=n-finline-small-functions-fipa-modref-fipa-cp-fipa-cp-clone-fipa-bit-cp-fipa-vrp-fipa-pta-fipa-profile-fipa-pure-const-fipa-reference-fipa-reference-addressable-fipa-stack-alignment-fipa-icf-fira-algorithm=algorithm-flive-patching=level-fira-region=region-fira-hoist-pressure-fira-loop-pressure-fno-ira-share-save-slots-fno-ira-share-spill-slots-fisolate-erroneous-paths-dereference-fisolate-erroneous-paths-attribute-fivopts-fkeep-inline-functions-fkeep-static-functions-fkeep-static-consts-flimit-function-alignment-flive-range-shrinkage-floop-block-floop-interchange-floop-strip-mine-floop-unroll-and-jam-floop-nest-optimize-floop-parallelize-all-flra-remat-flto-flto-compression-level-flto-partition=alg-fmerge-all-constants-fmerge-constants-fmodulo-sched-fmodulo-sched-allow-regmoves-fmove-loop-invariants-fmove-loop-stores-fno-branch-count-reg-fno-defer-pop-fno-fp-int-builtin-inexact-fno-function-cse-fno-guess-branch-probability-fno-inline-fno-math-errno-fno-peephole-fno-peephole2-fno-printf-return-value-fno-sched-interblock-fno-sched-spec-fno-signed-zeros-fno-toplevel-reorder-fno-trapping-math-fno-zero-initialized-in-bss-fomit-frame-pointer-foptimize-sibling-calls-fpartial-inlining-fpeel-loops-fpredictive-commoning-fprefetch-loop-arrays-fprofile-correction-fprofile-use-fprofile-use=path-fprofile-partial-training-fprofile-values-fprofile-reorder-functions-freciprocal-math-free-frename-registers-freorder-blocks-freorder-blocks-algorithm=algorithm-freorder-blocks-and-partition-freorder-functions-frerun-cse-after-loop-freschedule-modulo-scheduled-loops-frounding-math-fsave-optimization-record-fsched2-use-superblocks-fsched-pressure-fsched-spec-load-fsched-spec-load-dangerous-fsched-stalled-insns-dep[=n]-fsched-stalled-insns[=n]-fsched-group-heuristic-fsched-critical-path-heuristic-fsched-spec-insn-heuristic-fsched-rank-heuristic-fsched-last-insn-heuristic-fsched-dep-count-heuristic-fschedule-fusion-fschedule-insns-fschedule-insns2-fsection-anchors-fselective-scheduling-fselective-scheduling2-fsel-sched-pipelining-fsel-sched-pipelining-outer-loops-fsemantic-interposition-fshrink-wrap-fshrink-wrap-separate-fsignaling-nans-fsingle-precision-constant-fsplit-ivs-in-unroller-fsplit-loops-fsplit-paths-fsplit-wide-types-fsplit-wide-types-early-fssa-backprop-fssa-phiopt-fstdarg-opt-fstore-merging-fstrict-aliasing-fipa-strict-aliasing-fthread-jumps-ftracer-ftree-bit-ccp-ftree-builtin-call-dce-ftree-ccp-ftree-ch-ftree-coalesce-vars-ftree-copy-prop-ftree-dce-ftree-dominator-opts-ftree-dse-ftree-forwprop-ftree-fre-fcode-hoisting-ftree-loop-if-convert-ftree-loop-im-ftree-phiprop-ftree-loop-distribution-ftree-loop-distribute-patterns-ftree-loop-ivcanon-ftree-loop-linear-ftree-loop-optimize-ftree-loop-vectorize-ftree-parallelize-loops=n-ftree-pre-ftree-partial-pre-ftree-pta-ftree-reassoc-ftree-scev-cprop-ftree-sink-ftree-slsr-ftree-sra-ftree-switch-conversion-ftree-tail-merge-ftree-ter-ftree-vectorize-ftree-vrp-ftrivial-auto-var-init-funconstrained-commons-funit-at-a-time-funroll-all-loops-funroll-loops-funsafe-math-optimizations-funswitch-loops-fipa-ra-fvariable-expansion-in-unroller-fvect-cost-model-fvpt-fweb-fwhole-program-fwpa-fuse-linker-plugin-fzero-call-used-regs--param name=value-O-O0-O1-O2-O3-Os-Ofast-Og-Oz
and yes, -O, -O0 through -O3, -Os, -Ofast, -Og and -Oz are all sitting right there at the end of the pile like the main characters they are. ๐
๐ซถ Program Instrumentation Options ๐ซถ
the little extra tools that keep an eye on your program while it's out there living its life. the whole roster:
-p-pg-fprofile-arcs--coverage-ftest-coverage-fprofile-abs-path-fprofile-dir=path-fprofile-generate-fprofile-generate=path-fprofile-info-section-fprofile-info-section=name-fprofile-note=path-fprofile-prefix-path=path-fprofile-update=method-fprofile-filter-files=regex-fprofile-exclude-files=regex-fprofile-reproducible=[multithreaded|parallel-runs|serial]-fsanitize=style-fsanitize-recover-fsanitize-recover=style-fsanitize-trap-fsanitize-trap=style-fasan-shadow-offset=number-fsanitize-sections=s1,s2,...-fsanitize-undefined-trap-on-error-fbounds-check-fcf-protection=[full|branch|return|none|check]-fharden-compares-fharden-conditional-branches-fstack-protector-fstack-protector-all-fstack-protector-strong-fstack-protector-explicit-fstack-check-fstack-limit-register=reg-fstack-limit-symbol=sym-fno-stack-limit-fsplit-stack-fvtable-verify=[std|preinit|none]-fvtv-counts-fvtv-debug-finstrument-functions-finstrument-functions-once-finstrument-functions-exclude-function-list=sym,sym,...-finstrument-functions-exclude-file-list=file,file,...-fprofile-prefix-map=old=new
๐ธ Preprocessor Options ๐ธ
the preprocessor era โจ these are the ones that get to work before your actual compile even wakes up:
-Aquestion=answer-A-question[=answer]-C-CC-Dmacro[=defn]-dD-dI-dM-dN-dU-fdebug-cpp-fdirectives-only-fdollars-in-identifiers-fexec-charset=charset-fextended-identifiers-finput-charset=charset-flarge-source-files-fmacro-prefix-map=old=new-fmax-include-depth=depth-fno-canonical-system-headers-fpch-deps-fpch-preprocess-fpreprocessed-ftabstop=width-ftrack-macro-expansion-fwide-exec-charset=charset-fworking-directory-H-imacros file-include file-M-MD-MF-MG-MM-MMD-MP-MQ-MT-Mno-modules-no-integrated-cpp-P-pthread-remap-traditional-traditional-cpp-trigraphs-Umacro-undef-Wp,option-Xpreprocessor option
๐ Assembler Options ๐
short but iconic. just two besties:
-Wa,option-Xassembler option
๐ Linker Options ๐
the linker menu, and it's lowkey stacked:
object-file-name-fuse-ld=linker-llibrary-nostartfiles-nodefaultlibs-nolibc-nostdlib-nostdlib++-e entry--entry=entry-pie-pthread-r-rdynamic-s-static-static-pie-static-libgcc-static-libstdc++-static-libasan-static-libtsan-static-liblsan-static-libubsan-shared-shared-libgcc-symbolic-T script-Wl,option-Xlinker option-u symbol-z keyword
๐ฆ Directory Options ๐ฆ
where do we look for stuff, bestie? these are the vibes that answer that:
-Bprefix-Idir-I--idirafter dir-imacros file-imultilib dir-iplugindir=dir-iprefix file-iquote dir-isysroot dir-isystem dir-iwithprefix dir-iwithprefixbefore dir-Ldir-no-canonical-prefixes--no-sysroot-suffix-nostdinc-nostdinc++--sysroot=dir
โญ Code Generation Options โญ
the codegen glow-up section, iykyk:
-fcall-saved-reg-fcall-used-reg-ffixed-reg-fexceptions-fnon-call-exceptions-fdelete-dead-exceptions-funwind-tables-fasynchronous-unwind-tables-fno-gnu-unique-finhibit-size-directive-fcommon-fno-ident-fpcc-struct-return-fpic-fPIC-fpie-fPIE-fno-plt-fno-jump-tables-fno-bit-tests-frecord-gcc-switches-freg-struct-return-fshort-enums-fshort-wchar-fverbose-asm-fpack-struct[=n]-fleading-underscore-ftls-model=model-fstack-reuse=reuse_level-ftrampolines-ftrapv-fwrapv-fvisibility=[default|internal|hidden|protected]-fstrict-volatile-bitfields-fsync-libcalls
๐ง Developer Options ๐ง
okay this is the backstage-pass section, the compiler-dev bestie zone. everything here, in order:
-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]
that's the whole option-summary wall, bestie ๐
Machine-Dependent Options ๐ปโจ
Okay so bestie, this is the part where GCC gets hyper-specific about your machine. No universal vibes here โ it's all about your architecture. Let's go architecture by architecture. ๐ซถ
AArch64 Options ๐ฆพ
AArch64 girlies, your flags are here:
-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 ๐ง
Epiphany besties, here's your list:
-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 ๐
AMD GCN vibes:
-march=gpu-mtune=gpu-mstack-size=bytes
ARC Options ๐
ARC crew, these are for you:
-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 ๐
ARM bestie, here's the whole squad:
-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 ๐
AVR girlies, here's your menu:
-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 ๐ค
Blackfin besties:
-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 ๐
C6X options, periodt:
-mbig-endian-mlittle-endian-march=cpu-msim-msdata=sdata-type
CRIS Options ๐ซ
CRIS cuties:
-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 โ๏ธ
C-SKY besties:
-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 ๐
Darwin darlings, here's the whole list (yes, there are some repeats, just like the original):
-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 ๐ฆ
DEC Alpha, iconic:
-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 ๐
eBPF bestie:
-mbig-endian-mlittle-endian-mkernel=version-mframe-limit=bytes-mxbpf-mco-re-mno-co-re-mjmpext-mjmp32-malu32-mcpu=version
FR30 Options ๐ธ
FR30 flags:
-msmall-model-mno-lsim
FT32 Options ๐ฆ
FT32 options:
-msim-mlra-mnodiv-mft32b-mcompress-mnopm
FRV Options ๐ฅ
FRV fire:
-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 ๐ง
GNU/Linux gang:
-mglibc-muclibc-mmusl-mbionic-mandroid-tno-android-cc-tno-android-ld
H8/300 Options ๐
H8/300 options:
-mrelax-mh-ms-mn-mexr-mno-exr-mint32-malign-300
HPPA Options ๐
HPPA bestie:
-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 ๐ธ
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 ๐
LM32 bestie:
-mbarrel-shift-enabled-mdivide-enabled-mmultiply-enabled-msign-extend-enabled-muser-enabled
LoongArch Options ๐
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 ๐ฆ
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 ๐
M32C options:
-mcpu=cpu-msim-memregs=number
๐ M680x0 Options ๐
okay bestie, this is the Motorola 680x0 family menu and it is a lot, so grab a snack ๐ซถ every single one of these is real and I'm not skipping a single flag:
-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 lineup, no cap, all present and accounted for โจ
-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 ๐ง
MicroBlaze girlies rise ๐ here's the whole set:
-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 ๐
the MIPS section is giving encyclopedia, bestie, but we're doing it, we're doing all of it ๐ญ and yes -mno-gopt is literally spelled like that, do not come for me, I am copying it exactly:
-EL-EB-march=arch-mtune=arch-mips1-mips2-mips3-mips4-mips32-mips32r2-mips32r3-mips32r5-mips32r6-mips64-mips64r2-mips64r3-mips64r5-mips64r6-mips16-mno-mips16-mflip-mips16-minterlink-compressed-mno-interlink-compressed-minterlink-mips16-mno-interlink-mips16-mabi=abi-mabicalls-mno-abicalls-mshared-mno-shared-mplt-mno-plt-mxgot-mno-xgot-mgp32-mgp64-mfp32-mfpxx-mfp64-mhard-float-msoft-float-mno-float-msingle-float-mdouble-float-modd-spreg-mno-odd-spreg-mabs=mode-mnan=encoding-mdsp-mno-dsp-mdspr2-mno-dspr2-mmcu-mmno-mcu-meva-mno-eva-mvirt-mno-virt-mxpa-mno-xpa-mcrc-mno-crc-mginv-mno-ginv-mmicromips-mno-micromips-mmsa-mno-msa-mloongson-mmi-mno-loongson-mmi-mloongson-ext-mno-loongson-ext-mloongson-ext2-mno-loongson-ext2-mfpu=fpu-type-msmartmips-mno-smartmips-mpaired-single-mno-paired-single-mdmx-mno-mdmx-mips3d-mno-mips3d-mmt-mno-mt-mllsc-mno-llsc-mlong64-mlong32-msym32-mno-sym32-Gnum-mlocal-sdata-mno-local-sdata-mextern-sdata-mno-extern-sdata-mgpopt-mno-gopt-membedded-data-mno-embedded-data-muninit-const-in-rodata-mno-uninit-const-in-rodata-mcode-readable=setting-msplit-addresses-mno-split-addresses-mexplicit-relocs-mno-explicit-relocs-mcheck-zero-division-mno-check-zero-division-mdivide-traps-mdivide-breaks-mload-store-pairs-mno-load-store-pairs-munaligned-access-mno-unaligned-access-mmemcpy-mno-memcpy-mlong-calls-mno-long-calls-mmad-mno-mad-mimadd-mno-imadd-mfused-madd-mno-fused-madd-nocpp-mfix-24k-mno-fix-24k-mfix-r4000-mno-fix-r4000-mfix-r4400-mno-fix-r4400-mfix-r5900-mno-fix-r5900-mfix-r10000-mno-fix-r10000-mfix-rm7000-mno-fix-rm7000-mfix-vr4120-mno-fix-vr4120-mfix-vr4130-mno-fix-vr4130-mfix-sb1-mno-fix-sb1-mflush-func=func-mno-flush-func-mbranch-cost=num-mbranch-likely-mno-branch-likely-mcompact-branches=policy-mfp-exceptions-mno-fp-exceptions-mvr4130-align-mno-vr4130-align-msynci-mno-synci-mlxc1-sxc1-mno-lxc1-sxc1-mmadd4-mno-madd4-mrelax-pic-calls-mno-relax-pic-calls-mmcount-ra-address-mframe-header-opt-mno-frame-header-opt
phew, we survived ๐ฎโ๐จ
๐ธ MMIX Options ๐ธ
-mlibfuncs-mno-libfuncs-mepsilon-mno-epsilon-mabi=gnu-mabi=mmixware-mzero-extend-mknuthdiv-mtoplevel-symbols-melf-mbranch-predict-mno-branch-predict-mbase-addresses-mno-base-addresses-msingle-exit-mno-single-exit
๐ MN10300 Options ๐
-mmult-bug-mno-mult-bug-mno-am33-mam33-mam33-2-mam34-mtune=cpu-type-mreturn-pointer-on-d0-mno-crt0-mrelax-mliw-msetlb
๐ฆ Moxie Options ๐ฆ
short and sweet, we love a low-effort icon โจ
-meb-mel-mmul.x-mno-crt0
๐ MSP430 Options ๐
-msim-masm-hex-mmcu=-mcpu=-mlarge-msmall-mrelax-mwarn-mcu-mcode-region=-mdata-region=-msilicon-errata=-msilicon-errata-warn=-mhwmult=-minrt-mtiny-printf-mmax-inline-shift=
๐ NDS32 Options ๐
-mbig-endian-mlittle-endian-mreduced-regs-mfull-regs-mcmov-mno-cmov-mext-perf-mno-ext-perf-mext-perf2-mno-ext-perf2-mext-string-mno-ext-string-mv3push-mno-v3push-m16bit-mno-16bit-misr-vector-size=num-mcache-block-size=num-march=arch-mcmodel=code-model-mctor-dtor-mrelax
๐ Nios II Options ๐
-G num-mgpopt=option-mgpopt-mno-gpopt-mgprel-sec=regexp-mr0rel-sec=regexp-mel-meb-mno-bypass-cache-mbypass-cache-mno-cache-volatile-mcache-volatile-mno-fast-sw-div-mfast-sw-div-mhw-mul-mno-hw-mul-mhw-mulx-mno-hw-mulx-mno-hw-div-mhw-div-mcustom-insn=N-mno-custom-insn-mcustom-fpu-cfg=name-mhal-msmallc-msys-crt0=name-msys-lib=name-march=arch-mbmx-mno-bmx-mcdx-mno-cdx
๐ Nvidia PTX Options ๐
tiny section, main character energy fr fr:
-m64-mmainkernel-moptimize
๐ง OpenRISC Options ๐ง
-mboard=name-mnewlib-mhard-mul-mhard-div-msoft-mul-msoft-div-msoft-float-mhard-float-mdouble-float-munordered-float-mcmov-mror-mrori-msext-msfimm-mshftimm-mcmodel=code-model
โญ PDP-11 Options โญ
retro queen behavior ๐
-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 ๐
bestie this one is not a list, it's a redirect, and I am not paraphrasing it:
See RS/6000 and PowerPC Options.
๐ PRU Options ๐
-mmcu=mcu-minrt-mno-relax-mloop-mabi=variant
๐ฅ RISC-V Options ๐ฅ
-mbranch-cost=N-instruction-mplt-mno-plt-mabi=ABI-string-mfdiv-mno-fdiv-mdiv-mno-div-misa-spec=ISA-spec-string-march=ISA-string-mtune=processor-string-mpreferred-stack-boundary=num-msmall-data-limit=N-bytes-msave-restore-mno-save-restore-mshorten-memrefs-mno-shorten-memrefs-mstrict-align-mno-strict-align-mcmodel=medlow-mcmodel=medany-mexplicit-relocs-mno-explicit-relocs-mrelax-mno-relax-mriscv-attribute-mno-riscv-attribute-malign-data=type-mbig-endian-mlittle-endian-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mcsr-check-mno-csr-check-minline-atomics-mno-inline-atomics
๐ RL78 Options ๐
-msim-mmul=none-mmul=g13-mmul=g14-mallregs-mcpu=g10-mcpu=g13-mcpu=g14-mg10-mg13-mg14-m64bit-doubles-m32bit-doubles-msave-mduc-in-interrupts
๐ RS/6000 and PowerPC Options ๐
okay this is the big one, the final boss, the moment we've been training for ๐ค every flag, exactly as written, no crumbs left behind:
-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
slayed, actually ๐ซถ
๐ฆ RX Options ๐ฆ
-m64bit-doubles-m32bit-doubles-fpu-nofpu-mcpu=-mbig-endian-data-mlittle-endian-data-msmall-data-msim-mno-sim-mas100-syntax-mno-as100-syntax-mrelax-mmax-constant-size=-mint-register=-mpid-mallow-string-insns-mno-allow-string-insns-mjsr-mno-warn-multiple-fast-interrupts-msave-acc-in-interrupts
๐ S/390 and zSeries Options ๐
last one of this part bestie, we made it ๐ญ๐
-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 ๐ฆ
bestie, if you're on SuperH, here's your whole lil flag wardrobe โ every single one, no skips, no cap:
-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 โ๏ธ
solaris girlies, this one's for you ๐ซถ:
-mclear-hwcap -mno-clear-hwcap -mimpure-text
-mno-impure-text -pthreads
๐ SPARC Options ๐
the SPARC roster, served fresh, literally all of it:
-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 ๐
old-school SysV energy, four lil flags:
-Qy -Qn -YP,paths -Ym,dir
๐ V850 Options ๐
V850 said "let me have 30+ flags actually" and honestly? iconic:
-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 ๐ธ
retro queen behavior:
-mg -mgnu -munix -mlra
โจ Visium Options โจ
visium's whole thing, right here:
-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 ๐
okay so THIS is the big one, the main character of architecture flags, the one that ate and left no crumbs. here is the ENTIRE list, bestie, every last one:
-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 get their own little set ๐ :
-mconsole -mcygwin -mno-cygwin -mdll
-mnop-fun-dllimport -mthread -municode -mwin32 -mwindows
-fno-set-stack-executable
โญ Xstormy16 Options โญ
one (1) flag. humble. we respect it:
-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 ๐ซ
no cap, this one just points you elsewhere: See S/390 and zSeries Options.
โจ Options Controlling the Kind of Output โจ
okay bestie, so compiling? it's not one single thing, it's a whole four-course meal ๐ฝ๏ธ โ and the order is locked in: preprocessing โ compilation proper โ assembly โ linking. always that order, every time, no substitutions.
GCC can preprocess and compile several files at once, and it can do it either into several assembler input files or into one assembler input file. Then each assembler input file turns into an object file, and the linking stage scoops up all the object files โ the freshly compiled ones and the ones you passed in as input โ and combines them into a single executable file. the way that works is so satisfying fr fr.
For any given input file, the file name suffix is what 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. ngl you must link with thelibobjclibrary to make an Objective-C program work.file.miโ Objective-C source code that should not be preprocessed.file.mmfile.Mโ Objective-C++ source code. and again: you must link with thelibobjclibrary to make an Objective-C++ program work. also heads up,.Mrefers to a literal capital M.file.miiโ Objective-C++ source code that should not be preprocessed.file.hโ C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (that's the default), or a C, C++ header file to be turned into an Ada spec (via the-fdump-ada-specswitch).file.ccfile.cpfile.cxxfile.cppfile.CPPfile.c++file.Cโ C++ source code that must be preprocessed. little gotcha: in.cxx, the last two letters must both be literallyx. likewise,.Crefers to a literal capitalC. ๐file.mmfile.Mโ Objective-C++ source code that must be preprocessed.file.miiโ Objective-C++ source code that should not be preprocessed.file.hhfile.Hfile.hpfile.hxxfile.hppfile.HPPfile.h++file.tccโ C++ header file to be turned into a precompiled header or Ada spec.file.ffile.forfile.ftnโ Fixed form Fortran source code that should not be preprocessed.file.Ffile.FORfile.fppfile.FPPfile.FTNโ Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).file.f90file.f95file.f03file.f08โ Free form Fortran source code that should not be preprocessed.file.F90file.F95file.F03file.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.Sfile.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 just say what language it is out loud 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 -x option. 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
objective-c++ objective-c++-header objective-c++-cpp-output
assembler assembler-with-cpp
ada
d
f77 f77-cpp-input f95 f95-cpp-input
go
-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 -x has not been used at all).
If you only want some of the stages of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop. lowkey important caveat tho: some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all. literally nothing. a whole no-op. ๐
-c
Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.
By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o. ๐
Unrecognized input files, not requiring compilation or assembly, are ignored. (Iconic behaviour, honestly. Not my problem, not my output. ๐)
-Sโ bestie, this one says STOP right 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.*.
When compiling and then linking from multiple input files, a defaulted or explicitly specified dumppfx also undergoes the dumpbase- transformation above (e.g. the compilation of foo.c and bar.c above, but without -c). If neither -dumpdir nor -dumpbase are given, the linker output base name, minus auxdropsuf, if specified, or the executable suffix otherwise, plus a dash is appended to the default dumppfx instead. Note, however, that unlike earlier cases of linking:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...
does not append the output name main to dumppfx, because -dumpdir was explicitly specified. The whole goal here is that the explicitly-specified dumppfx is allowed to contain the specified output name as part of the prefix if you want it to; only an explicitly-specified -dumpbase would get combined with it, so we don't just yeet a meaningful option into the void. ๐
When you compile and then link from a single input file, the linker output base name will only be appended to the default dumppfx as described above if it does not share the base name with the single input file name. That's been covered in the single-input linking cases already, but not 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 are named foo.*, and dump outputs foo.c.*, in the current working directory as ultimately requested by -save-temps=cwd. ๐
Summing it all up for an intuitive though slightly imprecise data flow: the primary output name is broken into a directory part and a basename part; dumppfx is set to the former, unless overridden by -dumpdir or -save-temps=*, and dumpbase is set to the latter, unless overriden by -dumpbase. If there are multiple inputs or linking, this dumpbase may be 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. ๐ฆ
When it comes to auxiliary and dump outputs created during LTO recompilation, a combination of dumppfx and dumpbase โ as given or as derived from the linker output name but not from inputs, even in cases in which this combination would not otherwise be used as such โ is passed down with a trailing period replacing the compiler-added dash, if any, as a -dumpdir option to lto-wrapper; being involved in linking, this program does not 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, ensures it contains a directory component so that it overrides any -dumpdir, and passes that as -dumpbase to sub-compilers.
-vโ Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. receipts for everything, bestie ๐งพ-###โ Like-vexcept the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or"./-_". This is useful for shell scripts to capture the driver-generated command lines. dry run mode, we love a preview โจ--helpโ Print (on the standard output) a description of the command-line options understood bygcc. If the-voption is also specified then--helpis also passed on to the various processes invoked bygcc, so that they can display the command-line options they accept. If the-Wextraoption has also been specified (prior to the--helpoption), then command-line options that have no documentation associated with them are also displayed. ๐--target-helpโ Print (on the standard output) a description of target-specific command-line options for each tool. For some targets extra target-specific information may also be printed.--help={class|[^]qualifier}[,...]โ Print (on the standard output) a description of the command-line options understood by the compiler that fit into all specified classes and qualifiers. These are the supported classes:optimizersโ Display all of the optimization options supported by the compiler. ๐ฅwarningsโ Display all of the options controlling warning messages produced by the compiler.targetโ Display target-specific options. Unlike the--target-helpoption however, target-specific options of the linker and assembler are not displayed. This is because those tools do not currently support the extended--help=syntax.paramsโ Display the values recognized by the--paramoption.languageโ Display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, one needs to selectcommonclass.commonโ Display the options that are common to all languages.
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.
Thus for example to display all the undocumented target-specific switches supported by the compiler, use:
--help=target,undocumented
The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e., ones that are either on or off and that do not take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
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 is nothing to display. One case where it does work, however, 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 those that have already been displayed. If --help is also specified anywhere on the command line then this 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 that the compiler knows this at the point where the --help= option is used).
Here is a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi= 2
-mabort-on-noreturn [disabled]
-mapcs [disabled]
The output is sensitive to the effects of previous command-line options, so for example it is 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
literally a whole investigation, detective era ๐
--versionโ Display 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. GNU stays winning fr fr-specs=fileโ Process file after the compiler reads in the standard specs file, in order to override the defaults which 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 are 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, thus the invocation of cc1 is 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 be normally 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โ Load the plugin code in filename.so, assumed to be a shared object to bedlopen'd by the compiler. The base name of the shared object file is used to identify the plugin for the purposes of argument parsing (See-fplugin-arg-name-key=valuebelow). Each plugin should define the callback functions specified in the Plugins API. ๐ง-fplugin-arg-name-key=valueโ Define an argument called key with a value of value for the plugin called name.-fdump-ada-spec[-slim]โ For C and C++ source and include files, generate corresponding Ada specs. ๐ธ-fada-spec-parent=unitโ bestie, this one only makes sense if you already know about-fdump-ada-spec[-slim]from earlier (go scroll up ๐ ). It teams up with that and says: make those Ada specs as child units of unit. That's it, that's the whole vibe. ๐-fdump-go-spec=fileโ for input files in any language, this generates matching Go declarations into file. It writes Goconst,type,var, andfuncdeclarations, which lowkey might be a really cute way to start writing a Go interface to code that was written in some other language. ๐@fileโ read command-line options from file, and the options it reads get inserted in place of the original@fileoption. If file doesn't exist, or can't be read, then the option is treated literally and not removed. Periodt.- Options inside file are separated by whitespace. Want whitespace inside an option? Wrap the entire option in either single or double quotes. Want any character at all (backslash included) to be included? Prefix it with a backslash. ๐
- The file can itself contain more
@fileoptions, and any of those get processed recursively. Yes bestie, it's turtles all the way down. ๐ข
๐ Compiling C++ Programs ๐
C++ source files conventionally rock 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 same way you would for compiling C programs (usually with the name gcc). โจ
However โ and this is the plot twist โ using gcc does not add the C++ library. ๐ญ
g++ is the 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. It's also the one you want when you're precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed under the name c++. ๐ธ
When you compile C++ programs, you may specify many of the same command-line options you'd 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. Mix and match, bestie. ๐ซถ
๐ 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's 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) โ think the asm and typeof keywords, plus predefined macros such as unix and vax that identify the type of system you're using. It also enables the undesirable and rarely used ISO trigraph feature (yeah, we're all side-eyeing that one ๐). For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.
The alternate keywords __asm__, __extension__, __inline__ and __typeof__ continue to work despite -ansi. You would not want to use them in an ISO C program, of course, but it's useful to put them in header files that might be included in compilations done with -ansi. Alternate predefined macros such as __unix__ and __vax__ are also available, with or without -ansi.
The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, you need -Wpedantic in addition to -ansi.
The macro __STRICT_ANSI__ is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things.
Functions that are normally built in but do not have semantics defined by ISO C (such as alloca and ffs) are not built-in functions when -ansi is used.
-std=โ determine the language standard. This option is currently only supported when compiling C or C++. ๐
The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, such as the asm and typeof keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a ?: expression. On the other hand, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard. As a result, some strict-conforming programs may be rejected. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example, -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not. ๐
A value for this option must be provided; possible values are:
c90c89iso9899: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.c99c9xiso9899:1999iso9899:199xโ ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). Seehttps://gcc.gnu.org/c99status.htmlfor more information. The namesc9xandiso9899:199xare deprecated. ๐c11c1xiso9899: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.c17c18iso9899:2017iso9899:2018โ ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is the 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. โ ๏ธgnu90gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17gnu18โ 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++98c++03โ the 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code.gnu++98gnu++03โ GNU dialect of-std=c++98.c++11c++0xโ the 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14c++1yโ the 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17c++1zโ the 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code. The namegnu++1zis deprecated. โญc++20c++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++20gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2bc++23โ the next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases. ๐gnu++2bgnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
-aux-info filenameโ output to the given filename prototyped declarations for all functions declared and/or defined in a translation unit, including those in header files. This option is silently ignored in any language other than C. ๐
Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration.
-fno-asmโ do not recognizeasm,inlineortypeofas a keyword, so that code can use these words as identifiers. You can use the keywords__asm__,__inline__and__typeof__instead. In C,-ansiimplies-fno-asm. ๐
In C++, inline is a standard keyword and this switch does not touch it. If you're trying to kill typeof without nuking asm and inline, bestie, reach for -fno-gnu-keywords instead โ that one disables typeof but leaves asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only messes with the asm and typeof keywords, because inline is a standard keyword in ISO C99. And in C2X mode (-std=c2x or -std=gnu2x), it only affects asm, since typeof is a standard keyword in ISO C2X too. the keyword lore is real โจ
-fno-builtin/-fno-builtin-functionโ okay so this one says don't recognize built-in functions that don't begin with__builtin_as prefix. ๐
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 become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. ๐ญ On top of that, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, 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. she's thorough like that
With the -fno-builtin-function option only the built-in function function is disabled. function must not begin with __builtin_. If a function is named that is not built-in in this version of GCC, this option is ignored. There is no corresponding -fbuiltin-function option; if you wish to enable built-in functions selectively when using -fno-builtin or -ffreestanding, you may define macros such as:
#define abs(n) __builtin_abs ((n))
#define strcpy(d, s) __builtin_strcpy ((d), (s))
-fcond-mismatchโ allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression isvoid. heads up: this option is not supported for C++. ๐ซถ-ffreestandingโ assert that compilation targets a freestanding environment. This implies-fno-builtin. A freestanding environment is one in which 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โ enable parsing of function definitions marked with__GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes.-fgnu-tmโ when this option is specified, 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 in C99 mode.
Using this option is roughly equivalent to adding the gnu_inline function attribute to all inline functions.
The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behavior). This option is not supported in -std=c90 or -std=gnu90 mode.
The preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions. iykyk โจ
-fhostedโ assert that compilation targets a hosted environment. This implies-fbuiltin. A hosted environment is one in which the entire standard library is available, and in whichmainhas a return type ofint. Examples are nearly everything except a kernel. This is equivalent to-fno-freestanding. ๐-flax-vector-conversionsโ allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code. ๐ฉ-fms-extensionsโ accept 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. look at this:
typedef int UOW;
struct ABC {
UOW UOW;
};
Some cases of unnamed fields in structures and unions are only accepted with this option.
Note that this option is off for all targets except for x86 targets using ms-abi.
-foffload=disable/-foffload=default/-foffload=target-listโ specify for which OpenMP and OpenACC offload targets code should be generated. The default behavior, equivalent to-foffload=default, is to generate code for all supported offload targets. The-foffload=disableform generates code only for the host fallback, while-foffload=target-listgenerates code only for the specified comma-separated list of offload targets.
Offload targets are specified in GCC's internal target-triplet format. You can run the compiler with -v to show the list of configured offload targets under OFFLOAD_TARGET_NAMES. ๐
-foffload-options=options/-foffload-options=target-triplet-list=optionsโ with-foffload-options=options, GCC passes the specified options to the compilers for all enabled offloading targets. You can specify options that apply only to a specific target or targets by using the-foffload-options=target-list=optionsform. The target-list is a comma-separated list in the same format as for the-foffload=option.
Typical command lines are
-foffload-options=-lgfortran -foffload-options=-lm
-foffload-options="-lgfortran -lm" -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906 -foffload-options=-lm
-fopenaccโ enable handling of OpenACC directives#pragma accin C/C++ and!$accin Fortran. When-fopenaccis specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6 <https://www.openacc.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread. ๐ฅ-fopenacc-dim=geomโ specify default compute dimensions for parallel offload regions that do not explicitly specify. The geom value is a triple of ':'-separated sizes, in order 'gang', 'worker' and, 'vector'. A size can be omitted, to use a target-specific default value.-fopenmpโ enable handling of OpenMP directives#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran. When-fopenmpis specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5 <https://www.openmp.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread.-fopenmpimplies-fopenmp-simd. parallelism slay ๐-fopenmp-simdโ enable handling of OpenMP'ssimd,declare simd,declare reduction,assume,ordered,scan,loopdirectives and combined or composite directives withsimdas constituent with#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran. Other OpenMP directives are ignored. ๐-fopenmp-target-simd-clone/-fopenmp-target-simd-clone=device-typeโ in addition to generating SIMD clones for functions marked with thedeclare simddirective, GCC also generates clones for functions marked with the OpenMPdeclare targetdirective that are suitable for vectorization when this option is in effect. The device-type may be one ofnone,host,nohost, andany, which correspond to keywords for thedevice_typeclause of thedeclare targetdirective; clones are generated for the intersection of devices specified.-fopenmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=anyand-fno-openmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=none.
At -O2 and higher (but not -Os or -Og) this optimization defaults to -fopenmp-target-simd-clone=nohost; otherwise it is disabled by default. โญ
-fpermitted-flt-eval-methods=styleโ ISO/IEC TS 18661-3 defines new permissible values forFLT_EVAL_METHODthat indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type. These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values ofFLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values. plot twist fr fr
-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โ accept 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โ these options control whether a bit-field is signed or unsigned, when the declaration does not use eithersignedorunsigned. By default, such a bit-field is signed, because this is consistent: the basic integer types such asintare signed types. ๐
-fsigned-charโ makes the typecharsigned, likesigned char. ๐
Heads up bestie: this is literally the same as -fno-unsigned-char, which is the negative form of -funsigned-char. And in the same way, -fno-signed-char is equivalent to -funsigned-char. It's giving mirror world. ๐ช
-funsigned-charโ makes the typecharunsigned, likeunsigned char.
Every kind of machine has a default for what char should be. Either it's like unsigned char by default, or it's like signed char by default. No in-between, that's just how it is. ๐
Ideally, a portable program should always use signed char or unsigned char when it actually depends on the signedness of an object. But so many programs were written to use plain char and just expect it to be signed, or expect it to be unsigned, depending on whatever machines they were originally written for. This option, and its inverse, let you make a program like that work with the opposite default. So iconic of it honestly.
The type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two. It's a whole separate main character, it just acts like one of them. ๐
-fstrict-flex-arraysโ controls when to treat the trailing array of a structure 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. A trailing array is treated as a flexible array member only when it is 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 are treated as flexible array members. From strict queen to chaos goblin, pick your vibe. ๐
-fstrict-flex-arrays=levelโ controls when to treat the trailing array of a structure as a flexible array member, for the purpose of accessing the elements of such an array. The value of level controls the level of strictness.
The possible values of level are the same as for the strict_flex_array attribute.
You can control this behavior for a specific trailing array field of a structure by using the variable attribute strict_flex_array attribute. Per-field control, we love to see it. โจ
-fsso-struct=endiannessโ sets the default scalar storage order of structures and unions to the specified endianness. The accepted values arebig-endian,little-endianandnativefor the native endianness of the target (the default). 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. Do not play with this casually, bestie. ๐จ
โจ Options Controlling C++ Dialect โจ
This section describes the command-line options that are only meaningful for C++ programs. You can also use most of the GNU compiler options regardless of 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. ๐
Some options for compiling C programs, such as -std, are also relevant for C++ programs. iykyk.
Here is a list of options that are only for compiling C++ programs:
-fabi-version=nโ use version n of the C++ ABI. The default is version 0. ๐
Version 0 refers to the version conforming most closely to the C++ ABI specification. Therefore, the ABI obtained using version 0 will change in different versions of G++ as ABI bugs are fixed. Yes, the "closest to the spec" one is also the shifty one. ๐
Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.
Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.
Version 3 corrects an error in mangling a constant address as a template argument.
Version 4, which first appeared in G++ 4.5, implements a standard mangling for vector types.
Version 5, which first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.
Version 6, which first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.
Version 7, which first appeared in G++ 4.8, that treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.
Version 8, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
Version 9, which first appeared in G++ 5.2, corrects the alignment of nullptr_t.
Version 10, which first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).
Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors.
Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Oopsie. ๐ญ
Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. The cleanup era. ๐งน
Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression.
Version 15, which first appeared in G++ 10.3, corrects G++ 10 ABI tag regression.
Version 16, which first appeared in G++ 11, changes the mangling of __alignof__ to be distinct from that of alignof, and dependent operator names.
Version 17, which first appeared in G++ 12, fixes layout of classes that inherit from aggregate classes with default member initializers in C++14 and up.
Version 18, which first appeard in G++ 13, fixes manglings of lambdas that have additional context.
See also -Wabi. ๐
-fabi-compat-version=nโ on targets that support strong aliases, G++ works around mangling changes by creating an alias with the correct mangled name when defining a symbol with an incorrect mangled name. This switch specifies which ABI version to use for the alias. ๐ฆ
With -fabi-version=0 (the default), this defaults to 13 (GCC 8.2 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option is not provided but -Wabi=n is, 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, honestly. ๐ซถ
-fno-access-controlโ turn off all access checking. This switch is mainly useful for working around bugs in the access control code. Breaking the rules for a good cause, we stan. ๐-faligned-newโ enable 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 few users will need to override the default ofalignof(std::max_align_t). โจ
This flag is enabled by default for -std=c++17.
-fchar8_tand-fno-char8_tโ enable support forchar8_tas adopted for C++20. This includes the addition of a 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. ๐ธ
This option enables functions to be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
and introduces new signatures for user-defined literals:
int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;
The change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. For example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified. ๐ญ
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
-fcheck-newโ check that the pointer returned byoperator newis non-null before attempting to modify the storage allocated. This check is normally unnecessary because the C++ standard specifies thatoperator newonly returns 0 if it is declaredthrow(), in which 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). ๐-fconceptsand-fconcepts-tsโ enable support for the C++ Concepts feature for constraining template arguments. With-std=c++20and above, Concepts are part of the language standard, so-fconceptsdefaults to on. ๐ฅ-fconcepts-tsโ okay so there were some constructs that the earlier C++ Extensions for Concepts Technical Specification, ISO 19217 (2015), allowed but that did not make it into the actual standard ๐. You can still turn those on with-fconcepts-ts. Blast from the past, lowkey iconic.-fconstexpr-depth=nโ sets the max nested evaluation depth for C++11 constexpr functions ton. Why do we even need a limit bestie? Because otherwise endless recursion during constant expression evaluation would just vibe forever and never stop ๐ญ. The minimum specified by the standard is 512.-fconstexpr-cache-depth=nโ sets the max level of nested evaluation depth for C++11 constexpr functions that will be cached ton. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations โจ) against memory consumption (when the cache grows super large from highly recursive evaluations ๐ฌ). The default is8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you. Do with that what you will ๐ .-fconstexpr-fp-exceptโ so Annex F of the C standard says that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value ๐. This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined. Look:
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
-fconstexpr-loop-limit=nโ sets the max number of iterations for a loop in C++14 constexpr functions ton. Again, a limit is needed to detect infinite loops during constant expression evaluation (we can't just let it spin fr fr ๐). The default is262144(1<<18).-fconstexpr-ops-limit=nโ sets the max number of operations during a single constexpr evaluation. Even when the number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long ๐ฎโ๐จ. The default is33554432(1<<25).-fcontractsโ enables experimental support for the C++ Contracts feature, as briefly added to and then removed from the C++20 working paper (N4820) ๐. The implementation also includes proposed enhancements from 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 ๐ซ.
-fcontract-mode=[on|off]โ control whether any contracts have any semantics at all. Defaults toon.-fcontract-assumption-mode=[on|off]โ [N4820] control whether contracts with level axiom should have the assume semantic. Defaults toon.-fcontract-build-level=[off|default|audit]โ [N4820] specify which level of contracts to generate checks for. Defaults todefault.-fcontract-continuation-mode=[on|off]โ [N4820] control whether to allow the program to continue executing after a contract violation. That is, do checked contracts have the maybe semantic described below rather than the never semantic. Defaults tooff.-fcontract-role=<name>:<default>,<audit>,<axiom>โ [P1332] specify the concrete semantics for each contract level of a particular contract role.-fcontract-semantic=[default|audit|axiom]:<semantic>โ [P1429] specify the concrete semantic for a particular contract level.-fcontract-strict-declarations=[on|off]โ control whether to reject adding contracts to a function after its first declaration. Defaults tooff.
The possible concrete semantics that can be specified with -fcontract-role or -fcontract-semantic are:
"ignore"โ this contract has no effect. Nothing to see here, moving on ๐."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::terminateis called. Yeah, it's over bestie ๐."check_maybe_continue","maybe"โ this contract is checked. If it fails, the violation handler is called. If the handler returns, execution continues normally. We keep it moving โจ.
-fcoroutinesโ enable support for the C++ coroutines extension (experimental). Experimental era, we love to see it ๐ง.-fno-elide-constructorsโ so the C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases ๐ค. This option also causes G++ to call trivial member functions which otherwise would be expanded inline.
In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions. Noted ๐
-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 definingNDEBUG. This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. So like... be careful, fr fr ๐ญ.-fextern-tls-init/-fno-extern-tls-initโ the C++11 and OpenMP standards allowthread_localandthreadprivatevariables to have dynamic (runtime) initialization. To support this, any use of such a variable goes through a wrapper function that performs any necessary initialization. When the use and definition of the variable are in the same translation unit, this overhead can be optimized away, but when the use is in a different translation unit there is significant overhead even if the variable doesn't actually need dynamic initialization ๐ฎโ๐จ. If the programmer can be sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because the variable is statically initialized, or a use of the variable in the defining TU will be executed before any uses in another TU), they can avoid this overhead with the-fno-extern-tls-initoption.
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init.
-ffold-simple-inlines/-fno-fold-simple-inlinesโ permit the C++ frontend to fold calls tostd::move,std::forward,std::addressofandstd::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. Big W for compile times ๐ฅ.-fno-gnu-keywordsโ do not recognizetypeofas a keyword, so that code can use this word as an identifier. You can use the keyword__typeof__instead. This option is implied by the strict ISO C++ dialects:-ansi,-std=c++98,-std=c++11, etc.-fimplicit-constexprโ make inline functions implicitly constexpr, if they satisfy the requirements for a constexpr function. This option can be used in C++14 mode or later. This can result in initialization changing from dynamic to static and other optimizations โจ.-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 โ ๏ธ. Structure it right or the linker will simply not have a good time.-fno-implicit-inline-templatesโ don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization need the same set of explicit instantiations.-fno-implement-inlinesโ to save space, do not emit out-of-line copies of inline functions controlled by#pragma implementation. This causes linker errors if these functions are not inlined everywhere they are called ๐ฌ. Saving space but at what cost.-fmodules-ts/-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, as that is the default. Even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. You gotta ask for it, periodt ๐ .-fmodule-header/-fmodule-header=user/-fmodule-header=systemโ compile a header file to create an importable header unit.-fmodule-implicit-inlineโ member functions defined in their class definitions are not implicitly inline for modular code. This is different to traditional C++ behavior, for good reasons. However, it may result in a difficulty during code porting. This option makes such function definitions implicitly inline. It does however generate an ABI incompatibility, so you must use it everywhere or nowhere โ ๏ธ. (Such definitions outside of a named module remain implicitly inline, regardless.)-fno-module-lazyโ disable lazy module importing and module mapper creation. No more procrastination for your modules ๐ โโ๏ธ.-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.-fmodule-onlyโ only emit the Compiled Module Interface, inhibiting any object file. Just the interface bestie, nothing else ๐.-fms-extensionsโ okay so this one turns off thoseWpedanticwarnings that pop up about MFC-style constructs, like implicitintand snagging a pointer to a member function through โจnon-standardโจ syntax. Basically it's like "chill, that's just how MFC does things" ๐-fnew-inheriting-ctorsโ turns on the P0136 glow-up to how C++11 constructor inheritance behaves ๐ it's technically part of C++17, but it's also treated as a Defect Report against C++11 and C++14, so it's fixing the past too, iconic. On by default unless you've specified-fabi-version=10or lower, in which case nope ๐-fnew-ttp-matchingโ enables the P0522 resolution to Core issue 150, all about template template parameters and default arguments ๐ฆ what it does: it lets a template with default template arguments be used as an argument for a template template parameter that has fewer template parameters. On by default for-std=c++17โญ-fno-nonansi-builtinsโ disables built-in declarations of functions that ANSI/ISO C does not mandate. The little lineup includesffs,alloca,_exit,index,bzero,conjf, and other related functions โ so it's giving "if the standard didn't ask for it, we're not declaring it" ๐-fnothrow-optโ treats athrow()exception specification like it were anoexceptspecification, so it can reduce or straight-up eliminate the text size overhead compared to a function with no exception specification at all ๐ซถ plot twist tho: if the function has local variables whose types have 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: an exception thrown out of a function with such an exception specification results in a call toterminaterather thanunexpected. so yeah, different ending, no cap ๐ญ-fno-operator-namesโ do not treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms as keywords. periodt ๐-fno-optional-diagsโ disables diagnostics that the standard says a compiler doesn't even need to issue. rn the only such diagnostic G++ issues is the one for a name having multiple meanings within a class, so like, that one specifically ๐-fpermissiveโ downgrades some diagnostics about nonconformant code from errors to warnings ๐ so using-fpermissivelets some nonconforming code actually compile. it's giving "not technically legal but I'll allow it" โจ-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. but if either of these behaviors make the error message harder to understand instead of easier, you can use-fno-pretty-templatesto disable them ๐ธ-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 with 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 ๐
โ ๏ธ mixing code compiled with-frttiwith code compiled with-fno-rttimay not work. for example, programs may fail to link if a class compiled with-fno-rttiis used as a base for a class compiled with-frtti. so like, don't do that ๐ญ
-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, so like, careful bestie ๐-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.-fstrong-eval-order=someenables just the ordering of member access and shift expressions, and is the default without-std=c++17๐-ftemplate-backtrace-limit=nโ sets the maximum number of template instantiation notes for a single warning or error to n. the default value is10๐-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, because the compiler can run out of stack space before hitting1024in some situations ๐ญ-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, iykyk ๐-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 it only works if your C library supports__cxa_atexit๐ซถ-fno-use-cxa-get-exception-ptrโ don't use the__cxa_get_exception_ptrruntime routine ๐ this causesstd::uncaught_exceptionto be incorrect, but it's necessary if the runtime routine is not available. so like, incorrect but required, we love a tradeoff ๐-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. ate โจ
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 ๐ณ
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. so like, not it โ
-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 ๐
โ ๏ธ 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++ ๐ bestie do not touch this one, fr fr
-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) ๐-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. the header form will inform of include translations relating to that specific header ๐ if header is of the formuseror<system>it will be resolved to a specific user or system header using the include path ๐ธ-flang-info-module-cmiโ bestie, this one spills the tea on Compiled Module Interface pathnames. Plain like this, it notes all the read CMI pathnames. ๐ธ- *
-flang-info-module-cmi=module* โ this flavor instead notes the reading of one specific module's CMI. The module can be a named module, or it can be a header-unit (you can tell it's a header-unit because it's either a pathname with directory separators in it, or it's wrapped in"<>"or""). ๐
-stdlib=libstdc++,libc++โ okay so when G++ is configured to support this option, it lets you pick alternate C++ runtime libraries. Two options on the menu:libstdc++(the default, the native C++ runtime for G++) andlibc++(the C++ runtime that's installed on some operating systems โ e.g. Darwin versions from Darwin11 onwards ๐). What this option does is switch G++ to use the headers from whichever library you named, and it emits-lstdc++or-lc++respectively whenever a C++ runtime is actually required for linking. โจ
๐ In addition, these warning options have meanings only for C++ programs ๐
-Wabi-tag(C++ and Objective-C++ only) โ warns when a type with an ABI tag gets used in a context that doesn't have that ABI tag. Wanna know more about ABI tags? Go peek at C++ Attributes. ๐-Wcomma-subscript(C++ and Objective-C++ only) โ warns about comma expressions used inside a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23. ๐ But plot twist: 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 actually valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and it supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that isn't valid in C++23 but used to be valid โ though deprecated โ in C++20, with a pedantic warning that you can turn off with -Wno-comma-subscript. ๐ซถ
It's enabled by default with -std=c++20 unless -Wno-deprecated is on, and with -std=c++23 regardless of -Wno-deprecated. โญ
-Wctad-maybe-unsupported(C++ and Objective-C++ only) โ warns when you're doing class template argument deduction (CTAD) on a type that has no explicitly written deduction guides. This one calls out the cases where CTAD only succeeded because the compiler synthesized the implicit deduction guides, which might not be what the programmer was going for. Some style guides only allow CTAD on types that specifically "opt-in", i.e. types designed to support CTAD. You can suppress this warning with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
S(T) { }
};
// Guide with incomplete parameter type will never be considered.
S(allow_ctad_t) -> S<void>;
-Wctor-dtor-privacy(C++ and Objective-C++ only) โ warns when a class looks straight up unusable because every constructor or destructor in it is private, and it has neither friends nor public static member functions. It 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. Like this:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling
In that example two temporaries get 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 catches dangling references in member initializer lists:
const int& f(const int& i) { return i; }
struct S {
const int &r; // r is dangling
S() : r(f(10)) { }
};
Member functions get checked too, but only their object argument:
struct S {
const S& self () { return *this; }
};
const S& s = S().self(); // s is dangling
Certain functions are safe in this respect โ std::use_facet for example โ because they take and return a reference but don't return one of their arguments, which can fool the warning. You can exclude such functions from the warning by wrapping them in a #pragma:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-reference"
const T& foo (const T&) { ... }
#pragma GCC diagnostic pop
-Wdangling-reference also warns about code like
auto p = std::minmax(1, 2);
where std::minmax returns std::pair<const int&, const int&>, and both references dangle after the end of the full expression containing the 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 a non-virtual destructor. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class 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. Enabled by-Wextra. And with-Wdeprecated-copy-dtor, it also deprecates if the class has a user-provided destructor. ๐-Wno-deprecated-enum-enum-conversion(C++ and Objective-C++ only) โ disables the warning about the case where the usual arithmetic conversions get applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;
-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, you can enable this warning with -Wenum-conversion. ๐
-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only) โ disables the warning about the case where the usual arithmetic conversions get applied on operands where one is of enumeration type and the other is of a floating-point type. This conversion was deprecated in C++20. 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, you can enable this warning with -Wenum-conversion. โญ
-Wno-init-list-lifetime(C++ and Objective-C++ only) โ nope, we are not warning about uses ofstd::initializer_listthat are likely to result in dangling pointers. Because the underlying array for aninitializer_listis handled like a normal C++ temporary object, it's so 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, 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, because it requires additional processing to figure out. 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 that doesn't 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);
}
so like โ in this case "PRId64" gets treated as a separate preprocessing token. that's the whole vibe bestie, it's not glued to the string literal around it ๐
This option also controls warnings when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization โ so like, hands off, that's the future's turf ๐ฎ
These warnings are enabled by default. โจ
-Wno-narrowing(C++ and Objective-C++ only) โ the narrowing-conversion callout.
For C++11 and later standards, narrowing conversions are diagnosed by default, as required by the standard. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but -Wno-narrowing suppresses the diagnostic. Note that this does not affect the meaning of well-formed code โ narrowing conversions are still considered ill-formed in SFINAE contexts. so like, the vibes are still off, we're just not yelling about it ๐ซถ
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.
int i = { 2.2 }; // error: narrowing from double to int
This flag is included in -Wall and -Wc++11-compat. ๐
-Wnoexcept(C++ and Objective-C++ only) โ Warn when a noexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e.throw()or"noexcept") but is known by the compiler to never throw an exception.-Wnoexcept-type(C++ and Objective-C++ only) โ Warn if the C++17 feature making"noexcept"part of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat. ๐ญ
As an example:
template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }
In C++14, "f" calls "f<void(*)()>", but in C++17 it calls "f<void(*)()noexcept>". yeah. the mangled name said glow up โจ
-Wclass-memaccess(C++ and Objective-C++ only) โ Warn when the destination of a call to a raw memory function such as"memset"or"memcpy"is an object of class type, and when writing into such an object might bypass the class non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects may violate invariants maintained by member functions of the class.
For example, the call to "memset" below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available. ๐ง
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. so like, if you know you know, cast it and the compiler will chill ๐
-Wnon-virtual-dtor(C++ and Objective-C++ only) โ Warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class, in which case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or base class.
This warning is automatically enabled if -Weffc++ is specified. The -Wdelete-non-virtual-dtor option (enabled by -Wall) should be preferred because it warns about the unsafe cases without false positives. bestie the sequel option ate, fr fr ๐
-Wregister(C++ and Objective-C++ only) โ Warn on uses of the"register"storage class specifier, except when it is part of the GNU Explicit Register Variables extension.
The use of the "register" keyword as storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17. it's giving nostalgia, it's giving RIP ๐ชฆ
-Wreorder(C++ and Objective-C++ only) โ Warn when the order of member initializers given in the code does not match the order in which they must be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for "i" and "j" to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall. the compiler said "not you writing it backwards" ๐ญ
-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. bestie you did the extra thing and it made it worse ๐
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. every single lap around the loop. new double. gone. new double. gone. it's giving chaos ๐ญ
This warning is enabled by -Wall.
-Wredundant-tags(C++ and Objective-C++ only) โ Warn about redundant class-key and enum-key in references to class types and enumerated types in contexts where the key can be eliminated without causing an ambiguity. For example:
struct foo;
struct foo *p; // warn that keyword struct can be eliminated
On the other hand, in this example there is no warning:
struct foo;
void foo (); // "hides" struct foo
void bar (struct foo&); // no warning, keyword struct is necessary
see, sometimes the keyword is carrying the whole meaning and you can't take it away ๐
-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 .C file, as those are unlikely to have multiple definitions.
-Wsubobject-linkage is enabled by default.
-Weffc++(C++ and Objective-C++ only) โ Warn about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:- Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
- Prefer initialization to assignment in constructors.
- Have
"operator="return a reference to*this. - Don't try to return a reference when you must return an object.
- Distinguish between prefix and postfix forms of increment and decrement operators.
- Never overload
"&&","||", or",".
This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of virtual destructor in accessible non-polymorphic bases classes too.
When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings. bestie the STL did not read the book and it is not sorry ๐
-Wno-exceptions(C++ and Objective-C++ only) โ Disable the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers.-Wstrict-null-sentinel(C++ and Objective-C++ only) โ Warn about the use of an uncasted"NULL"as sentinel.
When compiling only with GCC this is a valid sentinel, as "NULL" is defined to "__null". Although it is a null pointer constant rather than a null pointer, it is guaranteed to be of the same size as a pointer. But this use is not portable across different compilers. so like, GCC-only slay, everyone else side-eye ๐ซถ
-Wno-non-template-friend(C++ and Objective-C++ only) โ kills the warning you'd get when non-template friend functions get declared inside a template. Story time: in like, super old versions of GCC that existed before the ISO standard was actually implemented, a declaration likefriend int foo(int)โ where the friend's name is an unqualified-id โ could get read as a specific specialization of a template function. So this warning is here to catch compatibility drama, and bestie, it's enabled by default. ๐-Wold-style-cast(C++ and Objective-C++ only) โ warns you when an old-style (C-style) cast to a non-void type shows up in a C++ program. The glow-up casts โdynamic_cast,static_cast,reinterpret_cast, andconst_castโ are way less prone to unintended side effects and so much easier to grep for. it's giving "upgrade ur wardrobe". โจ-Woverloaded-virtual,-Woverloaded-virtual=nโ warns when a function declaration is hiding virtual functions from a base class. Like, look:
struct A {
virtual void f();
};
struct B: public A {
void f(int); // does not override
};
so the A version of f is now hidden in B, and code like:
B* b;
b->f();
straight up fails to compile. ๐ญ
When those differing signatures are not an accident, the simplest fix is adding a using-declaration to the derived class to un-hide the base function โ e.g. add using A::f; to B.
The optional level suffix controls what happens when all the declarations in the derived class override virtual functions in the base class, even if not all 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 of the 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) โ disables 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. rules are rules, periodt. ๐-Wtemplates(C++ and Objective-C++ only) โ warns when a primary template declaration is encountered. Some coding rules disallow templates and this may be used to enforce that rule. The warning is inactive inside a system header file, like the STL, so you can still use the STL. You may also instantiate or specialize templates.-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 covers 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 avoid it, either remove the redundant class-key struct or replace it with 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 โ the example above proves it. The -Wmismatched-tags option is just 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 caused by the difference in the mangling of symbols declared with different class-keys. You can use this option 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 can enforce that rule. The warning is inactive inside a system header file, such as the STL, so the STL is still usable. You may also define classes that indirectly use multiple inheritance.-Wvirtual-inheritanceโ warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this can enforce that rule. The warning is inactive inside a system header file, such as the STL, so the STL stays usable. You may 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. > Bestie, this is dangerous โ ๏ธ โ 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 can enforce that rule. The warning is inactive inside a system header file, such as the STL, so the STL is still there for you. 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 flags the cases where 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 dealing 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. like, it's never getting invited to the function call party. ๐-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 literal0is used as a null pointer constant. This can be useful to facilitate the conversion tonullptrin C++11. glow-up szn ๐ธ-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 that's smaller than the type of the object. For example, the placement new expression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large. ๐ญ
char buf [64];
new (buf) int[64];
This warning is enabled by default.
-Wplacement-new=1โ this is the default warning level of-Wplacement-new. At this level the warning is not issued for some strictly undefined constructs that GCC allows as extensions for compatibility with legacy code. For example, the followingnewexpression is not diagnosed at this level even though it has undefined behavior according to the C++ standard, because it writes past the end of the one-element array.
struct S { int n, a[1]; };
S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
new (s->a)int [32]();
-Wplacement-new=2โ bestie, this level is not playing around ๐. On top of everything level 1 already flags, it also yells at you for placement new expressions that construct an object inside the last member of a struct, when that member's type is an array of a single element and its size is smaller than the size of the object you're constructing. So yeah, the example above? Diagnosed. ๐
But wait โ here's the glow-up โจ. This next version uses the flexible member array extension to dodge the warning at level 2 entirely:
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
-Wcatch-value-Wcatch-value=n(C++ and Objective-C++ only) โ this one's about catch handlers that don't catch by reference ๐ค. The levels go like this:-Wcatch-value=1(or just plain-Wcatch-value, the short version) โ warns about polymorphic class types that get caught by value. Sloppy, honestly.-Wcatch-value=2โ now it warns about all class types caught by value.-Wcatch-value=3โ the strictest one, warning about all types that aren't caught by reference. periodt ๐
Also: -Wcatch-value is enabled by -Wall. ๐
-Wconditionally-supported(C++ and Objective-C++ only) โ warns you about conditionally-supported constructs, as defined in C++11[intro.defs]. iykyk ๐ฆ-Wno-delete-incomplete(C++ and Objective-C++ only) โ the "please don't tell me" flag ๐. It stops the warning you'd get when deleting a pointer to an incomplete type โ which, lowkey, may cause undefined behavior at runtime. This warning is enabled by default, so if you're silencing it, you know what you're doing.-Wextra-semi(C++, Objective-C++ only) โ warns about redundant semicolons after in-class function definitions. The extra;is giving nothing, bestie ๐-Wno-inaccessible-base(C++, Objective-C++ only) โ controls the warnings when a base class is inaccessible in a class derived from it due to ambiguity. This warning is enabled by default. Heads up though: the warning for ambiguous virtual bases is enabled by the-Wextraoption instead. ๐
Here's the little drama triangle:
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ suppresses warnings about using C++11 inheriting constructors when the base class you inherited from has a C variadic constructor. The warning is on by default because, fr fr, the ellipsis is not inherited. ๐ญ-Wno-invalid-offsetof(C++ and Objective-C++ only) โ suppresses warnings from applying the"offsetof"macro to a non-POD type. According to the 2014 ISO C++ standard, applying"offsetof"to a non-standard-layout type is undefined. But ngl, in existing C++ implementations"offsetof"typically gives meaningful results anyway. This flag is for the girlies who know they're writing nonportable code and have deliberately chosen to ignore the warning about it. ๐
Also, heads up: the restrictions on "offsetof" may be relaxed in a future version of the C++ standard. ๐
-Wsized-deallocation(C++ and Objective-C++ only) โ warns you when you define an unsized deallocation function:
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
...without defining the corresponding sized deallocation function:
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
...or vice versa. Enabled by -Wextra along with -fsized-deallocation. ๐ซถ
-Wsuggest-final-typesโ warns about types with virtual methods where your code quality would genuinely improve if the type were declared with the C++11"final"specifier, or โ if possible โ declared in an anonymous namespace. Why bother? Because it lets GCC more aggressively devirtualize the polymorphic calls ๐ฅ. This warning hits way harder with link-time optimization, where the info about the class hierarchy graph is more complete. โจ-Wsuggest-final-methodsโ same energy, but for virtual methods ๐. Warns when things would be better if the method were declared with the C++11"final"specifier, or if its type were declared in an anonymous namespace or with the"final"specifier. Again, more effective with link-time optimization since the class hierarchy graph info is more complete. Bestie's tip: it's recommended to first consider suggestions from-Wsuggest-final-typesand then rebuild with the new annotations. Do it in order, okay? ๐-Wsuggest-overrideโ warns about overriding virtual functions that aren't marked with the"override"keyword. Just sayoverride, it's free ๐ฆ-Wuse-after-free-Wuse-after-free=nโ warns about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. This warning is enabled at all optimization levels, but ngl it may yield different results with optimization than without. ๐-Wuse-after-free=1โ at level 1 the warning only tries to catch unconditional uses of pointers made indeterminate by a deallocation call, or by a successful call to"realloc"โ regardless of whether the call actually resulted in a reallocation of memory. This includes double-"free"calls, plus uses in arithmetic and relational expressions. Now, uses of indeterminate pointers in equality (or inequality) expressions are undefined too, but they are not diagnosed at this level. ๐-Wuse-after-free=2โ level 2 catches conditional uses on top of the unconditional ones โ pointers made indeterminate by a deallocation call. And same as the level before, uses in equality (or inequality) expressions are still not diagnosed. For example, the second call to"free"in this function gets diagnosed at this level:
struct A { int refcount; void *data; };
void release (struct A *p)
{
int refcount = --p->refcount;
free (p);
if (refcount == 0)
free (p->data); // warning: p may be used after free
}
-Wuse-after-free=3โ level 3 also diagnoses uses of indeterminate pointers inside equality expressions. Real talk: all uses of indeterminate pointers are undefined โ but equality tests sometimes show up after calls to"realloc"as an attempt to figure out whether the call relocated the object to a different address. They get diagnosed at a separate level just to help 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 โ that approach obviates needing to adjust the stored pointers after reallocation. ๐
-Wuse-after-free=2is included in-Wall. ๐
-Wuseless-cast(C++ and Objective-C++ only) โ warns when an expression is cast to its own type. The way that this one does not fire when a class object is converted to a non-reference type, though, because that's a legit way to create a temporary:
struct S { };
void g (S&&);
void f (S&& arg)
{
g (S(arg)); // make arg prvalue so that it can bind to S&&
}
-Wno-conversion-null(C++ and Objective-C++ only) โ stops warning for conversions between"NULL"and non-pointer types. Oh and btw,-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.
Okay so this section is all about the command-line options that are only meaningful for Objective-C and Objective-C++ programs. ๐ But you can also use most of the language-independent GNU compiler options too! 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. ๐
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). โจ
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 is"NXConstantString"if the GNU runtime is being used, and"NSConstantString"if the NeXT runtime is being used (see below ๐). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption โ if it's also present โ overrides the-fconstant-string-classsetting and causes"@"...""literals to be laid out as constant CoreFoundation strings. Also note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. ๐-fgnu-runtimeโ generates object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐ซถ-fnext-runtimeโ generates output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro"__NEXT_RUNTIME__"is predefined if (and only if) this option is used. ๐ฏ-fno-nil-receiversโ assumes that all Objective-C message dispatches ("[receiver message:arg]") in this translation unit ensure that the receiver is not"nil". This lets the runtime use more efficient entry points. Heads up though: this option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. ๐ฆ-fobjc-abi-version=nโ bestie, this picks which version n of the Objective-C ABI you want for whichever runtime you've selected. Rn it only works for the NeXT runtime, okay? So: Version 0 is the traditional (32-bit) ABI, and it does not support properties or the other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and the other Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. And if you specify literally nothing, the default is Version 0 on 32-bit target machines and Version 2 on 64-bit target machines. ๐-fobjc-call-cxx-cdtorsโ for every Objective-C class, this checks whether any of its instance variables is a C++ object with a non-trivial default constructor. If yeah, it synthesizes a special- (id) .cxx_constructinstance method that runs those non-trivial default constructors on any such instance variables, in order, and then returnsself. Same energy on the way out: it checks whether any instance variable is a C++ object with a non-trivial destructor, and if so it synthesizes a special- (void) .cxx_destructmethod that runs all such default destructors, in reverse order. ๐ฆ
The - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class โ not the ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods in an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime immediately after a new object instance is allocated, and the - (void) .cxx_destruct methods get invoked immediately before the runtime deallocates an object instance.
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the - (id) .cxx_construct and - (void) .cxx_destruct methods. ๐ญ
-fobjc-direct-dispatchโ lets you do fast jumps to the message dispatcher. On Darwin this happens via the comm page. slay. โจ-fobjc-exceptionsโ turns on syntactic support for structured exception handling in Objective-C, similar to what C++ offers. You need this option 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 available in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier. ๐ซถ-fobjc-gcโ enables garbage collection (GC) in Objective-C and Objective-C++ programs. Heads up: this option is only available with the NeXT runtime. The GNU runtime has a different garbage collection implementation that doesn't need special compiler flags. ๐-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, this checks for a nil receiver in method invocations before doing the actual method call. This is the default, and you can turn it off with-fno-objc-nilcheck. Class methods and super calls are never checked for nil this way, no matter what this flag is set to. And currently this flag does literally nothing when the GNU runtime is used, or with an older version of the NeXT runtime ABI. ๐-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 that GCC 4.0 doesn't recognize gets rejected. Super useful if you need to make sure your Objective-C code can be compiled with older versions of GCC. ๐-freplace-objc-classesโ emits a special marker tellingld(1)not to statically link in the resulting object file, and lettingdyld(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 in the course of program execution โ no need to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later. ๐ฅ-fzero-linkโ when compiling for the NeXT runtime, the compiler ordinarily replaces calls toobjc_getClass("...")(when the 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-fzero-linksuppresses this behavior and causes calls toobjc_getClass("...")to be retained. This is useful in Zero-Link debugging mode, since it lets individual class implementations be modified during program execution. The GNU runtime currently always retains calls toobjc_get_class("...")regardless of command-line options. ๐-fno-local-ivarsโ by default, instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. 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-fno-local-ivarsdisables this behavior, thus avoiding variable shadowing issues. no cap. ๐ธ-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 that specified visibility.-gen-declsโ dumps interface declarations for all classes seen in the source file to a file namedsourcename.decl. โจ-Wassign-intercept(Objective-C and Objective-C++ only) โ warns whenever an Objective-C assignment is being intercepted by the garbage collector.-Wno-property-assign-default(Objective-C and Objective-C++ only) โ do not warn if a property for an Objective-C object has no assign semantics specified.-Wno-protocol(Objective-C and Objective-C++ only) โ if a class is declared to implement a protocol, a warning is issued for every method in the protocol that isn't implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use-Wno-protocol, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them. ๐ง-Wobjc-root-class(Objective-C and Objective-C++ only) โ warns if a class interface lacks a superclass. Most classes will inherit fromNSObject(orObject), for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with__attribute__((objc_root_class)).-Wselector(Objective-C and Objective-C++ only) โ warns if multiple methods of different types for the same selector are found during compilation. The check 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 are not produced if the final stage of compilation is not reached โ for example because an error is found during compilation, or because the-fsyntax-onlyoption is being used. ๐ญ-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warns if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of typeidorClass. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment. โญ-Wundeclared-selector(Objective-C and Objective-C++ only) โ warns if a@selector(...)expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the@selector(...)expression, either explicitly in an@interfaceor@protocoldeclaration, or implicitly in an@implementationsection. This option always performs its checks as soon as a@selector(...)expression is found, while-Wselectoronly performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. ๐-print-objc-runtime-infoโ generates a C header describing the largest structure that is passed by value, if any.
๐ Options to Control Diagnostic Messages Formatting ๐
Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). You can use the options described below to control the formatting algorithm for diagnostic messages โ like how many characters per line, how often source location information should be reported. Note that some language front ends may not honor these options. ๐
-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#errorand#warningpre-processor directives, and the deprecated function/type/variable attribute. It does not, however, affect thepragma GCC warningandpragma GCC errorpragmas. ๐
-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. ๐
-fdiagnostics-show-location=onceโ only does anything in line-wrapping mode, bestie. It tells the diagnostic reporter to spill the source location info one single time; like, if the message is too long to fit on one physical line and has to wrap, the source location does not get re-emitted (as a prefix) over and over on every continuation line. This is the default behavior. Chill of it. ๐-fdiagnostics-show-location=every-lineโ also only meaningful in line-wrapping mode. This one makes the reporter emit the same source location info (as a prefix) for every physical line that comes out of breaking up a message that was too long to fit on a single line.-fdiagnostics-color[=WHEN]โ-fno-diagnostics-colorโ color in your diagnostics?? say less. ๐WHENisnever,always, orauto. The default depends on how the compiler was configured, and it can be any of thoseWHENoptions, or alsoneverif theGCC_COLORSenvironment variable isn't present in the environment, andautootherwise.automakes GCC use color only when standard error is a terminal, and when it's not executing in an emacs shell. The forms-fdiagnostics-colorand-fno-diagnostics-colorare aliases for-fdiagnostics-color=alwaysand-fdiagnostics-color=never, respectively. ๐
The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator. (See the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) These substring values are integers in decimal representation and can be concatenated with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. โจ
The default GCC_COLORS is
error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\
quote=01:path=01;36:fixit-insert=32:fixit-delete=31:\
diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
type-diff=01;32:fnname=01;32:targs=35
where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. Supported capabilities are as follows. ๐
"error="โ SGR substring forerror:markers."warning="โ SGR substring forwarning:markers."note="โ SGR substring fornote:markers."path="โ SGR substring for colorizing paths of control-flow events as printed via-fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns."range1="โ SGR substring for first additional range."range2="โ SGR substring for second additional range."locus="โ SGR substring for location information,file:lineorfile:line:columnetc."quote="โ SGR substring for information printed within quotes."fnname="โ SGR substring for names of C++ functions."targs="โ SGR substring for C++ function template parameter bindings."fixit-insert="โ SGR substring for fix-it hints suggesting text to be inserted or replaced."fixit-delete="โ SGR substring for fix-it hints suggesting text to be deleted."diff-filename="โ SGR substring for filename headers within generated patches."diff-hunk="โ SGR substring for the starts of hunks within generated patches."diff-delete="โ SGR substring for deleted lines within generated patches."diff-insert="โ SGR substring for inserted lines within generated patches."type-diff="โ SGR substring for highlighting mismatching types within template arguments in the C++ frontend.
-fdiagnostics-urls[=WHEN]โ use escape sequences to embed URLs in diagnostics ๐ฆ. For example, when-fdiagnostics-show-optionemits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option.
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when standard error is a terminal, and when not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature, see below.
The default depends on how the compiler has been configured. It can be any of the above WHEN options.
GCC can also be configured (via the --with-diagnostics-urls=auto-if-env configure-time option) so that the default is affected by environment variables. Under such a configuration, GCC defaults to using auto if either GCC_URLS or TERM_URLS environment variables are present and non-empty in the environment of the compiler, or never if neither are.
However, even with -fdiagnostics-urls=always the behavior is 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, each diagnostic emitted includes text indicating the command-line option that directly controls the diagnostic (if such an option is known to the diagnostic machinery). Specifying the-fno-diagnostics-show-optionflag suppresses that behavior. ๐-fno-diagnostics-show-caretโ by default, each diagnostic emitted includes the original source line and a caret^indicating the column. This option suppresses this information. The source line is truncated to n characters, if the-fmessage-length=noption is given. When the output is done to the terminal, the width is limited to the width given by theCOLUMNSenvironment variable or, if not set, to the terminal width.-fno-diagnostics-show-labelsโ by default, when printing source code (via-fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions:
printf ("foo %s bar", long_i + long_j);
~^ ~~~~~~~~~~~~~~~
| |
char * long int
This option suppresses the printing of these labels (in the example above, the vertical bars and the "char *" and "long int" text). ๐
-fno-diagnostics-show-cweโ diagnostic messages can optionally have an associated CWE ("https://cwe.mitre.org/index.html") identifier. GCC itself only provides such metadata for some of the-fanalyzerdiagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata.-fno-diagnostics-show-rulesโ diagnostic messages can optionally have rules associated with them, such as from a coding standard, or a specification. GCC itself does not do this for any of its diagnostics, but plugins may do so. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata.-fno-diagnostics-show-line-numbersโ by default, when printing source code (via-fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin. โจ-fdiagnostics-minimum-margin-width=widthโ this option controls the minimum width of the left margin printed by-fdiagnostics-show-line-numbers. It defaults to6.-fdiagnostics-parseable-fixitsโ emit fix-it hints in a machine-parseable format, suitable for consumption by IDEs. For each fix-it, a line will be printed after the relevant diagnostic, starting with the string"fix-it:". For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013").
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position. ๐
-fdiagnostics-generate-patchโ print fix-it hints to stderr in unified diff format, after any diagnostics are printed. For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
void show_cb(GtkDialog *dlg)
{
- gtk_widget_showall(dlg);
+ gtk_widget_show_all(dlg);
}
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color). ๐ฅ
-fdiagnostics-show-template-treeโ okay so in the C++ frontend, when it's printing diagnostics about mismatching template types, like this:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
this flag makes it print a whole tree-like structure showing which parts of the types are common and which are different, like:
map<
[...],
vector<
[double != float]>>
The bits that differ get highlighted with color (that's "double" and "float" in this case). It's giving annotated diff energy, honestly iconic. ๐
-fno-elide-typeโ by default, when the C++ frontend prints diagnostics about mismatching template types, the common parts of the types get printed as"[...]"to keep the error message simple. For example:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
Specifying the -fno-elide-type flag suppresses that behavior. Heads up bestie, this flag also affects the output of the -fdiagnostics-show-template-tree flag too. โจ
-fdiagnostics-path-format=KINDโ this one picks how paths of control-flow events get printed for diagnostics that have such a path attached to them.
KIND is none, separate-events, or inline-events, and inline-events is the default.
none means literally don't print diagnostic paths. Nothing. Zip. ๐ซ
separate-events means print a separate "note" diagnostic for every single event inside the diagnostic. For example:
test.c:29:5: error: passing NULL as argument 1 to 'PyList_Append' which requires a non-NULL parameter
test.c:25:10: note: (1) when 'PyList_New' fails, returning NULL
test.c:27:3: note: (2) when 'i < count'
test.c:29:5: note: (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
inline-events means print the events "inline" right within the source code. This view tries to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges inside the source.
For example, the same events as above might come out 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 stack frames are nested, pushed, and popped. Nesting!! ๐ช
For example:
'test': events 1-2
|
| 133 | {
| | ^
| | |
| | (1) entering 'test'
| 134 | boxed_int *obj = make_boxed_int (i);
| | ~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling 'make_boxed_int'
|
+--> 'make_boxed_int': events 3-4
|
| 120 | {
| | ^
| | |
| | (3) entering 'make_boxed_int'
| 121 | boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling 'wrapped_malloc'
|
+--> 'wrapped_malloc': events 5-6
|
| 7 | {
| | ^
| | |
| | (5) entering 'wrapped_malloc'
| 8 | return malloc (size);
| | ~~~~~~~~~~~~~
| | |
| | (6) calling 'malloc'
|
<-------------+
|
'test': event 7
|
| 138 | free_boxed_int (obj);
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (7) calling 'free_boxed_int'
|
(etc)
-fdiagnostics-show-path-depthsโ this option gives you extra info when printing control-flow paths that are attached to a diagnostic. ๐ซถ
If this option is provided, then the stack depth gets printed for each run of events within -fdiagnostics-path-format=inline-events. And if you provide it together with -fdiagnostics-path-format=separate-events, then the stack depth and the function declaration get appended when printing each event.
Ngl this one is intended for use by GCC developers and plugin developers when they're debugging diagnostics that report interprocedural control flow. So like, devs only, iykyk. ๐
-fno-show-columnโ don't print column numbers in diagnostics. This may be necessary if your diagnostics are being scanned by a program that doesn't understand column numbers, such asdejagnu. No columns for you, periodt. ๐-fdiagnostics-column-unit=UNITโ picks the units for the column number. This affects traditional diagnostics (when-fno-show-columnisn't 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. This can be larger than the number of bytes needed to encode the character (tab characters, looking at you), or it can be smaller (multibyte characters, looking at you). For example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding needs two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding needs four bytes. The math is mathing. ๐งฎ
Setting UNIT to byte changes the column number to the raw byte count in all cases, exactly like GCC traditionally output before version 11.1.0.
-fdiagnostics-column-origin=ORIGINโ picks 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 may be specified. ๐-fdiagnostics-escape-format=FORMATโ when GCC prints the pertinent source lines for a diagnostic it normally tries to print the source bytes directly. But some diagnostics relate to encoding issues in the source file, like malformed UTF-8, or issues with Unicode normalization. Those diagnostics get flagged so GCC will escape bytes that aren't printable ASCII when printing their pertinent source lines.
This option controls how those bytes get escaped.
The default FORMAT, unicode, displays Unicode characters that aren't printable ASCII in the form <U+XXXX>, and bytes that don't correspond to a Unicode character validly-encoded in UTF-8 get displayed as hexadecimal in the form <XX>.
For example, a source line containing the string before followed by the Unicode character U+03C0 ("GREEK SMALL LETTER PI", with UTF-8 encoding 0xCF 0x80) followed by the byte 0xBF (a stray UTF-8 trailing byte), followed by the string after will be printed for such a diagnostic as:
before<U+03C0><BF>after
Setting FORMAT to bytes displays all non-printable-ASCII bytes in the form <XX>, thus showing the underlying encoding of non-ASCII Unicode characters. For the example above, this gets printed:
before<CF><80><BF>after
-fdiagnostics-format=FORMATโ selects a different format for printing diagnostics. FORMAT istext,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 gets emitted to โ with the former, the JSON is emitted to stderr, whereas with json-file it's written to source.gcc.json. Same vibes, different destination. ๐
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.
Diagnostics can have child diagnostics. For example, this error and note:
misleading-indentation.c:15:3: warning: this 'if' clause does not
guard... [-Wmisleading-indentation]
15 | if (flag)
| ^~
misleading-indentation.c:17:5: note: ...this statement, but the latter
is misleadingly indented as if it were guarded by the 'if'
17 | y = 2;
| ^
might be printed in JSON form (after formatting) like this:
...where that "note" is a child of the "warning". ๐ซถ yes bestie, diagnostics have family trees now, we love a supportive-parent moment
Every diagnostic has a "kind". If that kind is "warning", then there's an "option" key sitting right there describing the command-line option that controls the warning. iykyk.
A diagnostic can contain zero or more locations. Each location gets an optional "label" string and up to three positions inside it: a "caret" position, plus optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers that say where the column is:
"display-column"โ counts display columns, and it actually accounts for tabs and multibyte characters ๐"byte-column"โ counts raw bytes, no thoughts head empty"column"โ is equal to one of the previous two, whichever one the-fdiagnostics-column-unitoption says it should be
All three of those columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but can be set, for instance, to 0 for compatibility with other utilities that number columns from 0. The column origin gets recorded in the JSON output in the "column-origin" tag. And in the remaining examples below, the extra column number outputs have been omitted for brevity โ don't come for me, it's just for the vibes.
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, and those ones 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 made of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. For example, this diagnostic with a replacement fix-it hint:
demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
mean 'color'?
8 | return ptr->colour;
| ^~~~~~
| color
might be printed in JSON form as:
{
"children": [],
"fixits": [
{
"next": {
"column": 21,
"file": "demo.c",
"line": 8
},
"start": {
"column": 15,
"file": "demo.c",
"line": 8
},
"string": "color"
}
],
"kind": "error",
"locations": [
{
"caret": {
"column": 15,
"file": "demo.c",
"line": 8
},
"finish": {
"column": 20,
"file": "demo.c",
"line": 8
}
}
],
"escape-source": false,
"message": "\u2018struct s\u2019 has no member named ..."
}
where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value. Deletions are expressed via an empty value for "string", and insertions happen by having "start" equal "next". ๐
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" is the current function at that event, and the "depth" is the stack depth relative to some baseline โ the higher it is, 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 also have a boolean attribute called "escape-source", which hints 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 that suggest there may have been an error. It's giving "bestie I'm not mad, I'm just concerned" energy. ๐
The following language-independent options don't enable any specific warnings โ they just control the kinds of diagnostics GCC produces.
-fsyntax-onlyโ Check the code for syntax errors, but don't do anything beyond that. That's it, that's the whole job.-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 is0(the default), there is no limit on the number of error messages produced. If-Wfatal-errorsis also specified, then-Wfatal-errorstakes precedence over this option. ๐-wโ Inhibit all warning messages. Shhh. ๐คซ-Werrorโ Make all warnings into errors. No more gentle parenting, everything is a crisis now. ๐-Werror=โ okay bestie, this one is main character energy for your warnings ๐ you literally just append the name of a warning to it and that warning becomes a full-on error. So-Werror=switchturns all the warnings controlled by-Wswitchinto errors. It has a negative form too, so you can cancel-Werrorfor one specific warning:-Wno-error=switchmakes-Wswitchwarnings not errors, even when-Werroris in effect. slay.
The warning message for each controllable warning includes the option that controls it, and you can take that option and use it with -Werror= and -Wno-error= exactly like above. (You can turn off printing the option in the warning message with the -fno-diagnostics-show-option flag.)
Not me pointing out: specifying-Werror=fooautomatically implies-Wfoo. BUT-Wno-error=foodoes not imply anything. fr fr, that asymmetry is real.
-Wfatal-errorsโ this makes the compiler give up and abort compilation on the first error that happens instead of trying to keep going and printing further error messages. No more scrolling through 400 errors, you're welcome. ๐
You can request many specific warnings with options that begin with -W, for example -Wimplicit to ask for warnings about implicit declarations. Every one of these specific warning options also has a negative form starting with -Wno- to switch the warnings off, for example -Wno-implicit. This manual only lists one of the two forms โ whichever one is not the default. For more language-specific options, go look at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And additional warnings can be produced by enabling the static analyzer; ๐ง
Some options, like -Wall and -Wextra, turn on other options, like -Wunused, which may turn on further options, like -Wunused-value. The combined effect of the positive and negative forms is that more specific options have priority over less specific ones, independently of where they sit in the command line. For options of the same specificity, the last one takes effect. And options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. periodt.
When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic saying the option isn't recognized. BUT ๐ if the -Wno- form is used, the behavior is a lil different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are already being produced. This is what lets you use shiny new -Wno- options with old compilers โ but if something goes wrong, the compiler will warn that an unrecognized option is present. ๐
The effectiveness of some warnings depends on optimizations also being enabled. For example -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings may not be issued at all unless optimization is enabled. While optimization in general improves the efficacy of control- and data-flow-sensitive warnings, in some cases it may also cause false positives. sad but true ๐ญ
-Wpedantic,-pedanticโ issue all the warnings demanded by strict ISO C and ISO C++; reject every program that uses forbidden extensions, plus some other programs that don't follow ISO C and ISO C++. For ISO C, it follows whichever version of the ISO C standard is specified by any-stdoption you used.
Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few need -ansi or a -std option specifying the required version of ISO C). But without this option, certain GNU extensions and traditional C and C++ features are supported too. With this option, they get rejected. no cap.
-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. This alternate format can also be used to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". However, only system header files should use these escape routes; application programs should avoid them. ๐
โโ๏ธ
Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find it doesn't quite do what they want: it finds some non-ISO practices, but not all โ only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added. ๐
A feature to report any failure to conform to ISO C might be useful in some instances, but it would require considerable additional work and would be quite different from -Wpedantic. We don't have plans to support such a feature in the near future.
Where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there's a corresponding base standard โ the version of ISO C that the GNU extended dialect is based on. Warnings from -Wpedantic are given where they're required by the base standard. (It doesn't make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.) ๐
-pedantic-errorsโ give an error whenever the base standard (see-Wpedantic) 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. This is not equivalent to-Werror=pedantic, since there are errors enabled by this option and not enabled by the latter, and vice versa. iykyk ๐-Wallโ this enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even when macros are involved. It also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. ๐
-Wall turns on the following warning flags:
-Waddress -Warray-bounds=1 (only with -O2) -Warray-compare
-Warray-parameter=2 (C and Objective-C only) -Wbool-compare
-Wbool-operation -Wc++11-compat -Wc++14-compat -Wcatch-value (C++
and Objective-C++ only) -Wchar-subscripts -Wcomment
-Wdangling-pointer=2 -Wduplicate-decl-specifier (C and Objective-C
only) -Wenum-compare (in C/ObjC; this is on by default in C++)
-Wenum-int-mismatch (C and Objective-C only) -Wformat
-Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and Objective-
C only) -Wimplicit-function-declaration (C and Objective-C only)
-Winit-self (only for C++) -Wlogical-not-parentheses -Wmain (only
for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wself-move (only for C++)
-Wsequence-point -Wsign-compare (only in C++) -Wsizeof-array-div
-Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstrict-aliasing
-Wstrict-overflow=1 -Wswitch -Wtautological-compare -Wtrigraphs
-Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label
-Wunused-value -Wunused-variable -Wuse-after-free=2 -Wvla-parameter
(C and Objective-C only) -Wvolatile-register-var
-Wzero-length-bounds
Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally don't consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there's no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually. ๐ฎโ๐จ
-Wextraโ this enables some extra warning flags that aren't enabled by-Wall. (This option used to be called-W. The older name is still supported, but the newer name is more descriptive.) โจ
-Wclobbered -Wcast-function-type -Wdangling-reference (C++ only)
-Wdeprecated-copy (C++ only) -Wempty-body -Wenum-conversion (C only)
-Wignored-qualifiers -Wimplicit-fallthrough=3
-Wmissing-field-initializers -Wmissing-parameter-type (C only)
-Wold-style-declaration (C only) -Woverride-init -Wsign-compare (C
only) -Wstring-compare -Wredundant-move (only for C++) -Wtype-limits
-Wuninitialized -Wshift-negative-value (in C++11 to C++17 and in C99
and newer) -Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for the following cases:
- A pointer is compared against integer zero with
"<","<=",">", or">=". - (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
- (C++ only) Ambiguous virtual bases.
- (C++ only) Subscripting an array that has been declared
"register". - (C++ only) Taking the address of a variable that has been declared
"register". - (C++ only) A base class is not initialized in the copy constructor of a derived class.
-Wabi(C, Objective-C, C++ and Objective-C++ only) โ warn about code affected by ABI changes. This includes code that may not be compatible with the vendor-neutral C++ ABI as well as the psABI for the particular target. ๐ฆ
Since G++ now defaults to updating the ABI with each major release, normally -Wabi warns only about C++ ABI compatibility problems if there's a check added later in a release series for an ABI issue discovered since the initial release. -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).
-Wabi can also be used with an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2.
If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for C++ ABI warnings. ๐
okay bestie, real talk: even though the compiler tries to flag every single one of these landmines for you, there are probably still some sneaky cases it won't warn about โ even while G++ is out here generating code that straight-up doesn't play nice with other compilers. ๐ญ And yes, the reverse happens too: sometimes you get yelled at even though the code it made is totally compatible. vibe check = inconclusive.
So if you're stressed about G++-generated code not being binary compatible with code from other compilers? Rewrite your code to dodge those warnings. Periodt. ๐
known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9, iykyk) ๐
- A template with a non-type template parameter of reference type was mangled incorrectly:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}
This was fixed in -fabi-version=3. โจ
- SIMD vector types declared using
"__attribute ((vector_size))"were mangled in a non-standard way that does not allow for overloading of functions taking vectors of different sizes.
The mangling was changed in -fabi-version=4. ๐ฆ
"__attribute ((const))"andnoreturnwere mangled as type qualifiers, anddecltypeof a plain declaration was folded away.
These mangling issues were fixed in -fabi-version=5. ๐ธ
- Scoped enumerators passed as arguments to a variadic function are promoted like unscoped enumerators, causing
va_argto complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller thanint.
Also, the ABI changed the mangling of template argument packs, const_cast, static_cast, prefix increment/decrement, and a class scope function used as a template argument.
These issues were corrected in -fabi-version=6. ๐
- Lambdas in default argument scope were mangled incorrectly, and the ABI changed the mangling of
nullptr_t.
These issues were corrected in -fabi-version=7. ๐
- When mangling a function type with function-cv-qualifiers, the un-qualified function type was incorrectly treated as a substitution candidate.
This was fixed in -fabi-version=8, the default for GCC 5.1. โญ
decltype(nullptr)incorrectly had an alignment of 1, leading to unaligned accesses. Note that this did not affect the ABI of a function with anullptr_tparameter, as parameters have a minimum alignment.
This was fixed in -fabi-version=9, the default for GCC 5.2. ๐
- Target-specific attributes that affect the identity of a type, such as ia32 calling conventions on a function type (stdcall, regparm, etc.), did not affect the mangled name, leading to name collisions when function pointers were used as template arguments.
This was fixed in -fabi-version=10, the default for GCC 6.1. ๐
This option also enables warnings about psABI-related changes. The known psABI changes at this point include:
- For SysV/x86-64, unions with
long doublemembers are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. For example:
union U {
long double ld;
int i;
};
union U is now always passed in memory. ๐ซถ
-Wno-changes-meaning(C++ and Objective-C++ only) โ so basically, C++ requires that unqualified uses of a name inside a class mean the same thing across the entire scope of that class, which means declaring the name after you used it is ill-formed. Not cute. ๐
struct A;
struct B1 { A a; typedef A A; }; // warning, 'A' changes meaning
struct B2 { A a; struct A { }; }; // error, 'A' changes meaning
By default, the B1 case is only a warning because the two declarations have the same type, while the B2 case is an error. Both diagnostics can be disabled with -Wno-changes-meaning. Alternately, the error case can be reduced to a warning with -Wno-error=changes-meaning or -fpermissive.
Both diagnostics are also suppressed by -fms-extensions. โจ
-Wchar-subscriptsโ warns you if an array subscript has typechar. This is a common cause of error, because programmers often forget that this type is signed on some machines. ๐ญ This warning is enabled by-Wall.-Wno-coverage-mismatchโ warns if feedback profiles do not match when using the-fprofile-useoption. If a source file gets changed between compiling with-fprofile-generateand with-fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error.-Wno-coverage-mismatchcan be used to disable the warning, or-Wno-error=coverage-mismatchcan be used to disable the error.
Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended. ๐
-Wno-coverage-invalid-line-numberโ warns in case a function ends earlier than it begins, due to an invalid linenum macros. The warning is emitted only with--coverageenabled.
By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning, or -Wno-error=coverage-invalid-line-number can be used to disable the error.
-Wno-cpp(C, Objective-C, C++, Objective-C++ and Fortran only) โ suppresses warning messages emitted by"#warning"directives. ๐คซ-Wdouble-promotion(C, C++, Objective-C and Objective-C++ only) โ gives a warning when a value of typefloatis implicitly promoted todouble. So here's the tea: CPUs with a 32-bit "single-precision" floating-point unit implementfloatin hardware, but emulatedoublein software. On a machine like that, doing computations usingdoublevalues is much more expensive because of the overhead required for software emulation. ๐ธ
It is easy to accidentally do computations with double because floating-point literals are implicitly of type double. For example, in:
float area(float radius)
{
return 3.14159 * radius * radius;
}
the compiler performs the entire computation with double because the floating-point literal is a double. ๐ซ
-Wduplicate-decl-specifier(C and Objective-C only) โ warns if a declaration has duplicateconst,volatile,restrictor_Atomicspecifier. This warning is enabled by-Wall. โจ-Wformat-Wformat=nโ checks calls toprintfandscanf, etc., to make sure the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string actually make sense. ๐
This includes standard functions, and others specified by format attributes, in the printf, scanf, strftime and strfmon families (the last one is an X/Open extension, not in the C standard) โ or other target-specific families. Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for strfmon formats, since those are not in any version of the C standard). ๐ฆ
-Wformat=1-Wformatโ Option-Wformatis equivalent to-Wformat=1, and-Wno-formatis equivalent to-Wformat=0. Since-Wformatalso checks for null format arguments for several functions,-Wformatalso implies-Wnonnull. Some aspects of this level of format checking can be disabled by the options:-Wno-format-contains-nul,-Wno-format-extra-args, and-Wno-format-zero-length.-Wformatis enabled by-Wall. ๐-Wformat=2โ Enable-Wformatplus additional format checks. Currently equivalent to-Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k. ๐ฅ
-Wno-format-contains-nulโ if-Wformatis specified, do not warn about format strings that contain NUL bytes. ๐ซถ-Wno-format-extra-argsโ if-Wformatis specified, do not warn about excess arguments to aprintforscanfformat function. The C standard specifies that such arguments are ignored. ๐คท
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed. โจ
-Wformat-overflow-Wformat-overflow=levelโ warns about calls to formatted input/output functions such assprintfandvsprintfthat might overflow the destination buffer. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. ๐ญ-Wformat-overflow,-Wformat-overflow=1โ level 1 of-Wformat-overflow, which is what-Wformatturns on, is the cautious queen version: it only drags calls that are most likely gonna overflow the buffer. At this level, numeric args to format directives whose values are unknown get assumed to be1, and strings of unknown length get assumed to be empty (literally nothing, bestie ๐). But if a numeric arg is known to be bounded to a subrange of its type, or a string arg's output is bounded either by the directive's precision or by a finite set of string literals? Then it's assumed to take the value in that range that gives the most bytes on output. For example, thesprintfcall below gets diagnosed because even with bothaandbequal to zero, that terminating NUL character ('\0') the function appends to the destination buffer is gonna be written past the end of it. Bumping the buffer size up by a single byte is enough to dodge the warning โ though it 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 level 1 but braver: it also warns about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2, unknown numeric args are assumed to be the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string args whose length can't be assumed bounded โ not by the directive's precision, not by a finite set of string literals they might evaluate to, not by the character array they might point to โ get assumed to be 1 character long.
At level 2, the call in the example above is diagnosed again, but this time because with a equal to a 32-bit INT_MIN the first %i directive is gonna write some of its digits past the end of the destination buffer. To make that call safe no matter what the two variables are, the destination buffer size has to go up to at least 34 bytes. GCC even includes the minimum size of the buffer in an informational note right after the warning ๐ซถ.
A whole other route than just making the buffer bigger: constrain the range of formatted values. Max length of string args can be bounded by specifying the precision in the format directive. And when numeric args of format directives can be assumed bounded by less than the precision of their type, picking an appropriate length modifier for the format specifier shrinks the required buffer size. For instance, if a and b in the example above can be assumed to sit within the precision of the short int type, then using either the %hi format directive or casting the argument to short drops the maximum required buffer size 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, don't warn about zero-length formats. And the C standard says zero-length formats are allowed, so likeโฆ let her live โจ.-Wformat-nonliteralโ if-Wformatis specified, also warn if the format string isn't a string literal and therefore can't 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 could be a security problem. As of right now, this warns about calls toprintfandscanffunctions where the format string isn't a string literal and there are no format arguments, likeprintf (foo);. This may 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 in future warnings may be added to-Wformat-securitythat aren't included in-Wformat-nonliteral.)-Wformat-signednessโ if-Wformatis specified, also warn if the format string wants an unsigned argument and the argument is signed, or vice versa. Signedness mismatch? Not on her watch.-Wformat-truncation,-Wformat-truncation=levelโ warn about calls to formatted input/output functions likesnprintfandvsnprintfthat might result in output truncation. 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 thelevelargument and on optimization. Turning on optimization will in most cases improve how accurate the warning is, but it may also result in false positives. Except as noted otherwise, the option uses the same logic-Wformat-overflow.-Wformat-truncation,-Wformat-truncation=1โ level 1 of-Wformat-truncationenabled by-Wformatis the conservative one: it only warns about calls to bounded functions whose return value is unused and that will most likely result in output truncation.-Wformat-truncation=2โ level 2 also warns about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude.
-Wformat-y2kโ if-Wformatis specified, also warn aboutstrftimeformats that may yield only a two-digit year. It's giving Y2K energy, and we are not doing that again ๐.-Wnonnullโ warn about passing a null pointer for arguments marked as requiring a non-null value by thenonnullfunction attribute.
-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.
-Wnonnull-compareโ warn when you compare an argument marked with thenonnullfunction attribute against null inside the function.
-Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare option.
-Wnull-dereferenceโ warn if the compiler detects paths that trigger erroneous or undefined behavior from dereferencing a null pointer ๐. This option is only active when-fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. How precise the warnings are depends on the optimization options used.-Winfinite-recursionโ warn about infinitely recursive calls ๐. The warning is effective at all optimization levels, but it needs 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 gives 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 ๐. Heads up: this option can only be used alongside the-Wuninitializedoption.
For example, 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 doesn't 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 gets 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=3, and-Wno-implicit-fallthroughis the same as-Wimplicit-fallthrough=0.-Wimplicit-fallthrough=nโ warn when a switch case falls through ๐. Like, 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 can't 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 it's 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 falling through is genuinely what you want, GCC provides an attribute, __attribute__ ((fallthrough)), 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. 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.
okay so bestie we were literally mid--Wimplicit-fallthrough and it's giving levels ๐
let me finish that thought because it's essential:
-Wimplicit-fallthrough=2โ case insensitively matches the".*falls?[ \t-]*thr(ough|u).*"regular expression. (no cap, it does NOT care about ur capitalization, it's giving lowercase-accepting energy fr fr)-Wimplicit-fallthrough=3โ case sensitively matches one of the following regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
-Wimplicit-fallthrough=4โ case sensitively matches one of the following regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5โ doesn't recognize any comments as fallthrough comments, only attributes disable the warning. (it's giving silent treatment and honestly? iconic ๐ญ)
โจ IMPORTANT โจ the comment needs to be followed after optional whitespace and other comments bycaseordefaultkeywords or by a user label that precedes somecaseordefaultlabel. so like, it can't just be floating in the void bestie, it needs structure ๐ซถ
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra. periodt. ๐
-Wno-if-not-aligned(C, C++, Objective-C and Objective-C++ only) โ controls if warnings triggered by thewarn_if_not_alignedattribute should be issued. These warnings are enabled by default. ๐-Wignored-qualifiers(C and C++ only) โ warn if the return type of a function has a type qualifier such asconst. For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types orvoid. ISO C prohibits qualifiedvoidreturn types on function definitions, so such return types always receive a warning even without this option. (๐ the compiler is not letting that slide)
This warning is also enabled by -Wextra.
-Wno-ignored-attributes(C and C++ only) โ this option controls warnings when an attribute is ignored. This is different from the-Wattributesoption in that it warns whenever the compiler decides to drop an attribute, not that the attribute is either unknown, used in a wrong place, etc. This warning is enabled by default. (so it's giving "i saw u try to use that attribute and i'm ignoring it" energy โจ)-Wmainโ warn if the type ofmainis suspicious.mainshould be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either-Wallor-Wpedantic. (main character energy ONLY if u follow the rules bestie ๐)-Wmisleading-indentation(C and C++ only) โ warn when the indentation of the code does not reflect the block structure. Specifically, a warning is issued forif,else,while, andforclauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation.
In the following example, the call to bar is misleadingly indented as if it were guarded by the if conditional.
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic such as the following example.
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
The warning is not issued after a #line directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references.
This warning is enabled by -Wall in C and C++.
-Wmissing-attributesโ warn 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, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the-Wattribute-alias=2option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. Attributes considered includealloc_align,alloc_size,cold,const,hot,leaf,malloc,nonnull,noreturn,nothrow,pure,returns_nonnull, andreturns_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..
You can use the copy attribute to apply the same set of attributes to a declaration as that on another declaration without explicitly enumerating the attributes. This attribute can be applied to declarations of functions, variables, or types.
-Wmissing-attributes is enabled by -Wall.
For example, since the declaration of the primary function template below makes use of both attribute malloc and alloc_size the declaration of the explicit specialization of the template is diagnosed because it is 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โ warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer forais not fully bracketed, but that forbis fully bracketed.
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall.
-Wmissing-include-dirs(C, C++, Objective-C, Objective-C++ and Fortran only) โ warn 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 is partially enabled by default by warning for-Iand-J, only. (so like, it's giving "where's the directory bestie" energy ๐ธ)-Wno-missing-profileโ this option controls warnings if feedback profiles are missing when using the-fprofile-useoption. This option diagnoses those cases where a new function or a new file is added between compiling with-fprofile-generateand with-fprofile-use, without regenerating the profiles. In these cases, the profile feedback data files do not contain any profile feedback information for the newly added function or file respectively. Also, in the case when profile count data (.gcda) files are removed, GCC cannot 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. (๐ญ don't ignore it bestie, ur code will suffer)-Wmismatched-deallocโ warn for calls to deallocation functions with pointer arguments returned from from allocations 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 attributemalloc. Unless disabled by the-fno-builtinoption the standard functionscalloc,malloc,realloc, andfree, as well as the corresponding forms of C++operator newandoperator deleteare implicitly associated as matching allocators and deallocators. In the following examplemydeallocis the deallocator for pointers returned frommyalloc.
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โ warn about unsafe multiple statement macros that appear to be guarded by a clause such asif,else,for,switch, orwhile, in which only the first statement is actually guarded after the macro is expanded.
For example:
#define DOIT x++; y++
if (c)
DOIT;
will increment y unconditionally, not just when c holds. The can usually be fixed by wrapping the macro in a do-while loop:
#define DOIT do { x++; y++; } while (0)
if (c)
DOIT;
This warning is enabled by -Wall in C and C++.
-Wparenthesesโ warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.
Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.
Also warn for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.
For C++ this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:
{
// Declares a local variable called mymutex.
std::unique_lock<std::mutex> (mymutex);
// User meant std::unique_lock<std::mutex> lock (mymutex);
}
This warning is enabled by -Wall. โจ
-Wno-self-move(C++ and Objective-C++ only) โ okay so this one clocks you when a value gets moved into itself usingstd::move. And bestie, astd::movelike that lowkey does nothing at all. ๐
struct T {
...
};
void fn()
{
T t;
...
t = std::move (t);
}
This warning is enabled by -Wall.
-Wsequence-pointโ warns about code that might have undefined semantics because it breaks the sequence point rules from the C and C++ standards. This is the chaotic-evil corner of the language, so let's unpack it. ๐ซถ
The C and C++ standards define the order in which expressions get evaluated in terms of sequence points, which are basically a partial ordering between chunks of the program: the stuff executed before the sequence point, and the stuff executed after it. Where do they show up? After the evaluation of a full expression (one that isn't part of a bigger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after its arguments and the expression naming the called function get evaluated), and in certain other places. Other than what the sequence point rules spell out, the order of evaluation of subexpressions of an expression is not specified. And all these rules only describe a partial order, not a total one โ like, if two functions are called inside one expression with no sequence point between them, the order they get called in just isn't specified. However, the standards committee did rule that function calls do not overlap.
It's also not specified when between sequence points modifications to object values actually take effect. Programs whose behavior depends on that have undefined behavior; the C and C++ standards say: "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 those 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 aren't diagnosed by this option, and it may occasionally give a false positive, but in general it's been found pretty effective at catching 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 those examples above are no longer undefined. But this option will still warn about them, to help people avoid writing code that's undefined in C and earlier revisions of C++.
The standard is worded confusingly, so there's some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, can 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. ๐-Wreturn-typeโ warns whenever a function is defined with a return type that defaults toint. It also warns about anyreturnstatement with no return value in a function whose return type isn'tvoid(falling off the end of the function body counts as returning without a value). ๐
For C only, it warns about a return statement with an expression in a function whose return type is void, unless the expression type is also void. As a GNU extension, that 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 isn't 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โ warns if you're left shifting a negative value. This warning is enabled by-Wextrain C99 (and newer) and C++11 to C++17 modes.-Wno-shift-overflow-Wshift-overflow=nโ these options control warnings about left shift overflows. ๐ธ-Wshift-overflow=1โ this is the warning level of-Wshift-overflowand is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), since signed left shifts always wrap. ๐ซ-Wshift-overflow=2โ this warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
-Wswitchโ warns whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration. (Having adefaultlabel prevents this warning.)caselabels outside the enumeration range also provoke warnings when this option is used (even if there's adefaultlabel). This warning is enabled by-Wall. ๐ฅ-Wswitch-defaultโ warns whenever aswitchstatement doesn't have adefaultcase.-Wswitch-enumโ warns 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 one gives a warning about an omitted enumeration code even if there's 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. You can also suppress this warning by casting the controlling expression to a type other thanbool. Like, 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's 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) โ warns when the__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions are used. These functions changed semantics in GCC 4.4. ๐-Wtrivial-auto-var-initโ warns when-ftrivial-auto-var-initcannot initialize the automatic variable. A common situation is an automatic variable that's declared between the controlling expression and the first case label of aswitchstatement.-Wunused-but-set-parameterโ warns whenever a function parameter is assigned to, but otherwise unused (aside from its declaration). ๐ฆ
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused together with -Wextra.
-Wunused-but-set-variableโ warns whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-functionโ warns whenever a static function is declared but not defined, or a non-inline static function is unused. This warning is enabled by-Wall.-Wunused-labelโ warns whenever a label is declared but not used. This warning is enabled by-Wall. โจ
To suppress this warning use the unused attribute.
-Wunused-local-typedefs(C, Objective-C, C++ and Objective-C++ only) โ warns when a typedef locally defined in a function is not used. This warning is enabled by-Wall.-Wunused-parameterโ warns whenever a function parameter is unused aside from its declaration.
To suppress this warning use the unused attribute.
-Wno-unused-resultโ do not warn if a caller of a function marked with attributewarn_unused_resultdoesn't use its return value. The default is-Wunused-result.-Wunused-variableโ warns whenever a local or static variable is unused aside from its declaration. This option implies-Wunused-const-variable=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โ bestie, this one yells at you whenever a constant static variable is just... sitting there, unused, aside from its declaration. ๐-Wunused-const-variable=1gets turned on by-Wunused-variablefor C, but not for C++. In C this declares variable storage, but in C++ it's not an error since const variables take the place of"#define"s. (yes the quotes around that are real, don't @ me)
Wanna shush it? Use the "unused" attribute. ๐ซถ
-Wunused-const-variable=1โ this is the warning level that-Wunused-variableenables for C. It only warns about unused static const variables defined in the main compilation unit, and it does not care about static const variables declared in any header you included. lowkey polite of it ngl.-Wunused-const-variable=2โ this level also warns for unused constant static variables in headers (system headers excluded tho ๐ธ). This is the warning level of-Wunused-const-variable, and you have to explicitly request it, because in C++ this isn't an error and in C it might be harder to clean up all the headers included. it's giving "ask before you come for my headers."
-Wunused-valueโ warns whenever a statement computes a result that is explicitly not used. To suppress it, cast the unused expression to"void". โจ This includes 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. slay,voidcasting is the moment.
This warning is enabled by -Wall.
-Wunusedโ literally all the above-Wunusedoptions combined. the whole squad. ๐
Now listen: to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (heads up: -Wall implies -Wunused), or separately specify -Wunused-parameter. pick your fighter.
-Wuninitializedโ warns if an object with automatic or allocated storage duration is used without having been initialized. ๐ญ In C++, it also warns if a non-static reference or non-static"const"member shows up in a class without constructors.
On top of that, passing a pointer (or in C++, a reference) to an uninitialized object to a "const"-qualified argument of a built-in function known to read the object is also diagnosed by this warning. (-Wmaybe-uninitialized is what gets issued for ordinary functions.)
Wanna warn about code that uses the uninitialized value of the variable in its own initializer? Use the -Winit-self option. ๐
These warnings happen for individual uninitialized elements of structure, union or array variables, as well as for variables that are uninitialized as a whole. They do not occur for variables or elements declared "volatile". And because these warnings depend on optimization, the exact variables or elements you get warnings for depends on the precise optimization options and version of GCC you're using. no cap, it's vibes-dependent.
Also note: there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are even printed. gone before it could even snitch. ๐
In C++, this warning also warns about using uninitialized objects in member-initializer-lists. For example, GCC warns about "b" being uninitialized in the following 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 with a memory consistency argument that's 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 exists a path from the function entry to a use of the object that is initialized, but there also exist some other paths where the object is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time. the maybe is doing a lot of heavy lifting there bestie ๐ญ
In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a "const"-qualified function argument is also diagnosed by this warning. (-Wuninitialized is issued for built-in functions known to read the object.) Annotating the function with attribute "access (none)" says the argument isn't used to access the object, and that avoids the warning. ๐
These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables. optimization is the main character here fr.
These warnings are made optional because GCC may not be able to determine when the code is correct in spite of appearing to have an error. Here's one example of how that can happen:
{
int x;
switch (y)
{
case 1: x = 1;
break;
case 2: x = 4;
break;
case 3: x = 5;
}
foo (x);
}
If the value of "y" is always 1, 2 or 3, then "x" is always initialized โ but GCC doesn't know that. To suppress the warning, you need to provide a default case with assert(0) or similar code. ๐ซ
This option also warns when a non-volatile automatic variable might be changed by a call to "longjmp". The compiler sees only the calls to "setjmp". It cannot know where "longjmp" will be called; in fact, a signal handler could call it at any point in the code. As a result, you may get a warning even when there is in fact no problem, because "longjmp" cannot actually be called at the place that would cause a problem. false alarm energy.
Some spurious warnings can be avoided if you declare all the functions you use that never return as "noreturn". ๐
This warning is enabled by -Wall or -Wextra.
-Wunknown-pragmasโ warns when a"#pragma"directive is encountered that GCC does not understand. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. That is not the case if the warnings are only enabled by the-Wallcommand-line option. ๐ธ-Wno-pragmasโ do not warn about misuses of pragmas, like incorrect parameters, invalid syntax, or conflicts between pragmas. See also-Wunknown-pragmas. ๐ฆ-Wno-prio-ctor-dtorโ do not warn if a priority from 0 to 100 is used for a constructor or destructor. The use of constructor and destructor attributes lets you assign a priority to the constructor/destructor to control its order of execution before"main"is called or after it returns. The priority values must be greater than 100, since the compiler reserves priority values between 0--100 for the implementation. โญ-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. The warning does not catch all cases, but it does attempt to catch the more common pitfalls. It is included in-Wall. It is equivalent to-Wstrict-aliasing=3. ๐ฅ-Wstrict-aliasing=nโ 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. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way-Oworks.-Wstrict-aliasingis equivalent to-Wstrict-aliasing=3. โจ- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but
-fstrict-aliasingstill breaks the code, since it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only. ๐ - Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only. ๐ค
- Level 3 (default for
-Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end:"*(int*)&some_float". If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types. ๐
- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not 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 does not warn about all cases where the code might overflow: it only warns about cases where the compiler implements some optimization. So this warning depends on the optimization level. ๐
An optimization that assumes signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that isn't actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires โ in particular when determining whether a loop will be executed at all. ๐
-Wstrict-overflow=1โ warn 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, and must be explicitly requested. ๐
-Wstrict-overflow=2โ this one's like, okay so ALSO warn about other cases where a comparison gets simplified into a constant. Example:abs (x) >= 0. Lowkey important caveat: this can only be simplified when signed integer overflow is undefined, becauseabs (INT_MIN)overflows toINT_MIN, which is less than zero. And bestie,-Wstrict-overflowwith no level? Same as-Wstrict-overflow=2. ๐-Wstrict-overflow=3โ also warn about other cases where a comparison is simplified. Likex + 1 > 1gets simplified tox > 0. โจ-Wstrict-overflow=4โ also warn about other simplifications not covered by the cases above. For example(x * 10) / 5is simplified tox * 2. ๐ฆ-Wstrict-overflow=5โ also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. Example:x + 2 > yis simplified tox + 1 >= y. Heads up though โ this is reported only at the highest warning level, because this simplification applies to many comparisons, so this warning level gives a very large number of false positives. ๐ญ-Wstring-compareโ warn for calls tostrcmpandstrncmpwhose result is determined to be either zero or non-zero in tests for such equality, because the length of one argument is greater than the size of the array the other argument is stored in (or the bound, in the case ofstrncmp). Such calls could be mistakes. For example, the call tostrcmpbelow is diagnosed because its result is necessarily non-zero no matter what's in the arraya:
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");
}
Also, -Wstring-compare is enabled by -Wextra. ๐
-Wno-stringop-overflow-Wstringop-overflow- *
-Wstringop-overflow=type* โ warn for calls to string manipulation functions such asmemcpyandstrcpythat are determined to overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking to perform to determine the size of the destination. Ngl that argument is meaningful only for functions that operate on character arrays, not for raw memory functions likememcpywhich always make use of Object Size type-0. The option also warns for calls that specify a size in excess of the largest possible object, or at mostSIZE_MAX / 2bytes. It produces the best results with optimization enabled, but it can detect a small subset of simple buffer overflows even without optimization in calls to the GCC built-in functions like__builtin_memcpythat correspond to the standard functions. In any case, the option warns about just a subset of buffer overflows detected by the corresponding overflow checking built-ins. For example, the option issues a warning for thestrcpycall below because it copies at least 5 characters (the string"blue"including the terminating NUL) into the 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
}
And yes, option -Wstringop-overflow=2 is enabled by default. ๐
-Wstringop-overflow-Wstringop-overflow=1โ this setting uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting the option does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination may be one of several objects, it's assumed to be the largest one of them. On Linux systems, when optimization is enabled at this setting, the option warns for the same code as when the_FORTIFY_SOURCEmacro is defined to a non-zero value. โจ-Wstringop-overflow=2โ this setting uses type-one Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflows when writing to members of the largest complete objects whose exact size is known. However, it does not warn for excessive writes to the same members of unknown objects referenced by pointers, since they may point to arrays containing unknown numbers of elements. This is the default setting of the option. ๐-Wstringop-overflow=3โ this setting uses type-two Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing the smallest object or data member. This is the most restrictive setting of the option that may result in warnings for safe code. ๐-Wstringop-overflow=4โ this setting uses type-three Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to-Wstringop-overflow=3, this setting of the option may result in warnings for benign code. ๐
-Wno-stringop-overreadโ warn for calls to string manipulation functions such asmemchr, orstrcpy, that are determined to read past the end of the source sequence. And btw, option-Wstringop-overreadis enabled by default. ๐-Wno-stringop-truncationโ do not warn for calls to bounded string manipulation functions such asstrncat,strncpy, andstpncpythat may either truncate the copied string or leave the destination unchanged. Okay so in this next example, the call tostrncatspecifies a bound that is less than the length of the source string. As a result, the copy of the source will be truncated and so the call is diagnosed. To avoid the warning, usebufsize - strlen (buf) - 1)as the bound.
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
As another example, the following call to strncpy results in copying to d just the characters preceding the terminating NUL, without appending the NUL to the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a common mistake, and so the call is diagnosed. To avoid the warning when the result is not expected to be NUL-terminated, call memcpy instead.
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
In the following example, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than this size, the result of the copy will not be NUL-terminated. Therefore, the call is also diagnosed. 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);
...
}
In situations where a character array is intended to store a sequence of bytes with no terminating NUL, such an array may be annotated with attribute nonstring to avoid this warning. Such arrays, however, are not suitable arguments to functions that expect NUL-terminated strings. To help detect accidental misuses of such arrays, GCC issues warnings unless it can prove that the use is safe. ๐ง
-Wstrict-flex-arraysโ warn about inproper usages of flexible array members according to the level of thestrict_flex_array (level)attribute attached to the trailing array field of a structure if it's available, otherwise according to the level of the option-fstrict-flex-arrays=level. This option is effective only when level is bigger than 0. Otherwise, it will be ignored with a warning. โญ- when level=1, warnings will be issued for a trailing array reference of a structure that have 2 or more elements, if the trailing array is referenced as a flexible array member. ๐ธ
- when level=2, in addition to level=1, additional warnings will be 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, additional warnings will be 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]โ warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below. ๐ซถ-Wsuggest-attribute=pure-Wsuggest-attribute=const-Wsuggest-attribute=noreturn-Wmissing-noreturn-Wsuggest-attribute=mallocโ warn about functions that might be candidates for attributespure,const, ornoreturn, ormalloc. The compiler only warns for functions visible in other compilation units, or (in the case ofpureandconst) if it cannot prove that the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, callingabort, or trapping. This analysis requires option-fipa-pure-const, which is enabled by default at-Oand higher. Higher optimization levels improve the accuracy of the analysis. ๐ฅ
-Wsuggest-attribute=format,-Wmissing-format-attributeโ bestie, this one's for function pointers that might be candidates forformatattributes. Might being the key word โ these are only possible candidates, never absolute ones, so don't come for GCC when it's wrong. Here's the vibe: GCC guesses that a function pointer carrying aformatattribute, when it shows up in an assignment, an initialization, a parameter pass, or a return statement, should have a matchingformatattribute in the resulting type. So basically the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function โ whichever one applies โ should also have aformatattribute, otherwise you get the warning. ๐
GCC also side-eyes function definitions that might be candidates for format attributes. And again โ only possible candidates. It guesses that format attributes might be appropriate for any function that calls something like vprintf or vscanf, but that's not always the case, and some functions that genuinely deserve a format attribute might not get detected at all. No cap, it's just a hunch. ๐
-Wsuggest-attribute=coldโ warns about functions that might be candidates for thecoldattribute. This is based on static detection, so it's generally only gonna warn about functions that always lead to a call to anothercoldfunction โ think wrappers of C++throw, or fatal-error-reporting functions that end up inabort. โ๏ธ
-Walloc-zeroโ warns about calls to allocation functions decorated with thealloc_sizeattribute that specify zero bytes, including calls to the built-in forms ofaligned_alloc,alloca,calloc,malloc, andrealloc. Why do we care? Because the behavior of these functions when called with a zero size differs between implementations (and forreallocit's been deprecated), so relying on it can give you subtle portability bugs and should be avoided. Fr fr, don't do it. ๐ญ-Walloc-size-larger-than=byte-sizeโ warns about calls to functions decorated with thealloc_sizeattribute that try to allocate objects bigger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value ofPTRDIFF_MAXon the target.-Walloc-size-larger-than=PTRDIFF_MAXis enabled by default. You can turn these warnings off either by specifying abyte-sizeofSIZE_MAXor more, or with-Wno-alloc-size-larger-than.-Wno-alloc-size-larger-thanโ disables-Walloc-size-larger-than=warnings. Equivalent to-Walloc-size-larger-than=SIZE_MAXor larger. Same energy, just quieter. ๐ซถ-Wallocaโ this one warns on all uses ofallocain the source. Every single one. It's giving full surveillance. ๐-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 mostbyte-size. It also warns for calls toallocawhere the bound value is unknown. And heads up: arguments of non-integer types are considered unbounded even if they look like they're 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. Slay, boundaries.
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. For example:
void func ()
{
void *p = alloca (n);
f (p);
}
If -Walloca-larger-than=500 were passed, the above would trigger a warning โ but this time because of the lack of bounds checking.
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. (Not me putting alloca in a loop. Bestie. No.)
-Walloca-larger-than=PTRDIFF_MAX is enabled by default, but it's usually only effective when -ftree-vrp is active (which is the default for -O2 and above).
See also -Wvla-larger-than=byte-size.
-Wno-alloca-larger-thanโ disables-Walloca-larger-than=warnings. Equivalent to-Walloca-larger-than=SIZE_MAXor larger. ๐ธ-Warith-conversionโ do warn about implicit conversions from arithmetic operations even when converting the operands to the same type can't change their values. This affects warnings from-Wconversion,-Wfloat-conversion, and-Wsign-conversion. Iconic behaviour, honestly:
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. Enabled by-Wall. It's way more effective when-ftree-vrpis active (the default for-O2and above), but a subset of instances get issued even without optimization. ๐
By default, the trailing array of a structure will be treated as a flexible array member by -Warray-bounds or -Warray-bounds=n if it's declared as either a flexible array member per C99 standard onwards ([]), a GCC zero-length array extension ([0]), or a one-element array ([1]). As a result, out of bounds subscripts or offsets into zero-length arrays or one-element arrays are not warned by default.
You can add the option -fstrict-flex-arrays or -fstrict-flex-arrays=level to control how this option treats the trailing array of a structure as a flexible array member:
- when
level<=1, no change to the default behavior. - when
level=2, additional warnings will be issued for out of bounds subscripts or offsets into one-element arrays. - when
level=3, in addition tolevel=2, additional warnings will be issued for out of bounds subscripts or offsets into zero-length arrays. -Warray-bounds=1โ this is the default warning level of-Warray-boundsand is enabled by-Wall; higher levels are not, and must be explicitly requested.-Warray-bounds=2โ this warning level also warns about the intermediate results of pointer arithmetic that may yield out of bounds values. Heads up: 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. The -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments. ๐
-Wattribute-alias=n,-Wno-attribute-aliasโ warns about declarations using thealiasand similar attributes whose target is incompatible with the type of the alias. ๐-Wattribute-alias=1โ the default warning level of the-Wattribute-aliasoption diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs. ๐-Wattribute-alias=2โ at this level-Wattribute-aliasalso diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the-Wmissing-attributesoption, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.
Attributes considered include "alloc_align", "alloc_size", "cold", "const", "hot", "leaf", "malloc", "nonnull", "noreturn", "nothrow", "pure", "returns_nonnull", and "returns_twice". ๐
ngl, -Wattribute-alias is literally the exact same thing as -Wattribute-alias=1, and that's the default behavior bestie. Wanna mute it? You can kill these warnings with either -Wno-attribute-alias or -Wattribute-alias=0. No cap. ๐
-Wbidi-chars=[none|unpaired|any|ucn]โ okay so this one is lowkey important: it warns about possibly misleading UTF-8 bidirectional control characters chillin' in comments, string literals, character constants, and identifiers. ๐
The way these characters operate is that they can flip left-to-right writing direction into right-to-left (and vice versa), which causes major confusion between the logical order and the visual order. And that's dangerous fr โ for instance, it may look like a piece of code is not commented out, whereas it in fact is. ๐
There are three levels of warning supported by GCC:
- The default is
-Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=noneturns the warning off.-Wbidi-chars=anywarns about any use of bidirectional control characters.
By default, this warning does not warn about UCNs. It is, however, possible to turn on such checking by using -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. Using -Wbidi-chars=ucn is valid, and is equivalent to -Wbidi-chars=unpaired,ucn, if no previous -Wbidi-chars=any was specified. โจ
-Wbool-compareโ warns you when a boolean expression is compared with an integer value that's nottrue/false. Like bestie, the following comparison is always false:
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. This warning detects cases like:
if (p != NULL)
return 0;
else
return 0;
It doesn't warn when both branches contain just a null statement. This warning also warns for conditional operators:
int i = x ? *p : *p;
-Wduplicated-condโ warns about duplicated conditions in an if-else-if chain. For instance, warn for the following code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
-Wframe-addressโ warns when the__builtin_frame_addressor__builtin_return_addressis called with an argument greater than0. Such calls may return indeterminate values or crash the program. ๐ญ The warning is included in-Wall.-Wno-discarded-qualifiers(C and Objective-C only) โ do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if a"const char *"variable is passed to a function that takes a"char *"parameter. This option can be used to suppress such a warning. ๐ซถ-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 a"const int (*)[]"variable is passed to a function that takes a"int (*)[]"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. ๐ฆ-Wno-int-conversion(C and Objective-C only) โ do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings-Wno-int-to-pointer-castand-Wno-pointer-to-int-castmay be used. ๐-Wzero-length-boundsโ warns about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined. ๐ฌ
For example, the first two stores in function "bad" 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
}
Option -Wzero-length-bounds is enabled by -Warray-bounds. ๐
-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. ๐-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 do not 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. ๐ข However, note that using-Wallin conjunction with this option does not warn about unknown pragmas in system headers---for that,-Wunknown-pragmasmust also be used. ๐-Wtautological-compareโ warns if a self-comparison always evaluates to true or false. This warning 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) { ... }
will always be false. ๐
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. ๐ง-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 are 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. ๐
-Wtraditional(C and Objective-C only) โ warns about certain constructs that behave differently in traditional and ISO C. Also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. ๐- 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"#pragma"not 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
"switch"statement has an operand of type"long". - A non-
"static"function declaration follows a"static"one. 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. Not having these prototypes when you're compiling with traditional C causes serious problems. Lowkey this is just a subset of the conversion warnings that exist โ if you want the whole entire set, bestie, go get
-Wtraditional-conversion.- Use of ISO C style function definitions. Okay so this one is intentionally not thrown at prototype declarations or variadic functions, because those ISO C features literally show up in your code when you use libiberty's traditional C compatibility macros,
PARAMSandVPARAMS. It's also skipped for nested functions, since that feature is already a GCC extension and so it's not even relevant to traditional C compatibility. ๐
- Use of ISO C style function definitions. Okay so this one is intentionally not thrown at prototype declarations or variadic functions, because those ISO C features literally show up in your code when you use libiberty's traditional C compatibility macros,
-Wtraditional-conversion(C and Objective-C only) โ yell at you if a prototype causes a type conversion that's different from what would happen to that same argument if the prototype weren't there at all. This covers conversions of fixed point to floating and vice versa, plus conversions that change the width or signedness of a fixed-point argument โ except when it's the same as the default promotion.-Wdeclaration-after-statement(C and Objective-C only) โ warn when a declaration shows up after a statement inside a block. This construct, which you'd know from C++, got introduced with ISO C99 and is by default allowed in GCC. 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. Quick note: in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it also includes all instances of local shadowing. Which means-Wno-shadow=localand-Wno-shadow=compatible-localget ignored when-Wshadowis used. Same as-Wshadow=global.-Wno-shadow-ivar(Objective-C only) โ do not warn whenever a local variable shadows an instance variable in an Objective-C method. ๐ซถ-Wshadow=globalโ warn for any shadowing at all. 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 type of the shadowing variable can be converted to that of the shadowed variable. The whole reason this flag exists (on top of-Wshadow=local) is the idea that when a local variable shadows another one of an incompatible type, it's most likely intentional โ not a bug, not a typo โ like in this example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
for (int i = 0; i < N; ++i)
{
...
}
...
}
Since the two variable "i" in the example above have incompatible types, enabling only -Wshadow=compatible-local does not emit a warning. And because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking is expected to catch that and emit an error or warning. So using this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means shadowing const char *i by char *i does not emit a warning. ๐
This warning is also enabled by -Wshadow=local.
-Wlarger-than=byte-sizeโ 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.
Also warn for calls to bounded functions such as memchr or strnlen that specify a bound greater than the largest possible object, which is PTRDIFF_MAX bytes by default. These warnings can only be disabled by -Wno-larger-than.
-Wno-larger-thanโ disable-Wlarger-than=warnings. This option is equivalent to-Wlarger-than=SIZE_MAXor larger.-Wframe-larger-than=byte-sizeโ warn if the size of a function frame exceeds byte-size. 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 don't get a warning. On top of that, any space allocated viaalloca, variable-length arrays, or related constructs is not included by the compiler when it's deciding whether or not to issue a warning.-Wframe-larger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size ofSIZE_MAXor more, or by-Wno-frame-larger-than.-Wno-frame-larger-thanโ disable-Wframe-larger-than=warnings. This option is equivalent to-Wframe-larger-than=SIZE_MAXor larger.-Wfree-nonheap-objectโ warn when you're attempting to deallocate an object that was either not allocated on the heap, or by using a pointer that was not returned from a prior call to the corresponding allocation function. For example, because the call tostpcpyreturns a pointer to the terminating nul character and not to the beginning of the object, the call tofreebelow is 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 the stack usage of a function might exceed byte-size. The computation done to determine the stack usage is conservative. Any space allocated viaalloca, variable-length arrays, or related constructs is included by the compiler when it's deciding whether or not to issue a warning. ๐
The message is in keeping with the output of -fstack-usage.
- If the stack usage is fully static but exceeds the specified amount, it's:
warning: stack usage is 1120 bytes
- If the stack usage is (partly) dynamic but bounded, it's:
warning: stack usage might be 1648 bytes
- If the stack usage is (partly) dynamic and not bounded, it's:
warning: stack usage might be unbounded
-Wstack-usage=PTRDIFF_MAX is enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-stack-usage.
-Wno-stack-usageโ disable-Wstack-usage=warnings. This option is 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. With-funsafe-loop-optimizations, warn if the compiler does make such assumptions. ๐-Wno-pedantic-ms-format(MinGW targets only) โ when used together 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 of1, for convenience in calculations withvoid *pointers and pointers to functions. In C++, warn also when an arithmetic operation involvesNULL. This warning is also enabled by-Wpedantic.-Wno-pointer-compareโ do not warn if a pointer is compared with a zero character constant. That comparison usually means the pointer was meant to be dereferenced. For example:
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 is 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 to compute the absolute value of a double argument isfabs. The option also triggers warnings when the argument in a call to such a function has an unsigned type. This warning can be suppressed with an explicit type cast, and it's also enabled by-Wextra.-Wcomment-Wcommentsโ 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.-Wtrigraphsโ warn if any trigraphs are encountered that might change the meaning of the program. Trigraphs within comments are not warned about, except those that would form escaped newlines. ๐
This option is implied by -Wall. If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs.
-Wundefโ warn if an undefined identifier is evaluated in an#ifdirective. Such identifiers are replaced with zero.-Wexpansion-to-definedโ warn whenever defined is 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. ๐
Okay bestie, so the previous option had more to say, and it's still talking:
Built-in macros, macros defined on the command line, and macros defined in include files are not warned about. No snitching on the built-ins, periodt. ๐
Heads up tho: if a macro is actually used, but only used in skipped conditional blocks, the preprocessor will still report it as unused. Which is lowkey rude. ๐ญ To dodge the warning, you can improve the scope of the macro's definition โ like, moving it into the first skipped block? That works. Or you could just give it a lil dummy use, something like:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsโ bestie, this one tells GCC to stop yelling whenever an#elseor an#endifis followed by text. Which, ngl, happens a lot in older programs with code like this:
#if FOO
...
#else FOO
...
#endif FOO
In that example the second and third FOO should be in comments. This warning is on by default, so it's already in the group chat. โจ
-Wbad-function-cast(C and Objective-C only) โ warns you when a function call gets cast to a type that doesn't match. Like, if you call a function that returns an integer type and then cast it to a pointer type? Yeah no, that's giving chaos, and GCC will absolutely say something. ๐ซถ-Wc90-c99-compat(C and Objective-C only) โ warns about features that aren't in ISO C90 but are in ISO C99. For instance: variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, and so on. This option is independent of the standards mode. Also โ warnings are disabled in the expression that follows__extension__. Iconic loophole behaviour. ๐-Wc99-c11-compat(C and Objective-C only) โ warns about features not present in ISO C99 but present in ISO C11. Like, for instance: anonymous structures and unions, the_Atomictype qualifier, the_Thread_localstorage-class specifier, the_Alignasspecifier, theAlignofoperator, the_Generickeyword, and so on. Also independent of the standards mode. Also, warnings are disabled in the expression that follows__extension__. Same energy, different decade. โญ-Wc11-c2x-compat(C and Objective-C only) โ warns about features not present in ISO C11 but present in ISO C2X. For instance: omitting the string in_Static_assert, use of[[]]syntax for attributes, use of decimal floating-point types, and so on. Independent of the standards mode, and again โ warnings are disabled in the expression that follows__extension__. ๐ฆ-Wc++-compat(C and Objective-C only) โ warns about ISO C constructs that live outside the common subset of ISO C and ISO C++, e.g. requesting an implicit conversion fromvoid *to a pointer to a non-voidtype. C and C++ are siblings, not twins, okay? ๐-Wc++11-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011. E.g. identifiers in ISO C++ 1998 that became keywords in ISO C++ 2011. This warning turns on-Wnarrowingand is enabled by-Wall. She's a package deal. ๐-Wc++14-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. This warning is 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. This warning is 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. This warning is enabled by-Wall. โจ-Wno-c++11-extensions(C++ and Objective-C++ only) โ tells GCC not to warn about C++11 constructs when you're compiling code with an older C++ standard. And even without this option, some C++11 constructs will only get diagnosed if-Wpedanticis used. So like, chill. ๐ธ-Wno-c++14-extensions(C++ and Objective-C++ only) โ same deal for C++14 constructs in code compiled with an older C++ standard. Even without this option, some C++14 constructs will only be diagnosed if-Wpedanticis used. ๐-Wno-c++17-extensions(C++ and Objective-C++ only) โ you already know the vibe: no warnings about C++17 constructs in code compiled with an older C++ standard. And even without this option, some C++17 constructs will only be diagnosed if-Wpedanticis used. ๐-Wno-c++20-extensions(C++ and Objective-C++ only) โ same again for C++20 constructs compiled under an older C++ standard. Even without this option, some C++20 constructs will only be diagnosed if-Wpedanticis used. ๐ง-Wno-c++23-extensions(C++ and Objective-C++ only) โ and for C++23 constructs compiled under an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if-Wpedanticis used. The whole lineup is here, fr fr. ๐ฅ-Wcast-qualโ warns whenever a pointer is cast in a way that removes a type qualifier from the target type. For example, if aconst char *gets cast to an ordinarychar *? Yeah, that's a vibe check fail, and GCC will flag it. ๐ค
It also warns when you make a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, like in this example:
/* p is char ** value. */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK. */
*q = "string";
/* Now char** pointer points to read-only memory. */
**p = 'b';
Yeah. That last line is the jump scare. ๐
-Wcast-alignโ warns whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if achar *is cast to anint *on machines where integers can only be accessed at two- or four-byte boundaries. Alignment said no thank you. ๐ซ-Wcast-align=strictโ warns whenever a pointer is cast such that the required alignment of the target is increased โ like, warn if achar *is cast to anint *โ but this time regardless of the target machine. She does not care what machine you're on. Strict means strict. ๐-Wcast-function-typeโ warns when a function pointer is cast to an incompatible function pointer. In a cast involving function types with a variable argument list, only the types of the initial arguments that are provided are considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are ignored, likeintvs.longon ILP32 targets. Likewise, type qualifiers are ignored. The function typevoid (*) (void)is special and matches everything, which can be used to suppress this warning. In a cast involving pointer to member types, this warning warns whenever the type cast is changing the pointer to member type. This warning is enabled by-Wextra. Thevoid (*) (void)being the universal bestie is so real. ๐ซถ-Wwrite-stringsโ when compiling C, this gives string constants the typeconst char[length], so that copying the address of one into a non-constchar *pointer produces a warning. These warnings help you find, at compile time, code that can try to write into a string constant โ but only if you have been very careful about usingconstin declarations and prototypes. Otherwise it's just a nuisance. That's literally why-Walldoesn't request these warnings. ๐ญ
When compiling C++, it warns about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs. C++ said "we handle this ourselves, thanks." โจ
-Wclobberedโ warns for variables that might be changed bylongjmporvfork. This warning is also enabled by-Wextra. Those variables are living dangerously and GCC is concerned. ๐ซฃ-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 disable that with-Wno-complain-wrong-lang, which is mostly useful when you're invoking a single compiler driver for multiple source files written in different languages. For example:
$ g++ -fno-rtti a.cc b.f90
The driver g++ invokes the C++ front end to compile a.cc and the Fortran front end to compile b.f90. That latter front end diagnoses:
f951: Warning: command-line option '-fno-rtti' is valid for
C++/D/ObjC++ but not for Fortran
...which may be disabled with -Wno-complain-wrong-lang. Not the Fortran front end catching strays. ๐
-Wconversionโ warns for implicit conversions that may alter a value. This includes conversions between real and integer, likeabs (x)whenxisdouble; conversions between signed and unsigned, likeunsigned ui = -1; and conversions to smaller types, likesqrtf (M_PI). It does not warn for explicit casts likeabs ((int) x)andui = (unsigned) -1, or if the value is not changed by the conversion, like inabs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using-Wno-sign-conversion.
For C++, it also warns for confusing overload resolution for user-defined conversions, and conversions that never use a type conversion operator: conversions to void, the same type, a base class, or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.
Warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion. So many layers, so much lore. ๐
-Wdangling-elseโ warns about constructions where there may be confusion about whichifstatement anelsebranch belongs to. Here's an example of such a case:
{
if (a)
if (b)
foo ();
else
bar ();
}
In C/C++, every else branch belongs to the innermost possible if statement โ which, in this example, is if (b). This is often not what the programmer expected, as illustrated above by the indentation the programmer chose. ๐ญ When there's the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. The resulting code looks like this:
{
if (a)
{
if (b)
foo ();
else
bar ();
}
}
This warning is enabled by -Wparentheses. Braces: the friendship bracelets of C. ๐
-Wdangling-pointer/-Wdangling-pointer=nโ okay so this one is literally the dangling pointer detector ๐ It warns about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. That means local variables declared in nested blocks, compound literals and other unnamed temporary objects. Also 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 array a in the following function is out of scope when the pointer s that 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 may be used
strcat (s, ".tmp");
...
}
-Wdangling-pointer=2is included in-Wall.
-Wdate-timeโ Warn when macros"__TIME__","__DATE__"or"__TIMESTAMP__"are encountered, because they might prevent bit-wise-identical reproducible compilations. โฐ fr fr-Wempty-bodyโ Warn if an empty body occurs in an"if","else"or"do while"statement. This warning is also enabled by-Wextra. lowkey useful-Wno-endif-labelsโ Do not warn about stray tokens after"#else"and"#endif". periodt-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. iykyk-Wenum-conversionโ Warn when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by-Wextrain C. ngl-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. bestie
-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-initis included in-Wc++-compat. It can be disabled with the-Wno-jump-misses-initoption. no cap-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. fr-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. slay-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. obsessed-Wno-scalar-storage-orderโ Do not warn on suspicious constructs involving reverse scalar storage order. okay-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. ate
-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. bestie-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-memaccessalso 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. iykyk
-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. periodt-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. fr fr-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. no cap-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. bestie
-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. lowkey-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) { ... }
obsessed
-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) { ... }
slay
ok so plot twist: you can suppress this warning by wrapping the LHS into parentheses, like this:
if ((!a) > 1) { ... }
And bestie, this warning is enabled by -Wall โ so it's coming along for the ride whether you invited it or not ๐
-Waggregate-returnโ Warn if any functions that return structures or unions are defined or called. (And in languages where you can return an array, that also gets you a warning, jsyk.)-Wno-aggressive-loop-optimizationsโ Warn if, in a loop with a constant number of iterations, the compiler detects undefined behavior in some statement during one or more of the iterations.-Wno-attributesโ Do not warn if an unexpected"__attribute__"is used โ like unrecognized attributes, function attributes slapped onto variables, etc. Heads up though: this does not stop errors for incorrect use of supported attributes.
Also, with -Wno-attributes=, you can suppress 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();
You can also kill the warning for all attributes in a namespace by writing -Wno-attributes=vendor::, which prevents warnings about both of these declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Note that-Wno-attributes=does not imply-Wno-attributes. Two different things, no cap.
-Wno-builtin-declaration-mismatchโ Warn if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that doesn't include a prototype is called with arguments whose promoted types don't match what the function expects. When-Wextrais specified, it also warns when a built-in function that takes arguments is declared without a prototype. The-Wbuiltin-declaration-mismatchwarning is enabled by default. To dodge the warning, include the appropriate header so the prototypes of built-in functions come into scope ๐ซถ
For example, the call to memset below gets diagnosed by the warning because the function expects a value of type size_t as its argument, but the type of 32 is int. With -Wextra, the declaration of the function gets diagnosed too.
extern void* memset ();
void f (void *d)
{
memset (d, '\0', 32);
}
-Wno-builtin-macro-redefinedโ Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of__TIMESTAMP__,__TIME__,__DATE__,__FILE__, and__BASE_FILE__.-Wstrict-prototypes(C and Objective-C only) โ Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is allowed with no warning if it's preceded by a declaration that specifies the argument types. cute little exception โจ)-Wold-style-declaration(C and Objective-C only) โ Warn for obsolescent usages, per the C Standard, in a declaration. For example, warn if storage-class specifiers likestaticaren't the first things in a declaration. This warning is also enabled by-Wextra.-Wold-style-definition(C and Objective-C only) โ Warn if an old-style function definition is used. You get a warning even if there's a previous prototype. A definition using()is not considered an old-style definition in C2X mode, because it's equivalent to(void)in that case โ but it is considered an old-style definition for older standards.-Wmissing-parameter-type(C and Objective-C only) โ A function parameter is declared without a type specifier in K&R-style functions:
void foo(bar) { }
This warning is also enabled by -Wextra.
-Wmissing-prototypes(C and Objective-C only) โ Warn if a global function is defined without a previous prototype declaration. This warning fires even if the definition itself provides a prototype. Use this option to detect global functions that don't have a matching prototype declaration in a header file. This option is not valid for C++ because all function declarations provide prototypes, and a non-matching declaration declares an overload rather than conflicting with an earlier declaration. Use-Wmissing-declarationsto detect missing declarations in C++.-Wmissing-declarationsโ Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that aren't declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations โ use-Wmissing-prototypesto detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces.-Wmissing-field-initializersโ Warn if a structure's initializer has some fields missing. For example, this code causes such a warning, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so this lil modification doesn't trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
In C, this option does not warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
Likewise, in C++ this option does not warn about the empty { } initializer, for example:
struct s { int f, g, h; };
s x = { };
This warning is included in -Wextra. To get 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 appearing as a C++20 simple-requirement:
bool satisfied = requires { C<T> };
Here satisfied will be true if C<T> is a valid expression, which it is for all T. Presumably the user meant to write
bool satisfied = requires { requires C<T> };
so satisfied is only true if concept C is satisfied for type T.
This warning can be disabled with -Wno-missing-requires.
-Wno-missing-template-keywordโ The member access tokens.,->and::must be followed by the"template"keyword if the parent object is dependent and the member being named is a template.
template <class X>
void DoStuff (X x)
{
x.template DoSomeOtherStuff<X>(); // Good.
x.DoMoreStuff<X>(); // Warning, x is dependent.
}
In rare cases it's possible to get false positives ๐ญ To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:
void NotATemplate (my_class t)
{
int N = 5;
bool test = t.m < N > (0); // Treated as a template.
test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}
This warning can be disabled with -Wno-missing-template-keyword.
-Wno-multicharโ Do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, since they have implementation-defined values, and they should not be used in portable code. ๐ฉ-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 character set are used, you can have two different character sequences that look the same ๐ To avoid confusion, the ISO 10646 standard sets out some normalization rules which, when applied, ensure that two sequences that look the same get turned into the same sequence. GCC can warn you if you're using identifiers that haven't been normalized, and this option controls that warning.
There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It's equivalent to -Wnormalized.
Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It's hoped that future versions of the standards involved will correct this, which is why this option isn't 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 ๐
Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance, "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that's been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code isn't in NFKC when you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, so it's not the default โ but it may be useful as a local coding convention if the programming environment can't be fixed to display these characters distinctly.
-Wno-attribute-warningโ Do not warn about usage of functions declared with the"warning"attribute. By default, this warning is enabled.-Wno-attribute-warningcan be used to disable the warning, or-Wno-error=attribute-warningcan be used to disable the error when compiled with the-Werrorflag.-Wno-deprecatedโ Do not warn about usage of deprecated features.-Wno-deprecated-declarationsโ Do not warn about uses of functions, variables, and types marked as deprecated by using the"deprecated"attribute.-Wno-overflowโ Do not warn about compile-time overflow in constant expressions.
-Wno-odrโ bestie, this one yells at you about One Definition Rule violations when link-time optimization is doing its thing โจ. It's enabled by default, so it's just out here doing the most for you already.-Wopenacc-parallelismโ warns you when your OpenACC parallelism choices are giving "potentially suboptimal" ๐. Not wrong, justโฆ not the vibe you were going for.-Wopenmp-simdโ warns if the vectorizer cost model overrides the OpenMP simd directive you set, because rude ๐. If you wanna loosen that cost model up, the-fsimd-cost-model=unlimitedoption is right there.-Woverride-init(C and Objective-C only) โ warns when an initialized field without side effects gets overridden while you're using designated initializers. This one is part of-Wextra๐ซถ. Want all the other-Wextrawarnings but not this one? Do-Wextra -Wno-override-initand you're golden.-Wno-override-init-side-effects(C and Objective-C only) โ the opposite energy: don't warn when an initialized field with side effects gets overridden during designated initializers. Enabled by default, no cap.-Wpackedโ warns when a structure gets the packed attribute but that attribute literally does nothing to the layout or size ๐. Structures like that can end up mis-aligned for basically zero benefit. Example: here the variablef.xinsidestruct baris misaligned, even thoughstruct baritself has no packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compatโ story time ๐: the 4.1, 4.2 and 4.3 series of GCC ignore thepackedattribute on bit-fields of typechar. GCC 4.4 fixed that, but the fix can change your structure layout. So GCC tells you when the offset of such a field changed in GCC 4.4. Like, there's no longer a 4-bit padding between fieldaandbin this structure:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
Enabled by default โจ. Use -Wno-packed-bitfield-compat if you wanna silence it.
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warns when a structure field with explicitly specified alignment inside a packed struct or union ends up misaligned ๐ญ. Example: you'd get a warning onstruct S, likewarning: 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 warning is enabled by -Wall ๐
.
-Wpaddedโ warns when padding sneaks into a structure, either to align one element or to align the whole thing ๐ธ. And lowkey? Sometimes when that happens you can shuffle the fields around to shrink the padding and make the whole structure smaller. Free wins.-Wredundant-declsโ warns if anything is declared more than once in the same scope, even in cases where the multiple declaration is valid and changes absolutely nothing ๐.-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: the call tostrcpybelow is trying to truncate the string by replacing its initial characters with the last four. But because the call writes the terminating NUL intoa[4], the copies overlap, and the call gets diagnosed:
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
The -Wrestrict option catches some instances of simple overlap even with no optimization, but it works best at -O2 and above โจ. It's included in -Wall.
-Wnested-externs(C and Objective-C only) โ warns if anexterndeclaration shows up inside a function. Nested. In a function. Girl. ๐ญ-Winlineโ warns when a function declared as inline can't actually be inlined ๐ฆ. Even with this option on, the compiler stays quiet about failures to inline functions declared in system headers.
The compiler uses a whole bunch of heuristics to decide whether to inline a function. For example, it considers the size of the function being inlined and how much inlining has already happened in the current function. So, like, seemingly tiny changes in your source program can make -Winline warnings appear or vanish. Chaos, honestly.
-Winterference-sizeโ warns about using C++17std::hardware_destructive_interference_sizewithout specifying its value via--param destructive-interference-sizeโญ. It also warns about questionable values for that option.
This variable is meant to control class layout, to avoid false sharing in concurrent code:
struct independent_fields {
alignas(std::hardware_destructive_interference_size)
std::atomic<int> one;
alignas(std::hardware_destructive_interference_size)
std::atomic<int> two;
};
Here one and two are meant to be far enough apart that stores to one won't need to go reload the other's 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, and sometimes a range if you're tuning for a generic target. So every translation unit that depends on ABI compatibility for these variables must be compiled with the same -mtune (or -mcpu). No cap.
If ABI stability matters to you โ like, if this is used in a header for a library โ you should probably just not use the hardware interference size variables at all ๐. Alternatively, you can force a particular value with --param.
And if you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can turn the warning off with -Wno-interference-size ๐.
-Wint-in-bool-contextโ warns about suspicious use of integer values where boolean values are expected ๐. Like conditional expressions (?:) using non-boolean integer constants in a boolean context, e.g.if (a <= b ? 2 : 3). Or left shifting signed integers in boolean context, likefor (a = 0; 1 << a; a++);. Same energy for all kinds of multiplications regardless of data type. This warning is enabled by-Wallโจ.-Wno-int-to-pointer-castโ suppresses warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error ๐.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 found in the search path but can't actually be used ๐ญ. So close, and yet.-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โ don't diagnose invalid forms of delimited or named escape sequences that are treated as separate tokens.Wunicodeis enabled by default ๐.-Wlong-longโ warns if thelong longtype is used. This gets enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. Wanna mute it? Use-Wno-long-long๐ .-Wvariadic-macrosโ warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode ๐ธ. Enabled by either-Wpedanticor-Wtraditional. To silence it, use-Wno-variadic-macros.-Wno-varargsโ don't warn about 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 architecture's SIMD capabilities โญ. Mainly useful for performance tuning. A vector operation can be implemented:- "piecewise" โ the scalar operation is performed on every vector element;
- "in parallel" โ the vector operation is implemented using scalars of a wider type, which is normally more performance efficient;
- "as a single scalar" โ the vector fits into a scalar type.
-Wvlaโ warns if a variable-length array is used in the code. And-Wno-vlaprevents the-Wpedanticwarning about the variable-length array ๐.- *
-Wvla-larger-than=byte-size* โ with this option on, the compiler warns about declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that would let the array size exceedbyte-sizebytes ๐ฑ. It's similar to how-Walloca-larger-than=byte-sizeworks, except, you know, with variable-length arrays.
Heads up: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning might not even trigger for those ๐.
-Wvla-larger-than=PTRDIFF_MAX is enabled by default, but it's typically only effective when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=byte-size.
-Wno-vla-larger-thanโ disables the-Wvla-larger-than=warnings. This option is equivalent to-Wvla-larger-than=SIZE_MAXor larger ๐.-Wvla-parameterโ warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enables the 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 the maximum number of elements, may get diagnosed ๐.
okay bestie so like, the warning pops off for these redeclarations because the first one is giving "any size array can come through to f" energy while the second one is out here demanding the array argument have at least n elements. and like, calling f with the VLA bound parameter in excess of the actual VLA bound? yeah that triggers a warning too. ๐
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 is included in -Wall, no cap. and if you've got the same kinda chaos but with plain old array arguments instead of VLAs, that's -Warray-parameter's whole job. โจ
-Wvolatile-register-varโ warns when a register variable is declaredvolatile. like, plot twist: thatvolatilemodifier does NOT inhibit all the optimizations that could eliminate reads and/or writes to register variables. so it's not the safety blanket you think it is, bestie. ๐ซถ this warning is enabled by-Wall.-Wxor-used-as-pow(C, C++, Objective-C and Objective-C++ only) โ warns about uses of^, the exclusive or operator, where it's giving "the user thought this was exponentiation." specifically, the warning happens when the left-hand side is the decimal constant2or10and the right-hand side is also a decimal constant.
so the tea is: in C and C++, ^ means exclusive or, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. so if you came from TeX or BASIC, this one's for you. ๐
this warning is enabled by default. it can be silenced by converting one of the operands to hexadecimal. iconic little escape hatch.
-Wdisabled-optimizationโ warns if a requested optimization pass is disabled. and like, this does not generally indicate that there is anything wrong with your code, bestie โ it merely indicates that GCC's optimizers are unable to handle the code effectively. usually the problem is that your code is too big or too complex. GCC straight up refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time. it's not judging you, it's just protecting its peace. ๐ญ-Wpointer-sign(C and Objective-C only) โ warns for pointer argument passing or assignment with different signedness. this option is only supported for C and Objective-C. it's implied by-Walland by-Wpedantic, which can be disabled with-Wno-pointer-sign.-Wstack-protectorโ this one is only active when-fstack-protectoris active. it warns about functions that are not protected against stack smashing. ๐ก๏ธ-Woverlength-stringsโ warns about string constants that are longer than the "minimum maximum" length specified in the C standard. modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings. no cap, that's the vibe.
the limit applies after string constant concatenation, and it does not count the trailing NUL. in C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++. so C++ girlies, you're free. ๐ฆ
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 does not have a suffix. when used together with-Wsystem-headersit warns about such constants in system header files. this can be useful when preparing code to use with theFLOAT_CONST_DECIMAL64pragma from the decimal floating-point extension to C99. very niche, very valid. โจ-Wno-lto-type-mismatchโ during the link-time optimization, do not warn about type mismatches in global declarations from different compilation units. requires-fltoto be enabled. enabled by default.-Wno-designated-init(C and Objective-C only) โ suppresses warnings when a positional initializer is used to initialize a structure that has been marked with thedesignated_initattribute. okay periodt, sometimes you just wanna init the old way. ๐
๐ง Options That Control Static Analysis ๐ง
okay so this is where things get serious, bestie. like, actual detective work on your code. ๐
-fanalyzerโ this option enables a static analysis of program flow which looks for "interesting" interprocedural paths through the code, and issues warnings for problems found on them. it's giving main character energy for real.
heads up: this analysis is much more expensive than other GCC warnings. like, your compile time is gonna feel it.
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 come for it when it's wrong, it never claimed to be perfect. ๐
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. so if it's not there, that's why bestie. ๐ญ
-Wanalyzer-too-complexโ if-fanalyzeris enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. like, your code is just too much for it to handle. ๐
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 now you'll actually know when it gave up on you.
-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). math girlies, check your math. ๐ฅ
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. like bestie, you closed the barn door after the horse left. ๐
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.
ngl 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. so if you're trying to catch it, turn the optimizations off. periodt.
-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. closing the same file twice? not the vibe. ๐ญ
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. freeing twice is giving chaos, bestie. ๐
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). bestie. bestie no. ๐จ
see CWE-532: Information Exposure Through Log Files (https://cwe.mitre.org/data/definitions/532.html).
-Wanalyzer-exposure-through-uninit-copyโ this warning requires both-fanalyzerand the use of a plugin to specify a function that copies across a "trust boundary". use-Wno-analyzer-exposure-through-uninit-copyto disable it.
this diagnostic warns for "infoleaks" โ paths through the code in which uninitialized values are copied across a security boundary (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. like, you can't read a write-only file bestie, it literally says so in the name. ๐
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โ okay so this one needs-fanalyzerto even exist, because that's what turns it on in the first place; use-Wno-analyzer-fd-double-closeto turn it back off. ๐ซถ
It flags paths through your code where a file descriptor can get closed more than once โ like bestie, it's already gone, let it rest. ๐ญ
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-fd-leakโ needs-fanalyzer(it's enabled by it); use-Wno-analyzer-fd-leakto disable. โจ
This one warns for paths through code where an open file descriptor is leaked โ never closed, just vibing out there 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; use-Wno-analyzer-fd-phase-mismatchto disable it. ๐
Warns for paths through code where an operation is attempted in the wrong phase of a file descriptor's lifetime. Like for example it'll call out attempts to call accept on a stream socket that hasn't had listen successfully called on it yet. Not the moment, bestie, read the room. ๐
See CWE-666: Operation on Resource in Wrong Phase of Lifetime (https://cwe.mitre.org/data/definitions/666.html).
-Wno-analyzer-fd-type-mismatchโ needs-fanalyzer; use-Wno-analyzer-fd-type-mismatchto disable. ๐ธ
Warns for paths through code where an operation is attempted on the wrong type of file descriptor. Example: it'll warn on attempts to use socket operations on a file descriptor obtained via open, or when you're trying to use a stream socket operation on a datagram socket. it's giving mismatched energy fr fr. ๐
-Wno-analyzer-fd-use-after-closeโ needs-fanalyzer; use-Wno-analyzer-fd-use-after-closeto disable it. ๐
Warns for paths through code where a read or write is called on a closed file descriptor. (not me reading from a ghost ๐ญ)
It also warns for paths through code where 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โ needs-fanalyzer; use-Wno-analyzer-fd-use-without-checkto disable. โญ
Warns for paths through code where a file descriptor is used without being checked for validity. like girl, check first!!
It also warns for paths through code where 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; use-Wno-analyzer-file-leakto disable. ๐
Warns for paths through the code where a <stdio.h> FILE * stream object is leaked. the stream just wandered off into the void, iconic but illegal. ๐ฆ
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โ needs-fanalyzer; use-Wno-analyzer-free-of-non-heapto disable it. ๐
Warns for paths through the code where free is called on a non-heap pointer โ e.g. an on-stack buffer, or a global. ma'am you cannot free the stack, that is NOT its journey. ๐ญ
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; use-Wno-analyzer-imprecise-fp-arithmeticto disable. โจ
Warns for paths through the code where floating-point arithmetic is used in locations where precise computation is needed. Heads up tho: at the moment this diagnostic only warns on use of floating-point operands inside the calculation of an allocation size. that's it, that's the whole scope. ๐ฏ
-Wno-analyzer-infinite-recursionโ needs-fanalyzer; use-Wno-analyzer-infinite-recursionto disable it. ๐
Warns for paths through the code which appear to lead to infinite recursion. the call stack said "no thoughts, just loops". ๐
Specifically: 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 thus suppress the warning.
Real talk bestie: this diagnostic is likely to miss cases of infinite recursion that are converted to iteration by the optimizer before the analyzer sees them. So if you're trying to trigger it, disable optimization. ๐
Compare with -Winfinite-recursion, which provides a similar diagnostic, but is implemented in a different way. (same vibe, different lore โจ)
-Wno-analyzer-jump-through-nullโ needs-fanalyzer; use-Wno-analyzer-jump-through-nullto disable it. ๐
Warns for paths through the code where a NULL function pointer is called. yeah that pointer is giving absolutely nothing. ๐
-Wno-analyzer-malloc-leakโ needs-fanalyzer; use-Wno-analyzer-malloc-leakto disable. ๐ฅ
Warns for paths through the code where a pointer allocated via an allocator is leaked โ either malloc, or a function marked with attribute malloc. the memory said "I'll find my way home" and then did not. ๐ญ
See CWE-401: Missing Release of Memory after Effective Lifetime (https://cwe.mitre.org/data/definitions/401.html).
-Wno-analyzer-mismatching-deallocationโ needs-fanalyzer; use-Wno-analyzer-mismatching-deallocationto disable it. ๐
Warns for paths through the code where the wrong deallocation function is called on a pointer value, based on which function was used to allocate the pointer value. The diagnostic will warn about mismatches between free, scalar delete and vector delete[], and those marked as allocator/deallocator pairs using attribute malloc. it's giving "you are not her, stop trying to free her" energy. ๐
See CWE-762: Mismatched Memory Management Routines (https://cwe.mitre.org/data/definitions/762.html).
-Wno-analyzer-out-of-boundsโ needs-fanalyzer; use-Wno-analyzer-out-of-boundsto disable it. ๐ธ
Warns for paths through the code where a buffer is definitely read or written out-of-bounds. This diagnostic applies for cases where the analyzer is able to determine a constant offset and for accesses past the end of a buffer, also a constant capacity. Further, the diagnostic does limited checking for accesses past the end when the offset as well as the capacity is symbolic.
See CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer (https://cwe.mitre.org/data/definitions/119.html).
-Wno-analyzer-possible-null-argumentโ needs-fanalyzer; use-Wno-analyzer-possible-null-argumentto disable it. โญ
Warns for paths through the code where a possibly-NULL value is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. the attribute said "no NULLs allowed" and you brought a maybe-NULL. awkward. ๐ฌ
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; use-Wno-analyzer-possible-null-dereferenceto disable. ๐ฆ
Warns for paths through the code where a possibly-NULL value is dereferenced.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-null-argumentโ needs-fanalyzer; use-Wno-analyzer-null-argumentto disable it. ๐
Warns for paths through the code where a value known to be NULL is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. no more "possibly" โ we KNOW. ๐
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-null-dereferenceโ needs-fanalyzer; use-Wno-analyzer-null-dereferenceto disable it. ๐
Warns for paths through the code where a value known to be NULL is dereferenced. straight up nothing there, bestie. ๐ญ
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-putenv-of-auto-varโ needs-fanalyzer; use-Wno-analyzer-putenv-of-auto-varto disable it. ๐
Warns for paths through the code where a call to putenv is passed a pointer to an automatic variable or an on-stack buffer. that variable is gonna leave the function and never come back, and you gave its address away. ๐ซ
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; use-Wno-analyzer-shift-count-negativeto disable it. โจ
Warns for paths through the code where a shift is attempted with a negative count. It's analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but is implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. However โ heads up โ the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. ๐ซถ
-Wno-analyzer-shift-count-overflowโ needs-fanalyzer; use-Wno-analyzer-shift-count-overflowto disable it. ๐
This diagnostic is like, yelling at you for paths through the code where a shift is attempted with a count greater than or equal to the precision of the operand's type. It's giving -Wshift-count-overflow, the one the C/C++ front ends have, except this one is built on analyzing interprocedural paths instead of just vibing with the syntax tree. But โ and this is the tea โ the analyzer does not prioritize detection of these paths, so false negatives are more likely compared to other warnings. ๐
-Wno-analyzer-stale-setjmp-bufferโ okay so this warning needs-fanalyzerto turn it on in the first place, and you use-Wno-analyzer-stale-setjmp-bufferto turn it back off ๐
It flags paths through the code where longjmp is called to rewind to a jmp_buf that belongs to a setjmp call in a function that has already returned. ๐ญ
Here's the deal: when setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. And that stack frame becomes invalid the moment the function containing the setjmp call returns. So trying to rewind to it via longjmp? That's referencing a stack frame that does not exist anymore, and it'll likely lead to a crash. Or worse. ๐
-Wno-analyzer-tainted-allocation-sizeโ bestie this one needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-allocation-sizeโจ
It warns for paths through the code where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized. Which means 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โ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-assertion๐
It warns for paths through the code where a value that could be under an attacker's control gets used as part of a condition without being sanitized first, and that condition guards a call to a function marked with attribute noreturn (like the function __builtin_unreachable). Those functions typically mean the program is terminating abnormally, like for assertion failure handlers. For example:
assert (some_tainted_value < SOME_LIMIT);
In such cases:
- when assertion-checking is enabled: an attacker could trigger a denial of service by injecting an assertion failure ๐
- when assertion-checking is disabled, like by defining
NDEBUG, an attacker could inject data that subverts the process, since it presumably violates a precondition that is being assumed by the code. ๐ญ
Heads up though: when assertion-checking is disabled, the assertions are typically removed by the preprocessor before the analyzer even gets a chance to "see" them, so this diagnostic can only generate warnings on builds where assertion-checking is enabled. no cap.
For the purpose of this warning, any function marked with attribute noreturn counts as a possible assertion failure handler, including __builtin_unreachable. And ngl, those functions are sometimes removed by the optimizer before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic. periodt.
See CWE-617: Reachable Assertion (https://cwe.mitre.org/data/definitions/617.html).
The warning can also report problematic constructions such as
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โ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-array-index๐ฆ
It warns for paths through the code where a value that could be under an attacker's control gets used as the index of an array access without being sanitized, so an attacker could inject an out-of-bounds access. ๐
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).
-Wno-analyzer-tainted-divisorโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-divisor๐ธ
It warns for paths through the code where a value that could be under an attacker's control gets used as the divisor in a division or modulus operation without being sanitized, so an attacker could inject a division-by-zero. ๐ญ
See CWE-369: Divide By Zero (https://cwe.mitre.org/data/definitions/369.html).
-Wno-analyzer-tainted-offsetโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-offset๐
It warns for paths through the code where a value that could be under an attacker's control gets used as a pointer offset without being sanitized, so an attacker could inject an out-of-bounds access. ๐
See CWE-823: Use of Out-of-range Pointer Offset (https://cwe.mitre.org/data/definitions/823.html).
-Wno-analyzer-tainted-sizeโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; disable it with-Wno-analyzer-tainted-size๐ง
It warns for paths through the code where a value that could be under an attacker's control gets 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 warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-unsafe-call-within-signal-handler๐
It warns for paths through the code where a function known to be async-signal-unsafe (such as fprintf) gets called from a signal handler. like. bestie. why. ๐ญ
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 warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-use-after-free๐
It warns for paths through the code where a pointer gets used after a deallocator was 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 warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-use-of-pointer-in-stale-stack-frame๐
It warns for paths through the code where a pointer gets dereferenced that points to a variable in a stale stack frame. ๐ญ
-Wno-analyzer-va-arg-type-mismatchโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-va-arg-type-mismatchโจ
It warns for interprocedural paths through the code where the analyzer detects an attempt to use va_arg to extract a value passed to a variadic call, but it uses a type that does not match the type of the expression passed to the call. ๐
See CWE-686: Function Call With Incorrect Argument Type (https://cwe.mitre.org/data/definitions/686.html).
-Wno-analyzer-va-list-exhaustedโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-va-list-exhausted๐
It warns for interprocedural paths through the code where the analyzer detects an attempt to use va_arg to access the next value passed to a variadic call, but all of the values in the va_list have already been consumed. rip. ๐
See CWE-685: Function Call With Incorrect Number of Arguments (https://cwe.mitre.org/data/definitions/685.html).
-Wno-analyzer-va-list-leakโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-va-list-leak๐ฆ
It warns for interprocedural paths through the code where the analyzer detects that va_start or va_copy has been called on a va_list without a corresponding call to va_end. ๐ญ
-Wno-analyzer-va-list-use-after-va-endโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-va-list-use-after-va-end๐ธ
It warns for interprocedural paths through the code where the analyzer detects an attempt to use a va_list after va_end has been called on it. va_list. ๐
-Wno-analyzer-write-to-constโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-write-to-const๐
It warns for paths through the code where the analyzer detects an attempt to write through a pointer to a const object. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. ๐
-Wno-analyzer-write-to-string-literalโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-write-to-string-literal๐ง
It warns for paths through the code where the analyzer detects an attempt to write through a pointer to a string literal. But again โ the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. ๐
-Wno-analyzer-use-of-uninitialized-valueโ this warning requires-fanalyzer, which enables it; disable it with-Wno-analyzer-use-of-uninitialized-value๐
It warns for paths through the code where an uninitialized value is used. ๐ญ
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: ๐ซถ
"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" "calloc""free""malloc""memset""operator delete""operator delete []""operator new""operator new []""realloc""strdup""strndup"
and bestie, the functions it's got a whole situationship with for working with file descriptors? these ones:
"open""close""creat""dup","dup2"and"dup3""isatty""pipe", and"pipe2""read""write""socket","bind","listen","accept", and"connect"
and the ones for working with <stdio.h> streams, periodt:
- 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" "fopen""fclose""ferror""fgets""fgets_unlocked""fileno""fread""getc""getchar""fprintf""printf""fwrite"
and last but never least, these 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
"error"and"error_at_line" "getpass""longjmp""putenv""setjmp""siglongjmp""signal""sigsetjmp""strchr""strlen"
okay and bonus round ๐ โ various functions rockin' an __analyzer_ prefix have special meaning to the analyzer, and that whole thing is described in the GCC Internals manual. iykyk.
The pertinent parameters for controlling the exploration are, no cap:
--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 โจ
-fanalyzer-call-summariesโ this one simplifies the interprocedural analysis by computing the effect of certain calls, instead of exploring every single path through the function from callsite to each possible return. way less chaotic ๐
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โ restricts the analyzer to run just the named checker, and enables it. focused. laser. singular.
Some checkers are disabled by default (even with -fanalyzer), such as the "taint" checker that implements -Wanalyzer-tainted-array-index, and this option is required to enable them. like, you literally have to ask.
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โ okay so 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. one statement, one edge, no sharing, boundaries babe ๐
-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. it's giving receipts for the ones it threw away ๐ซถ-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. nothing gets deleted on your watch bestie ๐
-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. it's protecting you from the doom spiral ๐ญ
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. the transitive property said hi โจ-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. the frames are lowkey lying to you ๐
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. extra. chatty. detailed. ๐ฆ-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-"free"diagnostic, both calls to"free"will be shown. both of them. caught in 4k. ๐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. the main character level, if you will ๐
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 tostderr. 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. aesthetically organized, as it should be ๐-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. like, a LOT of files. prepare yourself. ๐ญ-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 whole compressed JSON representation of the analyzer's internals intofile.analyzer.json.gz. heads up tho: the precise format is subject to change, so don't go hardcoding your whole life around it ๐ญ-fdump-analyzer-state-purgeโ literally 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 goes tofile.state-purge.dot. cute, informative, slay ๐-fdump-analyzer-supergraphโ dumps representations of the "supergraph" suitable for viewing with GraphViz intofile.supergraph.dotandfile.supergraph-eg.dot. these show, like, all of the control flow graphs in the program, with interprocedural edges for calls and returns. the second dump has annotations showing nodes in the "exploded graph" plus the diagnostics associated with them. iconic behavior fr fr ๐-fdump-analyzer-untrackedโ emits custom warnings with internal details, and those are intended for analyzer developers. iykyk ๐
๐โจ Options for Debugging Your Program โจ๐
okay so bestie, if you want GCC to emit extra info for a debugger to snack on, in almost all cases you just add -g to your other options and call it a day. some debug formats can co-exist (like DWARF hanging out with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options ๐ซถ
GCC lets you use -g together with -O. the shortcuts taken by optimized code may occasionally be surprising, and i'm gonna be real with you:
- some variables you declared may not exist at all ๐
- flow of control may briefly move where you did not expect it
- some statements may not be executed because they compute constant results or their values are already at hand
- some statements may execute in different places because they have been moved out of loops
nevertheless it is possible to debug optimized output. this makes it reasonable to use the optimizer for programs that might have bugs. no cap.
if you're not using some other optimization option, consider using -Og with -g. with no -O option at all, some compiler passes that collect info useful for debugging do not run at all, so -Og may result in a better debugging experience. the way that's just good advice ๐ธ
-gโ produce debugging information in the operating system's native format (stabs,COFF,XCOFF, orDWARF). GDB can work with this debugging information.
on most systems that use stabs format, -g enables use of extra debugging information that only GDB can use. this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program ๐ญ if you want to control for certain whether to generate the extra information, use -gvms (see below).
-ggdbโ produce 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. giving main character energy to your debugger โจ-gdwarf,-gdwarf-versionโ produce 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. it's giving "legacy naming, we don't talk about it" ๐
-gbtfโ request 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. besties coexisting ๐ซถ-gctf,-gctflevelโ request CTF debug information and use 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
0produces no CTF debug information at all. thus,-gctf0negates-gctf. - Level
1produces CTF information for tracebacks only. this includes callsite information, but does not include type information. - Level
2produces type information for entities (functions, data objects etc.) at file-scope or global-scope only.
-gvmsโ produce debugging information in Alpha/VMS debug format (if that is supported). this is the format used byDEBUGon Alpha/VMS systems.-glevel,-ggdblevel,-gvmslevelโ request debugging information and also use level to specify how much information. the default level is2.- Level
0produces no debug information at all. thus,-g0negates-g. - Level
1produces 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
3includes extra information, such as all the macro definitions present in the program. some debuggers support macro expansion when you use-g3.
- Level
if you use multiple -g options, with or without level numbers, the last such option is the one that is effective. last one wins, periodt ๐
-gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. instead use an additional -glevel option to change the debug level for DWARF. don't try to be clever bestie, it will not work ๐
-fno-eliminate-unused-debug-symbolsโ by default, no debug information is produced for symbols that are not actually used. use this option if you want debug information for all symbols.-femit-class-debug-alwaysโ instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class. this option should be used only with debuggers that are unable to handle the way GCC normally emits debugging information for classes, because using this option increases the size of debugging information by as much as a factor of two ๐ญ that's a lot of bytes, girl-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.-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. very "path glow-up" of you โจ-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.
-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.
-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. girlboss split ๐-gdwarf32,-gdwarf64โ if DWARF debugging information is enabled,-gdwarf32selects the 32-bit DWARF format and-gdwarf64selects the 64-bit DWARF format. the default is target specific, on most targets it is-gdwarf32though. the 32-bit DWARF format is smaller, but can't support more than2GiBof debug information in any of the DWARF debug information sections. the 64-bit DWARF format allows larger debug information and might not be well supported by all consumers yet ๐ฌ-gdescribe-diesโ add description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. very "give the unnamed ones a lil name tag" ๐-gpubnamesโ generate DWARF.debug_pubnamesand.debug_pubtypessections.-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.-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's giving "sometimes the upgrade is a downgrade"-grecord-gcc-switches/-gno-record-gcc-switchesโ ok so this one takes the command-line options you used to invoke the compiler (the ones that may affect code generation, obviously) and appends them to theDW_AT_producerattribute inside your DWARF debugging info ๐. They get concatenated together, spaces between each other and between them and the compiler version. It's enabled by default btw. Also peep-frecord-gcc-switchesif you want another way to stash compiler options into the object file ๐-gstrict-dwarfโ disallows using extensions of a later DWARF standard version than whatever you picked with-gdwarf-version. Like, stay in your lane bestie. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed, but this shuts that down.-gno-strict-dwarfโ the opposite vibe: allow using extensions of later DWARF standard versions than the one selected with-gdwarf-versionโจ-gas-loc-supportโ tells the compiler that the assembler supports".loc"directives. Then it may use them so the assembler generates DWARF2+ line number tables for it ๐. This is generally desirable because assembler-generated line-number tables are a lot more compact than the ones the compiler can make by itself. This option gets enabled by default if, at GCC configure time, the assembler was found to support those directives.-gno-as-loc-supportโ forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are going to be generated at all.-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, if-gvariable-location-viewsis explicitly requested.-gcolumn-info/-gno-column-infoโ emit location column information into DWARF debugging info instead of just file and line. Not me being extra, it's enabled by default ๐ฆ-gstatement-frontiers/-gno-statement-frontiersโ makes GCC drop markers into the internal representation at the beginning of statements, and keep them roughly in place throughout compilation, using them to guide the output of"is_stmt"markers in the line number table โจ. Enabled by default when compiling with optimization (-Os,-O1,-O2, ...) and outputting DWARF 2 debug information at the normal level.-gvariable-location-views/-gvariable-location-views=incompat5/-gno-variable-location-viewsโ augments variable location lists with progressive view numbers implied from the line number table. This lets debug info consumers inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point ๐. If the assembler lacks support for view numbers in line number tables, this makes the compiler emit the line number table, which generally makes them somewhat less compact. The augmented line number tables and location lists are fully backward-compatible, so debug info consumers that aren't aware of these augmentations can still consume them โ they just won't get any benefit from them either ๐
Enabled by default when outputting DWARF 2 debug info at the normal level, as long as there's assembler support, -fvar-tracking-assignments is enabled, and -gstrict-dwarf is not. When assembler support is not available, it may still be enabled, but it forces GCC to output internal line number tables, and if -ginternal-reset-location-views is not enabled, that will most certainly lead to silently mismatching location views ๐
There's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, and you turn it on with -gvariable-location-views=incompat5. Heads up: this option may be removed in the future, it's only provided as a reference implementation of the proposed representation. Debug info consumers aren't expected to support this extended format, and they'd be rendered unable to decode location lists using it ๐ญ
-ginternal-reset-location-views/-gno-internal-reset-location-viewsโ attempts to determine location views that can be omitted from location view lists. This requires the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when 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 that address and view numbers can be computed and output in debug info. This can be enabled independently of location views โ in which case the view numbers won't be output โ but it can only be enabled along with statement frontiers, and it's only enabled by default if location views are enabled ๐ธ-gz[=type]โ produce compressed debug sections in DWARF format, if that's supported. If type isn't given, the default type depends on the capabilities of the assembler and linker used. type may be one ofnone(don't compress debug sections), orzlib(use zlib compression in ELF gABI format). If the linker doesn't support writing compressed debug sections, the option is rejected. Otherwise, if the assembler doesn't support them,-gzis silently ignored when producing object files.-femit-struct-debug-baseonlyโ emit 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 one substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger ๐ฌ. Check -femit-struct-debug-reduced for a less aggressive option. Check -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF debug output.
-femit-struct-debug-reducedโ emit 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 type is defined โ unless the struct is a template or defined in a system header. This significantly reduces the size of debugging information, with some potential loss in type information to the debugger. Check-femit-struct-debug-baseonlyfor a more aggressive option. Check-femit-struct-debug-detailedfor more detailed control โจ
This option works only with DWARF debug output.
-femit-struct-debug-detailed[=spec-list]โ specify the struct-like types for which the compiler generates debug info. The intent is to reduce duplicate struct debug info between different object files within the same program ๐
This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serves for most needs.
A specification has the syntax
[dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word limits the specification to structs that are used directly (dir:) or used indirectly (ind:). A struct type is used directly when it is the type of a variable, member. Indirect uses arise through pointers to structs. That is, when use of an incomplete struct is valid, the use is indirect. An example is struct one direct; struct two * indirect;.
The optional second word limits the specification to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed does not 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 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โ emit DWARF unwind info as a compiler generated".eh_frame"section instead of using GAS".cfi_*"directives.-fno-eliminate-unused-debug-typesโ normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are nowhere used in the source file being compiled. Sometimes it's useful to have GCC emit debugging information for all types declared in a compilation unit, regardless of whether or not they're actually used in that compilation unit โ for example if, in the debugger, you want to cast a value to a type that is 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, bestie. It's giving power ๐
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. No cap โจ
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 ๐ญ
The compiler does its optimization thing based on everything it knows about ur program, bestie. And the way it can compile multiple files at once into a single output file? That lets it use deets from all the files when it's compiling each one. It's giving teamwork, it's giving collaborative queen energy. ๐
Not every optimization has a flag controlling it directly, okay? Only the ones with flags get listed here. The rest are just out there doing their thing, mysterious and unbothered. โจ
Most optimizations are completely disabled at -O0 or if no -O level is set on the command line โ even if you specify individual optimization flags! Like, they just don't show up to the party. ๐ Same vibe with -Og: it suppresses a whole bunch of optimization passes too.
Depending on the target and how GCC was configured, the set of optimizations at each -O level might be slightly different from what's listed here. Wanna know the exact set? Run GCC with -Q --help=optimizers and it'll spill all the tea. โ
โจ THE -O LEVELS (the main character energy) ๐
-O-O1โ Optimize, bestie! Optimizing compilation takes a lil more time and a lot more memory for a large function. With-O, the compiler tries to reduce code size and execution time, without doing any optimizations that take a huge amount of compilation time.
-O turns on these 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, queen! GCC performs nearly all supported optimizations that don't involve a space-speed tradeoff. Compared to-O, this option increases both compilation time and the performance of the generated code. It's the glow-up. ๐
-O2 turns on all optimization flags from -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
Bestie, pls note the warning under-fgcseabout invoking-O2on programs that use computed gotos. Don't say I didn't warn u. ๐ญ
NOTE: In Ubuntu 8.10 and later versions,-D_FORTIFY_SOURCE=2, in Ubuntu 24.04 and later versions,-D_FORTIFY_SOURCE=3, is set by default, and is activated when-Ois set to 2 or higher. This enables additional compile-time and run-time checks for several libc functions. To disable, specify either-U_FORTIFY_SOURCEor-D_FORTIFY_SOURCE=0.
NOTE: In Debian 13 and Ubuntu 24.04 and later versions,-D_TIME_BITS=64together with-D_FILE_OFFSET_BITS=64is set by default on the 32bit architecturesarmel,armhf,hppa,m68k,mips,mipsel,powerpcandsh4.
-O3โ Optimize yet more.-O3turns on all optimizations from-O2and also turns 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 expected results. This is the default. The chill, no-frills, baseline vibe. ๐งโโ๏ธ-Osโ Optimize for size.-Osenables all-O2optimizations except those that often increase code size:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size. Tiny but mighty. ๐
-Ofastโ Disregard strict standards compliance, bestie.-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. Living dangerously, love that for u. ๐ฅ-Ogโ Optimize debugging experience.-Ogshould be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience. It's a better choice than-O0for producing debuggable code because some compiler passes that collect debug information are disabled at-O0.
Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect. Otherwise -Og enables all -O1 optimization flags except for those that may interfere with debugging:
-fbranch-count-reg -fdelayed-branch -fdse -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants -fmove-loop-stores -fssa-phiopt
-ftree-bit-ccp -ftree-dse -ftree-pta -ftree-sra
-Ozโ Optimize aggressively for size rather than speed. This may increase the number of instructions executed if those instructions require fewer bytes to encode.-Ozbehaves similarly to-Osincluding enabling most-O2optimizations. Smallest code possible, no cap. ๐ฆ
If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. Last one wins, periodt.
๐ง THE -f FLAGS (fine-tuning era) โจ
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed โ the one you typically use. You can figure out the other form by either removing no- or adding it. It's giving reversible jacket. ๐งฅ
These options control specific optimizations. They're either activated by -O options or related to ones that are. Use these flags in the rare cases when "fine-tuning" of optimizations is desired.
-fno-defer-popโ For machines that must pop arguments after a function call, always pop the arguments as soon as each function returns. At levels-O1and higher,-fdefer-popis the default; this allows the compiler to let arguments accumulate on the stack for several function calls and pop them all at once. Efficiency queen. ๐-fforward-propagateโ Perform a forward propagation pass on RTL. The pass tries to combine two instructions and checks if the result can be simplified. If loop unrolling is active, two passes are performed and the second is scheduled after loop unrolling.
This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.
-ffp-contract=styleโ-ffp-contract=offdisables floating-point expression contraction.-ffp-contract=fastenables floating-point expression contraction such as forming of fused multiply-add operations if the target has native support for them.-ffp-contract=onenables floating-point expression contraction if allowed by the language standard. This is currently not implemented and treated equal to-ffp-contract=off.
The default is -ffp-contract=fast.
-fomit-frame-pointerโ Omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available. Free real estate! ๐
On some targets this flag has no effect because the standard calling sequence always uses a frame pointer, so it cannot be omitted.
Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions. Several targets always omit the frame pointer in leaf functions.
Enabled by default at -O1 and higher.
-foptimize-sibling-callsโ Optimize sibling and tail recursive calls.
Enabled at levels -O2, -O3, -Os.
-foptimize-strlenโ Optimize various standard C string functions (e.g.strlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives. Glow-up for ur strings. โจ
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. Not me blocking the inlining ๐
-finline-small-functionsโ Integrate functions into their callers when their body is smaller than expected function call code (so overall size of program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating in this way. This inlining applies to all functions, even those not declared inline.
Enabled at levels -O2, -O3, -Os.
-findirect-inliningโ Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has any effect only when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
Enabled at levels -O2, -O3, -Os.
-finline-functionsโ Consider all functions for inlining, even if they are not declared inline. The compiler heuristically decides which functions are worth integrating in this way.
If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.
Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.
-finline-functions-called-onceโ bestie, this one says: consider allstaticfunctions that get called exactly once for inlining into whoever called them, even if nobody bothered to mark theminline. And if a call to a given function does get integrated? Then that function doesn't get output as assembler code in its own right anymore. gone, reduced to atoms ๐
It's enabled at levels -O1, -O2, -O3 and -Os, but not -Og.
-fearly-inliningโ inline functions marked byalways_inline, plus functions whose body seems smaller than the function call overhead, and do it early โ like, before the-fprofile-generateinstrumentation and the real inlining pass even show up. Why? Because doing it this way makes profiling significantly cheaper and usually makes inlining faster on programs that have big chains of nested wrapper functions. it's giving efficiency โจ
Enabled by default.
-fipa-sraโ perform interprocedural scalar replacement of aggregates, removal of unused parameters, and replacement of parameters passed by reference with parameters passed by value. glow-up for your function signatures fr fr ๐ฆ
Enabled at levels -O2, -O3 and -Os.
-finline-limit=nโ okay so by default, GCC limits the size of functions that can be inlined. This flag lets you have 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 bunch of parameters, which you can specify individually using --param name=value. The -finline-limit=n option sets some of these parameters like this:
max-inline-insns-singleโ is set ton/2.max-inline-insns-autoโ is set ton/2.
See below for docs on 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. like, none. wild.
Note: "pseudo instruction" here means an abstract measurement of a function's size, in this particular context. In no way does it represent a count of assembly instructions, and as such its exact meaning might change from one release to another. so don't @ me.
-fno-keep-inline-dllexportโ this is a more fine-grained version of-fkeep-inline-functions, and it applies only to functions that are declared using thedllexportattribute or declspec.-fkeep-inline-functionsโ in C, emitstaticfunctions that are declaredinlineinto the object file, even if the function has been inlined into all of its callers. Heads up: this switch does not affect functions using theextern inlineextension in GNU C90. In C++, emit any and all inline functions into the object file. periodt.-fkeep-static-functionsโ emitstaticfunctions into the object file, even if the function is never used. iconique, keeping things around for no reason (relatable).-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, bestie. But if you want to force the compiler to check if a variable is referenced regardless of whether optimization is on or off, use the -fno-keep-static-consts option.
-fmerge-constantsโ attempt to merge identical constants (string constants and floating-point constants) across compilation units. ๐
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 option implies -fmerge-constants. In addition to -fmerge-constants, it considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. But โ and this is important, bestie โ 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. ๐ญ you've been warned.
-fmodulo-schedโ perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. lowkey hypnotic tbh ๐ธ-fmodulo-sched-allow-regmovesโ perform more aggressive SMS-based modulo scheduling with register moves allowed. By setting this flag, certain anti-dependences edges are deleted, which triggers the generation of reg-moves based on the life-range analysis. This option is effective only with-fmodulo-schedenabled. so don't come for it solo, it needs its partner ๐ซถ-fno-branch-count-regโ disable the optimization pass that scans for opportunities to usedecrement and branchinstructions on a count register, instead of instruction sequences that decrement a register, compare it against zero, and then branch based upon the result. This option is only meaningful on architectures that support such instructions, which include x86, PowerPC, IA-64 and S/390. Note that the-fno-branch-count-regoption doesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes. sneaky sneaky ๐
The default is -fbranch-count-reg at -O1 and higher, except for -Og.
-fno-function-cseโ do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly.
This option results in less efficient code, ngl, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used. it's giving "for the weird ones" ๐ง
The default is -ffunction-cse.
-fno-zero-initialized-in-bssโ if the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code. ๐
This option turns off this behavior, because some programs explicitly rely on variables going to the data section โ e.g., so that the resulting executable can find the beginning of that section and/or make assumptions based on that.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ perform optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is redirected 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. queen of knowing where to go โจ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-typesโ when using a type that occupies multiple registers, such aslong longon a 32-bit system, split the registers apart and allocate them independently. This normally generates better code for those types, but may make debugging more difficult. ๐ซ tradeoffs, bestie.
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.
This is the default on some targets.
-fcse-follow-jumpsโ in common subexpression elimination (CSE), scan through jump instructions when the target of the jump is not reached by any other path. For example, when CSE encounters anifstatement with anelseclause, CSE follows the jump when the condition tested is false. it's giving "not me chasing the branch" ๐
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ this is similar to-fcse-follow-jumps, but it causes CSE to follow jumps that conditionally skip over blocks. When CSE encounters a simpleifstatement with no else clause,-fcse-skip-blockscauses CSE to follow the jump around the body of theif.
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-run common subexpression elimination after loop optimizations are performed. round two, bestie ๐ฅ
Enabled at levels -O2, -O3, -Os.
-fgcseโ perform a global common subexpression elimination pass. This pass also performs global constant and copy propagation. โจ
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. lowkey genius behavior ๐ธ
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.
-fgcse-lasโ when-fgcse-lasis enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies). no cap, it cleans up ๐งน
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. โจ
Enabled by -O3, -fprofile-use and -fauto-profile.
-faggressive-loop-optimizationsโ this option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. This assumes that loop code does not invoke undefined behavior โ by, for example, causing signed integer overflows or out-of-bound array accesses. The bounds for the number of iterations of a loop are used to guide loop unrolling and peeling and loop exit test optimizations. This option is enabled by default. it's giving confident and slightly unhinged, we stan ๐-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. so like, mystery sizes, beware ๐ฆ-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. bestie that's so real, no promises ๐ญ
Enabled at levels -O2, -O3, -Os.
-fauto-inc-decโ combine increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that do not have instructions to support this. Enabled by default at-O1and higher on architectures that support this. slay ๐-fdceโ does dead code elimination (DCE) on RTL. bestie it's on by default at-O1and up โจ-fdseโ dead store elimination (DSE) on RTL ๐ also enabled by default at-O1and higher.-fif-conversionโ tries to turn conditional jumps into branch-less equivalents ๐ฆ that means conditional moves,min,max, set flags andabsinstructions, plus some lil arithmetic tricks. the use of conditional execution on chips where it 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 ๐
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fdeclone-ctor-dtorโ okay so the C++ ABI 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, meaning two copies of the function ๐ญ with this option, the base and complete variants get changed into thunks that call a common implementation.
Enabled by -Os.
-fdelete-null-pointer-checksโ assume programs can't 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 traps, so if a pointer is checked after it's already been dereferenced, it can't be null.
heads up though: in some environments that assumption is just 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โ tries 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โ tries 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 the 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 ๐ when they seem useless after further optimization, they get converted back into their original form.-fdevirtualize-at-ltransโ streams extra info needed for aggressive devirtualization when running the link-time optimizer in local transformation mode ๐ธ this option enables more devirtualization but significantly increases the size of streamed data. for this reason it's disabled by default.-fexpensive-optimizationsโ performs a bunch of minor optimizations that are relatively expensive ๐ธ
Enabled at levels -O2, -O3, -Os.
-freeโ tries to remove redundant extension instructions ๐ especially helpful for x86-64, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. ngl that's kinda iconic.
Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.
-fno-lifetime-dseโ 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 object's lifetime 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.-flifetime-dse=0is equivalent to-fno-lifetime-dse๐ฆ-flive-range-shrinkageโ tries to decrease register pressure through register live range shrinkage ๐ซถ helpful for fast processors with small or moderate size register sets.- *
-fira-algorithm=algorithm* โ uses 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 isn't implemented for all architectures, but for the targets that do support it, it's the default because it generates better code ๐ - *
-fira-region=region* โ uses specified regions for the integrated register allocator. the region argument should be one of these: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 ๐ฅ 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 doesn't get a hard register gets a separate stack slot, and as a result function stack frames are larger.-flra-rematโ enables CFG-sensitive rematerialization in LRA โจ instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it's profitable.
Enabled at levels -O2, -O3, -Os.
-fdelayed-branchโ if supported for the target machine, tries 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, tries to reorder instructions to eliminate execution stalls due to required data being unavailable ๐ this helps machines with slow floating point or memory load instructions by letting other instructions be issued until the result of the load or floating-point instruction is needed.
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 ๐ 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 increasing 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's no limit on how many queued insns can be moved prematurely.-fsched-stalled-insnswithout a value is equivalent to-fsched-stalled-insns=1โจ -fsched-stalled-insns-dep,-fsched-stalled-insns-dep=n โ bestie this one sets how many insn groups (cycles) get peeked at for a dependency on a stalled insn that's a candidate for getting yeeted early out of the queue of stalled insns ๐ . Heads up tho: this only does anything during the second scheduling pass, and only if-fsched-stalled-insnsis in play.-fno-sched-stalled-insns-depis the exact same vibe as-fsched-stalled-insns-dep=0, and-fsched-stalled-insns-depwith no value at all is equivalent to-fsched-stalled-insns-dep=1. Periodt.-fsched2-use-superblocksโ when we're scheduling after register allocation, this says use superblock scheduling, which lets motion happen across basic block boundaries, giving you faster schedules โจ. But babes, this option is experimental, because not all machine descriptions used by GCC model the CPU closely enough to dodge unreliable results from the algorithm ๐ญ. Also it only 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โ enables the critical-path heuristic in the scheduler, which favors instructions on the critical path ๐ฅ. Enabled by default whenever scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-spec-insn-heuristicโ enables the speculative instruction heuristic in the scheduler, which favors speculative instructions with greater dependency weakness ๐ฆ. Enabled by default whenever scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-rank-heuristicโ enables the rank heuristic in the scheduler, which favors the instruction belonging to a basic block with greater size or frequency ๐. Enabled by default whenever scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-last-insn-heuristicโ enables the last-instruction heuristic in the scheduler, which favors the instruction that is less dependent on the last instruction scheduled ๐ธ. Enabled by default whenever scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-dep-count-heuristicโ enables the dependent-count heuristic in the scheduler, which favors the instruction that has more instructions depending on it ๐. Enabled by default whenever scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-freschedule-modulo-scheduled-loopsโ so modulo scheduling happens before traditional scheduling, right? And if a loop is modulo scheduled, later scheduling passes might go and change its schedule ๐ฌ. Use this option to control that behavior.-fselective-schedulingโ schedule instructions using the selective scheduling algorithm. Selective scheduling runs instead of the first scheduler pass โจ.-fselective-scheduling2โ schedule instructions using the selective scheduling algorithm. Selective scheduling runs instead of the second scheduler pass ๐ซ.-fsel-sched-pipeliningโ enables software pipelining of innermost loops during selective scheduling ๐. This option has no effect unless one of-fselective-schedulingor-fselective-scheduling2is turned on.-fsel-sched-pipelining-outer-loopsโ when pipelining loops during selective scheduling, also pipeline outer loops ๐. This option has no effect unless-fsel-sched-pipeliningis turned on.-fsemantic-interpositionโ okay so some object formats, like ELF, let the dynamic linker interpose symbols ๐. Which means 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. And while this feature is useful โ say, to rewrite memory allocation functions with a debugging implementation โ it's expensive in terms of code quality ๐. With-fno-semantic-interpositionthe compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Same deal for variables: if interposition happens for variables, the constructor of the variable will be the same. This flag has no effect for functions explicitly declared inline (where it's never allowed for interposition to change semantics) and for symbols explicitly declared weak ๐ซถ.-fshrink-wrapโ emit function prologues only before the parts of the function that actually need it, rather than 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 are only executed when needed ๐ . This option is on by default, but has no effect unless-fshrink-wrapis also turned on and the target supports this.-fcaller-savesโ enables allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls ๐พ. Such allocation is only done when it seems to result in better code. This option is always enabled by default on certain machines, usually those which 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, and then tries to find ways to combine them ๐งฉ. Enabled by default at-O1and higher.-fipa-raโ use caller save registers for allocation if those registers aren't used by any called function ๐. In that case it's not necessary to save and restore them around calls. This is only possible if called functions are part of the same compilation unit as the current function and they are 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 callee's register usage cannot be known exactly (this happens on targets that do not expose prologues and epilogues in RTL) ๐ญ.-fconserve-stackโ attempt to minimize stack usage ๐ซถ. The compiler attempts to use less stack space, even if that makes the program slower. This option implies setting the large-stack-frame parameter to100and the large-stack-frame-growth parameter to400.-ftree-reassocโ perform reassociation on trees ๐ณ. This flag is enabled by default at-O1and higher.-fcode-hoistingโ perform code hoisting โจ. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at-O2and higher.-ftree-preโ perform partial redundancy elimination (PRE) on trees ๐ธ. This flag is enabled by default at-O2and-O3.-ftree-partial-preโ 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. This analysis is faster than PRE, though it exposes fewer redundancies. This flag is enabled by default at-O1and higher.-ftree-phipropโ perform hoisting of loads from conditional pointers on trees ๐. This pass is enabled by default at-O1and higher.-fhoist-adjacent-loadsโ speculatively hoist loads from both branches of an if-then-else if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction ๐. This flag is enabled by default at-O2and higher.-ftree-copy-propโ perform copy propagation on trees ๐. This pass eliminates unnecessary copy operations. This flag is enabled by default at-O1and higher.-fipa-pure-constโ discover which functions are pure or constant ๐. Enabled by default at-O1and higher.-fipa-referenceโ discover which static variables do not escape the compilation unit ๐ซถ. Enabled by default at-O1and higher.-fipa-reference-addressableโ discover read-only, write-only and non-addressable static variables ๐ . Enabled by default at-O1and higher.-fipa-stack-alignmentโ reduce stack alignment on call sites if possible ๐ง. Enabled by default.-fipa-ptaโ perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐. Careful tho โ 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 are marked as cold. Also functions executed once (such as"cold","noreturn", static constructors or destructors) are identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at-O1and higher.-fipa-modrefโ perform interprocedural mod/ref analysis ๐. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. This flag is enabled by default at-O1and higher.-fipa-cpโ perform interprocedural constant propagation ๐. This optimization analyzes the program to determine when values passed to functions are constants and then optimizes accordingly. This optimization 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 to make interprocedural constant propagation stronger. โจ When it's on, IPA constant propagation clones functions whenever an externally visible function can get called with constant arguments. The vibe? More copies of functions = significantly bigger code size (peep--param ipa-cp-unit-growth=valuefor that). It's on by default at-O3, and also gets enabled by-fprofile-useand-fauto-profile. ๐-fipa-bit-cpโ when enabled, it does interprocedural bitwise constant propagation. On by default at-O2, and by-fprofile-useand-fauto-profile. It requires-fipa-cpto be enabled. no cap. ๐ซถ-fipa-vrpโ when enabled, it does interprocedural propagation of value ranges. On by default at-O2. It requires-fipa-cpto be enabled. ๐ฆ-fipa-icfโ Identical Code Folding for functions and read-only variables. ๐ It reduces code size and may disturb unwind stacks by swapping a function for an equivalent one with a different name (yeah, that part is giving chaos ngl). It works more effectively with link-time optimization enabled.
Okay so the behavior is similar to the Gold Linker's ICF optimization, but GCC ICF works on different levels, so the optimizations are not the same โ there are equivalences found only by GCC and equivalences found only by Gold. Two different queens, two different crowns. ๐
This flag is on by default at -O2 and -Os.
-flive-patching=levelโ controls GCC's optimizations so the output is suitable for live-patching. ๐ฉน
So here's the tea: if the compiler's optimization uses a function's body (or info extracted from its body) to optimize/change another function, that latter one is called an impacted function of the former. If a function gets patched, its impacted functions should be patched too. Periodt.
The impacted functions are determined by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, cloning a function and changing its caller to call this new clone, or extracting a function's pureness/constness information to optimize its direct or indirect callers, etc.
Usually the more IPA optimizations you enable, the larger the number of impacted functions for each function. To control the number of impacted functions and more easily compute the list of impacted functions, IPA optimizations can be partially enabled at two different levels.
The level argument should be one of the following:
inline-cloneโ only enable inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. As a result, when patching a function, all its callers and its clones' callers are impacted, so they need to be patched as well. ๐ญ
-flive-patching=inline-clone disables 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-modref
inline-only-staticโ only enable inlining of static functions. So when patching a static function, all its callers are impacted and need to be patched too.
In addition to all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables these extra 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.
Heads up bestie:-flive-patchingis not supported with link-time optimization (-flto). ๐
-fisolate-erroneous-paths-dereferenceโ detects paths that trigger erroneous or undefined behavior by dereferencing a null pointer. It isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. ๐ชค On 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. 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 may be enabled by-O2in the future. ๐-ftree-sinkโ does forward store motion on trees. On by default at-O1and higher. ๐ธ-ftree-bit-ccpโ does sparse conditional bit constant propagation on trees and propagates pointer alignment information. This pass only operates on local scalar variables and is on by default at-O1and higher, except for-Og. It requires that-ftree-ccpis enabled.-ftree-ccpโ does sparse conditional constant propagation (CCP) on trees. This pass only operates on local scalar variables and is on by default at-O1and higher. ๐-fssa-backpropโ propagates information about uses of a value up the definition chain so the definitions get simplified. For example, this pass strips sign operations if the sign of a value never matters. On by default at-O1and higher. โจ-fssa-phioptโ does pattern matching on SSA PHI nodes to optimize conditional code. On by default at-O1and higher, except for-Og. ๐ฆ-ftree-switch-conversionโ converts simple initializations in a switch into initializations from a scalar array. On by default at-O2and higher. ๐-ftree-tail-mergeโ looks for identical code sequences, and when it finds them, replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. On by default at-O2and higher. The compilation time in this pass can be limited usingmax-tail-merge-comparisonsparameter andmax-tail-merge-iterationsparameter. โฑ๏ธ-ftree-dceโ does dead code elimination (DCE) on trees. On by default at-O1and higher. ๐-ftree-builtin-call-dceโ does conditional dead code elimination (DCE) for calls to built-in functions that may seterrnobut are otherwise free of side effects. On by default at-O2and higher if-Osis not also specified.-ffinite-loopsโ assumes that a loop with an exit will eventually take the exit and not loop indefinitely. This lets the compiler remove loops that otherwise have no side-effects, since it doesn't count eventual endless looping as a side effect. ๐ On by default at-O2for C++ with-std=c++11or higher.-ftree-dominator-optsโ does a bunch of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. It also does jump threading (to reduce jumps to jumps). On by default at-O1and higher. ๐-ftree-dseโ does dead store elimination (DSE) on trees. A dead store is a store into a memory location that's later overwritten by another store without any intervening loads โ in that case the earlier store can be deleted. ๐๏ธ On by default at-O1and higher.-ftree-chโ does loop header copying on trees. This is a slay because it increases the effectiveness of code motion optimizations, and it also saves one jump. On by default at-O1and higher. It is not enabled for-Os, since it usually increases code size. ๐-ftree-loop-optimizeโ does loop optimizations on trees. On by default at-O1and higher. ๐-ftree-loop-linear-floop-strip-mine-floop-blockโ perform loop nest optimizations. Same as-floop-nest-optimize. To use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure. โญ-fgraphite-identityโ enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using-fgraphite-identitywe can check the costs or benefits of 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. ๐-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's profitable to parallelize the loops. ๐ฅ-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. This option is on 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
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
...and this flag is on by default at -O3, and -fprofile-use and -fauto-profile turn it on too. ๐
-ftree-loop-distribute-patternsโ does loop distribution on the patterns that can literally just be code-generated with library calls. On by default at-O2and up, plus via-fprofile-useand-fauto-profile. โจ
So this pass spreads out the initialization loops and generates a call to memset zero. Like, bestie, watch this loop:
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
get transformed 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 call to memset zero. Enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile. ๐
-floop-interchangeโ performs loop interchange outside of graphite. This one can improve cache performance on loop nest and lets further loop optimizations, like vectorization, actually happen. Example time, the loop
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
becomes
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];
On by default at -O3, and also enabled by -fprofile-use and -fauto-profile. ๐ฅ
-floop-unroll-and-jamโ applies unroll and jam transformations on feasible loops. In a loop nest this unrolls the outer loop by some factor and fuses the resulting multiple inner loops. On by default at-O3, and 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 handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). With-funswitch-loopsit also moves operands of conditions that are invariant out of the loop, so that we can use just trivial invariantness analysis in loop unswitching. The pass also includes store motion. ๐-ftree-loop-ivcanonโ creates a canonical counter for number of iterations in loops where figuring out the number of iterations requires complicated analysis. Later optimizations then may determine the number easily. Useful especially in connection with unrolling. ๐ข-ftree-scev-cpropโ performs final value replacement. If a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, replace uses of the final value by such a computation, provided it is sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at-O1and higher. ๐-fivoptsโ performs induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees. ๐๐- *
-ftree-parallelize-loops=n* โ parallelize loops, i.e., split their iteration space to run in n threads. This is only possible for loops whose iterations are independent and can be arbitrarily reordered. The optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive, rather than constrained e.g. by memory bandwidth. This option implies-pthread, and thus is only supported on targets that have support for-pthread. ๐งต๐งต๐งต -ftree-ptaโ performs function-local points-to analysis on trees. On by default at-O1and higher, except for-Og. ๐ฏ-ftree-sraโ performs scalar replacement of aggregates. This pass replaces structure references with scalars to prevent committing structures to memory too early. On by default at-O1and higher, except for-Og. ๐ซถ-fstore-mergingโ performs merging of narrow stores to consecutive memory addresses. This pass merges contiguous stores of immediate values narrower than a word into fewer wider stores to reduce the number of instructions. Enabled by default at-O2and higher as well as-Os. ๐ฆ-ftree-terโ performs temporary expression replacement during the SSA->normal phase. Single use/single def temporaries are replaced at their use location with their defining expression. This results in non-GIMPLE code, but gives the expanders much more complex trees to work on resulting in better RTL generation. Enabled by default at-O1and higher. ๐ณ-ftree-slsrโ performs straight-line strength reduction on trees. This recognizes related expressions involving multiplications and replaces them by less expensive calculations when possible. Enabled by default at-O1and higher. โจ-ftree-vectorizeโ performs vectorization on trees. This flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif not explicitly specified. ๐-ftree-loop-vectorizeโ performs loop vectorization on trees. On by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile. ๐-ftree-slp-vectorizeโ performs basic block vectorization on trees. On 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 increases the security and predictability of a program by preventing uninitialized memory disclosure and use. GCC still considers an automatic variable that doesn't have an explicit initializer as uninitialized, so-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still report warning messages on such automatic variables and the compiler will perform optimization as if the variable were uninitialized. With this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. **However, the current implementation cannot initialize automatic variables that are declared between the controlling expression and the firstcaseof aswitchstatement. Use-Wtrivial-auto-var-initto report all such cases. ๐ญ
The three values of choice are:
uninitializeddoesn't initialize any automatic variables. This is C and C++'s default. ๐patternโ initialize automatic variables with values which will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump and without being values that programmers can rely on for useful program semantics. The current value is byte-repeatable pattern with byte"0xFE". The values used for pattern initialization might be changed in the future. ๐zeroโ initialize automatic variables with zeroes. 0๏ธโฃ
The default is uninitialized.
You can control this behavior for a specific variable by using the variable attribute uninitialized. ๐
- *
-fvect-cost-model=model* โ alters the cost model used for vectorization. The model argument should be one ofunlimited,dynamic,cheaporvery-cheap. With theunlimitedmodel the vectorized code-path is assumed to be profitable, while with thedynamicmodel a runtime check guards the vectorized code-path to enable it only for iteration counts that will likely execute faster than when executing the original scalar loop. Thecheapmodel disables vectorization of loops where doing so would be cost prohibitive, for example due to required runtime checks for data dependence or alignment, but otherwise is equal to thedynamicmodel. Thevery-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code that is being vectorized. For example, if each iteration of a vectorized loop would only be able to handle exactly four iterations of the scalar loop, thevery-cheapmodel would only allow vectorization if the scalar iteration count is known to be a multiple of four. ๐
The default cost model depends on other optimization flags and is either dynamic or cheap.
- *
-fsimd-cost-model=model* โ alters the cost model used for vectorization of loops marked with the OpenMPsimddirective. The model argument should be one ofunlimited,dynamic,cheap. All values of model have the same meaning as described in-fvect-cost-modeland by default a cost model defined with-fvect-cost-modelis used. ๐ -ftree-vrpโ performs Value Range Propagation on trees. This is similar to the constant propagation pass, but instead of values, ranges of values are propagated. This allows the optimizers to remove unnecessary range checks like array bound checks and null pointer checks. On by default at-O2and higher. Null pointer check elimination is only done if-fdelete-null-pointer-checksis enabled. ๐-fsplit-pathsโ splits paths leading to loop backedges. This can improve dead code elimination and common subexpression elimination. On by default at-O3and above. โ๏ธ-fsplit-ivs-in-unrollerโ enables expression of values of induction variables in later iterations of the unrolled loop using the value in the first iteration. This breaks long dependency chains, thus improving efficiency of the scheduling passes. โ๏ธ๐ฅ
A combination of -fweb and CSE is often sufficient to obtain the same effect. However, that is not reliable in cases where the loop body is more complicated than a single basic block. It also does not work at all on some architectures due to restrictions in the CSE pass.
This optimization is enabled by default. ๐
-fvariable-expansion-in-unrollerโ with this option, the compiler creates multiple copies of some local variables when unrolling a loop, which can result in superior code. ๐
This optimization is enabled by default for PowerPC targets, but disabled by default otherwise. ๐ซ
-fpartial-inliningโ okay so this one inlines parts of functions. It only does anything when inlining itself is already turned on by-finline-functionsor-finline-small-functions. Enabled at levels-O2,-O3,-Os. โจ-fpredictive-commoningโ perform predictive commoning optimization, i.e., reusing computations (especially memory loads and stores) that happened in previous iterations of loops. This option is enabled at level-O3. It is also enabled by-fprofile-useand-fauto-profile. ๐ซ-fprefetch-loop-arraysโ If the target machine supports it, generate instructions to prefetch memory so loops that access large arrays get a performance glow-up. This option may generate better or worse code; results are highly dependent on the structure of loops within the source code. Disabled at level-Os. ๐ฆ-fno-printf-return-valueโ Do not substitute constants for known return value of formatted output functions such assprintf,snprintf,vsprintf, andvsnprintf(but notprintfoffprintf). This transformation allows GCC to optimize or even eliminate branches based on the known return value of these functions 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-valueis in effect, both the branch and the body of theifstatement (but not the call tosnprint) can be optimized away wheniis 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.-fpeepholeis enabled by default.-fpeephole2enabled at levels-O2,-O3,-Os. ๐-fno-guess-branch-probabilityโ Do not guess branch probabilities using heuristics. GCC uses heuristics to guess branch probabilities if they are not 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_expectinfo into account. The interactions between the heuristics and__builtin_expectcan be complex, and in some cases, it may be useful to disable the heuristics so that the effects of__builtin_expectare easier to understand. It is also possible to specify expected probability of the expression with__builtin_expect_with_probabilitybuilt-in function. The default is-fguess-branch-probabilityat levels-O,-O2,-O3,-Os. ๐-freorder-blocksโ Reorder basic blocks in the compiled function in order to reduce number of taken branches and improve code locality. Enabled at levels-O1,-O2,-O3,-Os. ๐-freorder-blocks-algorithm=algorithmโ Use the specified algorithm for basic block reordering. The algorithm argument can besimple, which does not increase code size (except sometimes due to secondary effects like alignment), orstc, the "software trace cache" algorithm, which tries to put all often executed code together, minimizing the number of branches executed by making extra copies of code. The default issimpleat levels-O1,-Os, andstcat levels-O2,-O3. โญ-freorder-blocks-and-partitionโ In addition to reordering basic blocks in the compiled function, in order to reduce number of taken branches, partitions hot and cold basic blocks into separate sections of the assembly and.ofiles, to improve paging and cache locality performance. This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets usingsetjump/longjumpor 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-stackis 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 object file format must support named sections and linker must place them in a reasonable way. This option isn't effective unless you either provide profile feedback (see-fprofile-arcsfor details) or manually annotate functions withhotorcoldattributes. 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, anunsigned intcan alias anint, but not avoid*or adouble. 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;
}
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os. ๐
-fipa-strict-aliasingโ Controls whether rules of-fstrict-aliasingare applied across function boundaries. Note that if multiple functions gets inlined into a single function the memory accesses are no longer considered to be crossing a function boundary. The-fipa-strict-aliasingoption 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. If m is not specified, it defaults to n. Examples:-falign-functions=32aligns functions to the next 32-byte boundary,-falign-functions=24aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less,-falign-functions=32:7aligns 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:3aligns 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-functionsand-falign-functions=1are 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. ๐ง-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-functionsoption.-fno-align-labelsand-falign-labels=1are equivalent and mean that labels are not aligned. If-falign-loopsor-falign-jumpsare 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. If-falign-labelsis greater than this value, then its value is used instead. Parameters of this option are analogous to the-falign-functionsoption.-fno-align-loopsand-falign-loops=1are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536. If n is not specified or is zero, use a machine-dependent default. Enabled at levels-O2,-O3. ๐-falign-jumps,-falign-jumps=n,-falign-jumps=n:m,-falign-jumps=n:m:n2,-falign-jumps=n:m:n2:m2 โ okay so this one lines up branch targets to a power-of-two boundary, but only for branch targets that you can only get to by jumping. And because of that, no dummy operations need to be executed. ๐
If -falign-labels is greater than this value, then its value is used instead. The parameters here are analogous to the -falign-functions option. -fno-align-jumps and -falign-jumps=1 are equivalent, and both mean that loops 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. โจ
-fno-allocation-dceโ do not remove unused C++ allocations in dead code elimination. That's it, that's the whole vibe. ๐ซถ-fallow-store-data-racesโ bestie this one is spicy, listen up: it allows the compiler to do optimizations that may introduce new data races on stores, without proving that the variable can't be concurrently accessed by other threads. It does not affect optimization of local data. It's safe to use this option if it is known that global data will not be accessed by multiple threads.
Examples of optimizations enabled by -fallow-store-data-races include hoisting or if-conversions that may cause a value that was already in memory to be re-written with that same value. Such re-writing is safe in a single threaded context but may be unsafe in a multi-threaded context. Note that on some processors, if-conversions may be required in order to enable vectorization.
Enabled at level -Ofast. ๐ฅ
-funit-at-a-timeโ this option is left for compatibility reasons, periodt.-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 that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.
-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Additionally -fno-toplevel-reorder implies -fno-section-anchors. ๐ฆ
-funreachable-trapsโ with this option, the compiler turns calls to__builtin_unreachableinto traps, instead of using them for optimization. This also affects any such calls implicitly generated by the compiler.
This option has the same effect as -fsanitize=unreachable -fsanitize-trap=unreachable, but does not affect the values of those options. If -fsanitize=unreachable is enabled, that option takes priority over this one.
This option is enabled by default at -O0 and -Og.
-fwebโ constructs webs as commonly used for register allocation purposes and assigns each web an individual pseudo register. This allows the register allocation pass to operate on pseudos directly, but it also strengthens several other optimization passes, such as CSE, loop optimizer and trivial dead code remover. It can, however, make debugging impossible, since variables no longer stay in a "home register". ๐
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 ofmainand those merged by attributeexternally_visibleโ become static functions and in effect are optimized 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 the resolution info passed to the link-time optimizer by the linker plugin. It is still useful if no linker plugin is used or during incremental link step when final code is produced (with -flto -flinker-output=nolto-rel).
-flto[=n] โ okay so THIS one, this is the main character. ๐ It runs the standard link-time optimizer. When invoked with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. When the object files are linked together, all the function bodies are read from these ELF sections and instantiated as if they had been part of the same translation unit.
To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is 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. ๐ซถ
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.
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.
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.
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.
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.
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.
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 if code not consistent with the setting at compile time.
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. โจ
okay so if you actually want debug info to come out of all this, you gotta hand -g over at compile time. and here's the cute part โ if any of the input files at link time were built with debug info generation turned on, the link turns it on too. ๐ but heads up bestie: fancy debug settings like the dwarf level -gdwarf-5 have to be repeated explicitly on the linker command line, and mixing different settings across different translation units is discouraged. don't do it. it's giving chaos.
If LTO bumps into objects with C linkage that were declared with incompatible types in separate translation units that are getting linked together (which is undefined behavior per ISO C99 6.2.7, no cap ๐), it might throw a non-fatal diagnostic at you. the behavior is still undefined at run time. and yeah, similar diagnostics can pop up for other languages too. so like, not me ignoring warnings.
Another iconic LTO feature? you can do interprocedural optimizations across files written in different languages. literally mixing the whole friend group:
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 is tacked on to get 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. same energy, same flags.
If you've got object files with GIMPLE bytecode chilling inside a library archive โ say libfoo.a โ you can extract and use them in an LTO link, but only if you're using a linker with plugin support. to make static libraries that are 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 so 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 to the running GCC so they become part of the aggregated GIMPLE image that gets optimized. slay. ๐
Now if you're not using a linker with plugin support and/or you don't enable the linker plugin, then the objects inside libfoo.a get extracted and linked as usual โ but they do not participate in the LTO optimization process. so if you want a static library that works for both LTO optimization and regular linkage, compile its object files with -flto -ffat-lto-objects. both, bestie. we contain multitudes.
Link-time optimizations don't need the whole program to be present to operate. if the program doesn't require any symbols to be exported, you can combine -flto and -fwhole-program so the interprocedural optimizers can make more aggressive assumptions, which may lead to better optimization opportunities. but note: you do not need -fwhole-program when the linker plugin is active (peep -fuse-linker-plugin). ๐
the current implementation of LTO makes no attempt to generate bytecode that's portable between different types of hosts. the bytecode files are versioned and there's a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC. fr fr, version match or nothing.
And link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF. ๐ญ
If you specify the optional n, the optimization and code generation done at link time runs in parallel using n parallel jobs, by utilizing an installed make program. the environment variable MAKE may be used to override the program used. โจ
You can also specify -flto=jobserver to use GNU make's job server mode to figure out the number of parallel jobs. this is 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. and even without the option value, GCC tries to automatically detect a running GNU make's job server. ๐
Use -flto=auto to use GNU make's job server, if it's available, or otherwise fall back to autodetection of the number of CPU threads present in your system. ๐
โจ OPTIONS (still going, obviously) โจ
-flto-partition=algโ pick the partitioning algorithm the link-time optimizer uses. the value is either1to1to specify a partitioning that mirrors the original source files, orbalancedto specify partitioning into equally sized chunks (whenever possible), ormaxto create 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 โ do not come for it. 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 in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms. forzstd, valid values are0(no compression) to19(maximum compression), whilezlibsupports 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 ingoldor in GNU ld 2.21 or newer. ๐
This option enables the extraction of object files with GIMPLE bytecode out of library archives. this improves optimization quality 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). 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. this 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 (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, identify arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. if possible, eliminate 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, perform 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 due to 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. ๐ซถ
This option is enabled by -fauto-profile.
-fprofile-partial-trainingโ with-fprofile-useall 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. (for example, a program may contain functions specific for a given hardware and training may not cover all hardware configurations the program is run on.) with-fprofile-partial-trainingprofile feedback will be ignored for all functions not executed during the train run, leading them to be optimized as if they were compiled without profile feedback. this leads to better performance when the train run isn't representative, but it also leads to significantly bigger code. trade-offs, bestie. ๐-fprofile-use-fprofile-use=pathโ enable profile feedback-directed optimizations, plus the following optimizations, many of which are generally profitable only when profile feedback is available: ๐ฅ
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-reorder-functions
Before you can use this option, you must first generate profiling information. no shortcuts, no skipping the homework. ๐
By default, GCC throws an error at you if the feedback profiles don't match the source code. You can demote that to just a warning with -Wno-error=coverage-mismatch โ but lowkey heads up, that might leave you with poorly optimized code. Also, by default, GCC warns you if the feedback profiles justโฆ aren't there at all (peep -Wmissing-profile). ๐
If path is specified, GCC goes looking at that path for the profile feedback data files. See -fprofile-dir.
๐ธ -fauto-profile, -fauto-profile=path ๐ธ
Turn on sampling-based feedback-directed optimizations, bestie โ plus the whole squad of optimizations below, most of which are only actually worth it when you've got profile feedback to work with:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-correction
path is the name of a file holding AutoFDO profile info. If you leave it out, it defaults to fbdata.afdo in the current directory. ๐
To actually produce an AutoFDO profile data file you gotta run your program with the perf utility on a supported GNU/Linux target system. More deets over at <https://perf.wiki.kernel.org/>.
E.g. โจ
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then use the create_gcov tool to convert that raw profile data into a format GCC can actually read. You also must hand this tool the unstripped binary for your program, no skipping. See <https://github.com/google/autofdo>.
E.g. ๐
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
๐ FLOATING-POINT OPTIONS ๐
Okay so these next ones control how the compiler behaves around floating-point arithmetic. They're all a tradeoff between speed and correctness. And fr fr, all of them have to be specifically enabled โ none of them just show up on their own. ๐
๐ -ffloat-store ๐
Do not store floating-point variables in registers, and shut down any other option that might change whether a floating-point value gets pulled from a register or from memory.
This one stops that cursed 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 for the x86 architecture. For most programs that extra precision is only doing good, but a few programs rely on the precise definition of IEEE floating point. So use -ffloat-store for those, after you've modified them to store all pertinent intermediate computations into variables. ๐ฆ
โญ -fexcess-precision=style โญ
This one lets you control excess precision even harder, on machines where floating-point ops happen in a format with more precision or range than the IEEE standard and interchange floating-point types. By default, -fexcess-precision=fast is in effect โ meaning operations may be carried out in a wider precision than the types specified in the source if that makes the code faster, and honestly it's unpredictable when rounding to the source-specified types even happens. ๐ญ
When compiling C or C++, if -fexcess-precision=standard is specified, then 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-store only affects assignments, just saying). This option is on by default for C or C++ if you use a strict conformance option like -std=c99 or -std=c++17. And -ffast-math enables -fexcess-precision=fast by default regardless of whether a strict conformance option is used.
Heads up bestie:-fexcess-precision=standardis not implemented for languages other than C or C++. On the x86, it has no effect if-mfpmath=sseor-mfpmath=sse+387is specified; in the former case IEEE semantics apply with no excess precision, and in the latter, rounding is unpredictable. ๐
๐ฅ -ffast-math ๐ฅ
Sets the following options:
-fno-math-errno-funsafe-math-optimizations-ffinite-math-only-fno-rounding-math-fno-signaling-nans-fcx-limited-range-fexcess-precision=fast
This option causes the preprocessor macro "__FAST_MATH__" to be defined. โจ
It is not turned on by any -O option besides -Ofast, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't need those guarantees. ๐
๐ -fno-math-errno ๐
Do not set "errno" after calling math functions that execute with a single instruction, e.g. "sqrt". A program that relies on IEEE exceptions for math error handling might want this flag for speed while keeping IEEE arithmetic compatibility.
Not turned on by any -O option, 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 need those guarantees. ๐ฆ
The default is -fmath-errno.
On Darwin systems the math library never sets "errno", so there's literally no reason for the compiler to even consider the possibility that it might โ and -fno-math-errno is the default there. Slay. ๐ธ
๐ -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.
Not turned on by any -O option, 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 need those guarantees. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math. โจ
The default is -fno-unsafe-math-optimizations.
๐ -fassociative-math ๐
Allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing the computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like "(x + 2**52) - 2**52"). May also reorder floating-point comparisons, so it may not be used when ordered comparisons are required. This option requires that both -fno-signed-zeros and -fno-trapping-math be in effect. Moreover, it doesn't make much sense with -frounding-math. For Fortran the option is automatically enabled when both -fno-signed-zeros and -fno-trapping-math are in effect. ๐ญ
The default is -fno-associative-math.
๐ -freciprocal-math ๐
Allow the reciprocal of a value to be used instead of dividing by the value, if that enables optimizations. For example "x / y" can be replaced with "x * (1/y)", which is useful if "(1/y)" is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value. ๐
The default is -fno-reciprocal-math.
๐ -ffinite-math-only ๐
Allow optimizations for floating-point arithmetic that assume arguments and results are not NaNs or +-Infs.
Not turned on by any -O option, 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 need 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 the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -ffinite-math-only). This option implies that the sign of a zero result isn't significant. ๐
The default is -fsigned-zeros.
๐ -fno-trapping-math ๐
Compile code assuming that floating-point operations cannot generate user-visible traps. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that -fno-signaling-nans be in effect. Setting this option may allow faster code if one relies on "non-stop" IEEE arithmetic, for example.
This option should never be turned on by any -O option, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. ๐ญ
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 default is round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. This option should be specified for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. This option disables constant folding of floating-point expressions at compile time (which may be affected by rounding mode) and arithmetic transformations that are unsafe in the presence of sign-dependent rounding modes. ๐ฆ
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. ๐ Future versions of GCC may provide finer control of this setting using C99's"FENV_ACCESS"pragma. This command-line option will be used along with-ftrapping-mathto specify the default state for"FENV_ACCESS". ๐
-fsignaling-nansโ compile your code assuming that IEEE signaling NaNs may pop off user-visible traps during floating-point ops. Turning this on disables optimizations that could change how many exceptions you actually see with signaling NaNs. It also implies-ftrapping-math.
Bestie, this option makes the preprocessor macro __SUPPORT_SNAN__ get defined. โจ
Default is -fno-signaling-nans.
โ ๏ธ This one is experimental and, as of right now, it does not guarantee to disable all GCC optimizations that affect signaling NaN behavior. So likeโฆ know that going in. ๐ซ
-fno-fp-int-builtin-inexactโ don't let the built-in functionsceil,floor,roundandtrunc(plus theirfloatandlong doublevariants) generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 do allow these functions to raiseinexact, but ISO/IEC TS 18661-1:2014, the C bindings to IEEE 754-2008, as integrated into ISO C2X, does not allow them to do that. Standards drama, honestly.
The default is -ffp-int-builtin-inexact, which lets the exception be raised โ unless C2X or a later C standard is selected. Also, this option does absolutely nothing unless -ftrapping-math is in effect. ๐
And even if -fno-fp-int-builtin-inexact is used, if those functions end up generating a call to a library function, the inexact exception may still get raised if the library implementation doesn't follow TS 18661. Not our fault, that's the library's vibe. ๐
-fsingle-precision-constantโ treat floating-point constants as single precision instead of quietly implicitly converting them to double-precision constants. Keep it as it was written, no glow-up. ๐-fcx-limited-rangeโ when enabled, this option states that a range reduction step is not needed when performing complex division. Also, there's no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. Default is-fno-cx-limited-range, but it gets enabled by-ffast-math. ๐๏ธ
This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. Nevertheless โ and this is the fun part โ the option applies to all languages. Periodt.
-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's still no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case.
Default is -fno-cx-fortran-rules.
OK so the following options control optimizations that may improve performance, but are not enabled by any -O options. Heads up though: this section also includes experimental options that may produce broken code. ๐ฅ๐ You've been warned, bestie.
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilitiesto improve optimizations based on how many times each branch was taken. When a program compiled with-fprofile-arcsexits, it saves arc execution counts to a file calledsourcename.gcdafor each source file. The info in that data file is very dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations. See details about the file naming 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 behavior honestly. ๐
Enabled by -fprofile-use and -fauto-profile.
-fprofile-valuesโ if combined 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 first time of execution of a function and orders these functions in ascending order. Organized queen. โจ
Enabled with -fprofile-use.
-fvptโ if combined with-fprofile-arcs, this option instructs the compiler to add code to gather information about values of expressions.
With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator. ๐
Enabled with -fprofile-use and -fauto-profile.
-frename-registersโ attempt to avoid false dependencies in scheduled code by making use of registers left over after register allocation. This optimization most benefits processors with lots of registers. Depending on the debug information format adopted by the target, however, 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 same type together, because the target machine can execute them more efficiently if they're adjacent to each other in the instruction flow. Matching outfits for the instructions, basically. ๐
Enabled at levels -O2, -O3, -Os.
-ftracerโ perform tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, allowing other optimizations to do a better job.
Enabled by -fprofile-use and -fauto-profile.
-funroll-loopsโ unroll loops whose number of iterations can be determined at compile time or upon entry to the loop.-funroll-loopsimplies-frerun-cse-after-loop,-fweband-frename-registers. It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). This option makes code larger, and may or may not make it run faster. No promises, it's giving chaos. ๐
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. So like, it's the same energy but worse. ๐-fpeel-loopsโ peels loops for which there's enough information that they do not roll much (from profile feedback or static analysis). It also turns on complete loop peeling (i.e. complete removal of loops with 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. Diplomatic solution, honestly. ๐ฆ
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 result of the condition). Clone drama but productive. ๐
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 is 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. Everyone gets their own little room. ๐
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.
Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping).
On ELF/DWARF systems these options do not degenerate the quality of the debug information. There could be issues with other object files/debug info formats.
โ ๏ธ Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower. These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit, since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions. So it's a trade, bestie โ know the cost. ๐ญ
-fstdarg-optโ optimize the prologue of variadic argument functions with respect to usage of those arguments. Snatched. ๐-fsection-anchorsโ try to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to reduce the number of GOT entries and GOT accesses on some targets.
For example, the implementation of the following function foo:
static int a, b, c;
int foo (void) { return a + b + c; }
...usually it's out here calculating the addresses of all three of those variables, but the second you compile it with -fsection-anchors it goes and grabs them all from one common anchor point instead. The vibe is basically this pseudocode (and bestie, this is not valid C, do not try it at home):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
Not all targets support this option. like, some architectures just said no ๐
-fzero-call-used-regs=choiceโ zeroes out call-used registers at function return, which is a whole security glow-up: it either mitigates Return-Oriented Programming (ROP) attacks or stops information from leaking through registers. โจ
The possible values of choice are the exact same ones as for the zero_call_used_regs attribute. The default is skip.
You can control this behavior for one specific function by using the function attribute zero_call_used_regs. per-function vibes, we love to see it
--param name=valueโ okay so GCC has all these little internal constants that control how much optimization happens. Example: GCC will not inline functions that contain more than a certain number of instructions. You can poke at some of those constants from the command line with the--paramoption. ๐
Heads up bestie: the names of the specific parameters, and what their values actually mean, are tied to the internals of the compiler, and they are subject to change without notice in future releases. So no cap, don't build your whole personality on them.
Wanna see the minimal, maximal and default values of a parameter? Use the --help=param -Q options. ๐ธ
In each case, the value is an integer. The following choices of name are recognized for all targets:
predictable-branch-outcomeโ when a branch is predicted to be taken with a probability lower than this threshold (in percent), then it gets considered well predictable.max-rtl-if-conversion-insnsโ RTL if-conversion tries to remove conditional branches around a block and swap them for conditionally executed instructions. This parameter sets the maximum number of instructions in a block that should even be considered for if-conversion. The compiler will also use other heuristics to decide whether if-conversion is likely to be profitable.max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove conditional branches around a block and replace them with conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that would be generated by if-conversion, depending on whether the branch is statically determined to be predictable or not. The units for this parameter are the same as those for the GCC internalseq_costmetric. The compiler will try to provide a reasonable default for this parameter using theBRANCH_COSTtarget macro.max-crossjump-edgesโ the maximum number of incoming edges to consider for cross-jumping. The algorithm used by-fcrossjumpingis O(N^2) in the number of edges incoming to each block. Increasing values mean more aggressive optimization, which makes compilation time go up with probably only a small improvement in executable size. tradeoffs, always tradeoffs ๐min-crossjump-insnsโ the minimum number of instructions that must be matched at the end of two blocks before cross-jumping is performed on them. This value is ignored in the case where all instructions in the block being cross-jumped from are matched.max-grow-copy-bb-insnsโ the maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.max-goto-duplication-insnsโ the maximum number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behavior in a bunch of passes, GCC factors computed gotos early in the compilation process, and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more thanmax-goto-duplication-insnsare unfactored.max-delay-slot-insn-searchโ the maximum number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions get searched, the time savings from filling the delay slot are minimal, so it stops searching. Increasing values mean more aggressive optimization, making compilation time go up with probably only a small improvement in execution time.max-delay-slot-live-searchโ when trying to fill delay slots, this is the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, which increases compilation time. This parameter should be removed when the delay slot code is rewritten to maintain the control-flow graph.max-gcse-memoryโ the approximate maximum amount of memory inkBthat can be allocated in order to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization is simply not done. it said "no thoughts, head empty"max-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream.max-pending-list-lengthโ the maximum number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources.max-modulo-backtrack-attemptsโ the maximum number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time. ๐max-inline-functions-called-once-loop-depthโ maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once.max-inline-functions-called-once-insnsโ maximal estimated size of functions produced while inlining functions called once.max-inline-insns-singleโ several parameters control the tree inliner used in GCC. This number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions 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 would otherwise not be considered for inlining by the compiler get investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto).max-inline-insns-smallโ this is the bound applied to calls which are considered relevant with-finline-small-functions.max-inline-insns-sizeโ this is the bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization opportunities exposed by inlining.uninlined-function-insnsโ number of instructions accounted by the inliner for function overhead such as function prologue and epilogue.uninlined-function-timeโ extra time accounted by the inliner for function overhead such as time needed to execute 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 hint that inlining is very profitable (it will enable later optimizations). โจuninlined-thunk-insns,uninlined-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 larger than this limit after inlining, inlining is constrained by--param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by non-linear algorithms used by the back end.large-function-growthโ specifies maximal growth of a large function caused by inlining, in percents. For example, parameter value100limits large function growth to 2.0 times the original size.large-unit-insnsโ the limit specifying a large translation unit. Growth caused by inlining of units larger than this limit is limited by--param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of function A that is inline and B that just calls A three times. If B is small relative to A, the growth of the unit is300\%and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. Thus for smaller units, the size is increased to--param large-unit-insnsbefore applying--param inline-unit-growth.lazy-modulesโ maximum number of concurrently open C++ module files when lazy loading.inline-unit-growthโ specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value20limits 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 maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value10limits unit growth to 1.1 times the original size. growth limits, keeping the codebase snatched since forever ๐
ipa-cp-large-unit-insnsโ the size a translation unit has to hit before the IPA-CP pass is like "okay bestie, this one is large". ๐large-stack-frameโ the cutoff that defines what counts as a large stack frame. While it's doing its inlining thing, the algorithm is actively trying not to grow past this limit too much. ๐ซถlarge-stack-frame-growthโ the maximal growth of large stack frames that inlining is allowed to cause, expressed in percents. So for example, a parameter value of1000limits large stack frame growth to 11 times the original size. yes, eleven. iconic math behavior. โจmax-inline-insns-recursive,max-inline-recursive-depthโฆ okay wait, let's take these in pairs like the original does, because they're a duo. ๐max-inline-insns-recursive,max-inline-insns-recursive-autoโ the maximum number of instructions that an out-of-line copy of a self-recursive inline function can grow into by doing recursive inlining.--param max-inline-insns-recursiveapplies to functions declaredinline. For functions not declaredinline, recursive inlining only happens when-finline-functions(which is included in-O3) is enabled, and--param max-inline-insns-recursive-autoapplies instead. iykyk ๐ธmax-inline-recursive-depth,max-inline-recursive-depth-autoโ the maximum recursion depth used for recursive inlining.--param max-inline-recursive-depthapplies to functions declaredinline. For functions not declaredinline, recursive inlining only happens when-finline-functions(included in-O3) is enabled, and--param max-inline-recursive-depth-autoapplies instead. same energy, different depth. ๐ฆmin-inline-recursive-probabilityโ so recursive inlining is only profitable for functions that have deep recursion on average, and it can actively hurt functions with little recursion depth by bloating 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 the 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โ the growth the early inliner is allowed to make. In effect it increases the amount of inlining for code that has a large abstraction penalty. lowkey a glow-up for your abstractions. ๐max-early-inliner-iterationsโ the limit on iterations of the early inliner. This basically bounds the number of nested indirect calls the early inliner can resolve. Deeper chains are still handled by late inlining, bestie, don't worry. ๐งcomdat-sharing-probabilityโ the probability (in percent) that a C++ inline function with comdat visibility gets shared across multiple compilation units.modref-max-bases,modref-max-refs,modref-max-accessesโ the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. three lil caps, one big vibe. ๐modref-max-testsโ the maximal 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โ the maximum depth of the DFS walk used by modref escape analysis.
Setting this to 0 disables the analysis completely. ๐ญ just fully off, no take-backs.
modref-max-escape-pointsโ the maximum number of escape points tracked by modref per SSA-name.modref-max-adjustmentsโ 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 that's based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. nostalgia-friendly profiles fr fr ๐min-vect-loop-boundโ the minimum number of iterations under which loops are not vectorized when-ftree-vectorizeis used. The number of iterations after vectorization needs to be greater than the value specified by this option to allow vectorization.gcse-cost-distance-ratioโ the scaling factor used to calculate 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., the expressions that cost less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions. ๐gcse-unrestricted-costโ the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations stop constraining the distance an expression can travel. This is currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting 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 of 0 does not 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 with. Used to dodge 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 is 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 attempting 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 attempt to merge them into wider stores in the store merging pass.max-unrolled-insnsโ the maximum number of instructions a loop may have in order to be unrolled. If a loop is unrolled, this parameter also determines 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 in order to be unrolled. If a loop is unrolled, this parameter also determines 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 in order to be peeled. If a loop is peeled, this parameter also determines 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 the loop invariant motion.min-loop-cond-split-probโ when FDO profile information is available,min-loop-cond-split-probspecifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split.iv-consider-all-candidates-boundโ the bound on the number of candidates for induction variables, below which all candidates are considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered, to avoid quadratic time complexity. ๐ฎโ๐จiv-max-considered-usesโ the induction variable optimizations give up on loops that contain more induction variable uses.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โ the bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down.scev-max-expr-complexityโ the bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down. it's giving "keep it simple bestie". ๐max-tree-if-conversion-phi-argsโ the maximum number of arguments in a PHI supported by TREE if conversion, unless the loop is marked with thesimdpragma.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 used to enhance access alignment for the vectorizer.
A value of -1 means no limit. ๐
max-iterations-to-trackโ the maximum number of iterations of a loop that the brute-force algorithm for analysis of the number of iterations of the loop tries to evaluate. ๐hot-bb-count-fractionโ the denominatornof fraction1/nof the maximal execution count of a basic block in the entire program that a basic block needs to at least have in order to be considered hot. The default is10000, which means a basic block is considered hot if its execution count is greater than1/10000of the maximal execution count.0means it is 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 to which the execution count of a basic block must be part of in order to be considered hot. The default is990, which means a basic block is considered hot if its execution count contributes to the upper990permilles, or99.0%, of the profiled execution of the entire program.0means it is never considered hot. Used in LTO mode. ๐hot-bb-frequency-fractionโ the denominatornof fraction1/nof the execution frequency of the entry block of a function that a basic block of this function needs to at least have in order to be considered hot. The default is1000, which means a basic block is considered hot in a function if it is executed more frequently than1/1000of the frequency of the entry block of the function.0means it is never considered hot. โจunlikely-bb-count-fractionโ the denominatornof fraction1/nof the number of profiled runs of the entire program below which the execution count of a basic block must be in order for the basic block to be considered unlikely executed. The default is20, which means a basic block is considered unlikely executed if it is executed in fewer than1/20, or5%, of the runs of the program.0means it is always considered unlikely executed. ๐ญmax-predicted-iterationsโ the maximum number of loop iterations we predict statically. This is useful in cases where a function contains a single loop with known bound and another loop with unknown bound. The known number of iterations is predicted correctly, while the unknown number of iterations average to roughly10. This means the loop without bounds appears artificially cold relative to the other one. ๐ฅถbuiltin-expect-probabilityโ control the probability of the expression having the specified value. This parameter takes a percentage (i.e.0 ... 100) as input. ๐ฒbuiltin-string-cmp-inline-lengthโ the maximum length of a constant string for a builtin string cmp call eligible for inlining. ๐งตalign-thresholdโ select fraction of the maximal frequency of executions of a basic block in a function to align the basic block. ๐align-loop-iterationsโ a loop expected to iterate at least the selected number of iterations is aligned. ๐tracer-dynamic-coverage,tracer-dynamic-coverage-feedbackโ this value is used to limit superblock formation once the given percentage of executed instructions is covered. This limits unnecessary code size expansion. Thetracer-dynamic-coverage-feedbackparameter is used only when profile feedback is available. The real profiles (as opposed to statically estimated ones) are much less balanced allowing the threshold to be larger value. ๐tracer-max-code-growthโ stop tail duplication once code growth has reached given percentage. This is a rather artificial limit, as most of the duplicates are eliminated later in cross jumping, so it may be set to much higher values than is the desired code growth. ๐งtracer-min-branch-ratioโ stop reverse growth when the reverse probability of 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 probability lower than this threshold. Similarly totracer-dynamic-coveragetwo parameters are provided.tracer-min-branch-probability-feedbackis used for compilation with profile feedback andtracer-min-branch-probabilitycompilation without. The value for compilation with profile feedback needs to be more conservative (higher) in order to make tracer effective. โฉstack-clash-protection-guard-sizeโ specify the size of the operating system provided stack guard as2raised tonumbytes. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks. ๐ก๏ธstack-clash-protection-probe-intervalโ stack clash protection involves probing stack space as it is allocated. This param controls the maximum distance between probes into the stack as2raised tonumbytes. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks. ๐max-cse-path-lengthโ the maximum number of basic blocks on path that CSE considers. ๐ฃ๏ธmax-cse-insnsโ the maximum number of instructions CSE processes before flushing. ๐งผggc-min-expandโ GCC uses a garbage collector to manage its own memory allocation. 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 is30% + 70% * (RAM/1GB)with an upper bound of100%whenRAM >= 1GB. Ifgetrlimitis available, the notion ofRAMis the smallest of actual RAM andRLIMIT_DATAorRLIMIT_AS. If GCC is not able to calculate RAM on a particular platform, the lower bound of30%is used. Setting this parameter andggc-min-heapsizeto zero causes a full collection to occur at every opportunity. This is extremely slow, but can be useful for debugging. ๐๏ธggc-min-heapsizeโ minimum size of the garbage collector's heap before it begins bothering to collect garbage. The first collection occurs after the heap expands byggc-min-expand%beyondggc-min-heapsize. Again, tuning this may improve compilation speed, and has no effect on code generation. The default is the smaller ofRAM/8,RLIMIT_RSS, or a limit that tries to ensure thatRLIMIT_DATAorRLIMIT_ASare not exceeded, but with a lower bound of4096(four megabytes) and an upper bound of131072(128 megabytes). If GCC is not able to calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter andggc-min-expandto zero causes a full collection to occur at every opportunity. ๐งmax-reload-search-insnsโ the maximum number of instruction reload should look backward for equivalent register. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance. โณmax-cselib-memory-locationsโ the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance. ๐งฎmax-sched-ready-insnsโ the maximum number of instructions ready to be issued the scheduler should consider at any given time during the first scheduling pass. Increasing values mean more thorough searches, making the compilation time increase with probably little benefit. ๐ดmax-sched-region-blocksโ the maximum number of blocks in a region to be considered for interblock scheduling. ๐งฑmax-pipeline-region-blocksโ the maximum number of blocks in a region to be considered for pipelining in the selective scheduler. ๐ฐmax-sched-region-insnsโ the maximum number of insns in a region to be considered for interblock scheduling. ๐ฆmax-pipeline-region-insnsโ the maximum number of insns in a region to be considered for pipelining in the selective scheduler. ๐งmin-spec-probโ the minimum probability (in percents) of reaching a source block for interblock speculative scheduling. ๐ฏmax-sched-extend-regions-itersโ the maximum number of iterations through CFG to extend regions. A value of0disables region extensions. ๐ซmax-sched-insn-conflict-delayโ the maximum conflict delay for an insn to be considered for speculative motion. โฑ๏ธsched-spec-prob-cutoffโ the minimal probability of speculation success (in percents), so that speculative insns are scheduled. ๐ฒsched-state-edge-prob-cutoffโ the minimum probability an edge must have for the scheduler to save its state across it. ๐พsched-mem-true-dep-costโ minimal distance (in CPU cycles) between store and load targeting same memory locations. ๐งselsched-max-lookaheadโ the maximum size of the lookahead window of selective scheduling. It is a depth of search for available instructions. ๐selsched-max-sched-timesโ the maximum number of times that an instruction is 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 swing modulo scheduler generates. ๐๏ธmax-last-value-rtlโ the biggest size, measured as a count of RTLs, that can get recorded for an expression in the combiner when it's tracking a pseudo register as that register's last known value. RTL counting era ๐max-combine-insnsโ the most instructions the RTL combiner will even try to combine. Bestie it has a limit and this is it.integer-share-limitโ small integer constants can share one data structure, which saves compiler memory and makes it faster. This sets the max value of a shared integer constant. sharing is caring fr fr ๐ซถssp-buffer-sizeโ the minimum size of buffers (aka arrays) that get stack smashing protection when-fstack-protectoris in play.
Fun lore: before Ubuntu 10.10 this default was"8". Currently it's"4", so more functions get protected by the stack protector. glow up โจ
min-size-for-stack-sharingโ the minimum size of variables that get to participate in stack slot sharing when we're not optimizing.max-jump-thread-duplication-stmtsโ max 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 while hunting for jump threading opportunities. When it arrives at a block, incoming edges only get considered if the number of paths searched so far, multiplied by the number of incoming edges, doesn't blow past this max.max-fields-for-field-sensitiveโ max number of fields in a struct that get treated in a field-sensitive way during pointer analysis.prefetch-latencyโ an estimate of the average number of instructions executed before a prefetch finishes. The distance prefetched ahead is proportional to this constant. Bumping it up may also mean fewer streams get prefetched (go peek atsimultaneous-prefetches).simultaneous-prefetchesโ max number of prefetches that can be running at the same time. multitasking queen ๐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 aren't constant. Sometimes that's a win, though the fact that the stride isn't constant can make it hard to tell when there's a clear benefit to issuing those hints.
Set to 1 if prefetch hints should be issued for non-constant strides. Set to 0 if prefetch hints should only be issued for strides that are known to be constant and below prefetch-minimum-stride.
prefetch-minimum-strideโ minimum constant stride, in bytes, to start using prefetch hints for. If the stride is under this threshold, prefetch hints won't be issued. under the threshold = no hints bestie ๐
This setting is useful for processors that have hardware prefetchers, since then there can be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, that's what you should put here to improve how the software prefetchers get used.
A value of -1 means there's no threshold, so prefetch hints can be issued for any constant stride.
This setting is only useful for strides that are known and constant.
destructive-interference-sizeconstructive-interference-size
The values for the C++17 variables std::hardware_destructive_interference_size and std::hardware_constructive_interference_size. The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both are 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 is the small end of the range and the destructive size is the large end.
The destructive interference size is meant for layout, so it has ABI impact. The default value is not expected to be stable, and on some targets it varies with -mtune, so using this variable in a context where ABI stability matters โ like the public interface of a library โ is strongly discouraged. If it does get used in that context, users can stabilize the value with this option.
The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure a type fits inside a cache line.
See also -Winterference-size.
loop-interchange-max-num-stmtsโ the max number of stmts in a loop that can be interchanged.loop-interchange-stride-ratioโ the minimum ratio between the strides of two loops for interchange to be profitable. do the math before you swap ๐min-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches needed to enable prefetching in a loop.prefetch-min-insn-to-mem-ratioโ the minimum ratio between the number of instructions and the number of memory references needed to enable prefetching in a loop.use-canonical-typesโ whether the compiler should use the"canonical"type system. Should always be1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. But if bugs in the canonical type system are causing compilation failures, set this value to0to disable canonical types.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.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 run away and consume all the memory available on the host machine. This parameter puts a limit on the length of the sets that get computed, which stops the runaway behavior. Setting a value of0for this parameter allows an unlimited set length. unlimited = unhinged, be careful bestie ๐ญrpo-vn-max-loop-depthโ 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 get value-numbered optimistically, and the rest don't.sccvn-max-alias-queries-per-accessโ max number of alias-oracle queries performed when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and the load or store isn't 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 that many of the most frequently-executed loops form regions for regional register allocation.ira-max-conflict-table-sizeโ even though IRA uses a sophisticated algorithm to compress the conflict table, that table can still need excessive amounts of memory for huge functions. If a function's conflict table 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 doesn't need to build a pseudo-register conflict table.ira-loop-reserved-regsโ IRA can be used to evaluate more accurate register pressure in loops for decisions about moving loop invariants (see-O3). The number of available registers reserved for some other purposes is given by this parameter. The default is the best found from numerous experiments. science slay โจira-consider-dup-in-all-altsโ makes IRA consider matching constraint (duplicated operand number) heavily in all available alternatives for the preferred register class. If it's set to zero, IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, IRA will check all available alternatives for the preferred register class even if it already found some choice with an appropriate register class, and respect the qualified matching constraint it found.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 the region to do this optimization in. The parameter defines a minimal fall-through edge probability, in percentage, used to add a BB to the inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64.loop-invariant-max-bbs-in-loopโ loop invariant motion can be very expensive, both in compilation time and in the amount of compile-time memory needed, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them.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 aren't handled by the optimizations that use loop data dependencies. big loop = left on read ๐
okay bestie we're back in the --param section and it is <em>dense</em> but honestly kind of iconic?? every single one of these is a knob you can turn with --param <name>=<value> when you're feeling brave. buckle up ๐
--param max-vartrack-sizeโ sets a max number of hash table slots to use during variable tracking dataflow analysis of any function. if this limit gets exceeded while variable tracking at assignments is enabled, the analysis for that function gets retried without it, after removing all debug insns from the function. and if the limit is exceeded even without debug insns? then var tracking analysis is completely disabled for that function. setting the parameter to zero makes it unlimited. ๐--param max-vartrack-expr-depthโ sets a max number of recursion levels when the compiler tries to map variable names or debug temporaries to value expressions. it's a trade: compilation time for more complete debug info. if you set this too low, value expressions that are available and could be represented in debug information may end up not being used; setting it higher may let the compiler find more complex debug expressions, but compile time and memory use may grow. ๐ฆ--param max-debug-marker-countโ sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. if a function has more such gimple stmts than the set limit, those stmts get dropped from the inlined copy of a function, and from its RTL expansion. no cap fr. ๐--param min-nondebug-insn-uidโ use uids starting at this parameter for nondebug insns. the range below the parameter is reserved exclusively for debug insns created by-fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted. ๐ง--param ipa-sra-deref-prob-thresholdโ IPA-SRA replaces a pointer which is known not be NULL with one or more new parameters only when the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter. โจ--param ipa-sra-ptr-growth-factorโ IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter. ๐ธ--param ipa-sra-ptrwrap-growth-factorโ additional maximum allowed growth of total size of new parameters that ipa-sra replaces a pointer to an aggregate with, if it points to a local variable that the caller only writes to and passes it as an argument to other functions. ๐ซถ--param ipa-sra-max-replacementsโ maximum pieces of an aggregate that IPA-SRA tracks. as a consequence, it is also the maximum number of replacements of a formal parameter. ๐--param sra-max-scalarization-size-Ospeed,--param sra-max-scalarization-size-Osizeโ the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. these parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively. ๐--param sra-max-propagationsโ the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation. ๐--param tm-max-aggregate-sizeโ when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. this option only applies when using-fgnu-tm. ๐--param graphite-max-nb-scop-paramsโ to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. a value of zero can be used to lift the bound. a variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP. ๐ฅ--param loop-block-tile-sizeโ loop blocking or strip mining transforms, enabled with-floop-blockor-floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. the strip length can be changed using theloop-block-tile-sizeparameter. ๐--param ipa-jump-function-lookupsโ specifies number of statements visited during jump function offset discovery. ๐ฆ--param ipa-cp-value-list-sizeโ IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization.ipa-cp-value-list-sizeis the maximum number of values and types it stores per one formal parameter of a function. โญ--param ipa-cp-eval-thresholdโ IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceedipa-cp-eval-threshold. ๐--param ipa-cp-max-recursive-depthโ maximum depth of recursive cloning for self-recursive function. ๐--param ipa-cp-min-recursive-probabilityโ recursive cloning only when the probability of call being executed exceeds the parameter. โจ--param ipa-cp-profile-count-baseโ when using-fprofile-useoption, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation. ๐ธ--param ipa-cp-recursive-freq-factorโ the number of times interprocedural copy propagation expects recursive functions to call themselves. ๐--param ipa-cp-recursion-penaltyโ percentage penalty the recursive functions will receive when they are evaluated for cloning. ๐ญ--param ipa-cp-single-call-penaltyโ percentage penalty functions containing a single call to another function will receive when they are evaluated for cloning. ๐--param ipa-max-agg-itemsโ IPA-CP is also capable to propagate a number of scalar values passed in an aggregate.ipa-max-agg-itemscontrols the maximum number of such values per one parameter. ๐--param ipa-cp-loop-hint-bonusโ when IPA-CP determines that a cloning candidate would make the number of iterations of a loop known, it adds a bonus ofipa-cp-loop-hint-bonusto the profitability score of the candidate. ๐--param ipa-max-loop-predicatesโ the maximum number of different predicates IPA will use to describe when loops in a function have known properties. ๐ฆ--param ipa-max-aa-stepsโ during its analysis of function bodies, IPA-CP employs alias analysis in order to track values pointed to by function parameters. in order not spend too much time analyzing huge functions, it gives up and consider all memory clobbered after examiningipa-max-aa-stepsstatements modifying memory. ๐ฅ--param ipa-max-switch-predicate-boundsโ maximal number of boundary endpoints of case ranges of switch statement. for switch exceeding this limit, IPA-CP will not construct cloning cost predicate, which is used to estimate cloning benefit, for default case of the switch statement. ๐--param ipa-max-param-expr-opsโ IPA-CP will analyze conditional statement that references some function parameter to estimate benefit for cloning upon certain constant value. but if number of operations in a parameter expression exceedsipa-max-param-expr-ops, the expression is treated as complicated one, and is not handled by IPA analysis. ๐--param lto-partitionsโ specify desired number of partitions produced during WHOPR compilation. the number of partitions should exceed the number of CPUs used for compilation. โญ--param lto-min-partitionโ size of minimal partition for WHOPR (in estimated instructions). this prevents expenses of splitting very small programs into too many partitions. ๐--param lto-max-partitionโ size of max partition for WHOPR (in estimated instructions). to provide an upper bound for individual size of partition. meant to be used only with balanced partitioning. ๐--param lto-max-streaming-parallelismโ maximal number of parallel processes used for LTO streaming. ๐--param cxx-max-namespaces-for-diagnostic-helpโ the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. bestie this one is literally just the compiler being nice to you ๐ญ--param sink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block to allow statement sinking of a statement. larger numbers result in more aggressive statement sinking. a small positive adjustment is applied for statements with memory operands as those are even more profitable so sink. โจ--param max-stores-to-sinkโ the maximum number of conditional store pairs that can be sunk. set to 0 if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled. ๐ธ--param case-values-thresholdโ the smallest number of different values for which it is best to use a jump-table instead of a tree of conditional branches. if the value is 0, use the default for the machine. ๐ซถ--param jump-table-max-growth-ratio-for-sizeโ the maximum code size growth ratio when expanding into a jump table (in percent). the parameter is used when optimizing for size. ๐--param jump-table-max-growth-ratio-for-speedโ the maximum code size growth ratio when expanding into a jump table (in percent). the parameter is used when optimizing for speed. ๐ฅ--param tree-reassoc-widthโ set the maximum number of instructions executed in parallel in reassociated tree. this parameter overrides target dependent heuristics used by default if has non zero value. ๐
and we're STILL going, the parameter list is giving infinite scroll energy ๐ more incoming bestie don't move
sched-pressure-algorithmโ picks which of the two available implementations of-fsched-pressureyou wanna run with. Algorithm 1 is the OG implementation, and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was designed as a compromise between algorithm 1's pretty conservative approach and the straight-up aggressive approach the default scheduler takes. It leans way harder on having a regular register file and accurate register pressure classes. Wanna know more? Go peek athaifa-sched.ccin the GCC sources, bestie. And the default choice? That depends on the target. ๐ฏmax-slsr-cand-scanโ sets the max number of existing candidates that get considered when we're out here seeking a basis for a new straight-line strength reduction candidate. ๐asan-globalsโ turns on buffer overflow detection for global objects. This kind of protection is on by default if you're using-fsanitize=address. Wanna turn global objects protection off?--param asan-globals=0. ๐ซถasan-stackโ turns on buffer overflow detection for stack objects. On by default when you use-fsanitize=address. To disable stack protection use the--param asan-stack=0option.asan-instrument-readsโ turns on buffer overflow detection for memory reads. On by default when using-fsanitize=address. To disable memory reads protection,--param asan-instrument-reads=0.asan-instrument-writesโ turns on buffer overflow detection for memory writes. On by default when using-fsanitize=address. To disable memory writes protection use the--param asan-instrument-writes=0option.asan-memintrinโ enables detection for built-in functions. On by default when using-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 when using the-fsanitize=addressoption. To disable it use--param asan-use-after-return=0.
โ ๏ธ Note, bestie: by default this check is disabled at run time. To actually enable it, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS. Don't forget, or you'll be sitting there like ๐๏ธ๐๐๏ธ wondering why nothing happened.
asan-instrumentation-with-call-thresholdโ if the number of memory accesses in the function being instrumented is greater 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 tomemcpy,memsetandmemmovewith__asan_or__hwasan_for-fsanitize=kernel-addressor-fsanitize=kernel-hwaddress, respectively. โจhwasan-instrument-stackโ enables hwasan instrumentation of statically sized stack-allocated variables. This kind of instrumentation is on by default when using-fsanitize=hwaddress, and off by default when using-fsanitize=kernel-hwaddress. To disable stack instrumentation use--param hwasan-instrument-stack=0, and to enable it use--param hwasan-instrument-stack=1. ๐ธhwasan-random-frame-tagโ when you're using stack instrumentation, this decides tags for stack variables using a deterministic sequence beginning at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. 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 when using-fsanitize=hwaddressand off by default when using-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 enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable checking memory reads use--param hwasan-instrument-reads=0.hwasan-instrument-writesโ enables hwasan checks on memory writes. Instrumentation of writes is enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable 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 enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To disable instrumentation of builtin functions use--param hwasan-instrument-mem-intrinsics=0.use-after-scope-direct-emission-thresholdโ if the size of a local variable in bytes is smaller or equal to this number, we directly poison (or unpoison) shadow memory instead of using run-time callbacks. ๐tsan-distinguish-volatileโ emit special instrumentation for accesses to volatiles.tsan-instrument-func-entry-exitโ emit instrumentation calls to__tsan_func_entry()and__tsan_func_exit().max-fsm-thread-path-insnsโ the maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.threader-debugโthreader-debug=[none|all]enables verbose dumping of the threader solver. ๐ต๏ธparloops-chunk-sizeโ 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 is two.max-ssa-name-query-depthโ maximum depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion corresponds to following a use-def chain. ๐max-speculative-devirt-maydefsโ the maximum number of may-defs we analyze when looking for a must-def specifying the dynamic type of an object that invokes a virtual call we may be able to devirtualize speculatively.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.unroll-jam-min-percentโ the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable. ๐ธunroll-jam-max-unrollโ the 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 is considered unpredictable.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris used, this is the maximum number of times that an individual variable will be expanded during loop unrolling.partial-inlining-entry-probabilityโ maximum probability of the entry BB of split region (in percent relative to entry BB of the function) to make partial inlining 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 loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enable loop epilogue vectorization using 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. Oh and โ 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 when we're spilling a non-reload pseudo. like, we're only looking at this many, bestie ๐max-pow-sqrt-depthโ maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant. sqrt chains are so real for this โจmax-dse-active-local-storesโ maximum number of active local stores in RTL dead store elimination.asan-instrument-allocasโ enable asan allocas/VLAs protection. we're protecting the allocas, periodt ๐ก๏ธmax-iterations-computation-costโ a bound on the cost of an expression to compute the number of iterations.max-isl-operationsโ maximum number of isl operations.0means unlimited, no cap fr fr ๐graphite-max-arrays-per-scopโ maximum number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of loc list for which reverse ops should be added.fsm-scale-path-stmtsโ scale factor to apply to the number of statements in a threading path crossing a loop backedge when comparing to--param=max-jump-thread-duplication-stmts.uninit-control-dep-attemptsโ maximum number of nested calls to search for control dependencies during uninitialized variable analysis. it's giving recursion energy ๐ญ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. the number of lookahead cycles the model looks into; at' 'only enable the instruction sorting heuristic. lowkey a vibe check for the scheduler ๐loop-versioning-max-inner-insnsโ the maximum number of instructions that an inner loop can have before the loop versioning pass considers it too big to copy.loop-versioning-max-outer-insnsโ the maximum number of instructions that an outer loop can have before the loop versioning pass considers it too big to copy, discounting any instructions in inner loops that directly benefit from versioning.ssa-name-def-chain-limitโ the maximum number of SSA_NAME assignments to follow in determining a property of a variable such as its value. this limits the number of iterations or recursive calls GCC performs when optimizing certain statements or when determining their validity prior to issuing diagnostics.store-merging-max-sizeโ maximum size of a single store merging region in bytes.hash-table-verification-limitโ the number of elements for which hash table verification is done for each searched element.max-find-base-term-valuesโ maximum number of VALUEs handled during a single find_base_term call.analyzer-max-enodes-per-program-pointโ the maximum number of exploded nodes per program point within the analyzer, before terminating analysis of that point. we're done analyzing, bye โanalyzer-max-constraintsโ the maximum number of constraints per state.analyzer-min-snodes-for-call-summaryโ the minimum number of supernodes within a function for the analyzer to consider summarizing its effects at call sites.analyzer-max-enodes-for-full-dumpโ the maximum depth of exploded nodes that should appear in a dot dump before switching to a less verbose format. we're going less verbose, bestie ๐analyzer-max-recursion-depthโ the maximum number of times a callsite can appear in a call stack within the analyzer, before terminating analysis of a call that would recurse deeper.analyzer-max-svalue-depthโ the maximum depth of a symbolic value, before approximating the value as unknown.analyzer-max-infeasible-edgesโ the maximum number of infeasible edges to reject before declaring a diagnostic as infeasible.gimple-fe-computed-hot-bb-thresholdโ the number of executions of a basic block which is considered 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 terminating analysis. explosion factor is such a name ngl ๐ranger-logical-depthโ maximum depth of logical expression evaluation 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โ specify the mode of OpenACCkernelsconstructs handling. with--param=openacc-kernels=decompose, OpenACCkernelsconstructs are 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. this is the current default.openacc-privatizationโ control 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 includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores. the way that it just... fits them in bigger boxes ๐
aarch64-float-recp-precisionโ the number of Newton iterations for calculating the reciprocal forfloattype. the precision of division is proportional to this param when division approximation is enabled. the default value is1.aarch64-double-recp-precisionโ the number of Newton iterations for calculating the reciprocal fordoubletype. the precision of division is propotional to this param when division approximation is enabled. the default value is2.
(yes bestie, that typo says "propotional" in the original and we are NOT fixing it. respect the source ๐ )
aarch64-autovec-preferenceโ force an ISA selection strategy for auto-vectorization. accepts values from0to4, inclusive.0โ use the default heuristics.1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE. prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE. prefer SVE when the costs are deemed equal.
the default value is 0.
aarch64-loop-vect-issue-rate-nitersโ the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. if this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations.aarch64-vect-unroll-limitโ the vectorizer will use available tuning information to determine whether it would be beneficial to unroll the main vectorized loop and by how much. this parameter set's the upper bound of 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โ instructions number above which STFL stall penalty can be compensated.x86-stv-max-visitsโ the maximum number of use and def visits when discovering a STV chain before the discovery is aborted.
๐ Program Instrumentation Options ๐
GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates. like, it's literally adding little spy cameras to your program, but make it fashion ๐ธ
for example, one purpose of instrumentation is to collect profiling statistics for use in finding program hot spots, code coverage analysis, or profile-guided optimizations. another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, as well as deliberately hostile attacks such as stack smashing or C++ vtable hijacking. we're detecting the haters ๐จ
there is also a general hook which can be used to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes.
-p-pgโ generate extra code to write profile information suitable for the analysis programprof(for-p) orgprof(for-pg). you must use this option when compiling the source files you want data about, and you must also use it when linking. both times bestie, don't skip it ๐ค
you can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.
-fprofile-arcsโ add code so that program flow arcs 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).
quick note bestie โ if your command line straight up links source files, the matching.gcdafiles get prefixed with the unsuffixed name of the output file. Like,gcc a.c b.c -o binaryis gonna spit outbinary-a.gcdaandbinary-b.gcda. that's just how it is ๐
--coverageโ this one is for compiling and linking code that's been instrumented for coverage analysis. It's literally a synonym for-fprofile-arcs -ftest-coverage(when you're compiling) and-lgcov(when you're linking). Wanna know more? Go read the docs for those options, they've got the whole lore. ๐- Compile the source files with
-fprofile-arcsplus your optimization and code generation options. For test coverage analysis specifically, also use-ftest-coverage. Oh and โ you do not need to profile every single source file in a program. not all of them have to be the main character. - Compile the source files additionally with
-fprofile-abs-pathso you get absolute path names in the.gcnofiles. This is what letsgcovfind the right sources in projects where compilations happen with different working directories. lowkey essential. - Link your object files with
-lgcovor-fprofile-arcs(the second one implies the first one, she contains multitudes โจ). - Run the program on a representative workload to generate the arc profile information. You can do this as many times as you want, no cap. You can even run concurrent instances of your program โ and as long as the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect,
forkcalls get detected and handled correctly without double counting. obsessed.- Also, an object file can be recompiled multiple times and the corresponding
.gcdafile merges, as long as the source file and the compiler options are unchanged. slay.
- Also, an object file can be recompiled multiple times and the corresponding
- 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. Refer to thegcovdocumentation for further info. ๐
- Compile the source files with
So 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 the number of times those arcs are 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 genuinely iconic ๐ง
-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. Wanna know whatauxnameeven means, and how to generate test coverage data? Refer back to the-fprofile-arcsoption above, bestie. oh and heads up: coverage data matches the source files more closely if you do not optimize. ๐-fprofile-abs-pathโ automatically convert relative source file names to absolute path names in the.gcnofiles. This letsgcovfind the correct sources in projects where compilations occur with different working directories. it's giving helpful fr fr.-fprofile-dir=pathโ set the directory to search for the profile data files in to path. This option affects only the profile data generated by-fprofile-generate,-ftest-coverage,-fprofile-arcs, and 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 isn't 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 in-fprofile-arcs. Also peep 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. You can do that with variables in path that get exported during run-time:
%pโ process ID.%q{VAR}โ value of environment variableVAR.
-fprofile-generate-fprofile-generate=pathโ enable options usually used for instrumenting an application to produce a profile that's useful for later recompilation with profile feedback based optimization. You must use-fprofile-generateboth when compiling and when linking your program. periodt.
The following options get 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-arcsis placed in the specified section for each translation unit. This option disables the profile information registration through a constructor, and it disables the profile information processing through a destructor. This option is not intended to be used in hosted environments like 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. Here's a GNU linker script example that defines a linker output section:
.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. โ ๏ธ But if you combine this option with multiple source files, the.gcnofile will be overwritten. so like, careful bestie.-fprofile-prefix-path=pathโ this option 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. This is not desirable when the directory used to build the instrumented binary differs from the directory used to build the binary optimized with profile feedback, because the profile data will not be found during the optimized build. In such setups,-fprofile-prefix-path=pathwith path pointing to the base directory of the build can be used to strip the irrelevant part of the path and keep all file names relative to the main build directory. ๐-fprofile-prefix-map=old=newโ when compiling files residing in directory old, record profiling information (with--coverage) describing them as if the files resided in directory new instead. See also-ffile-prefix-mapand-fcanon-prefix-map. cute little rename moment โจ-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 doesn't properly join all threads (or creates a detached thread), a profile file can still be corrupted. no cap, watch out. ๐
Using prefer-atomic would be transformed either to atomic, when supported by a target, or to single otherwise. The GCC driver automatically selects prefer-atomic when -pthread is present in the command line. she just knows ๐
-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]โ bestie, this one controls how reproducible the profile that-fprofile-generatecollects actually is. Why do you care? Because it lets you rebuild a program and get the same outcome every time, which is chef's kiss for distribution packages. ๐
With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible as long as the trained program behaves the same on every invocation of the train run, it's not multi-threaded, and profile data streaming always happens in the same order. Heads up though: profile streaming goes down at the end of the program run, but also before the fork function gets invoked. ๐ซถ
Ngl, it's super common that execution counts of some parts of programs depend on stuff like the length of temporary file names, or memory space randomization (which can mess with the hash-table collision rate). That kind of non-reproducible part can be annotated with the no_instrument_function function attribute. And gcov-dump with -l can dump the gathered data so you can verify it's actually reproducible. ๐
With -fprofile-reproducible=parallel-runs, the collected profile stays reproducible no matter what order the data streams into the gcda files. This setting lets you run multiple instances of the instrumented program in parallel (like with make -j). Fair warning bestie: this reduces the quality of the gathered data, especially for indirect call profiling. ๐ญ
-fsanitize=addressโ turn on AddressSanitizer, the fast memory error detector. Memory access instructions get instrumented so it can catch out-of-bounds and use-after-free bugs. This option also enables-fsanitize-address-use-after-scope. Want the tea? See<https://github.com/google/sanitizers/wiki/AddressSanitizer>for more deets. The run-time behavior can be influenced using theASAN_OPTIONSenvironment variable. Set it tohelp=1and the available options get shown at startup of the instrumented program. See<https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags>for a list of supported options.
Okay so this is a big one: the option cannot be combined with-fsanitize=threador-fsanitize=hwaddress. And ngl, the only target-fsanitize=hwaddressis currently supported on is AArch64.
To get more accurate stack traces, you can use options like -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which 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). And 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 so it can detect memory errors with low memory overhead. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This 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.
Fr fr, this one cannot be combined with-fsanitize=threador-fsanitize=address, and it's currently only available on AArch64.
-fsanitize=kernel-hwaddressโ enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel. It's similar to-fsanitize=kernel-addressbut uses an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences that are necessary for compiling the Linux kernel. Those differences? Avoiding hwasan library initialization calls, and accounting for the stack pointer having a different value in its top byte. ๐ธ
Note bestie: this option has different defaults than-fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but they're still possible by specifying the command-line options--param hwasan-instrument-stack=1and--param hwasan-instrument-allocas=1respectively. And using a random frame tag is not implemented for kernel instrumentation. ๐
-fsanitize=pointer-compareโ instruments comparison operations (<,<=,>,>=) with pointer operands. This option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. It cannot be combined with-fsanitize=thread.
Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to 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. This option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. It cannot be combined with-fsanitize=thread.
Note: by default the check is disabled at run time. To enable it, adddetect_invalid_pointer_pairs=2to 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). How does it work? It saves a function's return address to a separately allocated shadow call stack in the function prologue, and restores 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, and it's specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc. 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's 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 get 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, periodt. Build a program with this on and if you hit the end of a non-void function without actually returning a value, it's gonna throw an error message at you. C++ only, so don't come at me if you're writing C. ๐-fsanitize=signed-integer-overflowโ signed integer overflow checking, let's gooo. We're checking that the result of+,*, and both unary and binary-does not overflow in the signed arithmetics. Also snitches onINT_MIN / -1signed division, iconic. Note: integer promotion rules must be taken into account, so like, the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ instrumentation of array bounds, slay. Various out of bounds accesses get detected. Now the receipts: flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented, with the exception of flexible array member-like arrays for which-fstrict-flex-arraysor-fstrict-flex-arrays=options orstrict_flex_arrayattributes say they shouldn't be treated like flexible array member-like arrays. iykyk. โจ-fsanitize=bounds-strictโ the strict version, highkey. Strict instrumentation of array bounds: most out of bounds accesses get detected, including flexible array member-like arrays. Initializers of variables with static storage are not instrumented tho.-fsanitize=alignmentโ checking the 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. vibe check for your pointers fr. ๐ฆ-fsanitize=object-sizeโ instrumentation of 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 listen, unlike other similar options,-fsanitize=float-divide-by-zerois not enabled by-fsanitize=undefined, because floating-point division by zero can legitimately be how you obtain infinities and NaNs. Not a bug, it's a feature bestie. ๐-fsanitize=float-cast-overflowโ floating-point type to integer conversion checking. We check that the result of the conversion doesn't overflow. And again, unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Heads up: this one does not work well withFE_INVALIDexceptions enabled. ๐ญ-fsanitize=nonnull-attributeโ instrumentation of calls, checking whether null values aren't passed to arguments marked as requiring a non-null value by thenonnullfunction attribute. no nulls allowed on this dance floor ๐-fsanitize=returns-nonnull-attributeโ instrumentation of return statements in functions marked withreturns_nonnullfunction attribute, to detect returning of null values from such functions. caught in 4k ๐ธ-fsanitize=boolโ instrumentation of loads from bool. If a value other than 0/1 is loaded, a run-time error is issued. it's giving "how did you even" ๐ธ-fsanitize=enumโ instrumentation of loads from an enum type. If a value outside the range of values for the enum type is loaded, a run-time error is issued. stay in your lane enum ๐-fsanitize=vptrโ instrumentation of C++ member function calls, member accesses and some conversions between pointers to base and derived classes, to verify the referenced object has the correct dynamic type. main character energy, verifying the vibe. ๐ฅ-fsanitize=pointer-overflowโ instrumentation of pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued. math class but for pointers ๐ง-fsanitize=builtinโ instrumentation of arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing0as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and is diagnosed by this option. ๐
Note that sanitizers tend to increase the rate of false positive warnings, most notably those around-Wmaybe-uninitialized. We recommend against combining-Werrorand [the use of] sanitizers. fr fr, don't do it.
While -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message. This currently works only for the C family of languages.
-fno-sanitize=allโ this option disables all previously enabled sanitizers. And no,-fsanitize=allis not allowed, because some sanitizers literally cannot be used together. it's not me, it's them ๐-fasan-shadow-offset=numberโ forces GCC to use a custom shadow offset in AddressSanitizer checks. Useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer. lab rat energy ๐งช-fsanitize-sections=s1,s2,...โ sanitize global variables in selected user-defined sections.simay contain wildcards. โจ-fsanitize-recover[=opts]โ-fsanitize-recover=controls error recovery mode for sanitizers mentioned in the comma-separated list ofopts. Enabling this option for a sanitizer component makes it attempt to continue running the program as if no error happened. That means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors have been reported. The-fno-sanitize-recover=option can be used to alter this behavior: only the first detected error is reported and the program then exits with a non-zero exit code.
Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all 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 a recovery mode is turned on the compiler side, it needs to be also enabled on the runtime library side, otherwise the failures are still fatal. The runtime library defaults to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. This can be overridden through setting the halt_on_error flag in the corresponding environment variable.
Syntax without an explicitoptsparameter is deprecated. It is equivalent to specifying anoptslist of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scopeโ enable sanitization of local variables to detect use-after-scope bugs. The option sets-fstack-reusetonone. ๐-fsanitize-trap[=opts]โ the-fsanitize-trap=option instructs the compiler to report for sanitizers mentioned in the comma-separated list ofoptsundefined behavior using__builtin_traprather than alibubsanlibrary routine. If this option is enabled for a certain sanitizer, it takes precedence over the-fsanitizer-recover=for that sanitizer,__builtin_trapwill be emitted and be fatal regardless of whether recovery is enabled or disabled using-fsanitize-recover=.
The advantage of this is that the libubsan library is not needed and is not linked in, so this is usable even in freestanding environments. no lib, no problem โจ
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 as the instrumentation always needs libubsan support, and -fsanitize-trap=vptr is not allowed.
-fsanitize-undefined-trap-on-errorโ this option is the deprecated equivalent of-fsanitize-trap=all. ๐-fsanitize-coverage=trace-pcโ enable coverage-guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_pcinto every basic block. fuzzing bestie era ๐-fsanitize-coverage=trace-cmpโ enable dataflow guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8for integral comparison with both operands variable, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8for integral comparison with one operand constant,__sanitizer_cov_trace_cmpfor__sanitizer_cov_trace_cmpdfor float or double comparisons, and__sanitizer_cov_trace_switchfor switch statements. the way this one just covers everything ๐-fcf-protection=[full|branch|return|none|check]โ enable code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid. This prevents diverting the flow of control to an unexpected target. It's intended to protect against such threats as Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP). cybersecurity era ๐ก๏ธ
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 for the final link with link-time optimization (LTO) โ and it's kind of a vibe check, fr. If your LTO object files got compiled with different -fcf-protection values, it throws an error. Also bestie, "check" gets completely ignored at compile time, like it's not even in the group chat. ๐
The macro __CET__ gets defined whenever -fcf-protection is in use. First bit of __CET__ = 1 for the value "branch", and the second bit = 1 for the "return". So cute, so tidy. โจ
You can also use the nocf_check attribute to pick which functions and calls get skipped from instrumentation. Iconic escape hatch energy. ๐ซถ
Currently the x86 GNU/Linux target is the one serving looks with 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 stored into boolean variables), it emits extra code that computes and verifies the reversed condition, and calls__builtin_trapif the results don't match up. ๐จ Use it with-fharden-conditional-branchesif you want full coverage of all the conditionals. No gaps, no crumbs.-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 calls__builtin_trapif the result is unexpected. ๐ญ Pair it with-fharden-comparesto cover, like, literally every conditional. Periodt.-fstack-protectorโ emits extra code to check for buffer overflows, such as stack smashing attacks. It does this by adding a guard variable to functions with vulnerable objects. That includes functions that callalloca, 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 is printed and the program exits. ๐ Only variables that are actually allocated on the stack count โ optimized-away variables or variables allocated in registers don't get a say.-fstack-protector-allโ same as-fstack-protectorexcept all functions are protected. Everybody gets a guard, nobody's left out. ๐-fstack-protector-strongโ like-fstack-protectorbut it also includes additional functions to be protected --- those that have local array definitions, or have references to local frame addresses. And again: only variables actually allocated on the stack are considered, so optimized-away variables or register-allocated variables don't count. โจ
NOTE: In Ubuntu 14.10 and later versions,-fstack-protector-strongis enabled by default for C, C++, ObjC, ObjC++, if none of-fno-stack-protector,-nostdlib, nor-ffreestandingare found. ๐
-fstack-protector-explicitโ like-fstack-protectorbut it only protects those functions which have thestack_protectattribute. Exclusive, invite-only, very main character. ๐-fstack-checkโ generates 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 if there's only one stack.
Lowkey important: this switch does not actually cause checking to be done โ the operating system or the language runtime has to do that. The switch just causes generation of code to ensure that they see the stack being extended. ๐ซถ
You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, specific means use the best checking method and is equivalent to bare -fstack-check.
Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie it comes with the following drawbacks:
- Modified allocation strategy for large objects: they 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โ generates code to prevent stack clash style attacks. When this option is enabled, the compiler will only allocate one page of stack space at a time and each page is accessed immediately after allocation. So it stops allocations from jumping over any stack guard page provided by the operating system. Iconic. ๐ง
Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. It may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.
NOTE: In Ubuntu 19.10 and later versions,-fstack-clash-protectionis enabled by default for C, C++, ObjC, ObjC++, unless-fno-stack-clash-protectionis found. ๐
-fstack-limit-register=reg</br>-fstack-limit-symbol=sym</br>-fno-stack-limitโ generates 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โ generates 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. It's 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 one is only available when compiling C++ code. It turns on (or off, if 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 on the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std. Ranked, bestie. ๐
-fvtv-debugโ when used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called. This flag also causes the compiler to log information about which vtable pointers it finds for each class. That info gets written to a file namedvtv_set_ptr_data.login the directory named by the environment variableVTV_LOGS_DIRif that 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. ๐๏ธ
-fvtv-countsโ this is a debugging flag. When used in conjunction with-fvtable-verify=stdor-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 all that to a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif 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 information tovtv_class_set_sizes.login the same directory. ๐ธ
Note: This feature appends data to the log files. To get fresh log files, be sure to delete any existing ones. ๐
-finstrument-functionsโ bestie this one is so extra in the best way ๐ . It makes GCC drop instrumentation calls at the entry and exit of every function. Like, the literal millisecond a function starts, and the literal millisecond before it leaves, these lil profiling functions get called with the address of the current function plus its call site. ๐
Heads up though โ on some platforms __builtin_return_address does not work beyond the current function, so the call site info might justโฆ not be there for your profiling functions. ๐
Here's the exact signatures, copy them character for character:
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, which โ slay โ can be looked up exactly in the symbol table. ๐
This instrumentation also happens for functions that got expanded inline inside other functions. The profiling calls just point at where, conceptually, the inline function gets entered and exited. Which means addressable versions of those functions have to actually exist. If every single use of a function gets expanded inline, that can mean an extra expansion of code size, no cap. And if you're using extern inline in your C code, an addressable version of those functions must be provided. (Normally that's already the case, but if you got lucky and the optimizer always expands them inline, you might have gotten away without providing static copies. ๐)
You can also hand a function the attribute no_instrument_function, and then this instrumentation justโฆ doesn't happen for it. Use it for stuff like the profiling functions listed above, high-priority interrupt routines, and honestly any function where the profiling functions can't safely be called โ think signal handlers, if the profiling routines generate output or allocate memory. ๐
-finstrument-functions-onceโ basically-finstrument-functions's calmer sibling. 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 one fires before the exit that corresponds to that first entry.
Now, the definition of "once" here is a lil vague because the implementation is not protected against data races. ๐ญ What that means: it only guarantees the profiling functions get called at least once per process and at most once per thread โ but the calls are always paired. So if a thread calls the first function, it will call the second one, unless it never reaches the exit of the instrumented function. Periodt.
-finstrument-functions-exclude-file-list=file,file,...โ sets the list of functions that get excluded from instrumentation (see the-finstrument-functionsdescription above, bestie, it's right there). If the file containing a function definition matches one of file, that function is not instrumented. And the matching is done on substrings: if the file parameter is a substring of the file name, it counts as a match. ๐ฆ
Example moment:
-finstrument-functions-exclude-file-list=/bits/stl,include/sys
That excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.
And 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, except this one sets the list of function names to exclude from instrumentation. The name that gets matched is its user-visible name, likevector<int> blah(const vector<int> &), not the internal mangled name (e.g.,_Z4blahRSt6vectorIiSaIiEE). Matching is on substrings again: if the sym parameter is a substring of the function name, it's a match. And for C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. โจ-fpatchable-function-entry=N[,M]โ this one generatesNNOPs right at the beginning of each function, with the function entry point sitting before the Mth NOP. IfMis omitted it defaults to0, so the function entry points to the address just at the first NOP. Those NOP instructions reserve extra space that can be used 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. You can use that to increase the area size, or to remove it completely on a single function. And ifN=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 runs on each C source file before actual compilation. So like, the opening act before the main character comes out. ๐
If you use the -E option, nothing happens except preprocessing. And some of these options only make sense alongside -E, because they make the preprocessor output unsuitable for actual compilation. ๐
In addition to the options listed here, there's a whole bunch of options controlling search paths for include files, documented in Directory Options. And options to control preprocessor diagnostics are listed in Warning Options.
-Dname โ predefine name as a macro, with definition1.-Dname=definition โ the contents of definition get tokenized and processed as if they appeared during translation phase three in a#definedirective. In particular, the definition is truncated by embedded newline characters. ๐ญ
If you're invoking the preprocessor from a shell or shell-like program, you may need the shell's quoting syntax to protect characters like spaces that mean something in shell syntax.
If you want to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so quote the option. With sh and csh, -D'name(args...)=definition' works. โจ
And here's the order-of-operations tea: -D and -U options are processed in the order they're given on the command line. All -imacros file and -include file options are processed after all -D and -U options. Periodt.
-Uname โ cancel any previous definition of name, whether it was built in or provided with a-Doption. Bye bestie. ๐-includefile โ process file as if#include "file"appeared as the first line of the primary source file. However โ and this is the plot twist โ the first directory searched for file is the preprocessor's working directory, not the directory containing the main source file. If it's not found there, it's searched for in the remainder of the#include "..."search chain as normal. ๐ฆ
If multiple -include options are given, the files are included in the order they appear on the command line.
-imacrosfile โ exactly like-include, except any output produced by scanning file is thrown away. The macros it defines stay defined though. This lets you grab all the macros from a header without also processing its declarations. Iconic. ๐ธ
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. (The OGs stay. ๐)-pthreadโ define additional macros required for using the POSIX threads library. Use this option consistently for both compilation and linking, okay? Both. Consistently. ๐ 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 one make rule 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 lots of included files, the rule gets split into several lines using \-newline. The rule has no commands.
Real talk: this option does not suppress the preprocessor's debug output, like-dM. To avoid mixing that debug output with the dependency rules, explicitly specify the dependency output file with-MF, or use an environment variable likeDEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal.
Passing -M to the driver implies -E, and suppresses warnings with an implicit -w. ๐
-MMโ like-M, but 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 by itself determine whether that header shows up in -MM dependency output. iykyk ๐
-MFfile โ when used with-Mor-MM, specifies a file to write the dependencies to. If no-MFswitch is given, the preprocessor sends the rules to the same place it would send preprocessed output.
okay bestie, we're still deep in the preprocessor/dependency part of OPTIONS and there is so much good stuff here, keep up ๐
When you use it with the driver options -MD or -MMD, -MF overrides the default dependency output file.
And if file is -? then the dependencies get written straight to stdout. cute, clean, iconic โจ
-MGโ used together with an option like-Mthat asks for dependency generation,-MGjust assumes missing header files are generated files and adds them to the dependency list without throwing an error. the dependency filename is taken directly from the#includedirective, no path prepending, no drama. it also suppresses preprocessed output, because honestly a missing header file renders that useless anyway. this feature is used in automatic updating of makefiles.-Mno-modulesโ disable dependency generation for compiled module interfaces. that's it, that's the whole vibe ๐-MPโ this one tells CPP to add a phony target for every dependency other than the main file, so each one depends on nothing. these dummy rules work around the errorsmakegives you if you delete header files without updating the Makefile to match. very "not my problem" energy. typical output looks like:
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. boom, that's your target. an-MToption sets the target to be exactly the string you specify โ no edits, no opinions. want multiple targets? pass them as a single argument to-MT, or just use multiple-MToptions, live your truth ๐ฆ
for example, -MT '$(objpfx)foo.o' might give
$(objpfx)foo.o: foo.c
-MQtarget โ same as-MT, but it quotes any characters that are special to Make. so-MQ '$(objpfx)foo.o'gives
$$(objpfx)foo.o: foo.c
the default target gets automatically quoted too, as if it were given with -MQ. no cap.
-MDโ-MDis equivalent to-M -MF file, 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; otherwise it takes the name of the input file, removes any directory components and suffix, and slaps a.don there.
if -MD is used together with -E, any -o switch is understood to specify the dependency output file โ but if it's used without -E, each -o is understood to specify a target object file. sneaky.
and since -E isn't implied, -MD can generate a dependency output file as a side effect of the compilation process. multitasking queen ๐
-MMDโ like-MDexcept it mentions only user header files, not system header files. keep your circle small ๐-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. it still recognizes and removes comments though, so you can hand it a file preprocessed with-Cwithout any problems. in this mode the integrated preprocessor is basically just a tokenizer for the front ends, lowkey.
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi โ those are the extensions GCC uses for preprocessed files created by -save-temps.
-fdirectives-onlyโ when preprocessing, handle directives but do not expand macros. the behavior depends on the-Eand-fpreprocessedoptions:- with
-E, preprocessing is limited to handling directives like#define,#ifdef, and#error. other preprocessor operations, like macro expansion and trigraph conversion, are not performed. plus,-dDis 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 lets you compile files previously preprocessed with-E -fdirectives-only. - with both
-Eand-fpreprocessed, the rules for-fpreprocessedtake precedence. this enables full preprocessing of files previously preprocessed with-E -fdirectives-only.
- with
-fdollars-in-identifiersโ accept$in identifiers. yes really, let the dollar signs in ๐ธ-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++. slay.-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 is 200. ๐ณ๏ธ - *
-ftabstop=width* โ set the distance between tab stops. this helps the preprocessor report correct column numbers in warnings or errors, even when tabs appear on the line. if the value is less than 1 or greater than 100, the option is ignored. the default is 8. -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. fair warning bestie: using this makes the preprocessor and compiler eat more memory ๐ญ. the level parameter picks how precise the token location tracking is, so you can dial down memory consumption if you need to:- value
0of level de-activates this option. - value
1tracks token locations in a degraded mode for 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
2tracks token locations completely, and is the most memory hungry.
- value
when this option is given with 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 turn an absolute path into a relative one by using.for new, which can give you more reproducible builds that are location independent. it also affects__builtin_FILE()during compilation. see also-ffile-prefix-mapand-fcanon-prefix-map. - *
-fexec-charset=charset* โ set the execution character set, used for string and character constants. the default isUTF-8. charset can be any encoding supported by the system'siconvlibrary routine. ๐ -fwide-exec-charset=charset โ set the wide execution character set, used for wide string and character constants. the default is one ofUTF-32BE,UTF-32LE,UTF-16BE, orUTF-16LE, whichever corresponds to the width ofwchar_tand the big-endian or little-endian byte order being used for code generation. same deal as-fexec-charset, charset can be any encoding supported by the system'siconvlibrary routine โ **however, you will have problems with encodings that do not fit exactly inwchar_t. ๐- *
-finput-charset=charset* โ set the input character set, used to translate 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 โ and currently the command-line option takes precedence if there's a conflict. charset can be any encoding supported by the system'siconvlibrary routine. -fpch-depsโ when using precompiled headers, this flag makes the dependency-output flags also list the files from the precompiled header's dependencies. if it's not specified, only the precompiled header is listed and not the files used to create it, because those files aren't consulted when a precompiled header is used. makes sense fr fr.-fpch-preprocessโ this option lets you use a precompiled header together with-E. it inserts a special#pragma,#pragma GCC pch_preprocess "filename", in the output to mark 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 gets 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 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 that can be inhibited with the negated form-fno-working-directory. if the-Pflag is present on the command line, this option has no effect, since no#linedirectives are emitted whatsoever. periodt.- *
-A*predicate=answer โ make an assertion with the predicate predicate and answer answer. this form is preferred over the older form-Apredicate(answer), which is still supported, because it doesn't use shell special characters. modern, clean, we love to see it โจ - *
-A -predicate*=answer โ cancel an assertion with the predicate predicate and answer answer. bye bye assertion ๐ -Cโ do not discard comments. all comments get 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#. be careful bestie ๐ญ
-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. double the comment preservation, double the chaos ๐
okay so, on top of all the side effects of the -C option, -CC also converts every single C++-style comment hanging out inside a macro into a C-style comment ๐
. Why tho? Because otherwise a later use of that macro could lowkey comment out the remainder of the source line โ and that's a whole mess nobody asked for ๐ญ. The -CC option is generally used to support lint comments. โจ
-Pโ inhibits generation of linemarkers in the output from the preprocessor ๐ซ. This might be useful when you're running the preprocessor on something that is not C code, and it's going to be sent to a program that might get confused by the linemarkers.-traditional,-traditional-cppโ try to imitate the behavior of pre-standard C preprocessors, as opposed to ISO C preprocessors ๐ฆ. See the GNU CPP manual for details.
heads up bestie: GCC does not otherwise attempt to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly. Periodt. ๐
-trigraphsโ support ISO C trigraphs โจ. These are three-character sequences, all starting with??, that ISO C defines to stand 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โ enable special code to work around file systems which only permit very short file names, such as MS-DOS ๐๏ธ.-Hโ print the name of each header file used, in addition to other normal activities ๐. Each name is indented to show how deep in the#includestack it is. Precompiled header files are also printed, even if they are found to be invalid ๐ฌ; an invalid precompiled header file is printed with...xand a valid one with...!.-dlettersโ says to make debugging dumps during compilation as specified by letters. The flags documented here are those relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and so are silently ignored ๐ค. If you specify letters whose behavior conflicts, the result is undefined ๐.-dMโ instead of the normal output, generate a list of#definedirectives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is 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 emit only the macro names, not their expansions.-dIโ output#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, are 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 option is only useful for debugging GCC ๐. 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 directly through to the preprocessor ๐. If option contains commas, it is split into multiple options at the commas. However, many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and-Wpforcibly bypasses this 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.-Xpreprocessoroption โ pass option as an option to the preprocessor. You can use this to supply system-specific preprocessor options that GCC does not recognize. If you want to pass an option that takes an argument, you must use-Xpreprocessortwice, once for the option and once for the argument.-no-integrated-cppโ perform preprocessing as a separate pass before compilation. By default, GCC performs 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 option may be useful in conjunction with the-Bor-wrapperoptions to specify an alternate preprocessor or perform additional processing of the program source between normal preprocessing and compilation.-flarge-source-filesโ adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage ๐.
Specifically, GCC normally tracks both column numbers and line numbers within source files, and it 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. This means that diagnostics for later lines do not include column numbers. It also means that options like -Wmisleading-indentation cease to work at that point, although the compiler prints a note if this happens. Passing -flarge-source-files significantly increases the number of source lines that GCC can process before it stops tracking columns.
๐งฐ Passing Options to the Assembler ๐งฐ
You can pass options to the assembler, bestie ๐ง.
-Wa,optionโ pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas.-Xassembleroption โ pass option as an option to the assembler. You can use this to supply system-specific assembler options that GCC does not 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 are meaningless if the compiler is not doing a link step ๐ .
- object-file-name โ a file name that does not 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-fpicand-fpieare both disabled. - If type is
dyn, code generation produces a shared library. In this case-fpicor-fPICis preserved, but not enabled automatically. This allows to build shared libraries without position-independent code on architectures where this is possible, i.e. on x86. - If type is
pie, code generation produces an-fpieexecutable. This results in similar optimizations asexecexcept that-fpieis 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-objectsis 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-relconfigures 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 benefits of whole program optimizations are lost.
- If type is
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 object files in 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 static library instead. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects.
-fuse-ld=bfdโ use the bfd linker instead of the default linker.-fuse-ld=goldโ use the gold linker instead of the default linker.-fuse-ld=lldโ use the LLVM lld linker instead of the default linker.-fuse-ld=moldโ use the Modern Linker (mold) instead of the default linker.-llibrary,-llibrary โ 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.
The linker goes on a lil shopping spree through a standard list of directories looking for your library. That list is like: several standard system directories, plus anything extra you slid in with -L. Bestie behavior fr.
Static libraries are literally just archives of object files, and their names look like liblibrary.a. Some targets also vibe with shared libraries, which usually go by liblibrary.so. And if the linker finds both? It's giving shared-library preference, periodt โ unless you hit it with -static.
Okay this next bit is SO important, do not skip it: where you put this option in the command matters. The linker searches and processes libraries and object files in the order they are specified. Sofoo.o -lz bar.osearches libraryzafter filefoo.obut beforebar.o. And ifbar.orefers to functions inzโฆ those functions may not be loaded. ๐ญ Order is not a suggestion, it's the whole plot.
-lobjcโ the special-case edition of-lthat you need in order to link an Objective-C or Objective-C++ program. iykyk. ๐-nostartfilesโ don't use the standard system startup files when linking. The standard system libraries are still used like normal, unless you also threw-nostdlib,-nolibc, or-nodefaultlibsinto the mix.-nodefaultlibsโ don't use the standard system libraries when linking. Only the libraries you specify get passed to the linker, and any options that specify linkage of the system libraries โ think-static-libgccor-shared-libgccโ are just ignored. The standard startup files are used normally, unless-nostartfilesis used.
Also, lowkey important: the compiler may generate calls to memcmp, memset, memcpy and memmove. Those entries are usually resolved by entries in libc, so if you turn this on, you gotta supply those entry points through some other mechanism. No cap.
-nolibcโ don't use the C library, or the system libraries tightly coupled with it, when linking. It still links with the startup files, libgcc, or toolchain-provided language support libraries likelibgnat,libgfortranorlibstdc++โ unless you're also using 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 you're assuming there's no C library โ for example-lpthreador-lmin some configurations. This one is intended for bare-board targets, when there is indeed no C library available. ๐ฆ-nostdlibโ don't use the standard system startup files or libraries when linking. No startup files, and only the libraries you specify get passed to the linker, and options specifying linkage of the system libraries โ like-static-libgccor-shared-libgccโ are ignored.
Same deal as above: the compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.
Okay so here's the tea: one of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a, a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages.
In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, used to ensure C++ constructors are called.) ๐ซถ
-nostdlib++โ don't implicitly link with standard C++ libraries. Simple as that.-eentry /--entry=entry โ specify that the program entry point is entry. The argument is interpreted by the linker; the GNU linker accepts either a symbol name or an address. ๐-pieโ produce a dynamically linked position independent executable on targets that support it. For predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option. Don't skip that part, bestie.-no-pieโ don't produce a dynamically linked position independent executable. The anti--pie. โจ-static-pieโ produce a static position independent executable on targets that support it. A static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. And yes, for predictable results you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option.-pthreadโ link with the POSIX threads library. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. On some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking. Consistency is the vibe. ๐-rโ produce a relocatable object as output. Also known as partial linking. Main character of "I'm not done yet".-rdynamicโ pass the flag-export-dynamicto the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses ofdlopenor to allow obtaining backtraces from within a program. ๐ฅ-sโ remove all symbol table and relocation information from the executable. Gone. Poof. ๐-staticโ on systems that support dynamic linking, this overrides-pieand prevents linking with the shared libraries. On other systems, this option has no effect.-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 provide libgcc as a shared library, these options force the use of either the shared or static version, respectively. If no shared version of libgcc was built when the compiler was configured, these options have no effect.
There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.
Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do. Slay, honestly.
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.
However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc. ๐
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links against libasan. If libasan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libasan. The-static-libasanoption directs the GCC driver to link libasan statically, without necessarily linking other libraries statically. ๐ง-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links against libtsan. If libtsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libtsan. The-static-libtsanoption directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically.-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links against liblsan. If liblsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of liblsan. The-static-liblsanoption directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically.-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links against libubsan. If libubsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libubsan. The-static-libubsanoption directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically. ๐-static-libstdc++โ when theg++program is used to link a C++ program, it normally automatically links against libstdc++. If libstdc++ is available as a shared library, and the-staticoption is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. The-static-libstdc++option directs theg++driver to link libstdc++ statically, without necessarily linking other libraries statically. Obsessed with the precision here.-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. ๐-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. So like, mandatory sometimes. Noted.-Xlinkeroption โ pass option as an option to the linker. You can use this to supply system-specific linker options that GCC does not recognize. Your little backstage pass. ๐
If you're passing an option that wants its argument as a whole separate thing, you gotta hit -Xlinker twice โ once for the option, once for the argument. So for -assert definitions you write:
-Xlinker -assert -Xlinker definitions
and NOT -Xlinker "-assert definitions" ๐ because that hands the linker the entire string as one single argument, which is not the vibe the linker is expecting.
When you're on the GNU linker, it's usually way more chill to pass args to linker options with the option=value syntax instead of splitting them up. Like, you can say -Xlinker -Map=output.map instead of -Xlinker -Map -Xlinker output.map. But heads up bestie โ other linkers might not support that syntax for command-line options. ๐
-Wl,optionโ passesoptionthrough to the linker as an option. Ifoptionhas commas in it, it gets split into multiple options right at those commas. You can use this syntax to hand an argument to the option too. For example,-Wl,-Map,output.mappasses-Map output.mapto the linker. And when you're using the GNU linker, you can also get the exact same result with-Wl,-Map=output.map.
NOTE: on Ubuntu 8.10 and later, forLDFLAGS, the option-Wl,-z,relrois used. To turn it off, use-Wl,-z,norelro.
-u symbolโ pretends the symbolsymbolis undefined, which forces library modules to get linked in so they can define it. You can stack-umultiple times with different symbols to force loading of extra library modules. ๐-z keywordโ-zgets passed straight on through to the linker along with the keywordkeyword. Go check the section in your linker's documentation for the permitted values and what they mean.
โจ Options for Directory Search โจ
These options tell the compiler where to go hunting for header files, libraries, and parts of the compiler itself. ๐ต๏ธโโ๏ธ
-I dir-iquote dir-isystem dir-idirafter dirโ adds the directorydirto the list of directories to search for header files during preprocessing. Ifdirstarts with=or$SYSROOT, then that=or$SYSROOTgets replaced by the sysroot prefix; peep--sysrootand-isysroot.
Directories you specify with -iquote apply only to the quote form of the directive, #include "file". Directories specified with -I, -isystem, or -idirafter apply to lookups for both the #include "file" and #include <file> directives.
You can drop any number or combo of these options on the command line to search several directories for header files. The lookup order goes like this:
- For the quote form of the include directive, the directory of the current file is searched first.
- For the quote form of the include directive, the directories specified by
-iquoteoptions are searched left-to-right, in the order they appear on the command line. - Directories specified with
-Ioptions are scanned left-to-right. - Directories specified with
-isystemoptions are scanned left-to-right. - Standard system directories are scanned.
- Directories specified with
-idirafteroptions are scanned left-to-right.
You can use -I to override a system header file by swapping in your own version, since these directories get searched before the standard system header file directories. But do not use this option to add directories holding vendor-supplied system header files โ use -isystem for that, okay? ๐
The -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment the standard system directories get.
If a standard system include directory, or a directory given with -isystem, is also specified with -I, then the -I option is ignored. The directory is still searched, but as a system directory at its normal spot 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 accidentally changed. If you really need to change the search order for system directories, use -nostdinc and/or -isystem.
-I-โ split the include path. ๐ซ This option has been deprecated, so please use-iquoteinstead for-Idirectories before the-I-and just remove the-I-option.
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 are 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". And there is no way to override this effect of -I-.
-iprefix prefixโ specifyprefixas the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, include the final/.-iwithprefix dir-iwithprefixbefore dirโ appenddirto the prefix specified previously with-iprefix, and add the resulting directory to the include search path.-iwithprefixbeforeputs it in the same place-Iwould;-iwithprefixputs it where-idirafterwould.-isysroot dirโ this one is like the--sysrootoption, but it applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the--sysrootoption for more info.-imultilib dirโ usediras a subdirectory of the directory containing target-specific C++ headers.-nostdincโ don't search the standard system directories for header files. Only the directories explicitly specified with-I,-iquote,-isystem, and/or-idirafteroptions (plus 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 directorydirto 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 turns up 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 whether 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's all. The file is left out of the link if it's not 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โ don't expand any symbolic links, don't resolve references to/../or/./, and don't make the path absolute when generating a relative prefix.--sysroot=dirโ usediras the logical root directory for headers and libraries. For example, if the compiler normally searches for headers in/usr/includeand libraries in/usr/lib, it instead searchesdir/usr/includeanddir/usr/lib.
If you use both this option and the -isysroot option, then --sysroot applies to libraries, but -isysroot applies to header files.
The GNU linker (starting 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 headers may for example be found indir/suffix/usr/includeinstead ofdir/usr/include. This option disables adding that suffix.
โจ Options for Code Generation Conventions โจ
These machine-independent options control the interface conventions used in code generation. โจ
Most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed โ the one that is not the default. You can figure out the other form by either removing no- or adding it.
-fstack-reuse=reuse-level๐ โ okay bestie, 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. The option is needed when the 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. fr fr ๐ญ
For example,
int *p;
{
int local1;
p = &local1;
local1 = 10;
....
}
{
int local2;
local2 = 20;
...
}
if (*p == 10) // out of scope use of local1
{
}
Another example:
struct A
{
A(int k) : i(k), j(k) { }
int i;
int j;
};
A *ap;
void foo(const A& ar)
{
ap = &ar;
}
void bar()
{
foo(A(10)); // temp object's lifetime ends when foo returns
{
A a(20);
....
}
ap->i+= 10; // ap references out of scope temp whose space
// is reused with a. What is the value of ap->i?
}
The lifetime of a compiler generated temporary is well defined by the C++ standard. When a 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, the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization. periodt โจ
-ftrapv๐ โ this option generates traps for signed overflow on addition, subtraction, multiplication operations. The options-ftrapvand-fwrapvoverride each other, so using-ftrapv -fwrapvon the command-line results in-fwrapvbeing effective. Note that only active options override, so using-ftrapv -fwrapv -fno-wrapvon the command-line results in-ftrapvbeing effective. no cap ๐ซถ-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-ftrapvand-fwrapvoverride each other, so using-ftrapv -fwrapvon the command-line results in-fwrapvbeing effective. Note that only active options override, so using-ftrapv -fwrapv -fno-wrapvon the command-line results in-ftrapvbeing effective. iykyk ๐-fwrapv-pointer๐ โ this option 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. lowkey important ๐ธ-fstrict-overflowโญ โ this option implies-fno-wrapv -fno-wrapv-pointerand when negated implies-fwrapv -fwrapv-pointer. the way that it just does that ๐-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. obsessed ๐-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 as"SIGALRM". This enables-fexceptions. ngl, niche but iconic ๐-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 the"pure"or"const"attributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. ate โจ-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. main character energy ๐-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). vibe check passed ๐ฆ-fno-gnu-unique๐ โ On systems with recent GNU assembler and C library, the C++ compiler uses the"STB_GNU_UNIQUE"binding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence of"RTLD_LOCAL"; this is necessary to avoid problems with a library used by two different"RTLD_LOCAL"plugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. But this causes"dlclose"to be ignored for affected DSOs; if your program relies on reinitialization of a DSO via"dlclose"and"dlopen", you can use-fno-gnu-unique. the tea is piping hot โ-fpcc-struct-return๐ โ Return"short""struct"and"union"values in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers, particularly the Portable C Compiler (pcc).
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the-fpcc-struct-returnswitch is not binary compatible with code compiled with the-freg-struct-returnswitch. Use it to conform to a non-default application binary interface. don't mix these, bestie ๐ญ
-freg-struct-return๐ โ Return"struct"and"union"values in registers when possible. This is more efficient for small structures than-fpcc-struct-return.
If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there is no standard convention, GCC defaults to -fpcc-struct-return, except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative.
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. literally incompatible, be careful ๐
-fshort-enums๐ธ โ Allocate to an"enum"type only as many bytes as it needs for the declared range of possible values. Specifically, the"enum"type is equivalent to the smallest integer type that has enough room.
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. ABI tea โ
-fshort-wchar๐ง โ Override the underlying type for"wchar_t"to be"short unsigned int"instead of the default for the target. This option is useful for building programs to run under WINE.
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. WINE girlies know ๐ท
-fcommonโญ โ In C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with the"extern"keyword, which do not allocate storage.
The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit.
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 said help ๐
-fno-ident๐ โ Ignore the"#ident"directive. short and sweet ๐-finhibit-size-directiveโ bestie, this one says don't emit a.sizeassembler directive, or literally anything else that would blow up if the function got split right down the middle and the two halves got yeeted to completely different spots in memory. ๐ It exists for one (1) job: compilingcrtstuff.c. That's it. You should not need it for anything else, and if you think you do, take a deep breath. ๐-fverbose-asmโ ok so this one adds extra commentary into the generated assembly so it's actually readable, like little sticky notes for your eyes. โจ It's generally only useful for people who genuinely need to read the assembly (maybe you're debugging the compiler itself, no big deal, main character energy ๐).
-fno-verbose-asm, which is the default, makes that extra info not show up โ and it's the move when you're diffing two assembler files against each other. ๐ซถ
The added comments include:
- info on the compiler version and the command-line options, ๐ธ
- the source code lines that go with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE, and
- hints on which high-level expressions line up with the various assembly instruction operands. ๐ฆ
For example, given this C source file:
int test (int n)
{
int i;
int total = 0;
for (i = 0; i < n; i++)
total += i * i;
return total;
}
compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -
gcc -S test.c -fverbose-asm -Os -o -
gives output similar to this:
.file "test.c"
# GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu)
[...snip...]
# options passed:
[...snip...]
.text
.globl test
.type test, @function
test:
.LFB0:
.cfi_startproc
# test.c:4: int total = 0;
xorl %eax, %eax # <retval>
# test.c:6: for (i = 0; i < n; i++)
xorl %edx, %edx # i
.L2:
# test.c:6: for (i = 0; i < n; i++)
cmpl %edi, %edx # n, i
jge .L5 #,
# test.c:7: total += i * i;
movl %edx, %ecx # i, tmp92
imull %edx, %ecx # i, tmp92
# test.c:6: for (i = 0; i < n; i++)
incl %edx # i
# test.c:7: total += i * i;
addl %ecx, %eax # tmp92, <retval>
jmp .L2 #
.L5:
# test.c:10: }
ret
.cfi_endproc
.LFE0:
.size test, .-test
.ident "GCC: (GNU) 7.0.0 20160809 (experimental)"
.section .note.GNU-stack,"",@progbits
Heads up bestie โ these comments are for humans, not machines, so the exact format of them is subject to change. Don't parse them, ok? ๐ญ
-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 usually it's a section holding ASCII text. It's related to the-fverbose-asmswitch, except that one only writes info into the assembler output file as comments, so it never reaches the object file. See also-grecord-gcc-switchesfor another way of storing compiler options into the object file. ๐-fpicโ generate position-independent code (PIC) that's suitable for use in a shared library, if the target machine supports it. ๐ฆ This kind of code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC โ it's part of the operating system, ok?).
If the GOT size for the linked executable goes over a machine-specific maximum size, you get an error message from the linker saying -fpic does not work โ and in that case, recompile with -fPIC instead. ๐
(These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit.)
Position-independent code requires special support, so it only works on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent. โจ
When this flag is set, the macros __pic__ and __PIC__ are defined to 1.
-fPICโ if the target machine supports it, emit position-independent code suitable for dynamic linking and avoiding any limit on the size of the global offset table. ๐ This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Position-independent code requires special support, so it only works on certain machines.
When this flag is set, the macros __pic__ and __PIC__ are defined to 2.
-fpie-fPIEโ these are similar to-fpicand-fPIC, but the position-independent code they generate can only be linked into executables. ๐ Usually you'd use these to compile code that's going to be linked using the-pieGCC option.
-fpie and -fPIE both define the macros __pie__ and __PIE__. The macros have the value 1 for -fpie and 2 for -fPIE.
-fno-pltโ do not use the PLT for external function calls in position-independent code. Instead, load the callee address at call sites from the GOT and branch to it. ๐ฅ This leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures 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 is useful together with-fpicor-fPICfor building code that's 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 isn't 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 maybe 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. That's just how it is, bestie. ๐ซ
-fcall-used-regโ treat the register named reg as an allocable register that gets clobbered by function calls. It may be allocated for temporaries or variables that don't 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. And using this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results. Not a vibe. ๐
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. And using it for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results. ๐ญ
Also โ a different sort of disaster results from using this flag for a register in which function values may be returned. Yeah. Don't.
This flag does not have a negative form, because it specifies a three-way choice.
-fpack-struct[=n]โ with no value specified, pack all structure members together with no holes. When a value is specified (and it must be a small power of two), pack structure members according to that value, which represents 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. Plus, it makes the code suboptimal. Use it to conform to a non-default application binary interface โ and for nothing else, ok? ๐
-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. And not all targets provide complete support for this switch. ๐
-ftls-model=modelโ change the thread-local storage model that's 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 that aren't visible outside of the translation unit, or if -fpic isn't given on the command line.
The default without -fpic is initial-exec; with -fpic the default is global-dynamic. โจ
-ftrampolinesโ okay bestie, if your target normally needs trampolines for nested functions</p>, this makes GCC always generate them instead of using descriptors. And for targets that don't need them โ like, say, HP-PA or IA-64 ๐ โ it does nothing at all. Zero. Nada.
So what even is a trampoline? It's a small piece of code ๐ created at run time on the stack when the address of a nested function is taken, and it's used to call the nested function indirectly. Which means... yeah. It requires the stack to be made executable in order for the program to work properly. ๐ซฃ
-fno-trampolines is enabled by default on a language by language basis, so the compiler can avoid generating them when it computes that this is safe, and replace them with descriptors instead. Descriptors are made up of data only โจ, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.
And now the part where we all sit up straight: code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. So this option must therefore be used on a program-wide basis and be manipulated with extreme care. ๐จ
Also, 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]โ sets the default ELF image symbol visibility to the option you picked, and all symbols get marked with it unless something in the code overrides it. Using this feature can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export, and prevent symbol clashes. It is strongly recommended that you use this in any shared objects you distribute. ๐
Despite the nomenclature, default always means public โ i.e., available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage, so the only other commonly used option is hidden. If -fvisibility isn't specified, the default is default, i.e. make every symbol public. ๐
A good explanation of the benefits offered by ensuring ELF symbols have the correct visibility is given by How To Write Shared Libraries by Ulrich Drepper, which can be found at <https://www.akkadia.org/drepper/> โ however a superior solution made possible by this option, 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 to those working with cross-platform projects. ๐ฅ
If you're adding visibility support to existing code, you may find #pragma GCC visibility of use. It works by you enclosing the declarations you wish to set visibility for with (for example) #pragma GCC visibility push(hidden) and #pragma GCC visibility pop. Bear in mind that symbol visibility should be viewed as part of the API interface contract, and thus all new code should always specify visibility when it is not the default; i.e., declarations only for use within the local DSO should always be marked explicitly as hidden so as to avoid PLT indirection overheads โ and making this abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, operator new and operator delete must always be of default visibility. โญ
Heads up though: headers from outside your project โ in particular system headers and headers from any other library you use โ may not be expecting to be compiled with visibility other than the default. You 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 no modifications. However, this means that calls to extern functions with no explicit visibility use the PLT, so it is 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. This means that, for instance, an exception class that is thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. ๐
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. Example time: targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide. With this flag you can declare all peripheral bit-fields asunsigned short(assumingshortis 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access. โจ
If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction, even though that accesses bytes that do not contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. ๐ญ
In some cases, such as when the packed attribute is applied to a structure field, it may not be possible to access the field with a single read or write that is correctly aligned for the target machine. In this 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. It is therefore 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โ controls whether any out-of-line instance of the__syncfamily of functions may be used to implement the C++11__atomicfamily of functions.
The default value 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 โ including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That means options that produce debug dumps at various points in the compilation, options that print statistics such as memory use and execution time, and options that print information about GCC's configuration, like where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. ๐ซถ
Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error. ๐ฏ
If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, phase letter, and pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it is 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 are executed earlier. The phase letter is one of i (inter-procedural analysis), l (language-specific), r (RTL), or t (tree). The files are created in the directory of the output file. ๐๏ธ
-fcallgraph-info,-fcallgraph-info=MARKERSโ makes the compiler output callgraph information for the program, on a per-object-file basis. The information is generated in the common VCG format. It can be decorated with additional per-node and/or per-edge information if a list of comma-separated markers is additionally specified. When thesumarker is specified, the callgraph is decorated with stack usage information; it is equivalent to-fstack-usage. When thedamarker is specified, the callgraph is decorated with information about dynamically allocated objects.
When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files. ๐ฅ
-dletters,-fdump-rtl-pass,-fdump-rtl-pass=filenameโ says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler. ๐ง
Some -dletters switches have different meaning when -E is used for preprocessing.
Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings:
-fdump-rtl-alignmentsโ dump after branch alignments have been computed.-fdump-rtl-asmconsโ dump after fixing rtl statements that have unsatisfied in/out constraints.-fdump-rtl-auto_inc_decโ dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.-fdump-rtl-barriersโ dump after cleaning up the barrier instructions.-fdump-rtl-bbpartโ dump after partitioning hot and cold basic blocks.-fdump-rtl-bbroโ dump after block reordering.-fdump-rtl-btl1,-fdump-rtl-btl2โ-fdump-rtl-btl1and-fdump-rtl-btl2enable dumping after the two branch target load optimization passes.-fdump-rtl-bypassโ dump after jump bypassing and control flow optimizations.
-fdump-rtl-combineโ dumps the whole vibe right after the RTL instruction combination pass goes down. ๐ฅ-fdump-rtl-compgotosโ dumps after duplicating the computed gotos. yes bestie, that's a real pass name ๐-fdump-rtl-ce1,-fdump-rtl-ce2,-fdump-rtl-ce3โ these three enable dumping after the three if conversion passes. three passes, three flags, three little dump files living their best lives. โจ-fdump-rtl-cprop_hardregโ dumps after hard register copy propagation. slay.-fdump-rtl-csaโ dumps after combining stack adjustments. it's giving tidy stack energy ๐-fdump-rtl-cse1,-fdump-rtl-cse2โ enable dumping after the two common subexpression elimination passes. two passes, so obviously two flags, periodt.-fdump-rtl-dceโ dumps after the standalone dead code elimination passes. bye to the dead code, love that for us ๐-fdump-rtl-dbrโ dumps after delayed branch scheduling.-fdump-rtl-dce1,-fdump-rtl-dce2โ enable dumping after the two dead store elimination passes.-fdump-rtl-ehโ dumps after finalization of EH handling code.-fdump-rtl-eh_rangesโ dumps after conversion of EH handling range regions.-fdump-rtl-expandโ dumps after RTL generation. this is the origin story of your RTL, lowkey iconic ๐ฑ-fdump-rtl-fwprop1,-fdump-rtl-fwprop2โ enable dumping after the two forward propagation passes.-fdump-rtl-gcse1,-fdump-rtl-gcse2โ enable dumping after global common subexpression elimination.-fdump-rtl-init-regsโ dumps after the initialization of the registers.-fdump-rtl-initvalsโ dumps after the computation of the initial value sets.-fdump-rtl-into_cfglayoutโ dumps after converting to cfglayout mode. entering the cfglayout era ๐ฆ-fdump-rtl-iraโ dumps after iterated register allocation.-fdump-rtl-jumpโ dumps after the second jump optimization. the second one, bestie, keep up ๐-fdump-rtl-loop2โ enables dumping after the rtl loop optimization passes. looping looping looping ๐-fdump-rtl-machโ dumps after performing the machine dependent reorganization pass, if that pass exists. key detail: if it exists. no pass, no dump, no drama. ๐-fdump-rtl-mode_swโ dumps after removing redundant mode switches.-fdump-rtl-rnregโ dumps after register renumbering.-fdump-rtl-outof_cfglayoutโ dumps after converting from cfglayout mode. leaving the cfglayout era, it was a beautiful chapter ๐ญ-fdump-rtl-peephole2โ dumps after the peephole pass.-fdump-rtl-postreloadโ dumps after post-reload optimizations.-fdump-rtl-pro_and_epilogueโ dumps after generating the function prologues and epilogues. say hi to the prologue, say bye to the epilogue ๐-fdump-rtl-sched1,-fdump-rtl-sched2โ enable dumping after the basic block scheduling passes.-fdump-rtl-reeโ dumps after sign/zero extension elimination.-fdump-rtl-seqabstrโ dumps after common sequence discovery. found the common sequences, they're matching ๐-fdump-rtl-shortenโ dumps after shortening branches.-fdump-rtl-siblingโ dumps after sibling call optimizations. sibling energy fr fr ๐ซถ-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. five. rounds. that's not a typo, that's just the lore. ๐-fdump-rtl-smsโ dumps after modulo scheduling. > heads up bestie: this pass is only run on some architectures, so don't come for me if you get nothing.-fdump-rtl-stackโ dumps after conversion from GCC's"flat register file"registers to the x87's stack-like registers. > again: this pass is only run on x86 variants. x86 girlies only ๐-fdump-rtl-subreg1,-fdump-rtl-subreg2โ enable dumping after the two subreg expansion passes.-fdump-rtl-unshareโ dumps after all rtl has been unshared. sharing is over, we're independent now โจ-fdump-rtl-vartrackโ dumps after variable tracking.-fdump-rtl-vregsโ dumps after converting virtual registers to hard registers. glow-up from virtual to hard, no cap ๐-fdump-rtl-webโ dumps 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. every single time. they show up to the group chat and say nothing. ๐-da,-fdump-rtl-allโ produce all the dumps listed above. the full collection, the whole album, every track. ๐ฅ-dAโ annotate the assembler output with miscellaneous debugging information. little notes in the margins, very cute ๐-dDโ dump all macro definitions, at the end of preprocessing, in addition to normal output. you get the macros and the normal stuff, you're welcome.-dHโ produce a core dump whenever an error occurs. > this one is dramatic on purpose, it literally crashes out and leaves a core dump behind. ๐-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. receipts for every instruction, obsessed ๐-dPโ dump the RTL in the assembler output as a comment before each instruction. also turns on-dpannotation. two for one, main character move. โจ-dxโ just generate RTL for a function instead of compiling it. usually used with-fdump-rtl-expand. so like, do the RTL and then stop, no compiling today ๐ธ-fdump-debugโ dump debugging information generated during the debug generation phase.-fdump-earlydebugโ dump debugging information generated during the early debug generation phase. the prequel ๐ฆ-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. basically it makes diffing actually work, which is a slay. ๐-freport-bugโ collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs. so when things go ICE-cold, it saves the evidence. ๐ง-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. comparison girlies rise ๐ซถ-fdump-unnumbered-linksโ when doing debugging dumps (see-doption above), suppress instruction numbers for the links to the previous and next instructions in a sequence. the links stay, the numbers go. ๐-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. the everything bagel. ๐ฅฏ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. both sides of the story, love that. ๐
by default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis.
-fdump-langโ dump language-specific information. the file name is made by appending.langto the source file name. short, sweet,.langโจ-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 module information. optionslineno(locations),graph(reachability),blocks(clusters),uid(serialization),alias(mergeable),asmname(Elrond),eh(mapper) &vops(macros) may provide additional information. > this option is applicable to C++ only too.rawโ dump the raw internal tree data. > yep: C++ only.
-fdump-passesโ print onstderrthe list of optimization passes that are turned on and off by the current command-line options. a little receipt of which passes are activated, so useful. ๐งพ-fdump-statistics-optionโ enable and control dumping of pass statistics in a separate file. the file name is generated by appending a suffix ending in.statisticsto the source file name, and the file is created in the same directory as the output file. if the-optionform is used,-statscauses counters to be summed over the whole compilation unit while-detailsdumps every event as the passes generate them. the default with no option is to sum counters for each function compiled. pick your flavour bestie ๐-fdump-tree-all,-fdump-tree-switch,-fdump-tree-switch-options,-fdump-tree-switch-options=filenameโ control the dumping at various stages of processing the intermediate language tree to a file. if the-optionsform is used, options is a list of-separated options which control the details of the dump. > not all options are applicable to all dumps; those that are not meaningful are ignored. no error, just vibes, they get quietly skipped. ๐
the following options are available:
addressโ print the address of each node. usually this is not meaningful as it changes according to the environment and source file. its primary use is for tying up a dump file with a debug environment.asmnameโ if"DECL_ASSEMBLER_NAME"has been set for a given decl, use that in the dump instead of"DECL_NAME". its primary use is ease of use working backward from mangled names in the assembly file.slimโ when dumping front-end intermediate representations, inhibit dumping of members of a scope or body of a function merely because that scope has been reached. only dump such items when they are directly reachable by some other path.
when dumping pretty-printed trees, this option inhibits dumping the bodies of control structures.
when dumping RTL, print the RTL in slim (condensed) form instead of the default LISP-like representation.
rawโ print a raw representation of the tree. by default, trees are pretty-printed into a C-like representation.
okay bestie we're still deep in the dump-option lore, let's keep going, no thoughts just flags ๐
detailsโ turns on the extra-detailed dumps (and ngl, not every dump option actually respects this one ๐). It also pulls in info from the optimization passes.statsโ dumps a bunch of statistics about the pass. Again: not every dump option honors it, so don't come for me if it's quiet.blocksโ shows the basic block boundaries. (Disabled in raw dumps, fyi.)graphโ for each of the other indicated dump files (-fdump-rtl-pass), it dumps a representation of the control flow graph that's built for viewing with GraphViz intofile.passid.pass.dot. Every function in the file gets pretty-printed as a subgraph so GraphViz can render them all in one single plot. โจ
Heads up: this option currently only works for RTL dumps, and the RTL is always dumped in slim form. No exceptions, that's just the vibe.
vopsโ shows virtual operands for every statement.linenoโ shows line numbers for statements.uidโ shows the unique ID (DECL_UID) for each variable.verboseโ shows the tree dump for each statement.ehโ shows the EH region number holding each statement.scevโ shows scalar evolution analysis details.optimizedโ shows optimization information (only available in certain passes, so it's giving "sometimes" energy).missedโ shows missed optimization information (again, only in certain passes).noteโ shows other detailed optimization information (only available in certain passes).allโ turns on everything, exceptraw,slim,verboseandlineno.optallโ turns on all the optimization options, meaningoptimized,missed, andnote.
ok so if you're sitting there like "which tree dumps do I even have and where's the pass I care about" โ here's the little ritual, follow along ๐ง
- Invoke GCC with
-fdump-passesand then go stare at the stderr output for a code that matches the pass you want. Example: the codestree-evrp,tree-vrp1, andtree-vrp2correspond to the three Value Range Propagation passes. That number at the end is there to distinguish distinct invocations of the same pass. - To actually make the dump file, stick the pass code onto the
-fdump-option prefix and invoke GCC with it. So like, to enable the dump from the Early Value Range Propagation pass, you invoke GCC with the-fdump-tree-evrpoption. You can also specify the name of the dump file. If you don't, GCC creates one as described below. ๐ - Find the pass dump in a file whose name is made 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.
So for example, the Early VRP pass dump might be in a file named myfile.c.038t.evrp in the current working directory. ๐
Lowkey important: those numeric codes are not stable and may change from one version of GCC to another. Do not hardcode them, bestie, that's a trap. ๐
-fopt-info, -fopt-info-options, -fopt-info-options=filename
This trio controls the optimization dumps coming out of the various optimization passes. If you use the -options form, then options is a list of - separated option keywords that pick the dump details and optimizations.
The options break down into three groups:
- options describing what kinds of messages should be emitted,
- options describing the verbosity of the dump, and
- options describing which optimizations should be included.
You can freely mix options from each group because they don't overlap. BUT โ if there's any conflict, the later options override the earlier ones on the command line. So order matters, periodt.
The following options control which kinds of messages get emitted:
optimizedโ prints info when an optimization is successfully applied. It's up to a pass to decide which info is relevant. For example, the vectorizer passes print the source location of loops that were successfully vectorized. slay.missedโ prints info about missed optimizations. Individual passes control which info gets included in the output.noteโ prints verbose info about optimizations, like certain transformations, more detailed messages about decisions, etc.allโ prints 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. ๐ฉโ๐ป
And one or more of these option keywords can describe a group of optimizations:
ipaโ enables dumps from all interprocedural optimizations.loopโ enables dumps from all loop optimizations.inlineโ enables dumps from all inlining optimizations.ompโ enables dumps from all OMP (Offloading and Multi Processing) optimizations.vecโ enables dumps from all vectorization optimizations.optallโ enables 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, while omitting messages that are treated as "internals".
If filename is provided, then the dumps from all the applicable optimizations get concatenated into filename. Otherwise the dump goes to stderr. And yes, multiple -fopt-info options are accepted, but only one of them can include a filename. If other filenames are provided, then all but the first such option are ignored. ๐
Note that the output filename gets overwritten in the case of multiple translation units. If you want a combined output from multiple translation units, use stderr instead. That's the move. ๐
So in this next example, the optimization info goes to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs the missed optimization report from all the passes into missed.all. And this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from vectorization passes on stderr. Fun fact: -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.
And finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict, since only one output file is allowed. In this case only the first option takes effect and the subsequent options are ignored. So only vec.miss is produced, and it contains dumps from the vectorizer about missed opportunities. One file, one winner, sorry loop.opt. ๐ญ
-fsave-optimization-record
Writes a SRCFILE.opt-record.json.gz file detailing what optimizations were performed, for those optimizations that support -fopt-info.
This option is experimental and the format of the data inside that compressed JSON file is subject to change. So build your tooling around it at your own risk, bestie.
It's roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, plus these extra data for each message:
- the execution count of the code being optimized, along with metadata about whether this came from actual profile data or was 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 is inlined into several different places (which might themselves be inlined), the reader can distinguish between the copies,
- 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.
-fsched-verbose=n
On targets that use instruction scheduling, this option controls how much debugging output the scheduler prints to the dump files.
- For
ngreater than zero,-fsched-verboseoutputs the same information as-fdump-rtl-sched1and-fdump-rtl-sched2. - For
ngreater than one, it also outputs basic block probabilities, detailed ready list information and unit/insn info. - For
ngreater than two, it includes RTL at abort point, control-flow and regions info. - And for
nover four,-fsched-verbosealso includes dependence info.
Like, the higher you crank n, the more it yaps. ๐ฃ๏ธ
-fenable-kind-pass, -fdisable-kind-pass=range-list
This is a set of options used to explicitly disable/enable optimization passes.
These options are intended for debugging GCC. Compiler users should use the regular options for enabling/disabling passes instead. That's the rule, iykyk.
-fdisable-ipa-passโ disables IPA pass pass.passis 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โ turn off an RTL pass, bestie. pass is the pass name. If that same pass gets statically invoked in the compiler more than once, you gotta tack on a sequential number starting from1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair split by a colon, and the range is inclusive on both ends. If the range is trivial you can just write a single number instead of a pair. If the function's call graph node's uid lands inside one of the ranges you listed, the pass is disabled for that function. That uid shows up in the function header of a dump file, and you can dump the pass names with-fdump-passes. ๐-fdisable-tree-pass,-fdisable-tree-pass=range-listโ disable a tree pass. Same energy as-fdisable-rtlfor what the arguments mean, fr fr.-fenable-ipa-passโ enable IPA pass pass. Again, pass is the pass name, and if the same pass is statically invoked multiple times in the compiler, append a sequential number starting from1. โจ-fenable-rtl-pass,-fenable-rtl-pass=range-listโ enable an RTL pass. Peep-fdisable-rtlfor the argument description and examples, iykyk.-fenable-tree-pass,-fenable-tree-pass=range-listโ enable a tree pass. See-fdisable-rtlfor the description of the option arguments. ๐ฆ
Here are some examples showing how these options get used, no cap:
# 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โ turns on internal consistency checking. The default depends on how the compiler was configured. And-fchecking=2enables even further internal consistency checking that might affect code generation. ๐-frandom-seed=stringโ this one gives GCC a seed to use in place of random numbers when it generates certain symbol names that have to be different in every compiled file. It's also used to place unique stamps in coverage data files and in the object files that produce them. Use-frandom-seedand you can produce reproducibly identical object files. ๐
string can either be a number (decimal, octal or hex) or an arbitrary string โ and if it's an arbitrary string it gets converted to a number by computing CRC32.
The string should be different for every file you compile. Don't be lazy about it bestie, that's literally the whole point.
-save-tempsโ stores the usual "temporary" intermediate files permanently, naming them as auxiliary output files, as described under-dumpbaseand-dumpdir. ๐
When it's used together with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file that has the same extension as an intermediate file. You can still grab that corresponding intermediate file 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 you specified after the-ooption, including any directory separators. If you didn't use-o, then-save-temps=objjust behaves like-save-temps=cwd. Simple as that. ๐-time[=file]โ reports the CPU time each subprocess in the compilation sequence took. For C source files that's the compiler proper and the assembler (plus the linker if linking is happening). โฑ๏ธ
If you don't specify 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" โ 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.
If you do specify an output file, the output gets appended to that named file and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
The "user time" and "system time" move to before the program name, and the options passed to the program are displayed too, so later you can tell what file was being compiled and with which options. Iconic honestly.
-fdump-final-insns[=file]โ dumps 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, it runs the compiler a second time, adding opts and-fcompare-debug-secondto the arguments passed to that second compilation. It dumps the final internal representation in both compilations and prints an error if they differ. ๐
If the equal sign is omitted, the default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if it's defined, non-empty and nonzero, implicitly enables -fcompare-debug. And if GCC_COMPARE_DEBUG is defined to a string starting with a dash, then that gets 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). And if you only want a warning, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do it.
-fcompare-debug-secondโ this option is implicitly passed to the compiler for the second compilation that-fcompare-debugrequested, 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 get renamed so they contain the.gkadditional extension during the second compilation, so nothing overwrites what the first one generated. ๐ซถ
When this option gets 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โ turns off generation of debug info if leaving out this option would generate it, or turns it on at level 2 otherwise. The position of this argument on the command line doesn't matter; it takes effect after all other options are processed, and it does so only once, no matter how many times you give it. Mainly intended to be used with-fcompare-debug. โจ-fvar-tracking-assignments-toggleโ toggles-fvar-tracking-assignments, the same way that-gtoggletoggles-g. ๐-Qโ makes the compiler print out each function name as it's 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โ records the time consumed by infrastructure parts separately for each pass.-fira-verbose=nโ controls the verbosity of the dump file for the integrated register allocator. Default value is5. And if the value n is greater than or equal to10, the dump output gets sent to stderr using the same format as n minus 10. ๐-flto-reportโ prints a report with internal details on the workings of the link-time optimizer. The contents of this report vary from version to version. It's meant to be useful to GCC developers when processing object files in LTO mode (via-flto). ๐
Disabled by default.
-flto-report-wpaโ like-flto-report, but only prints for the WPA phase of link-time optimization.-fmem-reportโ makes the compiler print some statistics about permanent memory allocation when it finishes.-fmem-report-wpaโ makes the compiler print some statistics about permanent memory allocation for the WPA phase only.-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 option enables multilib-aware "TFLAGS" to be used to build target libraries with options different from the ones the compiler is configured to use by default, through the use of specs. ๐ฆ
Like "TFLAGS", this lets the target libraries be built for portable baseline environments, while the compiler defaults to more demanding ones. That's useful because users can easily override the defaults the compiler is configured to use to build 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. fr fr.
Unlike "TFLAGS", the use of specs enables different flags to be selected for different multilibs. The way to accomplish that 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 to check 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 consistency of the (estimated) profile and the effect of individual passes. ๐ฅ-fstack-usageโ bestie, this makes the compiler spill the tea on stack usage, per function. ๐ The dump filename? Take the auxname and slap.suon the end. And auxname is generated from the name of the output file (if you explicitly named one and it's not an executable), otherwise it's just the basename of the source file. Each entry is three fields:- the name of the function ๐ซถ
- a number of bytes
- one or more qualifiers:
static,dynamic,bounded
So the qualifier static means the function manipulates the stack statically: a fixed number of bytes gets allocated for the frame on function entry and released on function exit, and no other stack adjustments happen inside the function. In that case the second field is that fixed number of bytes.
The qualifier dynamic means the function manipulates the stack dynamically: on top of the static allocation above, stack adjustments get made in the body of the function, like pushing/popping arguments around function calls. And if bounded is also there? Then the amount of those adjustments is bounded at compile time and the second field is an upper bound of the total stack the function uses. If bounded is not there, the amount of those adjustments is not bounded at compile time and the second field only represents the bounded part. No cap, fr fr. ๐
-fstatsโ emits statistics about front-end processing at the end of the compilation. Ngl this one is only supported by the C++ front end, and the info is generally only useful to the G++ development team. So like, not for us, but okay. ๐-fdbg-cnt-listโ prints the name and the counter upper bound for all debug counters.- *
-fdbg-cnt=counter-value-list* โ sets 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. Thelower_boundis optional and is zero-initialized if not set. For example, with-fdbg-cnt=dce:2-4:10-11,tail_call:10,dbg_cnt(dce)returns true only for the second, third, fourth, tenth and eleventh invocation. And fordbg_cnt(tail_call)true is returned for the first 10 invocations. โจ - *
-print-file-name=library* โ prints the full absolute name of the library file library that would be used when linking โ and does nothing else. With this option, GCC does not compile or link anything; it just prints the file name. Iconic behavior honestly. -print-multi-directoryโ prints the directory name corresponding to the multilib selected by any other switches present on the command line. This directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ prints the mapping from multilib directory names to the 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โ prints 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., and if OS libraries are present inlibsuffixsibling directories this prints e.g.../lib64,../libor../lib32, or if OS libraries are present inlib/subdirsubdirectories it prints e.g.amd64,sparcv9orev6.-print-multiarchโ prints 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โ prints the name of the configured installation directory and a list of program and library directoriesgccsearches โ and don't do anything else. ๐
This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Don't forget the trailing /. โญ
-print-sysrootโ prints the target sysroot directory that is 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โ prints the suffix added to the target sysroot when searching for headers, or gives an error if the compiler is not configured with such a suffix โ and don't do anything else.-dumpmachineโ prints the compiler's target machine (for example,i686-pc-linux-gnu) โ and don't do anything else. ๐-dumpversionโ prints 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โ prints 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โ prints 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. No mixing, bestie, it will not slay. ๐
-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 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โ avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification.-momit-leaf-frame-pointer-mno-omit-leaf-frame-pointerโ omit or keep the frame pointer in leaf functions. The former behavior is the default.- *
-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 orsysregfor a canary in an appropriate system register.
With the latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which system register to use as 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. ๐ง
-mtls-dialect=descโ use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default.-mtls-dialect=traditionalโ use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables.- *
-mtls-size=size* โ specify the bit size of immediate TLS offsets. Valid values are12,24,32,48. This option requires binutils 2.26 or newer. ๐ซถ -mfix-cortex-a53-835769-mno-fix-cortex-a53-835769โ enable or disable the workaround for the ARM Cortex-A53 erratum number835769. This involves inserting aNOPinstruction between memory instructions and 64-bit integer multiply-accumulate instructions.-mfix-cortex-a53-843419-mno-fix-cortex-a53-843419โ enable or disable the workaround for the ARM Cortex-A53 erratum number843419. This erratum workaround is made at link time and this will only pass the corresponding flag to the linker.-mlow-precision-recip-sqrt-mno-low-precision-recip-sqrtโ enable or disable the reciprocal square root approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. ๐ง-mlow-precision-sqrt,-mno-low-precision-sqrtโ turns the square root approximation on or off. Heads up though: this one does nothing unless you also pass-ffast-mathor-funsafe-math-optimizations. Bestie, when it is on, your sqrt results get knocked down to roughly 16 bits for single precision and 32 bits for double precision. And if you enable it, it drags-mlow-precision-recip-sqrtin with it. ๐-mlow-precision-div,-mno-low-precision-divโ same deal but for division. Also only works if-ffast-mathor-funsafe-math-optimizationsis in the mix. Turning it on reduces the precision of division results to about 16 bits for single precision and 32 bits for double precision. precision? we don't know her ๐ฆ-mtrack-speculation,-mno-track-speculationโ enables or disables extra code generation that tracks speculative execution through conditional branches. Then the compiler can use that tracking state when it expands calls to__builtin_speculation_safe_copy, which lets it spit out a more efficient code sequence. security AND speed, we love a dual threat โจ-moutline-atomics,-mno-outline-atomicsโ enables or disables calls to out-of-line helpers that implement atomic operations. At runtime these helpers figure out whether the LSE instructions from ARMv8.1-A can be used; if they can't, they fall back to the load/store-exclusive instructions that live in the base ARMv8.0 ISA. ๐
This only applies when you're compiling for the base ARMv8.0 instruction set. If you're on a later revision โ say -march=armv8.1-a or -march=armv8-a+lse โ the ARMv8.1-Atomics instructions get used directly. Same story with -mcpu= when the cpu you picked supports the lse feature. This option is on by default.
-march=nameโ names the target architecture, and optionally tacks on one or more feature modifiers. The shape is:
-march=arch{+[no]feature}*
Here's the rundown of what arch values are allowed and which features each one switches on by default:
arch value : Architecture : Includes by default
armv8-a : Armv8-A : +fp, +simd
armv8.1-a : Armv8.1-A : armv8-a, +crc, +lse, +rdma
armv8.2-a : Armv8.2-A : armv8.1-a
armv8.3-a : Armv8.3-A : armv8.2-a, +pauth
armv8.4-a : Armv8.4-A : armv8.3-a, +flagm, +fp16fml, +dotprod
armv8.5-a : Armv8.5-A : armv8.4-a, +sb, +ssbs, +predres
armv8.6-a : Armv8.6-A : armv8.5-a, +bf16, +i8mm
armv8.7-a : Armv8.7-A : armv8.6-a, +ls64
armv8.8-a : Armv8.8-a : armv8.7-a, +mops
armv9-a : Armv9-A : armv8.5-a, +sve, +sve2
armv9.1-a : Armv9.1-A : armv9-a, +bf16, +i8mm
armv9.2-a : Armv9.2-A : armv9.1-a, +ls64
armv9.3-a : Armv9.3-A : armv9.2-a, +mops
armv8-r : Armv8-R : armv8-r
The value native exists on native AArch64 GNU/Linux, and it makes the compiler pick whatever architecture your host system is running. If the compiler can't figure out the host architecture, this option does nothing. ๐
The allowed feature values are listed over in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. When two feature modifiers conflict, the right-most one wins. ๐
GCC uses name to decide what kind of instructions it's allowed to emit when generating assembly code. And if you pass -march without also passing -mtune or -mcpu, the code gets tuned to perform well across a whole range of target processors that implement that target architecture. versatile queen energy ๐
-mtune=nameโ names the target processor GCC should tune the performance of the code for. The permissible values 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, 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. that's a whole roster bestie ๐
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 mean GCC should tune for a big.LITTLE system. ๐ซถ
The value neoverse-512tvb means GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. In other words, it's telling 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 (2 for 256-bit SVE, 4 for 128-bit SVE). That's more general than tuning for one specific core like Neoverse V1, but more specific than the default tuning described below. the way it's precise but also not, iconic โจ
Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. If the compiler can't recognize the processor of the host system, this option does nothing.
If none of -mtune=, -mcpu= or -march= are given, the code gets tuned to perform well across a range of target processors.
Important: this option cannot be suffixed by feature modifiers. no add-ons, periodt. ๐
-mcpu=nameโ names the target processor, optionally with one or more feature modifiers tacked on the end. The shape is:
-mcpu=cpu{+[no]feature}*
where the permissible cpu values are the exact same ones available for -mtune. The permissible feature values are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Conflicting feature modifiers? Right-most wins again. ๐
GCC uses name to determine what instructions it can emit when generating assembly code (as if by -march) and to determine the target processor to tune performance for (as if by -mtune). If you use this option together with -march or -mtune, those options take precedence over the relevant part of this one. teamwork but someone's clearly in charge
-mcpu=neoverse-512tvb is special โ it doesn't refer to one specific core, but instead to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless -march overrides it, -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 -mtune overrides it, -mcpu=neoverse-512tvb tunes code exactly the same way as -mtune=neoverse-512tvb. ๐ธ
-moverride=stringโ overrides tuning decisions the back-end made in response to a-mtune=switch. Fair warning: the syntax, semantics and accepted values forstringhere are not guaranteed to be consistent across releases. ๐
This option is only intended to be useful when you're developing GCC. iykyk. ๐ฅ
-mverbose-cost-dumpโ enables verbose cost model dumping in the debug dump files. This one's provided for use when debugging the compiler. ๐-mpc-relative-literal-loads,-mno-pc-relative-literal-loadsโ enables or disables PC-relative literal loads. With this on, literal pools get accessed using a single instruction and emitted after each function. That limits the maximum size of functions to 1MB. It's enabled by default for-mcmodel=tiny. ๐-msign-return-address=scopeโ picks the function scope that return address signing gets applied to. The permissible values arenone, which disables return address signing,non-leaf, which enables pointer signing for functions that aren't leaf functions, andall, which enables pointer signing for all functions. The default value isnone. This option has been deprecated by-mbranch-protection. โ ๏ธ-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ picks which branch protection features to use.noneis the default and turns off every type of branch protection.standardturns on all types of branch protection features โ and if a feature has extra tuning options,standardsets it to its standard level.pac-ret[+leaf]turns on return address signing to its standard level: signing functions that save the return address to memory (non-leaf functions will practically always do this) using the a-key. The optional argumentleafextends the signing to include leaf functions too. The optional argumentb-keysigns the functions with the B-key instead of the A-key. Andbtiturns on the branch target identification mechanism. protect yourself, bestie ๐ก๏ธโจ-mharden-sls=optsโ enables compiler hardening against straight line speculation (SLS).optsis a comma-separated list of the following options:retbrblr
On top of that, -mharden-sls=all enables all SLS hardening while -mharden-sls=none disables all SLS hardening. ๐ซถ
-msve-vector-bits=bitsโ specifies the number of bits in an SVE vector register. This option only does anything when SVE is enabled.
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. and listen the behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that's 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 ๐
okay so the feature modifiers you can slap onto -march and -mcpu? any of these, bestie โ and every single one of them has an inverse that's literally just no + the name, so like nofeature. the way that works is so clean actually ๐
crcโ turns on the CRC extension. on by default for-march=armv8.1-a, no cap.cryptoโ turns on the Crypto extension. bonus: this one also enables Advanced SIMD and floating-point instructions. two-for-one slay.fpโ enables floating-point instructions. on by default for every single possible value of the options-marchand-mcpu. periodt.simdโ enables Advanced SIMD instructions. also pulls in floating-point instructions along for the ride. on by default for all possible values of-marchand-mcpu.sveโ enables Scalable Vector Extension instructions. yup, also enables Advanced SIMD and floating-point. stacked โจlseโ enables Large System Extension instructions. on by default for-march=armv8.1-a.rdmaโ enables Round Double Multiply Accumulate instructions. on by default for-march=armv8.1-a.fp16โ enables the FP16 extension. also enables floating-point instructions.fp16fmlโ enables the FP16fmlaextension. also enables FP16 extensions and floating-point instructions. enabled by default for-march=armv8.4-a.
๐ซถ heads up bestie: using this one with architectures before Armv8.2-A is not supported. do not try it.
rcpcโ enables the RCpc extension. this one lets you use theLDAPRinstructions for load-acquire atomic semantics, and passes it on to the assembler, which means inline asm statements can use instructions from the RCpc extension. iykykdotprodโ enables the Dot Product extension. also enables Advanced SIMD instructions.aesโ enables the Armv8-aaesandpmullcrypto extension. also enables Advanced SIMD instructions.sha2โ enables the Armv8-asha2crypto extension. also enables Advanced SIMD instructions.sha3โ enables thesha512andsha3crypto extension. also enables Advanced SIMD instructions.
๐ and again: use of this option with architectures prior to Armv8.2-A is not supported.
sm4โ enables thesm3andsm4crypto extension. also enables Advanced SIMD instructions.
๐ same warning, bestie: not supported on architectures prior to Armv8.2-A.
profileโ enables the Statistical Profiling extension. important: this one is only to enable the extension at the assembler level and does not affect code generation.rngโ enables the Armv8.5-a Random Number instructions. again, assembler-level only, does not affect code generation.memtagโ enables the Armv8.5-a Memory Tagging Extensions.
๐ use of this option with architectures prior to Armv8.5-A is not supported.
sbโ enables the Armv8-a Speculation Barrier instruction. assembler-level only, does not affect code generation. enabled by default for-march=armv8.5-a.ssbsโ enables the Armv8-a Speculative Store Bypass Safe instruction. assembler-level only, no codegen impact. enabled by default for-march=armv8.5-a.predresโ enables the Armv8-a Execution and Data Prediction Restriction instructions. assembler-level only, no codegen impact. enabled by default for-march=armv8.5-a.sve2โ enables the Armv8-a Scalable Vector Extension 2. this also enables SVE instructions.sve2-bitpermโ enables SVE2bitperminstructions. also enables SVE2 instructions.sve2-sm4โ enables SVE2sm4instructions. also enables SVE2 instructions.sve2-aesโ enables SVE2aesinstructions. also enables SVE2 instructions.sve2-sha3โ enables SVE2sha3instructions. also enables SVE2 instructions.tmeโ enables the Transactional Memory Extension.i8mmโ enables 8-bit Integer Matrix Multiply instructions. also enables Advanced SIMD and floating-point instructions. enabled by default for-march=armv8.6-a.
๐ use of this option with architectures prior to Armv8.2-A is not supported.
f32mmโ enables 32-bit Floating point Matrix Multiply instructions. also enables SVE instructions.
๐ not supported on architectures prior to Armv8.2-A.
f64mmโ enables 64-bit Floating point Matrix Multiply instructions. also enables SVE instructions.
๐ once again: not supported on architectures prior to Armv8.2-A.
bf16โ enables brain half-precision floating-point instructions. also enables Advanced SIMD and floating-point instructions. enabled by default for-march=armv8.6-a.
๐ you already know: not supported on architectures prior to Armv8.2-A.
ls64โ enables the 64-byte atomic load and store instructions for accelerators. enabled by default for-march=armv8.7-a.mopsโ enables the instructions that accelerate memory operations likememcpy,memmove,memset. enabled by default for-march=armv8.8-a.flagmโ enables the Flag Manipulation instructions Extension.pauthโ enables the Pointer Authentication Extension.csscโ enables the Common Short Sequence Compression instructions.
okay so the tea on how these stack together: the feature crypto implies aes, sha2, and simd, which implies fp. and flipping it: nofp implies nosimd, which implies nocrypto, noaes and nosha2. cascading vibes ๐
๐ฆ Adapteva Epiphany Options ๐ฆ
these -m options are defined for Adapteva Epiphany: like, specifically for that one, bestie.
-mhalf-reg-fileโ don't allocate any register in the ranger32...r63. why? so your code can run on hardware variants that lack these registers. adaptable queen โจ-mprefer-short-insn-regsโ preferentially allocate registers that allow short instruction generation. heads up: this can increase the instruction count, so it may either reduce or increase your overall code size. it's giving chaos, honestly.-mbranch-cost=numโ set the cost of branches to roughlynum"simple" instructions. ngl 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. filler era ๐-mno-soft-cmpsfโ for single-precision floating-point comparisons, emit anfsubinstruction and test the flags. this is faster than a software comparison, but 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. pick your struggle ๐ซถ-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 rangesp+0...sp+7can be used by leaf functions without stack allocation. values other than 8 or 16 are untested and unlikely to work.
๐จ also note that this option changes the ABI; compiling a program with a different stack offset than the libraries have been compiled with generally does not work. it can be useful if you want to evaluate whether a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate --with-stack-offset=num option.
-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 theb/blinstructions, and therefore load the function address into a register before performing a (otherwise direct) call. this is the default.-mshort-callsโ if not otherwise specified by an attribute, assume all direct calls are in the range of theb/blinstructions, so use these instructions for direct calls. the default is-mlong-calls.-msmall16โ assume addresses can be loaded as 16-bit unsigned values. note: this does not apply to function addresses, for which-mlong-callssemantics are in effect.-mfp-mode=modeโ set the prevailing mode of the floating-point unit. this determines the floating-point mode that is provided and expected at function call and return time. making this mode match the mode you predominantly need at function start can make your programs smaller and faster by avoiding unnecessary mode switches. optimization slay โจ
mode can be set to one of the following values:
callerโ any mode at function entry is valid, and retained or restored when the function returns, and when it calls other functions. this mode is useful for compiling libraries or other compilation units you might want to incorporate into different programs with different prevailing FPU modes, and the convenience of being able to use a single object file outweighs the size and speed overhead for any extra mode switching that might be needed, compared with what would be needed with a more specific choice of prevailing FPU mode.truncateโ this is the mode used for floating-point calculations with truncating (i.e. round towards zero) rounding mode. that includes conversion from floating point to integer.round-nearestโ this is the mode used for floating-point calculations with round-to-nearest-or-even rounding mode.intโ this is the mode used to perform integer calculations in the FPU, e.g. integer multiply, or integer multiply-and-accumulate.
the default is -mfp-mode=caller.
-mno-split-lohi-mno-postinc-mno-postmodifyโ code generation tweaks that disable, respectively, splitting of 32-bit loads, generation of post-increment addresses, and generation of post-modify addresses. the defaults aremsplit-lohi,-mpost-inc, and-mpost-modify. iykyk ๐-mnovect-doubleโ change the preferred SIMD mode to SImode. the default is-mvect-double, which uses DImode as preferred SIMD mode.-max-vect-align=numโ the maximum alignment for SIMD vector mode types.nummay be 4 or 8. the default is 8.
๐ธ note that this is an ABI change, even though many library function interfaces are unaffected if they don't use SIMD vector modes in places that affect size and/or alignment of relevant types. so likeโฆ be careful bestie.
-msplit-vecmove-earlyโ bestie, this splits vector moves into single word moves before reload. In theory that means better register allocation โจ but lowkey so far the reverse is generally the case ๐. It's giving "sounded great on paper".-m1reg-regโ pick a register to hold the constant-1, which makes loading small negative constants and certain bitmasks faster ๐โโ๏ธ. The allowable values for reg arer43andr63(which say "use that register as a fixed register"), andnone, which means no register is used for this purpose. The default is-m1reg-none. Periodt.
๐ AMD GCN Options ๐
These options are defined specifically for the AMD GCN port. Iykyk.
-march=gpu-mtune=gpuโ set the architecture type or the tuning for gpu. The supported values for gpu are:fijiโ compile for GCN3 Fiji devices (gfx803). ๐งgfx900โ compile for GCN5 Vega 10 devices (gfx900).gfx906โ compile for GCN5 Vega 20 devices (gfx906).gfx908โ compile for CDNA1 Instinct MI100 series devices (gfx908).gfx90aโ compile for CDNA2 Instinct MI200 series devices (gfx90a). ๐
-msram-ecc=on-msram-ecc=off-msram-ecc=anyโ compile binaries suitable for devices with the SRAM-ECC feature enabled, disabled, or either mode. This feature can be enabled per-process on some devices. The compiled code must match the device mode. The default isany, for devices that support it.-mstack-size=bytesโ say how many bytes of stack space will be requested for each GPU thread (wave-front). โ ๏ธ Beware that there may be many threads and limited memory available. The size of the stack allocation may also have an impact on run-time performance. The default is32KBwhen using OpenACC or OpenMP, and1MBotherwise.-mxnackโ compile binaries suitable for devices with the XNACK feature enabled. Some devices always require XNACK and some let the user configure XNACK. The compiled code must match the device mode. The default is-mno-xnack. At present this option is a placeholder for support that is not yet implemented ๐.
๐ธ ARC Options ๐ธ
The following options control the architecture variant for which code is being compiled:
-mbarrel-shifterโ generate instructions supported by barrel shifter. This is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect.-mjli-alwaysโ force to call a function usingjli_sinstruction. This option is valid only for ARCv2 architecture.-mcpu=cpuโ set architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options available for backward compatibility and convenience ๐ซถ. Supported values for cpu are:arc600โ compile for ARC600. Aliases:-mA6,-mARC600.arc601โ compile for ARC601. Alias:-mARC601.arc700โ compile for ARC700. Aliases:-mA7,-mARC700. This is the default when configured with--with-cpu=arc700.arcemโ compile for ARC EM.archsโ compile for ARC HS.emโ compile for ARC EM CPU with no hardware extensions.em4โ compile for ARC EM4 CPU.em4_dmipsโ compile for ARC EM4 DMIPS CPU.em4_fpusโ compile for ARC EM4 DMIPS CPU with the single-precision floating-point extension.em4_fpudaโ compile for ARC EM4 DMIPS CPU with single-precision floating-point and double assist instructions.hsโ compile for ARC HS CPU with no hardware extensions except the atomic instructions.hs34โ compile for ARC HS34 CPU.hs38โ compile for ARC HS38 CPU.hs38_linuxโ compile for ARC HS38 CPU with all hardware extensions on.hs4xโ compile for ARC HS4x CPU.hs4xdโ compile for ARC HS4xD CPU.hs4x_rel31โ compile for ARC HS4x CPU release 3.10a.arc600_normโ compile for ARC 600 CPU with "norm" instructions enabled.arc600_mul32x16โ compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.arc601_normโ compile for ARC 601 CPU with "norm" instructions enabled.arc601_mul32x16โ compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring reduced register set. ๐
-mdpfp-mdpfp-compactโ generate double-precision FPX instructions, tuned for the compact implementation.-mdpfp-fastโ generate double-precision FPX instructions, tuned for the fast implementation.-mno-dpfp-lrsrโ disablelrandsrinstructions 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 generatempy-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โ generatenorminstructions. 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 is provided for compatibility purposes only ๐. Software floating-point code is emitted by default, and this default can be overridden by FPX options:-mspfp,-mspfp-compact, or-mspfp-fastfor single precision, and-mdpfp,-mdpfp-compact, or-mdpfp-fastfor double precision.-mswapโ generateswapinstructions. ๐-matomicโ this enables use of the locked load/store conditional extension to implement atomic memory built-in functions. Not available for ARC 6xx or ARC EM cores.-mdiv-remโ 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 for multo.wlh1is the default value. The recognized values are:0,noneโ no multiplier available.1,wโ 16x16 multiplier, fully pipelined. The following instructions are enabled: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. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.6,wlh5โ one 32x4 multiplier, blocking, sequential. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.7,plus_dmpyโ ARC HS SIMD support.8,plus_macdโ ARC HS SIMD support.9,plus_qmacwโ ARC HS SIMD support.
This option is only available for ARCv2 cores.
-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โ turns on support for single-precision floating-point + fused multiply-and-add hardware extensions โจfpud_fmaโ turns on support for double-precision floating-point + fused multiply-and-add hardware extensions. this one includesfpus_fmabestie, it's a package deal ๐. not available for ARC EM tho.fpus_allโ turns on support for all single-precision floating-point hardware extensions ๐fpud_allโ turns on support for all single- and double-precision floating-point hardware extensions. not available for ARC EM, sorry babes ๐ญ
-mirq-ctrl-saved=register-range, blink, lp_count โ this one says which general-purpose registers the processor auto-saves/restores on interrupt entry and exit ๐. register-range is written as two registers with a dash between them. the range always starts at"r0", and the upper limit is the"fp"register.blinkandlp_countare optional. only valid for ARC EM and ARC HS cores, iykyk.-mrgf-banked-regs=number โ sets how many registers get replicated in the second register bank when a fast interrupt hits ๐. "fast interrupts" = interrupts with the highest priority level P0. these guys only save thePCandSTATUS32registers, so they can skip memory transactions during interrupt entry/exit. use this when you're doing fast interrupts on an ARC V2 family processor. permitted values are4,8,16, and32โ that's it, that's the whole menu ๐.-mlpc-width=width โ sets the width of the"lp_count"register. valid width values are8,16,20,24,28and32bits. the default is locked to32bits. if your width is under 32, the compiler won't try to transform loops into the zero-delay loop mechanism unless it knows the"lp_count"register can hold the loop-counter value. depending on what width you pick, the compiler and run-time library might still keep using the loop mechanism for various needs. this option defines the macro"__ARC_LPC_WIDTH__"with the value of width โจ-mrf16โ tells the compiler to generate code for a 16-entry register file ๐ฆ. this option defines the"__ARC_RF16__"preprocessor macro.-mbranch-indexโ enables use of"bi"or"bih"instructions to implement jump tables ๐ฅ
these next ones get passed straight through to the assembler, and they also define preprocessor macro symbols.
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. also sets the preprocessor symbol"__Xdsp_packa". this option is deprecated.-mdvbfโ passed down to the assembler to enable the dual Viterbi butterfly extension. also sets the preprocessor symbol"__Xdvbf". this option is deprecated.-mlockโ passed down to the assembler to enable the locked load/store conditional extension. also sets the preprocessor symbol"__Xlock".-mmac-d16โ passed down to the assembler. also sets the preprocessor symbol"__Xxmac_d16". this option is deprecated.-mmac-24โ passed down to the assembler. also sets the preprocessor symbol"__Xxmac_24". this option is deprecated.-mrtscโ passed down to the assembler to enable the 64-bit time-stamp counter extension instruction. also sets the preprocessor symbol"__Xrtsc". this option is deprecated.-mswapeโ passed down to the assembler to enable the swap byte ordering extension instruction. also sets the preprocessor symbol"__Xswape".-mtelephonyโ passed down to the assembler to enable dual- and single-operand instructions for telephony. also sets the preprocessor symbol"__Xtelephony". this option is deprecated.-mxyโ passed down to the assembler to enable the XY memory extension. also sets the preprocessor symbol"__Xxy".
these next ones control how the assembly code gets annotated:
-misizeโ annotate assembler instructions with estimated addresses ๐-mannotate-alignโ explains what alignment considerations led to the decision to make an instruction short or long ๐
and these ones get 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.
these next ones control the semantics of the generated code:
-mlong-callsโ generate calls as register indirect calls, which gives you access to the full 32-bit address range ๐ซ-mmedium-callsโ don't use less than a 25-bit addressing range for calls โ that's the offset you get for an unconditional branch-and-link instruction. conditional execution of function calls gets suppressed so you can use the 25-bit range instead of the 21-bit range you'd get 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 num is4for any ARC configuration, or8when we have double load/store operations ๐-mno-sdataโ don't 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 โก
these next ones fine tune code generation:
-malign-callโ does nothing ๐. preserved for backward compatibility.-mauto-modify-regโ enable the use of pre/post modify with register displacement.-mbbit-peepholeโ enable bbit peephole2.-mno-brccโ this one disables a target-specific pass inarc_reorgthat generates 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 the compact"casesi"pattern. this is the default for-Os, and only available for ARCv1 cores. this option is deprecated.-mno-cond-execโ disable the ARCompact-specific pass that generates conditional execution instructions.
so like, because of delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass for generating conditional execution is often lacking ๐ญ. so the ARC port keeps a special pass around that hunts for more conditional execution opportunities after register allocation, branch shortening, and delay slot scheduling are all done. this pass generally โ but not always โ improves performance and code size, at the cost of extra compilation time, which is exactly why there's an option to switch it off. if you hit a problem where call instructions exceed their allowable offset range because they got 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 indexed stores exist, which is not the case ๐ฌ-mlraโ enable Local Register Allocation. this is still experimental for ARC, so by default the compiler uses standard reload (i.e.-mno-lra) ๐งช-mlra-priority-noneโ don't indicate any priority for target registers.-mlra-priority-compactโ indicate target register priority forr0..r3/r12..r15.-mlra-priority-noncompactโ reduce target register priority forr0..r3/r12..r15.-mmillicodeโ when optimizing for size (using-Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by calling a special function in libgcc โ this is called a millicode call. since these calls can cause performance issues and/or linking issues when you link in a nonstandard way, this option exists to turn millicode call generation on or off ๐-mcode-density-frameโ this option lets the compiler emit"enter"and"leave"instructions. these instructions are only valid for CPUs with the code-density feature โจ-mmixed-codeโ does nothing ๐. preserved for backward compatibility.-mq-classโ ths option is deprecated. (yes, "ths" โ that's the typo, we're keeping it, it's iconic ๐) enable 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 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โ the cost you assume for a multiply instruction, where4equals a normal instruction. so like, how expensive does the compiler think a multiply is? that's the vibe check. โจ-munalign-prob-threshold=probabilityโ does literally nothing. it's kept around purely for backward compatibility, bestie. it's giving decorative. ๐
The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release. so like, they still work, but they're on their way out the door, no cap. ๐
-margonautโ obsolete FPX.-mbig-endian,-EBโ compile code for big-endian targets. using these is now deprecated. big-endian code is supported by configuring GCC to buildarceb-elf32andarceb-linux-uclibctargets, for which big endian is the default.-mlittle-endian,-ELโ compile code for little-endian targets. also deprecated now. little-endian code is supported by configuring GCC to buildarc-elf32andarc-linux-uclibctargets, 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โ the 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, and there are so many of them. buckle up bestie ๐
-mabi=nameโ generate code for the specified ABI. permissible values are:apcs-gnu,atpcs,aapcs,aapcs-linuxandiwmmxt.-mapcs-frameโ generate a stack frame that's compliant with the ARM Procedure Call Standard for all functions, even if that's not strictly necessary for correct execution of the code. specifying-fomit-frame-pointerwith this option causes the stack frames not to be generated for leaf functions. the default is-mno-apcs-frame. > this option is deprecated, jsyk. ๐-mapcsโ this is a synonym for-mapcs-frameand is deprecated.-mthumb-interworkโ generate code that supports calling between the ARM and Thumb instruction sets. without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. the default is-mno-thumb-interwork, since slightly larger code is generated when-mthumb-interworkis specified. in AAPCS configurations this option is meaningless. ๐-mno-sched-prologโ prevent the reordering of instructions in the function prologue, or the merging of those instructions with the instructions in the function's body. this means all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this information 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 causes GCC to 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. note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. โ ๏ธ like, the whole program, bestie, no mixing.
-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. this will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. ๐-mlittle-endianโ generate code for a processor running in little-endian mode. this is the default for all standard configurations.-mbig-endianโ generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.-mbe8,-mbe32โ when linking a big-endian image, select between BE8 and BE32 formats. the option has no effect for little-endian images and is ignored. the default is dependent on the selected target architecture. for ARMv6 and later architectures the default isBE8, for older architectures the default isBE32. > 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. slay, order matters. โจ
most extension names are generically named, but have an effect that is dependent upon the architecture to which it is applied. for example, the +simd option can be applied to both armv7-a and armv8-a architectures, but will enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a and the ARMv8-A variant for armv8-a.
the table below lists the supported extensions for each architecture. architectures not mentioned do not support any extensions.
๐ฆ armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk
+fpโ the VFPv2 floating-point instructions. the extension+vfpv2can be used as an alias for this extension.+nofpโ disable the floating-point instructions.
๐ฆ armv7
the common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures.
+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this extension. note that floating-point is not supported by the base ARMv7-M architecture, but is compatible with both the ARMv7-A and ARMv7-R architectures.+nofpโ disable the floating-point instructions.
๐ฆ armv7-a
+mpโ the multiprocessing extension.+secโ the security extension.+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this extension.+simdโ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extensions+neonand+neon-vfpv3can be used as aliases for this extension.+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-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. ๐
+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, but with 16 double-precision registers ๐+vfpv4โ the VFPv4 floating-point instructions, and this time with 32 double-precision registers โจ+neonโ the Advanced SIMD (Neon) v1 instructions plus the VFPv3 floating-point instructions. Oh and bestie,+neon-vfpv3totally works as an alias for this one ๐ฆ+neon-fp16โ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations thrown in ๐ธ+nosimdโ turns OFF the Advanced SIMD instructions (and no, it does not disable floating point, so don't panic) ๐+nofpโ turns off the floating-point and Advanced SIMD instructions. like, all of it ๐
armv8-aโ the whole vibe, and it comes with:+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โ she's giving upgrade era โจ+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-aarmv8.3-aโ (both of these share the same set of extensions, and here they are ๐)+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โ the way she keeps stacking features, iconic ๐+fp16โ the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension.+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension.+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension.+nocryptoโ 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โ bestie she's literally glowing โจ+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โ main character energy fr fr ๐+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โ real-time era, she's focused ๐+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โ disable the ARM-state integer division extension.
armv7e-mโ microcontroller vibes ๐ฅ+fpโ the single-precision VFPv4 floating-point instructions.+fpv5โ the single-precision FPv5 floating-point instructions.+fp.dpโ the single- and double-precision FPv5 floating-point instructions.+nofpโ disable the floating-point extensions.
armv8.1-m.mainโ she's got range, ngl ๐+dspโ the DSP instructions.+mveโ the M-Profile Vector Extension (MVE) integer instructions.+mve.fpโ the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions.+fpโ the single-precision floating-point instructions.+fp.dpโ the single- and double-precision floating-point instructions.+nofpโ disable the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7.+pacbtiโ enable the Pointer Authentication and Branch Target Identification Extension.
armv8-m.mainโ sibling energy ๐+dspโ the DSP instructions.+nodspโ disable the DSP extension.+fpโ the single-precision floating-point instructions.+fp.dpโ the single- and double-precision floating-point instructions.+nofpโ disable the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7.
armv8-rโ the real-time one, periodt โญ+crcโ the Cyclic Redundancy Check (CRC) instructions.+fp.spโ the single-precision FPv5 floating-point instructions.+simdโ the ARMv8-A Advanced SIMD and floating-point instructions.+cryptoโ the cryptographic instructions.+nocryptoโ disable the cryptographic instructions.+nofpโ disable the floating-point, Advanced SIMD and cryptographic instructions.
-march=native makes the compiler โจauto-detectโจ the architecture of the build computer, no cap. Right now this only works on GNU/Linux, and ngl not every architecture is recognized. If the auto-detect doesn't pan out, the option justโฆ does nothing. ๐
-mtune=nameโ bestie, this one tells GCC which target ARM processor it should tune the performance of the code for. ๐ For some ARM implementations you get better performance by using this option. The 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.
Plus โ plot twist โ this option can also say "tune for a big.LITTLE system". ๐ฆ The 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.
-mtune=generic-arch says GCC should tune for a blend of processors within architecture arch. The whole vibe is: 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 though โ the effects of this option may change in future GCC versions as CPU models come and go. ๐
-mtune permits the same extension options as -mcpu, but (important!) 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. Right now this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. ๐ซ
-mcpu=name[+extension...]โ this specifies the name of the target ARM processor. GCC uses this name to derive the name of the target ARM architecture (as if you'd said it with-march) and the ARM processor type to tune for performance (as if you'd said it with-mtune). Where this option is used together with-marchor-mtune, those options take precedence over the appropriate part of this one. Periodt.
Many of the supported CPUs implement optional architectural extensions. Where that's the case, 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 -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. ๐
The permissible names for this option are the same as those for -mtune. (Yes, the whole long list above. Iconic, we know.)
The following extension options are common to the listed CPUs:
+nodspโ disable the DSP instructions oncortex-m33,cortex-m35p,cortex-m55andcortex-m85. Also disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85.+nopacbtiโ disable the Pointer Authentication and Branch Target Identification Extension oncortex-m85.+nomveโ disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions oncortex-m55andcortex-m85.+nomve.fpโ disable the M-Profile Vector Extension (MVE) single precision floating-point instructions oncortex-m55andcortex-m85.+cdecp0,+cdecp1, ... ,+cdecp7โ enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7 oncortex-m55.+nofpโ disables the floating-point instructions on:
arm9e, 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-m35p cortex-m4, cortex-m7,
cortex-m33, cortex-m35p, cortex-m55 and cortex-m85.
and disables the floating-point and SIMD instructions on:
generic-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-a53 and
cortex-a55.
+nofp.dpโ disables the double-precision component of the floating-point instructions oncortex-r5,cortex-r7,cortex-r8,cortex-r52,cortex-r52plusandcortex-m7.+nosimdโ disables the SIMD (but not floating-point) instructions ongeneric-armv7-a,cortex-a5,cortex-a7andcortex-a9.+cryptoโ enables the cryptographic instructions oncortex-a32,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,exynos-m1,xgene1,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53andcortex-a75.cortex-a55.
Additionally the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. ๐ธ It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a.
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information. ๐
-mcpu=native 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. ๐ญ
-mfpu=nameโ this specifies what floating-point hardware (or hardware emulation) is available on the target. The 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. ๐
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.
If the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), note that floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. This is because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so the use of NEON instructions may lead to a loss of precision. ๐ฌ
You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas. ๐
-mfp16-format=nameโ specify the format of the"__fp16"half-precision floating-point type. Permissible names arenone,ieee, andalternative; the default isnone, in which case the"__fp16"type is not defined. ๐ฆ-mstructure-size-boundary=nโ the sizes of all structures and unions are rounded up to a multiple of the number of bits set by this option. Permissible values are8,32and64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is8. A value of64is only allowed if the underlying ABI supports it.
Specifying a larger number can produce faster, more efficient code, but can also increase the size of the program. ๐ Different values are potentially incompatible. Code compiled with one value cannot necessarily expect to work with code or libraries compiled with another value, if they exchange information using structures or unions. ๐
This option is deprecated. ๐ซ
-mabort-on-noreturnโ generate a call to the function"abort"at the end of a"noreturn"function. It is executed if the function tries to return. ๐ซถ-mlong-calls-mno-long-calls
Tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction. ๐ฅ
...and like, lowkey that doesn't mean every call becomes a long call, bestie, so don't come for me. Here's the heuristic: static functions, functions that have the "short_call" attribute, functions sitting inside the scope of a "#pragma no_long_calls" directive, and functions whose definitions have already been compiled inside the current compilation unit โ none of those get turned into long calls. The plot twist โจ is that weak function definitions, functions with the "long_call" attribute or the "section" attribute, and functions inside the scope of a "#pragma long_calls" directive are always turned into long calls. Always always.
And no, this feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, and so does dropping your function calls inside the scope of a "#pragma long_calls_off" directive. ๐
Heads up though: these switches literally have no effect on how the compiler generates code to handle function calls via function pointers. Like, none. Zero. Don't @ me. ๐
-msingle-pic-baseโ treat the register used for PIC addressing as read-only, instead of loading it in the prologue for every single function. The runtime system is the one responsible for initializing this register with an appropriate value before execution begins. Not you. The runtime. ๐ซถ-mpic-register=regโ pick which register gets used for PIC addressing. For the standard PIC base case, the default is any suitable register the compiler determines. 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 the displacement between the text and data segments is fixed at static link time. This lets you use 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. And when it's disabled on those targets, it will enable-msingle-pic-baseby default. Sneaky little chain reaction, iykyk. ๐-mpoke-function-nameโ write the name of each function into the text section, directly preceding the function prologue. The generated code is giving:
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
So when you're doing 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 there's a function name embedded immediately preceding this location and it has length "((pc[-3]) & 0xff000000)". Detective work fr fr ๐
-mthumb,-marmโ select between generating code that executes in ARM state and Thumb state. 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. And yes, you can override the ARM and Thumb mode for each function by using thetarget("thumb")andtarget("arm")function attributes or pragmas. Main character energy, per-function edition ๐-mflip-thumbโ switch ARM/Thumb modes on alternating functions. This option is provided for regression testing of mixed Thumb/ARM code generation, and it is not intended for ordinary use in compiling code. Like, stay in your lane with this one please. ๐-mtpcs-frameโ generate a stack frame that's 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's compliant with the Thumb Procedure Call Standard for all leaf functions. (Again: 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. Not valid in AAPCS configurations though, because interworking is enabled by default there. ๐ซ-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's a small overhead in the cost of executing a function pointer if this option is enabled โ small price, big vibes. Also not valid in AAPCS configurations, because again, interworking is enabled by default. ๐ซ-mtp=nameโ specify the access model for the thread local storage pointer. The valid models are:softโ generates calls to"__aeabi_read_tp".cp15โ fetches the thread pointer from"cp15"directly (supported in thearm6karchitecture).autoโ uses the best available method for the selected processor.
The default setting is auto. Slay, let the compiler choose ๐
-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 it 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. Heads up: this option conflicts with-mslow-flash-data. ๐-mfix-cortex-m3-ldrdโ some Cortex-M3 cores can cause data corruption when"ldrd"instructions with overlapping destination and base registers are used. This option avoids generating those instructions. Enabled by default when-mcpu=cortex-m3is specified. Crisis averted, bestie โจ-mfix-cortex-a57-aes-1742098,-mno-fix-cortex-a57-aes-1742098,-mfix-cortex-a72-aes-1655431,-mno-fix-cortex-a72-aes-1655431โ enable (disable) mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions. This option is enabled by default when either-mcpu=cortex-a57or-mcpu=cortex-a72is specified. ๐-munaligned-access,-mno-unaligned-accessโ enables (or disables) reading and writing of 16- and 32-bit values from addresses that are not 16- or 32-bit aligned. By default unaligned access is disabled for all pre-ARMv6, all ARMv6-M and for ARMv8-M Baseline architectures, and enabled for all other architectures. If unaligned access is not enabled then words in packed data structures are accessed a byte at a time. ๐
The ARM attribute "Tag_CPU_unaligned_access" is set in the generated object file to either true or false, depending upon the setting of this option. If unaligned access is enabled then the preprocessor symbol "__ARM_FEATURE_UNALIGNED" is also defined. โ
-mneon-for-64bitsโ this option is deprecated and has no effect. That's it. That's the whole thing. ๐-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 it's 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 โ plot twist โ 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. Disabled by default. ๐-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler. ๐ง-mpure-codeโ do not allow constant data to be placed in code sections. Additionally, when compiling for ELF object format, give all text sections the ELF processor-specific section attribute"SHF_ARM_PURECODE". This option is only available when generating non-pic code for M-profile targets. ๐-mcmseโ generate secure code as per the "ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification", which can be found onhttps://developer.arm.com/documentation/ecm0359818/latest/. ๐โจ-mfix-cmse-cve-2021-35465โ mitigate against a potential security issue with the"VLLDM"instruction in some M-profile devices when using CMSE (CVE-2021-365465). This option is enabled by default when the option-mcpu=is used with"cortex-m33","cortex-m35p","cortex-m55","cortex-m85"or"star-mc1". The option-mno-fix-cmse-cve-2021-35465can be used to disable the mitigation. ๐ก๏ธ-mstack-protector-guard=guard,-mstack-protector-guard-offset=offsetโ generate stack protection code using canary at guard. Supported locations areglobalfor a global canary, ortlsfor a canary accessible via the TLS register. The option-mstack-protector-guard-offset=is for use with-fstack-protector-guard=tlsand not for use in user-land code. ๐ค-mfdpic,-mno-fdpicโ select the FDPIC ABI, which uses 64-bit function descriptors to represent pointers to functions. When the compiler is configured for"arm-*-uclinuxfdpiceabi"targets, this option is on by default and implies-fPIEif none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and the user should explicitly provide the PIC/PIE-related options as needed. ๐
Also, bestie, just so you know โ static linking is not supported here, because it would still drag the dynamic linker in when the program self-relocates. If that behavior is acceptable to you, use -static and -Wl,-dynamic-linker options. ๐
The opposite -mno-fdpic option is useful (and required!) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs. Slay. ๐
-mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]]โ Enable branch protection features (armv8.1-m.main only, okay? only there). Let's break it down:noneโ generate code without branch protection or return address signing.standard[+leaf]โ generate code with all the branch protection features enabled at their standard level.pac-ret[+leaf]โ generate code with return address signing set to its standard level, which is to sign all functions that save the return address to memory.leafโ when return address signing is enabled, also sign leaf functions even if they 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 all branch protection and return address signing operations are 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 the extra security can be enabled at run time on processors that support the PACBTI extension. โจ
Branch target enforcement using BTI can only be enabled at runtime if all code in the application has been compiled with at least -mbranch-protection=bti. No skipping, bestie, all of it. ๐ญ
Any setting other than none is supported only on armv8-m.main or later.
The default is to generate code without branch protection or return address signing.
๐ AVR Options ๐
These options are defined for AVR implementations:
-mmcu=mcuโ 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 the supported mcus 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","avr64da32","avr64da48","avr64da64","avr64db28","avr64db32","avr64db48","avr64db64","avr64dd14","avr64dd20","avr64dd28","avr64dd32","avr64du28","avr64du32","avr64ea28","avr64ea32","avr64ea48"."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","avr32da28","avr32da32","avr32da48","avr32db28","avr32db32","avr32db48","avr32dd14","avr32dd20","avr32dd28","avr32dd32","avr32du14","avr32du20","avr32du28","avr32du32","avr32ea28","avr32ea32","avr32ea48"."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","avr128da32","avr128da48","avr128da64","avr128db28","avr128db32","avr128db48","avr128db64"."avrxmega5"โ"XMEGA"devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM. mcu ="atxmega64a1","atxmega64a1u"."avrxmega6"โ"XMEGA"devices with more than 128 KiB of program memory. mcu ="atxmega128a3","atxmega128a3u","atxmega128b1","atxmega128b3","atxmega128c3","atxmega128d3","atxmega128d4","atxmega192a3","atxmega192a3u","atxmega192c3","atxmega192d3","atxmega256a3","atxmega256a3b","atxmega256a3bu","atxmega256a3u","atxmega256c3","atxmega256d3","atxmega384c3","atxmega384d3"."avrxmega7"โ"XMEGA"devices with more than 128 KiB of program memory and more than 64 KiB of RAM. mcu ="atxmega128a1","atxmega128a1u","atxmega128a4u"."avrtiny"โ"TINY"Tiny core devices with 512 B up to 4 KiB of program memory. mcu ="attiny4","attiny5","attiny9","attiny10","attiny102","attiny104","attiny20","attiny40"."avr1"โ This ISA is implemented by the minimal AVR core and supported for assembler only. mcu ="attiny11","attiny12","attiny15","attiny28","at90s1200".
-mabsdataโ Assume that all data in static storage can be accessed by LDS / STS instructions. Heads up: this option has only an effect on reduced Tiny devices like ATtiny40. See also the"absdata"AVR Variable Attributes, variable attribute. ๐ซถ-maccumulate-argsโ bestie, this one saves up all your outgoing function args and grabs/returns the stack space they need once, in the function prologue/epilogue. Without it, every outgoing arg gets pushed before a call and popped after. ๐
And popping args after a call is expensive on AVR, so accumulating the stack space can mean smaller executables โ because you don't have to rip args off the stack after every single call. Obsessed.
Real talk: this can shrink your code size for functions that call other functions several times, specifically the ones that get their args on the stack โ like calls to printf-style functions. ๐ธ
-mbranch-cost=costโ sets the branch cost for conditional branch instructions to cost. Reasonable values are small, non-negative integers. Default branch cost is0. no cap.-mcall-prologuesโ function prologues/epilogues get expanded as calls to the appropriate subroutines. Code size is smaller. it's giving compact. โจ-mdouble=bits-mlong-double=bitsโ set the size (in bits) of thedoubleorlong doubletype respectively. Possible values for bits are32and64. Whether a specific bits value is even allowed depends on the--with-double=and--with-long-double=configure options (seehttps://gcc.gnu.org/install/configure.html#avr), and the same goes for the default values of these options. ๐ฆ-mgas-isr-prologuesโ interrupt service routines (ISRs) may use the__gcc_isrpseudo instruction supported by GNU Binutils. If this option is on, you can still turn the feature off for individual ISRs via theAVR Function Attributesno_gccisrfunction attribute. This feature is activated per default if optimization is on (but not with-Og, see the Optimize Options section), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683). ๐-mint8โ assumesintis an 8-bit integer. This affects the sizes of all types: acharis 1 byte, anintis 1 byte, alongis 2 bytes, andlong longis 4 bytes. Please note: this option does not conform to the C standards, but it results in smaller code size. ๐ญ tradeoffs, babe.-mmain-is-OS_taskโ don't save registers inmain. Effect is the same as attaching theAVR Function AttributesOS_taskattribute tomain. Activated per default if optimization is on. ๐-mno-interruptsโ the generated code is not compatible with hardware interrupts. Code size is smaller. (yes, that's the deal. smaller, but not interrupt-friendly. ๐ซถ)-mrelaxโ tries to replaceCALLresp.JMPinstructions with the shorterRCALLresp.RJMPinstruction if applicable. Setting-mrelaxjust adds the--mlink-relaxoption to the assembler's command line and the--relaxoption to the linker's command line.
Jump relaxing is done 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. ๐
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. MeaningXis 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. tiny. precious. ๐ธ-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 and linker โ with appropriate command line options. Which means the user has to supply her private device specs file by means of-specs=path-to-specs-file. There's no more need for the option-mmcu=mcu. โจ
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.
-Waddr-space-convertโ warn about conversions between address spaces when 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. ๐
๐ EIND and Devices with More Than 128 Ki Bytes of Flash ๐
Pointers in this implementation are 16 bits wide. The address of a function or label is represented as a word address, so indirect jumps and calls can target any code address in the range of 64 Ki words.
So that indirect jumps work 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 when EICALL or EIJMP instructions are used. ๐
Indirect jumps and calls on these devices are handled as follows by the compiler, and are subject to some limitations:
- The compiler never sets
EIND. - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions, or might readEINDdirectly in order to emulate an indirect call/jump by means of aRETinstruction. - The compiler assumes
EINDnever changes during the startup code or during the application. In particular,EINDis not saved/restored in function or interrupt service routine prologue/epilogue. ๐ญ - For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads, sometimes also called trampolines. 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 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. ๐ - 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 starts with.trampolinesinto the segment whereEINDpoints to. - The startup code from libgcc never sets
EIND. 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, for example 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 the following 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 the following situations:- Taking address of a function or code label.
- Computed goto.
- If prologue-save function is used, see the
-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. โจ
- The startup code initializes the
RAMPspecial function registers with zero. - If an AVR Named Address Spaces named address space other than generic or
__flashis used, thenRAMPZis set as needed before the operation. - ๐จ If the device supports RAM larger than 64 KiB and the compiler needs to change
RAMPZto accomplish an operation,RAMPZis reset to zero after the operation. - ๐จ If the device comes with a specific
RAMPregister, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it. - ๐จ RAM larger than 64 KiB is not supported by GCC for AVR targets. If you use inline assembler to read from locations outside the 16-bit address range and change one of the
RAMPregisters, you must reset it to zero after the access.
โจ AVR Built-in Macros โจ
okay so 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. iykyk ๐ฆ
__AVR_ARCH__
Build-in macro that resolves to a decimal number that identifies the architecture and depends on the -mmcu=mcu option. Possible values are:
2, 25, 3, 31, 35, 4, 5, 51, 6
for mcu="avr2", "avr25", "avr3", "avr31", "avr35", "avr4", "avr5", "avr51", "avr6",
respectively and
100, 102, 103, 104, 105, 106, 107
for mcu="avrtiny", "avrxmega2", "avrxmega3", "avrxmega4", "avrxmega5", "avrxmega6", "avrxmega7", respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4. ๐ฅ
__AVR_Device__
Setting -mmcu=device defines this built-in macro which reflects the device's name. For example, -mmcu=atmega8 defines the built-in macro __AVR_ATmega8__, -mmcu=attiny261a defines __AVR_ATtiny261A__, etc.
The built-in macros' names follow the scheme __AVR_Device__ where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase.
If device is not a device but only a core architecture like avr51, this macro is not defined. ๐
__AVR_DEVICE_NAME__
Setting -mmcu=device defines this built-in macro to the device's name. For example, with -mmcu=atmega8 the macro is defined to "atmega8".
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 the ADIW and SBIW instructions.
__AVR_HAVE_ELPM__
The device has the ELPM instruction.
__AVR_HAVE_ELPMX__
The device has the ELPM Rn,Z and ELPM Rn,Z+ instructions.
__AVR_HAVE_LPMX__
The device has the LPM Rn,Z and LPM Rn,Z+ instructions.
__AVR_HAVE_MOVW__
The device has the MOVW instruction to perform 16-bit register-register moves.
__AVR_HAVE_MUL__
The device has a hardware multiplier. ๐ฅ
__AVR_HAVE_JMP_CALL__
The device has the JMP and CALL instructions. 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 the EIJMP and EICALL instructions. 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=avr2 and -mmcu=avr25 also by -msp8.
__AVR_HAVE_RAMPD__, __AVR_HAVE_RAMPX__, __AVR_HAVE_RAMPY__, __AVR_HAVE_RAMPZ__
The device has the RAMPD, RAMPX, RAMPY, RAMPZ special function register, respectively.
__NO_INTERRUPTS__
This macro reflects the -mno-interrupts command-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 are SBRS, SBRC, SBIS, SBIC and CPSE. 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 like IN, OUT, SBI, etc. may use a different address as if addressed by an instruction to access RAM like LD or STS. 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-calls command line option is set.
__AVR_PM_BASE_ADDRESS__=addr
Some devices support reading from flash memory by means of LD* 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 .rodata into RAM. This is handled by the default linker description file, and is currently available for avrtiny and avrxmega3. Even more convenient, there is no need to use address spaces like __flash or features like attribute progmem and pgm_read_*. ๐
__WITH_AVRLIBC__
The compiler is configured to be used together with AVR-Libc. See the --with-avrlibc configure 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 of double if -mdouble= is not set. To test the layout of double in 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 for long double instead of double.
__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 ๐ ๏ธ
The following options are used internally by the compiler and to communicate between device specs files and the compiler proper. You don't need to set these options by hand, in particular they are not optimization options. Using these options in the wrong way may lead to sub-optimal or wrong code. ๐ญ They are documented for completeness, and in order to get a better understanding of device specs (https://gcc.gnu.org/wiki/avr-gcc#spec-files) files.
-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 of bf512, 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 for bf561 is incomplete. For bf561, 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 for bfin-elf toolchain. Certain other options, such as-mid-shared-libraryand-mfdpic, imply-msim.-momit-leaf-frame-pointerโ Don't keep the frame pointer in a register for leaf functions. This avoids the instructions to save, set up and restore frame pointers and makes an extra register available in leaf functions. ๐ซถ-mspecld-anomalyโ bestie, when this is on the compiler makes sure the generated code has zero speculative loads chilling after jump instructions. If you use it,"__WORKAROUND_SPECULATIVE_LOADS"gets defined. โจ-mno-specld-anomalyโ please don't generate that extra code to stop speculative loads from happening. we're rawdogging it. ๐-mcsync-anomalyโ when enabled, the compiler makes sure the generated code doesn't haveCSYNCorSSYNCinstructions showing up too soon after conditional branches. If you use this,"__WORKAROUND_SPECULATIVE_SYNCS"is defined. ๐-mno-csync-anomalyโ no extra code to keepCSYNCorSSYNCinstructions from arriving too early after a conditional branch. live your truth.-mlow64kโ when enabled, the compiler is free to use the knowledge that the entire program fits into the low 64k of memory. cozy vibes only. ๐-mno-low64kโ assume the program is arbitrarily large. this is the default, bestie.-mstack-check-l1โ do stack checking using information placed into L1 scratchpad memory by the uClinux kernel. fancy.-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 a bfin-elf target, 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 lets the compiler use faster code for jumps and calls. slay. ๐-mno-leaf-id-shared-libraryโ do not assume that the code being compiled won't link against any ID shared libraries. slower code gets 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 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 > rules, iykyk.-minline-pltโ enable inlining of PLT entries in function calls to functions that are not known to bind locally. it has no effect without-mfdpic. ๐-mmulticoreโ build a standalone application for multicore Blackfin processors. this option causes proper start files and link scripts supporting multicore to be used, and defines the macro"__BFIN_MULTICORE". it can only be used with-mcpu=bf561[-sirevision].
this option can be used with -mcorea or -mcoreb, which selects the one-application-per-core programming model. without -mcorea or -mcoreb, the single-application/dual-core programming model is used. in this model, the main function of Core B should be named as "coreb_main".
if this option is not used, the single-core application programming model is used. ๐
-mcoreaโ build a standalone application for Core A of BF561 when using the one-application-per-core programming model. proper start files and link scripts are used to support Core A, and the macro"__BFIN_COREA"is defined. this option can only be used in conjunction with-mmulticore.-mcorebโ build a standalone application for Core B of BF561 when using the one-application-per-core programming model. proper start files and link scripts are used to support Core B, and the macro"__BFIN_COREB"is defined. when this option is used,"coreb_main"should be used instead of"main". 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_SDRAM"is defined. the loader should initialize SDRAM before loading the application. no skipping steps bestie.-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".neardata"section, which is pointed to by register"B14". put small uninitialized global and static data in the".bss"section, which is adjacent to the".neardata"section. put small read-only data into the".rodata"section. the corresponding sections used for large pieces of data are".fardata",".far"and".const". ๐๏ธ-msdata=allโ put all data, not just small objects, into the sections reserved for small data, and use addressing relative to the"B14"register 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".fardata"section, and all uninitialized data in the".far"section. put all constant data into the".const"section.
๐ฆ CRIS Options ๐ฆ
these options are defined specifically for the CRIS ports. special little guys, fr fr.
-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 to architecture-type everything applicable about the generated code, except for the ABI and the set of available instructions. the choices for architecture-type are the same as for-march=architecture-type.-mmax-stack-frame=nโ warn when the stack frame of a function exceeds n bytes. ๐จ-metrax4-metrax100โ the options-metrax4and-metrax100are synonyms for-march=v3and-march=v8respectively. same thing, different name, iconic.-mmul-bug-workaround-mno-mul-bug-workaroundโ work around a bug in the"muls"and"mulu"instructions for CPU models where it applies. this option is disabled by default. ๐-mpdebugโ enable CRIS-specific verbose debug-related information in the assembly code. this option also has the effect of turning off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file.-mcc-initโ do not use condition-code results from previous instruction; always emit compare and test instructions before use of condition codes.-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 (no-options) arrange (eliminate arrangements) for the stack frame, individual data and constants to be aligned for the maximum single data access size for the chosen CPU model. the default is to arrange for 32-bit alignment. ABI details such as structure layout are not affected by these options. ๐-m32-bit-m16-bit-m8-bitโ similar to the stack- data- and const-align options above, these options arrange for stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned. the default is 32-bit alignment.-mno-prologue-epilogue-mprologue-epilogueโ with-mno-prologue-epilogue, the normal function prologue and epilogue which set up the stack frame are omitted and no return instructions or return sequences are generated in the code.
bestie, use this option only together with visual inspection of the compiled code: no warnings or errors are generated when call-saved registers must be saved, or storage for local variables needs to be allocated. like, you're on your own here. ๐
-melfโ legacy no-op option. it does nothing, it's just here. a ghost. ๐ป-simโ this option arranges to link with input-output functions from a simulator library. code, initialized data and zero-initialized data are allocated consecutively.-sim2โ like-sim, but pass linker options to locate initialized data at0x40000000and zero-initialized data at0x80000000. โจ
๐ C-SKY Options ๐
GCC supports these options when compiling for C-SKY V2 processors.
-march=archโ specify the C-SKY target architecture. valid values for arch are:ck801,ck802,ck803,ck807, andck810. the default isck810. ๐-mcpu=cpuโ picks the C-SKY target processor, bestie. Valid values for cpu are:
ck801, ck801t, ck802, ck802t, ck802j, ck803, ck803h, ck803t,
ck803ht, ck803f, ck803fh, ck803e, ck803eh, ck803et, ck803eht,
ck803ef, ck803efh, ck803ft, ck803eft, ck803efht, ck803r1, ck803hr1,
ck803tr1, ck803htr1, ck803fr1, ck803fhr1, ck803er1, ck803ehr1,
ck803etr1, ck803ehtr1, ck803efr1, ck803efhr1, ck803ftr1, ck803eftr1,
ck803efhtr1, ck803s, ck803st, ck803se, ck803sf, ck803sef, ck803seft,
ck807e, ck807ef, ck807, ck807f, ck810e, ck810et, ck810ef, ck810eft,
ck810, ck810v, ck810f, ck810t, ck810fv, ck810tv, ck810ft, and
ck810ftv.
Fifty-seven of them. FIFTY-SEVEN. The way I need you to scroll through that list like it's a Spotify wrapped ๐ญ go off, chip designers ๐
-mbig-endian,-EB,-mlittle-endian,-ELโ picks big- or little-endian code. The default is little-endian. no cap-mfloat-abi=nameโ tells GCC which floating-point ABI we're vibing with. Permissible values are:soft,softfpandhard.softmakes GCC spit out output that contains library calls for floating-point operations ๐ซถsoftfplets it generate code with actual hardware floating-point instructions, but it still uses the soft-float calling conventionshardlets it generate floating-point instructions and use FPU-specific calling conventions- The default depends on the specific target configuration, so likeโฆ check your setup, bestie. And note: 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. Do not mix. I'm serious. ๐
-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. It's the default except when compiling for CK803. โจ-mfdivdu,-mno-fdivduโ when-mhard-floatis in effect, this enables generation offrecipd,fsqrtd, andfdivdinstructions. Also the default except when compiling for CK803.-mfpu=fpuโ selects the floating-point processor. Heads up: this one can only be used with-mhard-float. Values for fpu are:fpv2_sf(equivalent to-mno-double-float -mno-fdivdu),fpv2(-mdouble-float -mno-divdu), andfpv2_divd(-mdouble-float -mdivdu).-melrw,-mno-elrwโ enables the extendedlrwinstruction. Defaults to on for CK801 and off otherwise.-mistack,-mno-istackโ enables interrupt stack instructions; default is off.
The-mistackoption is required to handle theinterruptandisrfunction attributes. So if you're doing that and wondering why it's not workingโฆ it's this. ๐ซ
-mmpโ enables multiprocessor instructions; default is off.-mcpโ enables coprocessor instructions; default is off.-mcacheโ enables coprocessor instructions; default is off.-msecurityโ enables C-SKY security instructions; default is off.-mtrustโ enables C-SKY trust instructions; default is off.-mdsp,-medsp,-mvdspโ enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively. All three default to off.-mdiv,-mno-divโ generate divide instructions. Default is off.-msmart,-mno-smartโ generate code for Smart Mode, using only registers numbered 0-7 so you can use 16-bit instructions ๐ This one is ignored for CK801 (where that's just the required behavior anyway) and it defaults to on for CK802. For other targets, the default is off.-mhigh-registers,-mno-high-registersโ generate code using the high registers numbered 16-31. Not supported on CK801, CK802, or CK803, and it's enabled by default for 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. Not supported on CK801, but enabled by default on other processors.-mconstpool,-mno-constpoolโ create constant pools in the compiler instead of deferring it to the assembler. This is the default and it's required for correct code generation on CK801 and CK802, 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 of libgcc. Defaults to off.-mbranch-cost=nโ set the branch costs to roughlyninstructions. The default is1.-msched-prolog,-mno-sched-prologโ permit scheduling of function prologue and epilogue sequences.
โ ๏ธ Using 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. Leave it alone unless you truly know what you're doing, bestie. ๐
-msimโ links the librarylibsemi.awhich is in compatible with simulator. Applicable to ELF compiler only.
๐ Darwin Options ๐
These options are defined for all architectures running the Darwin operating system. Buckle up, this is a whole lil ecosystem ๐
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 more you know โจ
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 it's giving chaos:
- 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. ๐ซ quiet. silent. no warning. iconic behavior tbh. -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.
Okay so let me explain frameworks because this one's a whole thing, bestie ๐ A framework directory is a directory with frameworks in it. A framework is a directory with a Headers and/or PrivateHeaders directory contained directly in it that ends in .framework. The name of a framework is the name of this directory excluding the .framework. Headers associated with the framework are found in one of those two directories, with Headers being searched first. A subframework is a framework directory that is in a framework's Frameworks directory. Includes of subframework headers can only appear in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework. A subframework should not have the same name as a framework; a warning is issued if this is violated. Currently a subframework cannot have subframeworks; in the future, the mechanism may be extended to support this. The standard frameworks can be found in /System/Library/Frameworks and /Library/Frameworks. An example include looks like #include <Framework/header.h>, where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory.
-iframeworkdirโ like-Fexcept the directory is a treated as a system directory. The main difference between this-iframeworkand-Fis that with-iframeworkthe compiler does not warn about constructs contained within header files found via dir. This option is valid only for the C family of languages.-gusedโ emit debugging information for symbols that are used. For stabs debugging format, this enables-feliminate-unused-debug-symbols. This is by default ON. โ-gfullโ emit debugging information for all symbols and types.-fconstant-cfstringsโ the-fconstant-cfstringsis an alias for-mconstant-cfstrings.-mconstant-cfstringsโ when the NeXT runtime is being used (the default on these systems), override any-fconstant-string-classsetting and cause@"..."literals to be laid out as constant CoreFoundation strings.-mmacosx-version-min=versionโ the earliest version of MacOS X that this executable will run on is version. Typical values supported for version include12,10.12, and10.5.8.
If the compiler was built to use the system's headers by default, then the default for this option is the system version on which the compiler is running, otherwise the default is to make choices that are compatible with as many systems and code bases as possible.
-mkernelโ enable kernel development mode. ๐ The-mkerneloption sets-static,-fno-common,-fno-use-cxa-atexit,-fno-exceptions,-fno-non-call-exceptions,-fapple-kext,-fno-weakand-fno-rttiwhere applicable. This mode also sets-mno-altivec,-msoft-float,-fno-builtinand-mlong-branchfor PowerPC targets.-mone-byte-boolโ override the defaults 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, such as to allow GDB to dynamically load.ofiles into already-running programs.-findirect-dataand-ffix-and-continueare provided for backwards compatibility.-all_loadโ loads all members of static archive libraries. Seeman ld(1)for more information.-arch_errors_fatalโ cause the errors having to do with files that have the wrong architecture to be fatal. ๐-bind_at_loadโ marks your output file so the dynamic linker binds, like, every undefined reference the moment the file gets loaded or launched. No waiting around, bestie. ๐-bundleโ makes a Mach-o bundle format file. For the tea on that, go readman ld(1). ๐-bundle_loaderexecutable โ tells the linker which executable is gonna load the build output file you're linking. Again,man ld(1)has the details. ๐ซถ-dynamiclibโ pass this and GCC produces a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand. Iconic behavior honestly.-force_cpusubtype_ALLโ forces your output file to have the ALL subtype, instead of whatever subtype-mcpuor-marchwas controlling. It's giving "I do what I want". โจ
Okay so these next ones? They get handed straight off to the Darwin linker โ and the Darwin linker man page describes them in detail. Every single one, in order, no skips:
- These options are passed to the Darwin linker:
-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
Not me listing-sectobjectsymbols,-segs_read_only_addrand-segs_read_write_addrtwice โ that's literally how the original man page rolls, so we keep it exactly like that. No edits, no cap. ๐
The Darwin linker man page describes them in detail.
๐ DEC Alpha Options ๐
These -m options are defined for the DEC Alpha implementations, bestie. Buckle up. ๐ธ
-mno-soft-float,-msoft-floatโ use (or don't use) the hardware floating-point instructions for floating-point operations. When you say-msoft-float, functions inlibgcc.aget used to perform floating-point operations instead. Here's the catch though โ unless those routines get replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines still issue floating-point operations. If you're compiling for an Alpha without floating-point operations, you must make sure the library is built so as not to call them. ๐ซ
Also note: Alpha implementations without floating-point operations are required to have floating-point registers. Weird but true.
-mfp-reg,-mno-fp-regsโ generate code that uses (or does not use) the floating-point register set. Heads up:-mno-fp-regsimplies-msoft-float. If the floating-point register set isn't used, floating-point operands get passed in integer registers as if they were integers, and floating-point results get passed in$0instead of$f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with-mno-fp-regsmust also be compiled with that option. โ ๏ธ
A typical use of this option is building a kernel that doesn't use โ and therefore doesn't need to save and restore โ any floating-point registers. Slay, efficient.
-mieeeโ so 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). Turn it on and the preprocessor macro_IEEE_FPgets defined during compilation. The resulting code is less efficient, but it can correctly support denormalized numbers and exceptional IEEE values such as not-a-number and plus/minus infinity. Other Alpha compilers call this option-ieee_with_no_inexact. ๐ฆ
DEBIAN SPECIFIC: This option is on by default for alpha-linux-gnu, unless -ffinite-math-only (which is part of the -ffast-math set) is specified โ because the software functions in the GNU libc math libraries generate denormalized numbers, NaNs, and infs (all of which will cause a program to SIGFPE when it attempts to use the results without -mieee). ๐
-mieee-with-inexactโ just like-mieee, except the generated code also maintains the IEEE inexact-flag. Turning this on makes the generated code implement fully-compliant IEEE math. And on top of_IEEE_FP, the macro_IEEE_FP_EXACTgets defined as a preprocessor macro too. 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 one 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 the Alpha architecture reference manual) controls the rounding mode in effect. The C library initializes this register for rounding towards plus infinity. Thus, unless your program modifies thefpcr,dcorresponds to round towards plus infinity.
-mtrap-precision=trap-precision โ okay so in the Alpha architecture, floating-point traps are imprecise. That means without software assistance it's impossible to recover from a floating trap, and program execution normally needs to be terminated. ๐ญ GCC can generate code that assists 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_safe and -resumption_safe.
-mieee-conformantโ this marks the generated code as IEEE conformant. ๐ซถ But listen: 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. That's it, that's the whole vibe.-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 can't, 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. Main character energy, honestly.
-mbwx,-mno-bwx,-mcix,-mno-cix,-mfix,-mno-fix,-mmax,-mno-maxโ these 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 the-mcpu=option, or that of the CPU on which GCC was built if none is specified. ๐-mfloat-vax,-mfloat-ieeeโ generate code that uses (or does not use) VAX F and G floating-point arithmetic instead of IEEE single and double precision.-mexplicit-relocs,-mno-explicit-relocsโ older Alpha assemblers provided no way to generate symbol relocations except via assembler macros. Using those 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 use malloc or mmap to allocate the data in the heap instead of in the program's data segment.
When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data. โจ
-msmall-textโ bestie, when this is on, the compiler assumes the code of the entire program (or shared library) fits in 4MB, which means a branch instruction can actually reach all of it. ๐-mlarge-textโ the opposite vibe: no tiny-code assumptions. This is the default. โจ
Also, heads up: 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. Little glow-up for your call sites fr fr.
-mcpu=cpu_typeโ sets the instruction set and the instruction scheduling parameters for machine type cpu_type. You can hand it either the EV-style name or the matching chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 families of processors, and it picks the default instruction-set values from whatever processor you name. If you don't specify a processor type at all, GCC defaults to the processor it was built on. ๐ง
Supported values for cpu_type are:
ev4ev4521064โ schedules as an EV4 and has no instruction set extensions.ev521164โ schedules as an EV5 and has no instruction set extensions.ev5621164aโ schedules as an EV5 and supports the BWX extension.pca5621164pc21164PCโ schedules as an EV5 and supports the BWX and MAX extensions.ev621264โ schedules as an EV6 and supports the BWX, FIX, and MAX extensions.ev6721264aโ schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions.
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor. ๐ญ
-mtune=cpu_typeโ sets only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed. No cap, it's just a scheduling tweak. ๐
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.
-mmemory-latency=timeโ sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns your app uses and on the size of the external cache on the machine. Highkey a vibe-based number, ngl.
Valid options for time are:
numberโ a decimal number representing clock cycles.L1L2L3mainโ the compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note thatL3is only valid for EV5. ๐
๐ฆ eBPF Options ๐ฆ
-mframe-limit=bytesโ specifies the hard limit for frame sizes, in bytes. Currently, the value you can specify should be less than or equal to32767. Defaults to whatever limit is imposed by the version of the Linux kernel targeted. ๐-mkernel=versionโ specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to decide 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. Periodt. ๐-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โ specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default isv3. ๐ธ
Supported values for version are:
v1โ the first stable eBPF ISA with no special features or extensions.v2โ supports the jump extensions, as in-mjmpext.v3โ all features ofv2, plus:- 32-bit jump operations, as in
-mjmp32 - 32-bit ALU operations, as in
-malu32
- 32-bit jump operations, as in
-mco-reโ enable BPF Compile Once - Run Everywhere (CO-RE) support. Requires and is implied by-gbtf. ๐ซถ-mno-co-reโ disable BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is enabled by default when generating BTF debug information for the BPF target.-mxbpfโ generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture:- Save and restore callee-saved registers at function entry and exit, respectively.
๐ FR30 Options ๐
These options are defined specifically for the FR30 port.
-msmall-modelโ use the small address space model. This can produce smaller code, but it does assume that all symbolic values and addresses fit into a 20-bit range. ๐-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 usedivandmodinstructions.-mft32bโ enable use of the extended instructions of the FT32B processor.-mcompressโ compress all code using the Ft32B code compression scheme.-mnopmโ do not generate code that reads program memory.
๐ FRV Options ๐
-mgpr-32โ only use the first 32 general-purpose registers.-mgpr-64โ use all 64 general-purpose registers.-mfpr-32โ use only the first 32 floating-point registers.-mfpr-64โ use all 64 floating-point registers.-mhard-floatโ use hardware instructions for floating-point operations.-msoft-floatโ use library routines for floating-point operations.-malloc-ccโ dynamically allocate condition code registers.-mfixed-ccโ do not try to dynamically allocate condition code registers; only use"icc0"and"fcc0".-mdwordโ change ABI to use double word insns.-mno-dwordโ do not use double word instructions.-mdoubleโ use floating-point double instructions.-mno-doubleโ do not use 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โ select the FDPIC ABI, which uses function descriptors to represent pointers to functions. Without any PIC/PIE-related options, it implies-fPIE. With-fpicor-fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address; with-fPICor-fPIE, GOT offsets are computed with 32 bits. With abfin-elftarget, this option implies-msim. ๐ฅ-minline-pltโ enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without-mfdpic. It's enabled by default if optimizing for speed and compiling for shared libraries (i.e.,-fPICor-fpic), or when an optimization option such as-O3or above is present in the command line. โจ-mTLSโ assume a large TLS segment when generating thread-local code.-mtlsโ do not assume a large TLS segment when generating thread-local code.-mgprel-roโ enable the use of"GPREL"relocations in the FDPIC ABI for data that is known to be in read-only sections. It's enabled by default, except for-fpicor-fpie: even though it may help make the global offset table smaller, it trades 1 instruction for 4. With-fPICor-fPIE, it trades 3 instructions for 4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it is not,-mno-gprel-rocan be used to disable it. ๐ง-multilib-library-picโ link with the (library, not FD) pic libraries. It's implied by-mlibrary-pic, as well as by-fPICand-fpicwithout-mfdpic. You should never have to use it explicitly.-mlinked-fpโ follow the EABI requirement of always creating a frame pointer whenever a stack frame is allocated. This option is enabled by default and can be disabled with-mno-linked-fp.-mlong-callsโ use indirect addressing to call functions outside the current compilation unit. This allows the functions to be placed anywhere within the 32-bit address space. ๐-malign-labelsโ try to align labels to an 8-byte boundary by inserting NOPs into the previous packet. This option only has an effect when VLIW packing is enabled. It doesn't create new packets; it merely adds NOPs to existing ones. ๐-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.-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 (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โ turn ON the use of conditional execution (this is the default, bestie). Heads up: this switch is mainly for debugging the compiler and will likely be removed in a future version.-mno-cond-execโ turn OFF the use of conditional execution. Same deal: mainly for debugging the compiler, probably getting yeeted in a future version. ๐-mvliw-branchโ run a pass that packs branches into VLIW instructions (default behaviour, slay). Again, mainly for debugging the compiler and likely to be removed in a future version.-mno-vliw-branchโ do NOT run that branch-packing-into-VLIW pass. And yeah โ debugging switch, probably removed later. ๐-mmulti-cond-execโ enable optimization of"&&"and"||"inside conditional execution (default). Mainly for debugging the compiler, likely removed in a future version.-mno-multi-cond-execโ disable optimization of"&&"and"||"in conditional execution. Mainly for debugging the compiler, likely removed in a future version. ๐ซถ-mnested-cond-execโ enable nested conditional execution optimizations (default). Mainly for debugging the compiler, likely removed in a future version.-mno-nested-cond-execโ disable nested conditional execution optimizations. Mainly for debugging the compiler, likely removed in a future version.-moptimize-membarโ this one removes redundant"membar"instructions from the compiler-generated code. It's enabled by default. โจ-mno-optimize-membarโ disables that automatic removal of redundant"membar"instructions from the generated code.-mtomcat-statsโ causesgasto print out tomcat statistics. ๐ฑ iconic, honestly.- *
-mcpu=cpu* โ pick the processor type you're generating code for. 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 that's 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. ๐ฑ
-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; 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 stack before execution of a function with monitor attribute. Default option is-mexr. This option is valid only for H8S targets.-mno-exrโ extended registers are not stored on stack before execution of a function with monitor attribute. Default option is-mno-exr. This option is valid only for H8S targets.-mint32โ make"int"data 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-300causes them to be aligned on 2-byte boundaries. This option has no effect on the H8/300. ๐ง
๐ HPPA Options ๐
These -m options are defined for the HPPA family of computers:
-march=architecture-type โ generate code for the specified architecture. The choices for architecture-type are1.0for PA 1.0,1.1for PA 1.1, and2.0for PA 2.0 processors. Refer to/usr/lib/sched.modelson an HP-UX system to determine the proper architecture option for your machine. Code compiled for lower numbered architectures runs on higher numbered architectures, but **not the other way around. ๐จ-mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0โ 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. As a result, processor stores are not atomic with respect to other atomic operations. Processor loads up to DImode are atomic with respect to other atomic operations provided they are implemented as a single access.
The PA-RISC architecture does not support any atomic operations in hardware except for the "ldcw" instruction. Thus, all atomic support is implemented using sync and atomic libcalls. Sync libcall support is in libgcc.a. Atomic libcall support is in libatomic.
This option generates "__atomic_exchange" calls for atomic stores. It also provides special handling for atomic DImode accesses on 32-bit targets.
-mbig-switchโ does nothing. Preserved for backward compatibility. ๐-mcaller-copiesโ the caller copies function arguments passed by hidden reference. Use this one with care as it is not compatible with the default 32-bit runtime. However, only aggregates larger than eight bytes are passed by hidden reference and the option provides better compatibility with OpenMP.-mcoherent-ldcwโ useldcw/ldcdcoherent cache-control hint.-mdisable-fpregsโ disable floating-point registers. Equivalent to"-msoft-float".-mdisable-indexingโ stop the compiler from using indexing address modes. This avoids some rather obscure problems when compiling MIG generated code under MACH.-mfast-indirect-callsโ generate code that assumes calls never cross space boundaries. This allows GCC to emit code that performs faster indirect calls.
This option does not work in the presence of shared libraries or nested functions. ๐ฌ
- *
-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. -mgasโ enable the use of assembler directives only GAS understands.-mgnu-ldโ use options specific to GNUld. This passes-sharedtoldwhen building a shared library. It is the default when GCC is configured, explicitly or implicitly, with the GNU linker. This option does not affect whichldis called; it only changes what parameters are passed to thatld. Theldthat is called is determined by the--with-ldconfigure option, GCC's program search path, and finally by the user'sPATH. The linker used by GCC can be printed using whichgcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*.-mhp-ldโ use options specific to HPld. This passes-btoldwhen building a shared library and passes+Accept TypeMismatchtoldon all links. It is the default when GCC is configured, explicitly or implicitly, with the HP linker. This option does not affect whichldis called; it only changes what parameters are passed to thatld. Theldthat is called is determined by the--with-ldconfigure option, GCC's program search path, and finally by the user'sPATH. The linker used by GCC can be printed using whichgcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*. ๐ซถ-mlinker-optโ enable the optimization pass in the HP-UX linker. Note this makes symbolic debugging impossible. It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers in which they give bogus error messages when linking some programs. ๐-mlong-callsโ generate code that uses long call sequences. This ensures that a call is always able to reach linker generated stubs. The default is to generate long calls only when the distance from the call site to the beginning of the function or translation unit, as the case may be, exceeds 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 using the -ffunction-sections option, or when using the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker.
It is normally not desirable to use this option as it degrades performance. However, it may be useful in large applications, particularly when partial linking is used to build the application.
The types of long calls used depends on the capabilities of the assembler and linker, and 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. However, an indirect call is used on 32-bit ELF systems in pic code and it is quite long. ๐ฅ
still repping the HPPA options, bestie ๐ let's get it.
-mlong-load-storeโ generates 3-instruction load and store sequences as sometimes required by the HP-UX 10 linker. This is equivalent to the+koption to the HP compilers. slay. ๐-mjump-in-delayโ this option is ignored and provided for compatibility purposes only. bestie, it's literally just there. don't stress. ๐-mno-space-regsโ generates code that assumes the target has no space registers. This allows GCC to generate faster indirect calls and use unscaled index address modes. Such code is suitable for level 0 PA systems and kernels. no cap. โจ-morderedโ assumes memory references are ordered and barriers are not needed. periodt. ๐-mportable-runtimeโ uses the portable calling conventions proposed by HP for ELF systems. it's giving portable. ๐ฆ- *
-mschedule=cpu-type* โ schedules code according to the constraints for the machine type cpu-type. The choices for cpu-type are700 7100,7100LC,7200,7300and8000. Refer to/usr/lib/sched.modelson an HP-UX system to determine the proper scheduling option for your machine. The default scheduling is8000. ๐ -msioโ generates the predefine"_SIO"for server IO. The default is-mwsio. This generates the predefines"__hp9000s700","__hp9000s700__"and"_WSIO"for workstation IO. These options are available under HP-UX and HI-UX. ๐-msoft-floatโ generates output containing library calls for floating point.
Warning: the requisite libraries are not available for all HPPA targets. Normally the facilities of the machine's usual C compiler 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.
-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. no cap. ๐ญ
-msoft-multโ uses software integer multiplication. This disables the use of the"xmpyu"instruction. bye Felicia. ๐- *
-munix=unix-std* โ generates compiler predefines and selects 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 are
93for HP-UX 10.00,95for HP-UX 10.10 though to 11.00, and98for HP-UX 11.11 and later. -munix=93provides the same predefines as GCC 3.3 and 3.4.-munix=95provides additional predefines for"XOPEN_UNIX"and"_XOPEN_SOURCE_EXTENDED", and the startfileunix95.o.-munix=98provides additional predefines for"_XOPEN_UNIX","_XOPEN_SOURCE_EXTENDED","_INCLUDE__STDC_A1_SOURCE"and"_INCLUDE_XOPEN_SOURCE_500", and the startfileunix98.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. Thus, extreme care is needed in using this option. โ ๏ธ
- Library code that is intended to operate with more than one UNIX standard must test, set and restore the variable
"__xpg4_extended_mask"as appropriate. Most GNU software doesn't provide this capability. ๐
-nolibdldโ suppresses the generation of link options to searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later. bye. ๐-staticโ the HP-UX implementation ofsetlocaleinlibchas a dependency onlibdld.sl. There isn't an archive version oflibdld.sl. Thus, 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 withlibdld.slwhen the-staticoption 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-nolibdldoption can be used to prevent the GCC driver from adding these link options. ๐-threadsโ adds support for multithreading with thedcethread library under HP-UX. This option sets flags for both the preprocessor and linker. slay. ๐ฅ
โจ IA-64 Options โจ
These are the -m options defined for the Intel IA-64 architecture. bestie, let's get into it. ๐
-mbig-endianโ generates code for a big-endian target. This is the default for HP-UX. ๐-mlittle-endianโ generates 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โ generates code that does not use a global pointer register. The result is not position independent code, and violates the IA-64 ABI. > bestie, that's a yikes. ๐ญ-mvolatile-asm-stop,-mno-volatile-asm-stopโ generate (or don't) a stop bit immediately before and after volatile asm statements. ๐ฅ-mregister-names,-mno-register-namesโ generate (or don't)in,loc, andoutregister names for the stacked registers. This may make assembler output more readable. ๐-mno-sdata,-msdataโ disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs. no cap. ๐-mconstant-gpโ generates code that uses a single constant global pointer value. This is useful when compiling kernel code. ๐-mauto-picโ generates code that is self-relocatable. This implies-mconstant-gp. This is useful when compiling firmware code. โจ-minline-float-divide-min-latencyโ generates code for inline divides of floating-point values using the minimum latency algorithm. ๐-minline-float-divide-max-throughputโ generates 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. bye. ๐-minline-int-divide-min-latencyโ generates code for inline divides of integer values using the minimum latency algorithm. ๐-minline-int-divide-max-throughputโ generates 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. nope. ๐-minline-sqrt-min-latencyโ generates code for inline square roots using the minimum latency algorithm. ๐-minline-sqrt-max-throughputโ generates code for inline square roots using the maximum throughput algorithm. ๐ฅ-mno-inline-sqrtโ do not generate inline code for"sqrt". periodt. ๐-mfused-madd,-mno-fused-maddโ do (don't) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions. โจ-mno-dwarf2-asm,-mdwarf2-asmโ don't (or do) generate assembler code for the DWARF line number debugging info. This may be useful when not using the GNU assembler. ๐-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 does not always do so. no cap. ๐- *
-mfixed-range=register-range* โ generates 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. ๐ - *
-mtls-size=tls-size* โ specifies bit size of immediate TLS offsets. Valid values are14,22, and64. ๐ฅ - *
-mtune=cpu-type* โ tunes the instruction scheduling for a particular CPU. Valid values areitanium,itanium1,merced,itanium2, andmckinley. ๐ -milp32,-mlp64โ generates 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. โจ-mno-sched-br-data-spec,-msched-br-data-specโ (dis/en)able data speculative scheduling before reload. This results in generation of"ld.a"instructions 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 of"ld.a"instructions 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 the"ld.s"instructions and the corresponding check instructions"chk.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โ turn this on and speculative dependencies get counted when GCC is working out instruction priorities, which makes speculation a lil more conservative. Default? Off, bestie.-msched-spec-ldcโ uses a simple data speculation check. On by default. โจ-msched-control-spec-ldcโ uses a simple check for control speculation. Also on by default.-msched-stop-bits-after-every-cycleโ drops a stop bit after every cycle when it's scheduling. On by default, no notes.-msched-fp-mem-deps-zero-costโ tells GCC to assume floating-point stores and loads probably won't conflict when they land in the same instruction group. Disabled by default. ๐-msel-sched-dont-check-control-specโ generates checks for control speculation in selective scheduling. This flag is off by default.-msched-max-memory-insns=max-insnsโ caps how many memory insns can chill in one instruction group, and gives lower priority to any memory insns that try to schedule into that same group afterward. Super handy for dodging cache bank conflicts. Default value is1.-msched-max-memory-insns-hard-limitโ makes the limit you set withmsched-max-memory-insnsan actual hard limit: nothing over that number gets into an instruction group, periodt. Without it, the limit is "soft" โ meaning non-memory operations get preferred once you hit the limit, but memory operations can still sneak in and schedule. ๐
๐ LM32 Options
These -m options are the ones defined for the LatticeMico32 architecture:
-mbarrel-shift-enabledโ enables barrel-shift instructions.-mdivide-enabledโ enables divide and modulus instructions.-mmultiply-enabledโ enables multiply instructions.-msign-extend-enabledโ enables sign extend instructions.-muser-enabledโ enables user-defined instructions. your own little custom slay โจ
๐ LoongArch Options
These command-line options are the ones defined for LoongArch targets:
-march=cpu-typeโ generates instructions for the machine type cpu-type. And listen, this is not the same as-mtune=cpu-typeโ-mtune=cpu-typejust tunes the generated code for that cpu-type, whereas-march=cpu-typelets GCC generate code that might not run at all on any processor other than the one you named. Specifying-march=cpu-typeimplies-mtune=cpu-type, except where noted otherwise.
The choices for cpu-type are:
nativeโ picks the CPU to generate code for at compilation time by figuring out the processor type of the machine doing the compiling. Using-march=nativeenables all instruction subsets your local machine supports (so yeah, the result might not run on different machines, fair warning ๐ญ). Using-mtune=nativeproduces code optimized for the local machine, but under the constraints of the selected instruction set.loongarch64โ a generic CPU with 64-bit extensions.la464โ LoongArch LA464 CPU with LBT, LSX, LASX, LVZ.
-mtune=cpu-typeโ optimizes the output for the given processor, specified by microarchitecture name.-mabi=base-abi-typeโ generates 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โ generates 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โ forces-mfpu=noneand prevents floating-point registers from being used for parameter passing. Heads up: this option may change the target ABI.-msingle-floatโ forces-mfpu=32and allows 32-bit floating-point registers to be used for parameter passing. This option may change the target ABI.-mdouble-floatโ forces-mfpu=64and allows 32/64-bit floating-point registers to be used for parameter passing. This option may change the target ABI.-mbranch-cost=nโ sets the cost of branches to roughly n instructions.-mcheck-zero-division,-mno-check-zero-divisonโ trap (or don't trap) on integer division by zero. The default is-mcheck-zero-divisionfor-O0or-Og, and-mno-check-zero-divisionfor other optimization levels.-mcond-move-int,-mno-cond-move-intโ conditional moves for integral data in general-purpose registers are enabled (disabled). The default is-mcond-move-int.-mcond-move-float,-mno-cond-move-floatโ conditional moves for floating-point registers are enabled (disabled). The default is-mcond-move-float.-mmemcpy,-mno-memcpyโ force (or don't force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which lets GCC inline most constant-sized copies. Setting the optimization level to-Osalso forces the use ofmemcpy, but-mno-memcpymay override this behavior if you specify it explicitly, regardless of the order these options appear on the command line.-mstrict-align,-mno-strict-alignโ avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. The default is-mno-strict-align.-msmall-data-limit=numberโ puts global and static data smaller than number bytes into a special section (on some targets). The default value is0.-mmax-inline-memcpy-size=nโ inlines all block moves (like calls tomemcpyor structure copies) that are less than or equal to n bytes. The default value of n is1024.-mcmodel=code-modelโ sets the code model to one of:tiny-static(Not implemented yet)tiny(Not implemented yet)normalโ the text segment must be within 128MB addressing space. The data segment must be within 2GB addressing space.mediumโ the text segment and data segment must be within 2GB addressing space.large(Not implemented yet)extremeโ this mode does not limit the size of the code segment and data segment. The-mcmodel=extremeoption is incompatible with-fpltand-mno-explicit-relocs.
The default code model is normal.
-mexplicit-relocs,-mno-explicit-relocsโ use or don't use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit instruction scheduling but allow linker relaxation. The default value for this option is determined by the assembler capability detected during GCC build-time plus the setting of-mrelax:-mexplicit-relocsif the assembler supports relocation operators but-mrelaxis not enabled,-mno-explicit-relocsotherwise.-mdirect-extern-access,-mno-direct-extern-accessโ do not use or use GOT to access external symbols. The default is-mno-direct-extern-access: GOT is used for external symbols with default visibility, but not used for other external symbols.
With -mdirect-extern-access, GOT is not used and all external symbols are PC-relatively addressed. It's only suitable for environments where no dynamic link happens, like firmwares, OS kernels, executables linked with -static or -static-pie. Also -mdirect-extern-access is not compatible with -fPIC or -fpic. ๐
-mrelax,-mno-relaxโ take (or don't take) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option is also passed to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support:-mrelaxif the assembler supports both the-mrelaxoption and conditional branch relaxation (it's required, or the.aligndirectives and conditional branch instructions in the assembly code outputted by GCC may get rejected by the assembler because of a relocation overflow), and-mno-relaxotherwise.-mpass-mrelax-to-as,-mno-pass-mrelax-to-asโ pass (or don't pass) the-mrelaxor-mno-relaxoption to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption,-mno-pass-mrelax-to-asotherwise. This option is mostly useful for debugging, or for interoperation with assemblers different from the build-time one.
๐๏ธ M32C Options
-mcpu=nameโ selects the CPU for which code is generated. name may be one ofr8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series.-msimโ specifies that the program will be run on the simulator. This causes an alternate runtime library to be linked in, one that supports, like, file I/O and stuff. ๐ซถ
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. fr fr, do not do it.
-memregs=numberโ specifies the number of memory-based pseudo-registers GCC uses during code generation. These pseudo-registers are used like real registers, so there's a tradeoff between GCC's ability to fit the code into available registers and the performance penalty of using memory instead of registers. Note that all modules in a program must be compiled with the same value for this option. Because of that, you must not use this option with GCC's default runtime libraries. ๐
๐ฎ M32R/D Options
These -m options are the ones defined for Renesas M32R/D architectures:
-m32r2โ generates code for the M32R/2.-m32rxโ generates code for the M32R/X.-m32rโ generates code for the M32R. This is the default. โญ-mmodel=smallโ okay so this is the default vibe ๐ it's giving "everything lives close to home": assume all objects live in the lower 16MB of memory (so that their addresses can be loaded with theld24instruction), and assume all subroutines are reachable with theblinstruction.
The addressability of a particular object can be set with the model attribute. ๐
-mmodel=mediumโ bestie we're spreading out ๐ฆ 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โ full chaos mode, no cap ๐ 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 the small data area off. Variables are put into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default. โจ
The small data area consists of sections .sdata and .sbss. Objects may be explicitly put in the small data area with the section attribute using one of these sections.
-msdata=sdataโ put small global and static data in the small data area, but do not generate special code to reference them.-msdata=useโ put small global and static data in the small data area, and generate special instructions to reference them. She's doing the most and we love her ๐-Gnum โ put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is8. The-msdataoption must be set to one ofsdataorusefor this option to have any effect.
Heads up bestie: 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---incorrect code is not generated.
-mdebugโ makes the M32R-specific code in the compiler display some statistics that might help in debugging programs. ๐-malign-loopsโ align all loops to a 32-byte boundary. Snapped into place, iconic ๐-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 is1then branches are preferred over conditional code, if it is2, then the opposite applies. Pick your fighter ๐ฅ-mflush-trap=number โ specifies the trap number to use to flush the cache. The default is12. Valid numbers are between0and15inclusive.-mno-flush-trapโ specifies that the cache cannot be flushed by using a trap.-mflush-func=name โ specifies the name of the operating system function to call to flush the cache. The default is_flush_cache, but a function call is only used if a trap is not available.-mno-flush-funcโ indicates that there is no OS function for flushing the cache.
๐ธ M680x0 Options ๐ธ
These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below. ๐ซถ
-march=arch โ generate code for a specific M680x0 or ColdFire instruction set architecture. Permissible values of arch for M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures are selected according to Freescale's ISA classification and the permissible values are:isaa,isaaplus,isabandisac.
GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture. ๐ซ
-mcpu=cpu โ generate code for a specific M680x0 or ColdFire processor. The M680x0 *cpu*s are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire *cpu*s are given by the table below, which also classifies the CPUs into families: ๐51:5151ac51ag51cn51em51je51jf51jg51jm51mm51qe51qm5206:5202520452065206e:5206e5208:520752085211a:5210a5211a5213:5211521252135216:5214521652235:5223052231522325223352234522355225:5224522552259:5225252254522555225652258522595235:5232523352345235523x5249:52495250:52505271:527052715272:52725275:527452755282:528052815282528x53017:530115301253013530145301553016530175307:53075329:532753285329532x5373:53725373537x5407:54075475:547054715472547354745475547x548054815482548354845485
-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected. ๐ซ
GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the table above.
-mtune=tune โ tune the code for a particular microarchitecture within the constraints set by-marchand-mcpu. The M680x0 microarchitectures are:68000,68010,68020,68030,68040,68060andcpu32. The ColdFire microarchitectures are:cfv1,cfv2,cfv3,cfv4andcfv4e.
You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively. ๐
GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.
GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.
-m68000-mc68000โ generate output for a 68000. This is the default when the compiler is configured for 68000-based systems. It is equivalent to-march=68000.
Use this option for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356. ๐
-m68010โ generate output for a 68010. This is the default when the compiler is configured for 68010-based systems. It is equivalent to-march=68010.-m68020-mc68020โ generate output for a 68020. This is the default when the compiler is configured for 68020-based systems. It is equivalent to-march=68020.-m68030โ generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It is equivalent to-march=68030.-m68040โ generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It is equivalent to-march=68040.
This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option if your 68040 does not have code to emulate those instructions. ๐
-m68060โ generate output for a 68060. This is the default when the compiler is configured for 68060-based systems. It is equivalent to-march=68060.
This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use this option if your 68060 does not have code to emulate those instructions. ๐
-mcpu32โ generate output for a CPU32. This is the default when the compiler is configured for CPU32-based systems. It is equivalent to-march=cpu32.
Use this option for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360. ๐
-m5200โ generate output for a 520X ColdFire CPU. This is the default when the compiler is configured for 520X-based systems. It is equivalent to-mcpu=5206, and is now deprecated in favor of that option.
Use this option for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
-m5206eโ generate output for a 5206e ColdFire CPU. The option is now deprecated in favor of the equivalent-mcpu=5206e.-m528xโ generate output for a member of the ColdFire 528X family. The option is now deprecated in favor of the equivalent-mcpu=528x.-m5307โ generate output for a ColdFire 5307 CPU. The option is now deprecated in favor of the equivalent-mcpu=5307.-m5407โ generate output for a ColdFire 5407 CPU. The option is now deprecated in favor of the equivalent-mcpu=5407.-mcfv4eโ generate output for a ColdFire V4e family CPU (e.g.547x/548x). This includes use of hardware floating-point instructions. The option is equivalent to-mcpu=547x, and is now deprecated in favor of that option.-m68020-40โ generate output for a 68040, without using any of the new instructions. This results in code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.
The option is equivalent to -march=68020 -mtune=68020-40. โจ
-m68020-60โ generate output for a 68060, without using any of the new instructions. This results in code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68060.
The option is equivalent to -march=68020 -mtune=68020-60. โจ
-mhard-float-m68881โ generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro__HAVE_68881__on M680x0 targets and__mcffpu__on ColdFire targets. ๐ฅ-msoft-floatโ do not generate floating-point instructions, just call into the library instead. This is the default for 68000, 68010, and 68832 targets, and it's also the default for ColdFire devices that straight up 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 gets taken from the target CPU โ either the default CPU or whatever you passed to-mcpu. Example: it's"off"for-mcpu=5206and"on"for-mcpu=5206e. โจ
GCC defines the macro __mcfhwdiv__ when this option is enabled. iykyk ๐
-mshortโ consider typeintto be 16 bits wide, likeshort int. Also, parameters passed on the stack get aligned to a 16-bit boundary too, even on targets whose API mandates promotion to 32-bit. ๐-mno-shortโ do not consider typeintto be 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โ bestie, this is a whole different function-calling convention. Functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. It saves one instruction in the caller since there's no need to pop the arguments there. ๐
๐จ okay but listen: this calling convention is incompatible with the one normally used on Unix, so you can't use it if you need to call libraries compiled with the Unix compiler.
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf) โ otherwise incorrect code is generated for calls to those functions. ๐ญ
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored, so this is new and spicy.)
The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200. ๐
The default is -mno-rtd.
-malign-int,-mno-align-intโ control whether GCC alignsint,long,long long,float,double, andlong doublevariables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory. ๐ง
โ ๏ธ Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k.
Use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors. ๐ธ
-mno-strict-align,-mstrict-alignโ do not (do) assume that unaligned memory references are handled by the system.-msep-dataโ generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies-fPIC. โจ-mno-sep-dataโ generate code that assumes 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. shrug ๐-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 at all โ-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 this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol. ๐ญ
Note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. If you have such a linker, you should only need to use -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do. ๐
These options have no effect unless GCC is generating position-independent code.
-mlong-jump-table-offsetsโ use 32-bit offsets inswitchtables. The default is to use 16-bit offsets.
๐ MCore Options ๐
These are the -m options defined for the Motorola M*Core processors. slay โจ
-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โ emit callgraph information.-mslow-bytes,-mno-slow-bytesโ prefer word access when 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 and so omit the simulator library (libsim.a) from the linker command line.-mstack-increment=sizeโ set the maximum amount for a single stack increment operation. Large values can increase the speed of programs that contain functions needing a large amount of stack space, but they can also trigger a segmentation fault if the stack is extended too much. ๐ฌ The default value is0x1000.
๐ธ MicroBlaze Options ๐ธ
-msoft-floatโ use software emulation for floating point (default).-mhard-floatโ use hardware floating-point instructions. ๐ฅ-mmemcpyโ do not optimize block moves, usememcpy.-mno-clearbssโ 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โ this option is deprecated. Use-fstack-checkinstead.-mxl-gp-optโ use GP-relative.sdata/.sbsssections.-mxl-multiply-highโ use multiply high instructions for high part of 32x32 multiply.-mxl-float-convertโ use hardware floating-point conversion instructions.-mxl-float-sqrtโ use hardware floating-point square root instruction.-mbig-endianโ generate code for a big-endian target.-mlittle-endianโ generate code for a little-endian target.-mxl-reorderโ use reorder instructions (swap and byte reversed load/store).-mxl-mode-app-modelโ select application model app-model. The valid models are:executableโ normal executable (default), uses startup codecrt0.o.xmdstubโ for use with Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. This uses startup filecrt1.oand sets the start address of the program to0x800.bootstrapโ for applications that are loaded using a bootloader. This model uses startup filecrt2.owhich does not contain a processor reset vector handler. This is suitable for transferring control on a processor reset to the bootloader rather than the application.novectorsโ for applications that do not require any of the MicroBlaze vectors. This option may be useful for applications running within a monitoring application. This model usescrt3.oas a startup file.
Option -xl-mode-app-model is 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 allows data to be referenced by offset from start of text address instead of 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โ ok bestie this is THE one ๐ it generates code that actually runs on arch, and arch can be either a generic MIPS ISA name or the name of one specific 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.
And then there's the โจspecialโจ value from-abi, which picks the most compatible architecture for whatever ABI you've selected (so like, mips1 for 32-bit ABIs and mips3 for 64-bit ABIs).
The native Linux/GNU toolchain also supports the value native, which picks the best architecture option for the host processor. Heads up though: -march=native does absolutely nothing if GCC doesn't recognize the processor. ๐
Fun little shortcut for you: in processor names, a final 000 can be abbreviated as k (so -march=r2k is a whole vibe). Prefixes are optional, and vr may be written as just 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, no cap:
_MIPS_ARCHโ gives the name of the target architecture, as a string._MIPS_ARCH_fooโ where foo is the capitalized value of_MIPS_ARCH.
So for example, -march=r2000 sets _MIPS_ARCH to "r2000" and defines the macro _MIPS_ARCH_R2000. iconic behavior honestly ๐
Heads up though: the_MIPS_ARCHmacro uses the processor names given above. In other words, it has the full prefix and does not abbreviate000ask. In the case offrom-abi, the macro names the resolved architecture (either"mips1"or"mips3"). It names the default architecture when no-marchoption is given.
-mtune=archโ this one optimizes for arch ๐ง among other things, it controls the way instructions are scheduled, and the perceived cost of arithmetic operations. The list of arch values is the exact 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 whole family of processors, but optimizes the code for one particular member of that family. it's giving "one for all, all for one" โจ
-mtune defines the macros _MIPS_TUNE and _MIPS_TUNE_foo, which work in the same way as the -march ones described above.
-mips1โ Equivalent to-march=mips1.-mips2โ Equivalent to-march=mips2.-mips3โ Equivalent to-march=mips3.-mips4โ Equivalent to-march=mips4.-mips32โ Equivalent to-march=mips32.-mips32r3โ Equivalent to-march=mips32r3.-mips32r5โ Equivalent to-march=mips32r5.-mips32r6โ Equivalent to-march=mips32r6.-mips64โ Equivalent to-march=mips64.-mips64r2โ Equivalent to-march=mips64r2.-mips64r3โ Equivalent to-march=mips64r3.-mips64r5โ Equivalent to-march=mips64r5.-mips64r6โ Equivalent to-march=mips64r6.-mips16,-mno-mips16โ Generate (or 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. like bestie this is a lab experiment, not a lifestyle ๐-minterlink-compressed,-mno-interlink-compressedโ Require (or 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 info 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 additional variants of the o32 ABI are supported to enable a transition from 32-bit to 64-bit registers. These are FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension mandates that all code must execute correctly when run using 32-bit or 64-bit registers. The code can be interlinked with either FP32 or FP64, but not both. The FP64A extension is similar to the FP64 extension but forbids the use of odd-numbered single-precision registers. This can be used in conjunction with the FRE mode of FPUs in MIPS32R5 processors and allows both FP32 and FP64A code to interlink and run in the same process without changing FPU modes. slay ๐
-mabicalls,-mno-abicallsโ Generate (or do not generate) code that is suitable for SVR4-style dynamic objects.-mabicallsis the default for SVR4-based systems.-mshared,-mno-sharedโ Generate (or do not generate) code that is fully position-independent, and that can therefore be linked into shared libraries. This option only affects-mabicalls.
All -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. However, as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is selected by -mno-shared.
-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker. it's giving glow-up โจ
-mshared is the default.
-mplt,-mno-pltโ Assume (or do not assume) that the static and dynamic linkers support PLTs and copy relocations. This option only affects-mno-shared -mabicalls. For the n64 ABI, this option has no effect without-msym32.
You can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.
-mxgot,-mno-xgotโ Lift (or do not lift) the usual restrictions on the size of the global offset table. ๐
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_MIPS_GOT16 foobar
If this happens, you should recompile your code with -mxgot. This works with very large GOTs, although 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 to use -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. mystery era ๐-mhard-floatโ Use floating-point coprocessor instructions.-msoft-floatโ Do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.-mno-floatโ Equivalent to-msoft-float, but additionally asserts that the program being compiled does not perform any floating-point operations. 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-pointprintfformats).
If code compiled with -mno-float accidentally contains floating-point operations, it is likely to suffer a link-time or run-time failure. ๐ like fr fr do not do that
-msingle-floatโ Assume that the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ okay so this one says: assume the floating-point coprocessor can handle double-precision operations. It's the default, bestie, so it's already living its best life unless you changed it. โจ-modd-spreg,-mno-odd-spregโ enable the use of odd-numbered single-precision floating-point registers for the o32 ABI (or don't, if you're the second one). This is the default for processors that are known to support these registers. But heads up ๐ซถ when you're on the o32 FPXX ABI,-mno-odd-spregis set by default.-mabs=2008,-mabs=legacyโ these two control how the special not-a-number (NaN) IEEE 754 floating-point data gets treated with theabs.fmtandneg.fmtmachine instructions.
By default, or whenever you use -mabs=legacy, the legacy treatment is what you get. In that case those instructions are considered arithmetic, and they get avoided wherever correct operation is required and the input operand might be a NaN. Instead, a longer sequence of instructions that manipulates the sign bit of the floating-point datum manually is used โ unless you also passed -ffinite-math-only.
The -mabs=2008 option picks the IEEE 754-2008 treatment instead. Here those instructions are considered non-arithmetic, which means they operate correctly in all cases, including especially when the input operand is a NaN. So these instructions are always used for the respective operations. slay ๐
-mnan=2008,-mnan=legacyโ these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data. ๐
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.
The default is -mnan=legacy unless GCC has been configured with --with-nan=2008.
-mllsc,-mno-llscโ use (or do not 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 (do not use) revision 1 of the MIPS DSP ASE.
This option defines the preprocessor macro __mips_dsp. It also defines __mips_dsp_rev to 1.
-mdspr2,-mno-dspr2โ use (do not use) revision 2 of the MIPS DSP ASE.
This option defines the preprocessor macros __mips_dsp and __mips_dspr2. It also defines __mips_dsp_rev to 2.
-msmartmips,-mno-smartmipsโ use (do not use) the MIPS SmartMIPS ASE.-mpaired-single,-mno-paired-singleโ use (do not use) paired-single floating-point instructions.
This option requires hardware floating-point support to be enabled. ๐ซถ
-mdmx,-mno-mdmxโ use (do not 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 (do not use) the MIPS-3D ASE. The option-mips3dimplies-mpaired-single.-mmicromips,-mno-micromipsโ generate (do not 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 (do not use) MT Multithreading instructions.-mmcu,-mno-mcuโ use (do not use) the MIPS MCU ASE instructions.-meva,-mno-evaโ use (do not use) the MIPS Enhanced Virtual Addressing instructions.-mvirt,-mno-virtโ use (do not use) the MIPS Virtualization (VZ) instructions.-mxpa,-mno-xpaโ use (do not use) the MIPS eXtended Physical Address (XPA) instructions.-mcrc,-mno-crcโ use (do not use) the MIPS Cyclic Redundancy Check (CRC) instructions.-mginv,-mno-ginvโ use (do not use) the MIPS Global INValidate (GINV) instructions.-mloongson-mmi,-mno-loongson-mmiโ use (do not use) the MIPS Loongson MultiMedia extensions Instructions (MMI).-mloongson-ext,-mno-loongson-extโ use (do not use) the MIPS Loongson EXTensions (EXT) instructions.-mloongson-ext2,-mno-loongson-ext2โ use (do not 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 (do not 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 (do not extend) the-Gbehavior to local data too, like static variables in C.-mlocal-sdatais the default for all configurations.
If the linker complains that an application is using too much small data, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. You might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program. ๐ซถ
-mextern-sdata,-mno-extern-sdataโ assume (do not assume) that externally-defined data is in a small data section if the size of that data is within the-Glimit.-mextern-sdatais the default for all configurations.
If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a section attribute to Var's definition. If Var is common, you must link the application with a high-enough -G setting.
The easiest way of satisfying these restrictions is to compile and link every module with the same -G option. However, you may wish to build a library that supports several different small data limits. You can do this 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.
-mgpopt,-mno-gpoptโ use (do not use) GP-relative accesses for symbols that are known to be in a small data section; see-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations.
-mno-gpopt is useful for cases where the $gp register might not hold the value of _gp. For example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In such situations, the boot monitor itself is usually compiled with -G0.)
-mno-gpopt implies -mno-local-sdata and -mno-extern-sdata.
-membedded-data,-mno-embedded-dataโ allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. This gives slightly slower code than the default, but reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems.-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ put uninitializedconstvariables in the read-only data section. This option is only meaningful in conjunction with-membedded-data.-mcode-readable=settingโ specify whether GCC may generate code that reads from executable sections. There are three possible settings:-mcode-readable=yesโ instructions may freely access executable sections. This is the default setting.-mcode-readable=pcrelโ MIPS16 PC-relative load instructions can access executable sections, but other instructions must not do so. This option is useful on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set. It is also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM.-mcode-readable=noโ instructions must not access executable sections. This option can be useful on targets that are configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM.
-msplit-addresses,-mno-split-addressesโ enable (disable) use of the%hi()and%lo()assembler relocation operators. This option has been superseded by-mexplicit-relocsbut is retained for backwards compatibility.-mexplicit-relocs,-mno-explicit-relocsโ use (do not use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by-mno-explicit-relocs, is to use assembler macros instead.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators.
-mcheck-zero-division,-mno-check-zero-divisionโ trap (do not trap) on integer division by zero.
The default is -mcheck-zero-division. periodt ๐
-mdivide-traps/-mdivide-breaksโ okay so MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but is 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. Divide-by-zero checks can be completely disabled using -mno-check-zero-division. iykyk
-mload-store-pairs/-mno-load-store-pairsโ Enable (disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default but only takes effect when the selected architecture is known to support bonding. slay-munaligned-access/-mno-unaligned-accessโ Enable (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. fr fr-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. ate-mlong-calls/-mno-long-callsโ Disable (do not disable) use of thejalinstruction. Calling functions usingjalis more efficient but requires the caller and callee to be in the same 256 megabyte segment.
This option has no effect on abicalls code. The default is -mno-long-calls. periodt
-mmad/-mno-madโ Enable (disable) use of themad,maduandmulinstructions, as provided by the R4650 ISA. iconic-mimadd/-mno-imaddโ Enable (disable) use of themaddandmsubinteger instructions. The default is-mimaddon architectures that supportmaddandmsubexcept for the74karchitecture where it was found to generate slower code. lowkey-mfused-madd/-mno-fused-maddโ Enable (disable) use of the floating-point multiply-accumulate instructions, when they are available. The default is-mfused-madd.
On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions. the way that
-nocppโ Tell the MIPS assembler to not run its preprocessor over user assembler files (with a.ssuffix) when assembling them. no cap-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. obsessed-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.
-mfix-r4400/-mno-fix-r4400โ Work around certain R4400 CPU errata:- A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
-mfix-r10000/-mno-fix-r10000โ Work around certain R10000 errata:ll/scsequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier.
This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise. danger ๐
-mfix-r5900/-mno-fix-r5900โ Do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer and always schedule anopinstruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip. The workaround is implemented by the assembler rather than by GCC. iykyk-mfix-rm7000/-mno-fix-rm7000โ Work around the RM7000dmult/dmultuerrata. The workarounds are implemented by the assembler rather than by GCC. slay-mfix-vr4120/-mno-fix-vr4120โ Work around certain VR4120 errata:dmultudoes not always produce the correct result.divandddivdo not always produce the correct result if one of the operands is negative.
The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the mips64vr*-elf configurations.
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. fr fr
-mfix-vr4130โ Work around the VR4130mflo/mfhierrata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids usingmfloandmfhiif the VR4130macc,macchi,dmaccanddmacchiinstructions are available instead. iconic-mfix-sb1/-mno-fix-sb1โ Work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2F1andF2floating-point errata.) periodt-mr10k-cache-barrier=settingโ Specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors.
In common with many processors, the R10K tries to predict the outcome of a conditional branch and speculatively executes instructions from the "taken" branch. It later aborts these instructions if the predicted outcome is wrong. However, on the R10K, even aborted instructions can have side effects.
This problem only affects kernel stores and, depending on the system, kernel loads. As an example, 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 number 3 (to flush both caches). The default depends on the target GCC was configured for, but commonly is either_flush_funcor__cpu_flush. the way thatmbranch-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. lowkey-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. deprecated ๐-mcompact-branches=never/-mcompact-branches=optimal/-mcompact-branches=alwaysโ These options control which form of branches will be generated. The default is-mcompact-branches=optimal.
The -mcompact-branches=never option ensures that compact branch instructions will never be generated.
The -mcompact-branches=always option 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. periodt
The -mcompact-branches=optimal option 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. (bestie it's literally doing the "use it if u can, fall back if u can't" thing ๐
)
-mfp-exceptions,-mno-fp-exceptionsโ tells GCC whether FP exceptions are enabled or not. This affects how FP instructions get scheduled for some processors. Default? FP exceptions are enabled. So like, on the SB-1, if FP exceptions are disabled and we're emitting 64-bit code, we can use both FP pipes. Otherwise we only get one FP pipe. That's the whole tea. ๐ซ-mvr4130-align,-mno-vr4130-alignโ the VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. Turn this on and GCC will align pairs of instructions that it thinks should execute in parallel. โจ This one only does anything when you're optimizing for the VR4130. Normally it makes code faster, but the price is bigger code. It's enabled by default at optimization level-O3.-msynci,-mno-synciโ enable (or disable) generation ofsynciinstructions on architectures that support it. Thosesynciinstructions (when enabled) get generated when__builtin___clear_cacheis compiled. Default is-mno-synci, but that default can be overridden by configuring GCC with--with-synci.
๐จ When you're compiling for single processor systems it's generally safe to use synci. But on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior. no cap, be careful.
-mrelax-pic-calls,-mno-relax-pic-callsโ try to turn PIC calls that are normally dispatched via register$25into direct calls. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call.-mrelax-pic-callsis the default if GCC was configured to use an assembler and a linker that support the.relocassembly directive and-mexplicit-relocsis in effect. With-mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone, without the compiler helping. ๐ซ-mmcount-ra-address,-mno-mcount-ra-addressโ emit (or don't emit) code that lets_mcountmodify the calling function's return address. When enabled, this option extends the usual_mcountinterface with a new ra-address parameter, which has typeintptr_t *and is passed in register$12. Then_mcountcan modify the return address by doing both of these:- 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
Default is -mno-mcount-ra-address.
-mframe-header-opt,-mno-frame-header-optโ enable (disable) frame header optimization in the o32 ABI. When you're using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. With this enabled, the optimization suppresses the allocation of the frame header if it can be determined that it's unused. ๐ This optimization is off by default at all optimization levels.-mlxc1-sxc1,-mno-lxc1-sxc1โ when applicable, enable (disable) the generation oflwxc1,swxc1,ldxc1,sdxc1instructions. Enabled by default. ๐ธ-mmadd4,-mno-madd4โ when applicable, enable (disable) the generation of 4-operandmadd.s,madd.dand related instructions. Enabled by default.
๐ MMIX Options ๐
These options are defined for the MMIX:
-mlibfuncs,-mno-libfuncsโ specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.-mepsilon,-mno-epsilonโ generate floating-point comparison instructions that compare with respect to therEepsilon register.-mabi=mmixware,-mabi=gnuโ generate code that passes function parameters and return values that (in the called function) are seen as registers$0and up, as opposed to the GNU ABI which uses global registers$231and up.-mzero-extend,-mno-zero-extendโ when reading data from memory in sizes shorter than 64 bits, use (or don't 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 (or don't prepend) a:to all global symbols, so the assembly code can be used with thePREFIXassembly directive.-melfโ generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator.-mbranch-predict,-mno-branch-predictโ use (or don't use) the probable-branch instructions, when static branch prediction indicates a probable branch.-mbase-addresses,-mno-base-addressesโ generate (or don't generate) code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register. The register is used for one or more base address requests within the range0to255from the value held in the register. This generally leads to short and fast code, but the number of different data items that can be addressed is limited. Which means a program that uses lots of static data may require-mno-base-addresses. ๐ฆ-msingle-exit,-mno-single-exitโ force (or don't 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โ generate code to avoid bugs in the multiply instructions for the MN10300 processors. This is the default.-mno-mult-bugโ do not generate code to avoid bugs in the multiply instructions for the MN10300 processors.-mam33โ generate code using features specific to the AM33 processor.-mno-am33โ do not generate code using features specific to the AM33 processor. This is the default.-mam33-2โ generate code using features specific to the AM33/2.0 processor.-mam34โ generate code using features specific to the AM34 processor.-mtune=cpu-type โ use the timing characteristics of the indicated CPU type when scheduling instructions. This does not change the targeted processor type. The CPU type must be one ofmn10300,am33,am33-2oram34.-mreturn-pointer-on-d0โ when generating a function that returns a pointer, return the pointer in botha0andd0. Otherwise, the pointer is returned only ina0, and attempts to call such functions without a prototype result in errors. Note that this option is on by default; use-mno-return-pointer-on-d0to disable it.-mno-crt0โ do not link in the C run-time initialization object file.-mrelaxโ indicate to the linker that it should perform a relaxation optimization pass to shorten branches, calls and absolute memory addresses. This option only has an effect when used on the command line for the final link step.
๐ญ Heads up: this option makes symbolic debugging impossible.
-mliwโ allow the compiler to generate Long Instruction Word instructions if the target is the AM33 or later. This is the default. This option defines the preprocessor macro__LIW__.-mno-liwโ do not allow the compiler to generate Long Instruction Word instructions. This option defines the preprocessor macro__NO_LIW__.-msetlbโ allow the compiler to generate theSETLBandLccinstructions if the target is the AM33 or later. This is the default. This option defines the preprocessor macro__SETLB__.-mno-setlbโ do not allow the compiler to generateSETLBorLccinstructions. This option defines the preprocessor macro__NO_SETLB__.
๐ Moxie Options ๐
-mebโ generate big-endian code. This is the default formoxie-*-*configurations.-melโ generate little-endian code.-mmul.xโ generatemul.xandumul.xinstructions. This is the default formoxiebox-*-*configurations.-mno-crt0โ do not link in the C run-time initialization object file.
๐ MSP430 Options ๐
These options are defined for the MSP430:
-masm-hexโ force assembly output to always use hex constants. Normally such constants are signed decimals, but this option is available for testsuite and/or aesthetic purposes. (aesthetic purposes bestie, we love that ๐ )-mmcu=โ select the MCU to target. This is used to create a C preprocessor symbol based upon the MCU name, converted to upper case and pre- and post-fixed with__. This in turn is used by themsp430.hheader file to select an MCU-specific supplementary header file. The option also sets the ISA to use. If the MCU name is one that is known to only support the 430 ISA, then that is selected, otherwise the 430X ISA is selected. A generic MCU name ofmsp430can also be used to select the 430 ISA. Similarly the genericmsp430xMCU name selects the 430X ISA. In addition, an MCU-specific linker script is added to the linker command line. The script's name is the name of the MCU with.ldappended. So specifying-mmcu=xxxon the gcc command line defines the C preprocessor symbol__XXX__and causes the linker to search for a script calledxxx.ld. The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However, an externaldevices.csvfile can be used to extend device support beyond those that have been hard-coded. ๐ GCC searches for thedevices.csvfile using the following methods in the given precedence order, where the first method takes precedence over the second which takes precedence over the third.- Include path specified with
-Iand-Lโdevices.csvwill be searched for in each of the directories specified by include paths and linker library search paths.
- Include path specified with
- Path specified by the environment variable
MSP430_GCC_INCLUDE_DIRโ okay so set the global env varMSP430_GCC_INCLUDE_DIRto the full path of the directory that hasdevices.csvin it, and GCC will go look there fordevices.csv. And if it does finddevices.csvthere? Bestie, that directory gets registered as an include path and a linker library path too. So header files and linker scripts chillin' in that directory can be used without you manually typing-Iand-Lon the command line. so convenient ๐- The
msp430-elf{,bare}/include/devicesdirectory โ last stop on the tour: GCC will peek atmsp430-elf{,bare}/include/devicesfrom the toolchain root directory. This directory does not exist in a default installation, but if you made it yourself and copieddevices.csvin there, then the MCU data will be read. Same deal as above: this directory also gets registered as an include path and a linker library path. โจ
- The
And if none of the above search methods find devices.csv? Then the hard-coded MCU data is used. No cap, it's baked in.
๐ธ MSP430 Options (cont'd, we're still going bestie) ๐ธ
-mwarn-mcu-mno-warn-mcuโ turns warnings on/off about conflicts between the MCU name you gave with-mmcuand the ISA set by-mcpuand/or the hardware multiply support set by-mhwmult. It also toggles warnings about unrecognized MCU names. This one is on by default, so you'd have to actively silence it.-mcpu=โ specifies the ISA to use. Accepted values aremsp430,msp430xandmsp430xv2. This option is deprecated. Like, the-mmcu=option should be used to select the ISA instead, fr fr. ๐-msimโ link to the simulator runtime libraries and linker script. Overrides any scripts that would've been selected by the-mmcu=option.-mlargeโ use large-model addressing (20-bitpointers,20-bitsize_t).-msmallโ use small-model addressing (16-bitpointers,16-bitsize_t).-mrelaxโ this option is passed to the assembler and the linker, and it lets the linker do certain optimizations that literally cannot be done until the final link. iykyk.mhwmult=โ describes the type of hardware multiply your target supports. Accepted values:noneโ no hardware multiply16bitโ the original 16-bit-only multiply supported by early MCUs32bitโ the 16/32-bit multiply supported by later MCUsf5seriesโ the 16/32-bit multiply supported by F5-series MCUsautoโ also valid! This tells GCC to deduce the hardware multiply support based on the MCU name you handed it via-mmcu. If no-mmcuoption is specified, or if the MCU name is not recognized, then no hardware multiply support is assumed.autois the default setting.
Hardware multiplies are normally performed by calling a library routine โ that saves space in the generated code. But when compiling at -O3 or higher, the hardware multiplier gets invoked inline instead. Bigger code, but faster. โจ
The hardware multiply routines disable interrupts whilst running and restore the previous interrupt state when they finish. That makes them safe to use inside interrupt handlers as well as in normal code. ๐ซถ
-minrtโ enable the use of a minimum runtime environment โ no static initializers, no constructors. 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. Heads up bestie: the tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications. ๐ญ
Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it is sent to write.
This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.
-mmax-inline-shift=โ takes an integer between0and64inclusive, and sets the max 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 is used instead. The default value is4.
This only affects cases where a shift by multiple positions cannot be completed with a single instruction (e.g. all shifts >1 on the 430 ISA).
Shifts of a 32-bit value are at least twice as costly, so the value you pass for this option gets divided by 2 and that resulting value is used instead.
-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 โ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.-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.csvis not 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.-mno-ext-perfโ do not generate performance extension instructions.-mext-perf2โ generate performance extension 2 instructions.-mno-ext-perf2โ do not generate performance extension 2 instructions.-mext-stringโ generate string extension instructions.-mno-ext-stringโ do not generate string extension instructions.-mv3pushโ generate v3 push25/pop25 instructions.-mno-v3pushโ do not generate v3 push25/pop25 instructions.-m16-bitโ generate 16-bit instructions.-mno-16-bitโ do not generate 16-bit instructions.-misr-vector-size=numโ specify the size of each interrupt vector, which must be4or16.-mcache-block-size=numโ specify the size of each cache block, which must be a power of 2 between4and512.-march=archโ specify the name of the target architecture.-mcmodel=code-modelโ set the code model to one of: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 still be within16MBaddressing space.largeโ all the text and data segments can be within4GBaddressing space.
-mctor-dtorโ enable constructor/destructor feature.-mrelaxโ guide linker to relax instructions.
๐ Nios II Options ๐
These are the options defined for the Altera Nios II processor.
-G numโ put 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 (or don't generate) GP-relative accesses. The following option names are recognized: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 asectionattribute.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 that 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's most useful in conjunction withsectionattributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression.
This option does not affect the behavior of the -G option, and the specified sections are in addition to the standard .sdata and .sbss small-data sections that are recognized by -mgpopt. โจ
-mr0rel-sec=regexpโ bestie, this one lets you name sections that can be reached with a 16-bit offset fromr0๐ meaning they live in the low 32K or the high 32K of the 32-bit address space. It's most useful when you pair it withsectionattributes on your variable declarations and a custom linker script, iykyk. The regexp is a POSIX Extended Regular Expression.
Okay so quick contrast: unlike GP-relative addressing for small data, zero-based addressing is never generated by default, and there are no conventional section names chilling in standard linker scripts for sections in the low or high areas of memory. So you're on your own for those, fr fr.
-mel,-mebโ generate little-endian (that's the default ๐ซถ) or big-endian (experimental โ ๏ธ) code, respectively.-march=archโ this names your target Nios II architecture, and GCC uses that name to figure out what kind of instructions it's allowed to emit when it's making assembly. Permissible names are:r1,r2. The preprocessor macro__nios2_arch__is available to programs, and its value is1or2depending on which ISA level you're targeting. โจ-mbypass-cache,-mno-bypass-cacheโ force all load and store instructions to always bypass the cache by using the I/O variants of the instructions. The default is not to bypass the cache.-mno-cache-volatile,-mcache-volatileโ volatile memory access bypasses 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โ don't 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 themul,mulxanddivfamily of instructions by the compiler. The default is to emitmuland not emitdivandmulx.-mbmx,-mno-bmx,-mcdx,-mno-cdxโ enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. Heads up: enabling these also requires-march=r2๐จ. Since these 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 encoding N when generating code that uses insn. For example,-mcustom-fadds=253generates custom instruction253for single-precision floating-point add operations instead of the default behavior of using a library call. Iconic.
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. No cap. ๐ง
๐ธ Single-precision floating point ๐ธ
fadds,fsubs,fdivs,fmulsโ binary arithmetic operations.fnegsโ unary negation.fabssโ unary absolute value.fcmpeqs,fcmpges,fcmpgts,fcmples,fcmplts,fcmpnesโ comparison operations.fmins,fmaxsโ floating-point minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified.fsqrtsโ unary square root operation.fcoss,fsins,ftans,fatans,fexps,flogsโ floating-point trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified.
๐ Double-precision floating point ๐
faddd,fsubd,fdivd,fmuldโ binary arithmetic operations.fnegdโ unary negation.fabsdโ unary absolute value.fcmpeqd,fcmpged,fcmpgtd,fcmpled,fcmpltd,fcmpnedโ comparison operations.fmind,fmaxdโ double-precision minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified.fsqrtdโ unary square root operation.fcosd,fsind,ftand,fatand,fexpd,flogdโ double-precision trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified.
๐ฆ Conversions ๐ฆ
fextsdโ conversion from single precision to double precision.ftruncdsโ conversion from double precision to single precision.fixsi,fixsu,fixdi,fixduโ conversion from floating point to signed or unsigned integer types, with truncation towards zero.roundโ conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the__builtin_lroundffunction when-fno-math-errnois used.floatis,floatus,floatid,floatudโ conversion from signed or unsigned integer types to floating-point types.
In addition, all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or the 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. Lowkey magic. โจ
fwrxโ write src1 into the least significant half of X and src2 into the most significant half of X.fwryโ write src1 into Y.frdxhi,frdxloโ read the most or least (respectively) significant half of X and store it in dest.frdyโ read the value of Y and store it into dest.
Ngl, you can gain more local control over generation of Nios II custom instructions by using thetarget("custom-insn=N")andtarget("no-custom-insn")function attributes or pragmas. ๐
-mcustom-fpu-cfg=nameโ this enables a predefined, named set of custom instruction encodings (see-mcustom-insnabove). Currently, the following sets are defined:-mcustom-fpu-cfg=60-1is equivalent to:-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant-mcustom-fpu-cfg=60-2is equivalent to:-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant-mcustom-fpu-cfg=72-3is equivalent to:-mcustom-floatus=243 -mcustom-fixsi=244 -mcustom-floatis=245 -mcustom-fcmpgts=246 -mcustom-fcmples=249 -mcustom-fcmpeqs=250 -mcustom-fcmpnes=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant-mcustom-fpu-cfg=fph2is equivalent to:-mcustom-fabss=224 -mcustom-fnegs=225 -mcustom-fcmpnes=226 -mcustom-fcmpeqs=227 -mcustom-fcmpges=228 -mcustom-fcmpgts=229 -mcustom-fcmples=230 -mcustom-fcmplts=231 -mcustom-fmaxs=232 -mcustom-fmins=233 -mcustom-round=248 -mcustom-fixsi=249 -mcustom-floatis=250 -mcustom-fsqrts=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255
Custom instruction assignments given by individual -mcustom-insn= options override those given by -mcustom-fpu-cfg=, regardless of the order of the options on the command line. The order literally does not matter, periodt. ๐
Also, you can gain more local control over selection of a FPU configuration by using the target("custom-fpu-cfg=name") function attribute or pragma.
The name fph2 is an abbreviation for Nios II Floating Point Hardware 2 Component. Please note that the custom instructions enabled by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. The custom instruction enabled by -mcustom-round=248 is only generated if -fno-math-errno is specified. In contrast to the other configurations, -fsingle-precision-constant is not set. ๐
These additional -m options are available 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 in conjunction with-msys-crt0=to specify the location of the alternate startup code provided by the HAL BSP.-msmallcโ link with a limited version of the C library,-lsmallc, rather than Newlib.-msys-crt0=startfileโ startfile is the file name of the startfile (crt0) to use when linking. This option is only useful in conjunction with-mhal.-msys-lib=systemlibโ systemlib is the library name of the library that provides low-level system calls required by the C library, e.g.readandwrite. 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. It's giving "we keep it around so nothing breaks" energy. ๐ซถ-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. For instance, for-march-map=sm_50select-march=sm_35, and for-march-map=sm_53select-march=sm_53.-mptx=version-stringโ generate code for the specified PTX ISA version (e.g.7.0). Valid version strings include3.1,6.0,6.3, and7.0. The default PTX ISA version is6.0, unless a higher version is required for the specified PTX ISA target architecture via option-march=. This option sets the values of the preprocessor macros__PTX_ISA_VERSION_MAJOR__and__PTX_ISA_VERSION_MINOR__; for instance, for3.1the macros have the values3and1, respectively. ๐-mmainkernelโ Links in code for a__mainkernel. This is for stand-alone instead of offloading execution. no cap it's for when you're not offloading, bestie.-moptimizeโ Applies partitioned execution optimizations. This is the default when any level of optimization is selected. โจ So if you turn on any-Olevel, this is automatically on, periodt.-msoft-stackโ Generates code that does not use".local"memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or"alloca"), and when global memory is used for underlying storage, makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option-mgomp. iykyk it's a whole vibe.-muniform-simtโ Switches to code generation variant that allows to execute all threads in each warp, while maintaining memory state and side effects as if only one thread in each warp was active outside of OpenMP SIMD regions. All atomic operations and calls to runtime (malloc,free,vprintf) are conditionally executed (iff current lane index equals the master lane index), and the register being assigned is copied via a shuffle instruction from the master lane. Outside of SIMD regions lane 0 is the master; inside, each thread sees itself as the master. Shared memory array"int __nvptx_uni[]"stores all-zeros or all-ones bitmasks for each warp, indicating current mode (0 outside of SIMD regions). Each thread can bitwise-and the bitmask at position"tid.y"with current lane index to compute the master lane index. this is some main character energy for real.-mgompโ Generates code for use in OpenMP offloading: enables-msoft-stackand-muniform-simtoptions, and selects corresponding multilib variant. ๐ So it's like a combo deal, bestie.
OpenRISC Options ๐ฆ
okay so these are the OpenRISC ones, bestie:
-mboard=nameโ Configures a board specific runtime. This will be passed to the linker for newlib board library linking. The default is"or1ksim". ๐ So if you don't specify, it'sor1ksim.-mnewlibโ This option is ignored; it is for compatibility purposes only. This used to select linker and preprocessor options for use with newlib. not me being obsolete it's just for compat, bestie.-msoft-div,-mhard-divโ Select software or hardware divide ("l.div","l.divu") instructions. This default is hardware divide. ๐ฅ So default is-mhard-div.-msoft-mul,-mhard-mulโ Select software or hardware multiply ("l.mul","l.muli") instructions. This default is hardware multiply. โจ Default is-mhard-mul.-msoft-float,-mhard-floatโ Select software or hardware for floating point operations. The default is software. so-msoft-floatis the default.-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. ๐ง So if you want hardware double, you need-mhard-floatand this.-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 ๐น๏ธ
okay so PDP-11, bestie, here we go:
-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 ๐ค
okay so PRU target, bestie:
-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 that the compiler could still generate code with static initializers and constructors. It is up to the programmer to ensure that the source program will not use those features. so like, it's a risk, bestie.-mmcu=mcuโ Specify the PRU MCU variant to use. Check Newlib for the exact list of supported MCUs. ๐-mno-relaxโ Make GCC pass the--no-relaxcommand-line option to the linker instead of the--relaxoption. ๐-mloopโ Allow (or do not allow) GCC to use the LOOP instruction. โจ-mabi=variantโ Specify the ABI variant to output code for.-mabi=tiselects the unmodified TI ABI while-mabi=gnuselects a GNU variant that copes more naturally with certain GCC assumptions. These are the differences:- Function Pointer Size โ TI ABI specifies that function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers.
- Optional Return Value Pointer โ Function return values larger than 64 bits are passed by using a hidden pointer as the first argument of the function. TI ABI, though, mandates that the pointer can be NULL in case the caller is not using the returned value. GNU always passes and expects a valid return value pointer.
The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected. As a consequence the standard C library cannot be built and it is omitted when linking with -mabi=ti.
Relaxation is a GNU feature and for safety reasons is disabled when using -mabi=ti. The TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions. so -mabi=ti is a no-go for relaxation, bestie.
RISC-V Options ๐
okay so RISC-V, bestie, let's go:
-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 integer and floating-point calling convention. ABI-string contains two parts: the size of integer types and the registers used for floating-point types. For example-march=rv64ifd -mabi=lp64dmeans that long and pointers are 64-bit (implicitly defining int to be 32-bit), and that floating-point values up to 64 bits wide are passed in F registers. Contrast this with-march=rv64ifd -mabi=lp64f, which still allows the compiler to generate code that uses 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, in which no floating-point arguments will be passed in registers.
The default for this argument is system dependent, users who want a specific calling convention should specify one explicitly. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Some calling conventions are 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 is 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 yeah, pick your ABI wisely, bestie.
-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 the 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 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. ๐
okay so if you don't hand over either -march or -mcpu=, the default for this argument is system dependent โ so bestie, if you want specific architecture extensions, you gotta specify one explicitly. no vibes-based guessing allowed ๐
-mcpu=processor-stringโ use the architecture of and optimize the output for the given processor, specified by its particular CPU name. the permissible values are:sifive-e20,sifive-e21,sifive-e24,sifive-e31,sifive-e34,sifive-e76,sifive-s21,sifive-s51,sifive-s54,sifive-s76,sifive-u54, andsifive-u74. that's the whole roster, periodt โจ-mtune=processor-stringโ optimize the output for the given processor, specified by microarchitecture or particular CPU name. the permissible values are:rocket,sifive-3-series,sifive-5-series,sifive-7-series,thead-c906,size, plus all valid options for-mcpu=.
when -mtune= isn't specified, it uses the setting from -mcpu, and the default is rocket if both are missing. lowkey elegant.
the size choice is not intended for use by end-users โ it's what gets used when -Os is specified. it overrides the instruction cost info provided by -mtune=, but it does not override the pipeline info. this helps reduce code size while still giving good performance. it's giving "internals only, bestie" ๐ซถ
-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a2raised tonumbyte boundary. if-mpreferred-stack-boundaryisn't 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. no mixing, no exceptions, iykyk ๐ญ
-msmall-data-limit=nโ put global and static data smaller thannbytes 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. fast is the moment โจ-minline-atomics,-mno-inline-atomicsโ do or don't use smaller but slower subword atomic emulation code that useslibatomicfunction calls. the default is to use fast inline subword atomics that do not requirelibatomic.-mshorten-memrefs,-mno-shorten-memrefsโ do or do not attempt to make more use of compressed load/store instructions by replacing a load/store 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. niche but she ate ๐ฅ-mstrict-align,-mno-strict-alignโ do not or do generate unaligned memory accesses. the default is set depending on whether the processor we are 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. main character energy ๐-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 is not guaranteed to function correctly when linked into position-independent executables or libraries. read that twice, bestie ๐ซ
-mexplicit-relocs,-mno-exlicit-relocsโ use or do not use assembler relocation operators when dealing with symbolic addresses. the alternative is to use assembler macros instead, which may limit optimization.-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. we love a default that's already doing the most ๐-mriscv-attribute,-mno-riscv-attributeโ emit (do not emit) RISC-V attribute to record extra information into ELF objects. this feature requires at least binutils2.32. no old binutils erasure allowed.-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. the 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. the way that "but not" is doing so much heavy lifting ๐ฆ-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ generate stack protection code using canary at guard. the supported locations areglobalfor a global canary ortlsfor 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 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. kernel girlies only, everyone else go home ๐ซก
๐ 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".
in addition a C preprocessor macro is defined, based upon the setting of this option. possible values are: "__RL78_MUL_NONE__", "__RL78_MUL_G13__" or "__RL78_MUL_G14__". macros are the group chat of the preprocessor fr fr ๐
-mcpu=g10,-mcpu=g13,-mcpu=g14,-mcpu=rl78โ specifies the RL78 core to target. the default is the G14 core, also known as an S3 core or just RL78. the G13 or S2 core does not have multiply or divide instructions โ instead it uses a hardware peripheral for these operations. the G10 or S1 core does not have register banks, so it uses a different calling convention.
if this option is set it also selects the type of hardware multiply support to use, unless this is overridden by an explicit -mmul=none option on the command line. thus specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral and specifying -mcpu=g10 disables the use of hardware multiplications altogether.
note, although the RL78/G14 core is the default target, specifying -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain since it also enables G14 hardware multiply support. if these options are not specified on the command line then software multiplication routines will be used even though the code targets the RL78 core. this is for backwards compatibility with older toolchains which did not have hardware multiply and divide support. legacy behavior really said "i'm not leaving" ๐ญ
in addition a C preprocessor macro is defined, based upon the setting of this option. possible values are: "__RL78_G10__", "__RL78_G13__" or "__RL78_G14__".
-mg10,-mg13,-mg14,-mrl78โ these are aliases for the corresponding-mcpu=option. they are provided for backwards compatibility.-mallregsโ allow the compiler to use all of the available registers. by default registers"r24..r31"are reserved for use in interrupt handlers. with this option enabled these registers can be used in ordinary functions as well. let the normal functions have nice things โจ-m64bit-doubles,-m32bit-doublesโ make the"double"data type be 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โ specifies that interrupt handler functions should preserve the MDUC registers. this is only necessary if normal code might use the MDUC registers, for example because it performs multiplication and division operations. the default is to ignore the MDUC registers as this makes the interrupt handlers faster. the target option-mg13needs to be passed for this to work as this feature is only available on the G13 target (S2 core). the MDUC registers will only be saved if the interrupt handler performs a multiplication or division operation or it calls another function. conditional saving is so real of them ๐
๐ IBM RS/6000 and PowerPC Options ๐
these -m options are defined for the IBM RS/6000 and PowerPC:
-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 options to specify which instructions are available on the processor you are using. the default value of these options is determined when configuring GCC. specifying the -mcpu=cpu_type overrides the specification of these options. we recommend you use the -mcpu=cpu_type option rather than the options listed above. yes bestie, that's the official recommendation, we're not making it up ๐
specifying -mpowerpc-gpopt allows GCC to use the optional PowerPC architecture instructions in the General Purpose group, including floating-point square root. specifying -mpowerpc-gfxopt allows GCC to use the optional PowerPC architecture instructions in the Graphics group, including floating-point select.
-mmfcrfโ lets GCC emit the move from condition register field instruction ๐ that lives on the POWER4 processor and on every other processor rocking the PowerPC V2.01 architecture.-mpopcntbโ unlocks the popcount and double-precision FP reciprocal estimate instructions โจ, implemented on the POWER5 processor and other PowerPC V2.02 architecture girlies.-mpopcntdโ gives you the popcount instruction ๐งฎ, implemented on POWER7 and other processors that support the PowerPC V2.06 architecture.-mfprndโ emits the FP round to integer instructions ๐, implemented on POWER5+ and other PowerPC V2.03 architecture processors.-mcmpbโ emits the compare bytes instruction ๐ธ, implemented on POWER6 and other PowerPC V2.05 architecture processors.-mhard-dfpโ emits the decimal floating-point instructions ๐ implemented on some POWER processors.
The -mpowerpc64 option lets GCC generate the extra 64-bit instructions that live in the full PowerPC64 architecture, and treats 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 type cpu_type. ๐ ๏ธ
The supported values for cpu_type are:
401, 403, 405, 405fp, 440, 440fp, 464, 464fp, 476, 476fp, 505,
601, 602, 603, 603e, 604, 604e, 620, 630, 740, 7400, 7450, 750, 801,
821, 823, 860, 970, 8540, a2, e300c2, e300c3, e500mc, e500mc64,
e5500, e6500, ec603e, G3, G4, G5, titan, power3, power4, power5,
power5+, power6, power6x, power7, power8, power9, power10, powerpc,
powerpc64, powerpc64le, rs64, and native.
-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endianness, slay), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types respectively โ with an appropriate, generic processor model assumed for scheduling purposes. ๐ซ
Specifying native as the cpu type detects and selects the architecture option that matches the host processor of the system doing the compilation ๐. Heads up though: -mcpu=native has no effect if GCC doesn't recognize the processor. ๐
Every other option names 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
Which particular options get set for any particular CPU varies between compiler versions โ ๏ธ โ it depends on whatever setting seems to produce optimal code for that CPU, and it does not necessarily reflect the actual hardware's capabilities. So if you want to force an individual option to a particular value, just specify it after the -mcpu option, like -mcpu=970 -mno-altivec ๐โโ๏ธ.
On AIX, -maltivec and -mpowerpc64 are not enabled or disabled by the -mcpu option at present, because AIX doesn't have full support for these options. You can still flip them on or off individually if you're sure it'll work in your environment. ๐ซถ
-mtune=cpu_type โ sets the instruction scheduling parameters for machine type cpu_type, but does not set the architecture type or register usage the way-mcpu=cpu_type does. ๐ฏ Same values for cpu_type are used for-mtuneas for-mcpu. If you specify both, the code generated uses the architecture and registers set by-mcpu, but the scheduling parameters set by-mtune. iconic tbh โจ-mcmodel=smallโ generate PowerPC64 code for the small model: the TOC is limited to 64k. ๐-mcmodel=mediumโ generate 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โ generate 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โ generate code that uses (does not use) AltiVec instructions, and also enable 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โ generate VRSAVE instructions when generating AltiVec code. ๐-msecure-pltโ generate 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โ generate 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โ generate code that uses (does not use) vector/scalar (VSX) instructions, and also enable the use of built-in functions that allow more direct access to the VSX instruction set. โญ-mcrypto-mno-cryptoโ enable the use (disable) 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โ enable (disable) 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โ generate code that keeps (does not keep) some integer operations adjacent so that the instructions can be fused together on power8 and later processors. ๐ฅ-mpower8-vector-mno-power8-vectorโ generate code that uses (does not use) the vector and scalar instructions that were added in version 2.07 of the PowerPC ISA. Also enables the use of built-in functions that allow more direct access to the 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 use of 64-bit mode. โ ๏ธ-mquad-memory-atomic-mno-quad-memory-atomicโ generate code that uses (does not use) the atomic quad word memory instructions. And yep,-mquad-memory-atomicalso requires use of 64-bit mode. โ ๏ธ-mfloat128-mno-float128โ enable/disable the__float128keyword for IEEE 128-bit floating point, and use either software emulation for IEEE 128-bit floating point or hardware instructions. ๐
The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support. The IEEE 128-bit floating point is only supported on Linux. ๐ง
The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on other systems.
If you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ if you don't specify to generate ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ IEEE 128-bit floating point gets done with software emulation. ๐
-mfloat128-hardware-mno-float128-hardwareโ enable/disable using ISA 3.0 hardware instructions to support 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 (including GNU/Linux). 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, as for-mpowerpc64. ๐ช-mfull-toc-mno-fp-in-toc-mno-sum-in-toc-mminimal-tocโ modify generation of the TOC (Table Of Contents), which is created for every executable file. ๐
The -mfull-toc option is 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 places floating-point constants in the TOC. However โ only 16,384 entries are available in the TOC. ๐ฌ
If you get a linker error message saying you've overflowed the available TOC space, you can reduce the amount of TOC space used with the -mno-fp-in-toc and -mno-sum-in-toc options. -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 causes GCC to produce very slightly slower and larger code, at the expense of conserving TOC space. ๐
If you still run out of space in the TOC even when you specify both of those options, specify -mminimal-toc instead. This option causes GCC to make only one TOC entry for every file ๐. When you specify it, GCC produces code that is slower and larger but which uses extremely little TOC space. You may wish to use this option only on files that contain less frequently-executed code. ๐
-maix64โ bestie, this one turns on the 64-bit AIX ABI and calling convention: 64-bit pointers, a 64-bitlongtype, and all the infrastructure needed to support them. Slapping down-maix64implies-mpowerpc64. โจ-maix32โ and this one does the opposite ๐ it disables that 64-bit ABI and implies-mno-powerpc64. And heads up: GCC defaults to-maix32.-mxl-compatโ okay so this makes GCC produce code that conforms more closely to IBM XL compiler semantics when you're using the AIX-compatible ABI. What does that actually mean? Three things, no cap:- 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-bit
long doublevalue is properly rounded when comparing values and converting todouble. - Use XL symbol names for
long doublesupport routines.
-mno-xl-compatโ the off switch for the above, obviously ๐
ngl the lore here is kinda wild: the AIX calling convention was extended but not initially documented, to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared. IBM XL compilers access floating-point arguments that don't fit in the RSA from the stack when a subroutine is compiled without optimization. But 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 for the IBM RS/6000 SP Parallel Environment (PE) ๐ this links an application written to use message passing with special startup code so it 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 specify the appropriate directory location. And listen โ the Parallel Environment does not support threads, so-mpeand-pthreadare incompatible. pick a lane bestie ๐ญ
โจ alignment & float vibes โจ
-malign-naturalโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux, this overrides the ABI-defined alignment of larger types, like floating-point doubles, onto their natural size-based boundary. ๐ธ-malign-powerโ this one tells GCC to follow the ABI-specified alignment rules instead. And FYI, 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 there. periodt ๐
-msoft-floatโ generate code that does not use the floating-point register set. Software floating-point emulation is provided if you use this option, and โ important โ pass the option to GCC when linking too.-mhard-floatโ generate code that does use the floating-point register set. the classic โจ-mmultipleโ generate code that uses the load multiple word instructions and the store multiple word instructions. These are generated by default on POWER systems, and not generated on PowerPC systems.-mno-multipleโ the "don't do that" version.
๐จ do not use -mmultiple on 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. the more you know ๐
-mupdateโ generate code that uses the load or store instructions that update the base register to the address of the calculated memory location. These are generated by default.-mno-updateโ generate code that does not use them. But bestie, beware: if you use-mno-update, there is 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. ๐ญ-mavoid-indexed-addressesโ generate code that tries to avoid the use of indexed load or store instructions. These instructions can incur a performance penalty on Power6 processors in certain situations, such as when stepping through large arrays that cross a 16M boundary.-mno-avoid-indexed-addressesโ generate code that tries not to avoid them. This option is enabled by default when targeting Power6 and disabled otherwise.-mfused-maddโ generate code that uses the floating-point multiply and accumulate instructions. These are generated by default if hardware floating point is used.-mno-fused-maddโ generate code that does not use them. Also, tea โ: the machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. iconic crossover moment ๐-mmulhwโ generate code that uses the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These are generated by default when targeting those processors.-mno-mulhwโ generate code that does not use them.-mdlmzbโ generate code that uses the string-searchdlmzbinstruction on the IBM 405, 440, 464 and 476 processors. Generated by default when targeting those processors. โญ-mno-dlmzbโ you already know, it's the off switch ๐-mno-bit-alignโ on System V.4 and embedded PowerPC systems, do not force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.-mbit-alignโ do force them. Here's the visual, bestie: by default a structure containing nothing but 8unsignedbit-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. shrinkage ๐-mno-strict-alignโ on System V.4 and embedded PowerPC systems, do not assume that unaligned memory references are handled by the system.-mstrict-alignโ do assume that they are.
โจ relocation & endianness โจ
-mrelocatableโ generate code that allows 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.got2and 4-byte locations listed in the.fixupsection, a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with-mrelocatableor-mrelocatable-lib. Also,-mrelocatablecode aligns the stack to an 8-byte boundary.-mno-relocatableโ generate code that does not allow that. simple as ๐ธ-mrelocatable-libโ like-mrelocatable, this generates a.fixupsection to allow static executables to be relocated at run time, but-mrelocatable-libdoes not use the smaller stack alignment of-mrelocatable. Objects compiled with-mrelocatable-libmay be linked with objects compiled with any combination of the-mrelocatableoptions. ๐ซถ-mno-relocatable-libโ the "nah" version, obviously.-mno-tocโ on System V.4 and embedded PowerPC systems, do not assume that register 2 contains a pointer to a global area pointing to the addresses used in the program.-mtocโ do assume it. ๐-mlittleโ on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode.-mlittle-endianโ same thing, different name โจ the-mlittle-endianoption is the same as-mlittle.-mbigโ on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode.-mbig-endianโ and yes, the-mbig-endianoption is the same as-mbig. twins ๐-mdynamic-no-picโ on Darwin and Mac OS X systems, compile code so that it is not relocatable, but that its external references are relocatable. The resulting code is suitable for applications, but not shared libraries. โ ๏ธ-msingle-pic-baseโ treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function. The runtime system is responsible for initializing this register with an appropriate value before execution begins. no pressure runtime system ๐
โจ scheduling & NOPs โจ
-mprioritize-restricted-insns=priorityโ this option controls the priority that is assigned to dispatch-slot restricted instructions during the second scheduling pass. The argument priority takes the value0,1, or2to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions. โจ-msched-costly-dep=dependence_typeโ this option controls which dependences are considered costly by the target during instruction scheduling. The argument dependence_type takes one of the following values:noโ no dependence is costly.allโ all dependences are costly.true_store_to_loadโ a true dependence from store to load is costly.store_to_loadโ any dependence from store to load is costly.- number โ any dependence for which the latency is greater than or equal to number is costly.
-minsert-sched-nops=schemeโ this option controls which NOP insertion scheme is used during the second scheduling pass. The argument scheme takes one of the following values:noโ don't insert NOPs.padโ pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's grouping.regroup_exactโ insert NOPs to force costly dependent insns into separate groups. Insert exactly as many NOPs as needed to force an insn to a new group, according to the estimated processor grouping.- number โ insert NOPs to force costly dependent insns into separate groups. Insert number NOPs to force an insn to a new group.
โจ calling conventions โจ
-mcall-sysvโ on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement. This is the default unless you configured GCC usingpowerpc-*-eabiaix. ๐-mcall-sysv-eabiโ specify both-mcall-sysvand-meabioptions.-mcall-eabiโ yep, same as above ๐-mcall-sysv-noeabiโ specify both-mcall-sysvand-mno-eabioptions.-mcall-aixdescโ on System V.4 and embedded PowerPC systems, compile code for the AIX operating system. ๐ธ-mcall-linuxโ on System V.4 and embedded PowerPC systems, compile code for the Linux-based GNU system. ๐ง-mcall-freebsdโ on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system. ๐ฅ-mcall-netbsdโ on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system.-mcall-openbsdโ on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system. the whole family is here ๐ซถ-mtraceback=traceback_typeโ select the type of traceback table. Valid values for traceback_type arefull,part, andno. โญ-maix-struct-returnโ return all structures in memory (as specified by the AIX ABI).-msvr4-struct-returnโ return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI). โจ-mabi=abi-typeโ ok so this one extends the current ABI with one specific extension, or yeets an extension right back out ๐ . The valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX specifically:vec-extabi,vec-default.-mabi=ibmlongdoubleโ switches the current ABI to use IBM extended-precisionlong double. Heads up bestie: this is not likely to work if your system defaults to using IEEE extended-precisionlong double๐ญ. And if you change thelong doubletype away from IEEE extended-precision, the compiler will throw a warning at you unless you use the-Wno-psabioption. Also it requires-mlong-double-128to be enabled, periodt.-mabi=ieeelongdoubleโ switches the current ABI to use IEEE extended-precisionlong double. Same vibe check as above but flipped: this is not likely to work if your system defaults to IBM extended-precisionlong double๐. Change thelong doubletype away from IBM extended-precision and the compiler issues a warning unless you use-Wno-psabi. And yeah, it requires-mlong-double-128to be enabled too.-mabi=elfv1โ changes the current ABI to use the ELFv1 ABI. This is the default ABI for big-endian PowerPC 64-bit Linux โจ. But overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐. Like, spectacular.-mabi=elfv2โ changes the current ABI to use the ELFv2 ABI. This is the default ABI for little-endian PowerPC 64-bit Linux ๐ธ. And same warning as its sibling: overriding the default ABI needs special system support and is likely to fail in spectacular ways ๐.-mgnu-attribute,-mno-gnu-attributeโ emits.gnu_attributeassembly directives that set tag/value pairs in a.gnu.attributessection, which specify ABI variations in function parameters or return values. It's giving very metadata, very organized ๐.-mprototype,-mno-prototypeโ on System V.4 and embedded PowerPC systems, this assumes 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 bit 6 of the condition code register ("CR") to indicate whether floating-point values are passed in the floating-point registers, in case the function takes variable arguments ๐. With-mprototype, only calls to prototyped variable argument functions set or clear that bit.-msimโ on embedded PowerPC systems, assume the startup module is calledsim-crt0.oand that the standard C libraries arelibsim.aandlibc.a. This is the default forpowerpc-*-eabisimconfigurations โจ.-mmvmeโ on embedded PowerPC systems, assume 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. (the name is iconic, I don't make the rules ๐ )-mvxworksโ on System V.4 and embedded PowerPC systems, this specifies that you are compiling for a VxWorks system.-membโ on embedded PowerPC systems, sets 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) 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, and the-msdataoption can use both"r2"and"r13"to point to two separate small data areas. Picking-mno-eabimeans the stack is aligned to a 16-byte boundary, no EABI initialization function is called from"main", and the-msdataoption only uses"r13"to point to a single small data area. The-meabioption is on by default if you configured GCC using one of thepowerpc*-*-eabi*options.-msdata=eabiโ on System V.4 and embedded PowerPC systems, puts small initialized"const"global and static data in the.sdata2section, which is pointed to by register"r2". Puts small initialized non-"const"global and static data in the.sdatasection, pointed to by register"r13". Puts small uninitialized global and static data in the.sbsssection, which sits right next to the.sdatasection. Now listen: the-msdata=eabioption is incompatible with the-mrelocatableoption ๐ซ. And it also sets the-memboption.-msdata=sysvโ on System V.4 and embedded PowerPC systems, puts small global and static data in the.sdatasection, pointed to by register"r13". Puts small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. Also: the-msdata=sysvoption is incompatible with the-mrelocatableoption ๐ซ.-msdata=default,-msdataโ on System V.4 and embedded PowerPC systems: if-meabiis used, compile code the same as-msdata=eabi, otherwise compile code the same as-msdata=sysv. Choose-your-own-adventure but make it ABI โจ.-msdata=dataโ on System V.4 and embedded PowerPC systems, puts small global data in the.sdatasection. Puts small uninitialized global data in the.sbsssection. But do not use register"r13"to address small data, okay?? This is the default behavior unless other-msdataoptions are used.-msdata=none,-mno-sdataโ on embedded PowerPC systems, puts all initialized global and static data in the.datasection, and all uninitialized data in the.bsssection.-mreadonly-in-sdataโ puts read-only objects in the.sdatasection as well. This is the default ๐.-mblock-move-inline-limit=numโ inlines all block moves (like calls to"memcpy"or structure copies) that are less than or equal to num bytes. The minimum value for num is 32 bytes on 32-bit targets and 64 bytes on 64-bit targets. The default value is target-specific.-mblock-compare-inline-limit=numโ generates 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 is 0, all inline expansion (non-loop and loop) of block compare is disabled. The default value is target-specific.-mblock-compare-inline-loop-limit=numโ generates 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"is called to compare the rest of the block. The default value is target-specific.-mstring-compare-inline-limit=numโ compares at most num string bytes with inline code. If the difference or end of string isn't found at the end of the inline compare, a call to"strcmp"or"strncmp"will take care of the rest of the comparison. The default is 64 bytes.-G numโ on embedded PowerPC systems, puts global and static items less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS section. By default, num is 8. The-G numswitch is also passed to the linker, so heads up: all modules should be compiled with the same-G numvalue ๐.-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, do (or do not) emit register names in the assembly language output using symbolic forms.-mlongcall,-mno-longcallโ by default this assumes all calls are far away, so a longer and more expensive calling sequence is required. This is needed for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call gets generated if the compiler knows the call can't be that far away. This setting can be overridden by the"shortcall"function attribute, or by#pragma longcall(0).
Some linkers can detect out-of-range calls and generate glue code on the fly. On those systems, long calls are unnecessary and just generate slower code ๐ญ. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. It's planned to add this feature to the GNU linker for 32-bit PowerPC systems too.
On PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, GCC can generate long calls using an inline PLT call sequence (see -mpltseq). PowerPC with -mbss-plt and PowerPC64 ELFv1 (big-endian) do not support inline PLT calls.
On Darwin/PPC systems, "#pragma longcall" generates "jbsr callee, L42", plus a branch island (glue code). The 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 to the glue for every direct call, and the Darwin linker decides whether to use it or discard it.
In the future, GCC may ignore all longcall specifications when the linker is known to generate glue ๐.
-mpltseq,-mno-pltseqโ implement (or do not implement)-fno-pltand long calls using an inline PLT call sequence that supports lazy linking and long calls to functions in dlopen'd shared libraries. Inline PLT calls are only supported on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, and are 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. Heads up:-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together ๐ซ.-mtls-markers,-mno-tls-markersโ mark (or do not mark) calls to"__tls_get_addr"with a relocation specifying the function argument. The relocation lets the linker reliably associate the function call with the argument setup instructions for TLS optimization, which in turn lets GCC better schedule the sequence โจ๐ฅ.-mrecip,-mno-recipโ ok so this one turns on the reciprocal estimate and reciprocal square root estimate instructions, plus some extra Newton-Raphson steps to bump the precision, instead of doing a whole divide or square root + divide for floating-point args. ๐ bestie, you really wanna pair this with-ffast-mathwhen you use-mrecip(or at least-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math). and heads up: yeah the throughput of the sequence is generally higher than the non-reciprocal instruction, but the precision can drop by up to 2 ulp โ like, the inverse of1.0equals0.99999994๐ญ โ for reciprocal square roots.-mrecip=optโ this is the one that controls which reciprocal estimate instructions are allowed to show up.optis a comma-separated list of options, and any of them can be preceded by a!to invert it:allโ enable all estimate instructions. slay.defaultโ enable the default instructions, equivalent to-mrecip.noneโ disable all estimate instructions, equivalent to-mno-recip.divโ enable the reciprocal approximation instructions for both single and double precision.divfโ enable the single-precision reciprocal approximation instructions.divdโ enable the double-precision reciprocal approximation instructions.rsqrtโ enable the reciprocal square root approximation instructions for both single and double precision.rsqrtfโ enable the single-precision reciprocal square root approximation instructions.rsqrtdโ enable the double-precision reciprocal square root approximation instructions.
so 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. โจ
-mrecip-precision,-mno-recip-precisionโ assume (or do not assume ๐) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. picking-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precision. the double-precision square root estimate instructions are not generated by default on low-precision machines, since they don't provide an estimate that converges after three steps.-mveclibabi=typeโ specifies the ABI type to use for vectorizing intrinsics using an external library. the only type supported at present ismass, which says to use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using external libraries. GCC currently emits calls toacosd2,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, andtanhf4when generating code for power7. both-ftree-vectorizeand-funsafe-math-optimizationsmust also be enabled. the MASS libraries must be specified at link time.-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. thefrizinstruction does not return the same value if the floating-point number is too large to fit in an integer. ๐-mpointers-to-nested-functions,-mno-pointers-to-nested-functionsโ generate (or don't generate) code to load up the static chain register (r11) when calling through a pointer on AIX and 64-bit Linux systems where a function pointer points to a 3-word descriptor giving the function address, TOC value to be loaded in registerr2, and static chain value to be loaded in registerr11.-mpointers-to-nested-functionsis on by default. > real talk: 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... don't.-msave-toc-indirect,-mno-save-toc-indirectโ generate (or don't generate) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. if the TOC value isn't saved in the prologue, it's saved just before the call through the pointer.-mno-save-toc-indirectis the default.-mcompat-align-parm,-mno-compat-align-parmโ generate (or don't generate) code to pass structure parameters with a maximum alignment of 64 bits, for compatibility with older versions of GCC.
older versions of GCC (prior to 4.9.0) incorrectly did not align a structure parameter on a 128-bit boundary when that structure contained a member requiring 128-bit alignment. this is corrected in more recent versions of GCC. this option may be used to generate code that's compatible with functions compiled with older versions of GCC.
-mno-compat-align-parm 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 canary at guard. supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default with GNU libc version 2.4 or later).
with that second choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as 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. -mstack-protector-guard-symbol=symbol overrides the offset with a symbol reference to a canary in the TLS block. ๐ก๏ธ
-mpcrel,-mno-pcrelโ generate (or don't generate) pc-relative addressing.-mpcrelrequires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled.-mprefixed,-mno-prefixedโ generate (or don't generate) addressing modes using prefixed load and store instructions.-mprefixedrequires that the option-mcpu=power10(or later) is enabled.-mmma,-mno-mmaโ generate (or don't generate) the MMA instructions.-mmarequires that the option-mcpu=power10(or later) is enabled. (yes it's-mmmaup top and-mmadown here, that's not a typo, that's just the lore โจ)-mrop-protect,-mno-rop-protectโ generate (or don't generate) 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 ๐ธ
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-doubles option 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. ๐ณ no cap.
-mcpu=nameโ selects the type of RX CPU to be targeted. currently three types are supported: the generic RX600 and RX200 series hardware, and the specific RX610 CPU. the default is RX600.
the only difference between RX600 and RX610 is that the RX610 does not support the MVTIPL instruction.
the RX200 series does not have a hardware floating-point unit and so -nofpu is enabled by default when this type is selected.
-mbig-endian-data,-mlittle-endian-dataโ store data (but not code) in the big-endian format. the default is-mlittle-endian-data, i.e. to store data in the little-endian format.-msmall-data-limit=Nโ specifies the maximum size in bytes of global and static variables which can be placed into the small data area. using the small data area can lead to smaller and faster code, but the size of 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's 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. Ngl bestie, this feature is not enabled by default even with higher optimization levels (-O2 etc) because reserving a register can be genuinely detrimental. It's fully up to the programmer to experiment and discover whether this feature is of benefit to their program. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen. ๐
-msim,-mno-simโ Use the simulator runtime. The default is to use the libgloss board-specific runtime.-mas100-syntax,-mno-as100-syntaxโ When generating assembler output use a syntax that is compatible with Renesas's AS100 assembler. This syntax can also be handled by the GAS assembler, but it has some restrictions so it is not generated by default.-mmax-constant-size=Nโ Specifies the maximum size, in bytes, of a constant that can be used as an operand in a RX instruction. Like, the RX instruction set does allow constants of up to 4 bytes in length to be used in instructions, but a longer value equates to a longer instruction. So 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 between0and4. A value of1means that registerr13is reserved for the exclusive use of fast interrupt handlers. A value of2reservesr13andr12. A value of3reservesr13,r12andr11, and a value of4reservesr13throughr10. A value of0, 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.
Heads up tho โ using this feature reserves a register, usually r13, for the constant data base address. This can result in slower and/or larger code, especially in complicated functions. ๐ญ
The actual register chosen to hold the constant data base address depends upon whether the -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register r13 and proceeding downwards, registers are allocated first to satisfy the requirements of -mint-register, then -mpid and finally -msmall-data-limit. Thus it is possible for the small data area register to be r8 if both -mint-register=4 and -mpid are specified on the command line. Wild, ik.
By default this feature is not enabled. The default can be restored via the -mno-pid command-line option.
-mno-warn-multiple-fast-interrupts,-mwarn-multiple-fast-interruptsโ Prevents GCC from issuing a warning message if it finds more than one fast interrupt handler when it is compiling a file. The default is to issue a warning for each extra fast interrupt handler found, as the RX only supports one such interrupt. ๐-mallow-string-insns,-mno-allow-string-insnsโ Enables or disables the use of the string manipulation instructionsSMOVF,SCMPU,SMOVB,SMOVU,SUNTIL,SWHILEand also theRMPAinstruction. These instructions may prefetch data, which is not safe to do if accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more information).
The default is to allow these instructions, but it is not possible for GCC to reliably detect all circumstances where a string instruction might be used to access an I/O register, so their use cannot be disabled automatically. Instead it is reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space. ๐
When the instructions are enabled GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__, otherwise it defines the symbol __RX_DISALLOW_STRING_INSNS__.
-mjsr,-mno-jsrโ Use only (or not only)JSRinstructions to access functions. This option can be used when code size exceeds the range ofBSRinstructions. Note that-mno-jsrdoes not mean to not useJSRbut instead means that any type of branch may be used. ๐
Note: The generic GCC command-line option-ffixed-reghas special significance to the RX port when used with theinterruptfunction attribute. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registersr10,r11,r12and/orr13and only provided that the normal use of the corresponding registers have been restricted via the-ffixed-regor-mint-registercommand-line options.
๐ฆ S/390 and zSeries Options ๐ฆ
These are the -m options defined for the S/390 and zSeries architecture. Let's gooo. ๐
-mhard-float,-msoft-floatโ Use (do not use) the hardware floating-point instructions and registers for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. When-mhard-floatis specified, the compiler generates IEEE floating-point instructions. This is the default. โจ-mhard-dfp,-mno-hard-dfpโ Use (do not use) the hardware decimal-floating-point instructions for decimal-floating-point operations. When-mno-hard-dfpis specified, functions inlibgcc.aare used to perform decimal-floating-point operations. When-mhard-dfpis specified, the compiler generates decimal-floating-point hardware instructions. This is the default for-march=z9-ecor higher.-mlong-double-64,-mlong-double-128โ These switches control the size oflong doubletype. A size of 64 bits makes thelong doubletype equivalent to thedoubletype. This is the default.-mbackchain,-mno-backchainโ Store (do not store) the address of the caller's frame as backchain pointer into the callee's stack frame. A backchain may be needed to allow debugging using tools that do not understand DWARF call frame information. When-mno-packed-stackis in effect, the backchain pointer is stored at the bottom of the stack frame; when-mpacked-stackis in effect, the backchain is placed into the topmost word of the 96/160 byte register save area.
In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain; however, use of the backchain for debugging purposes usually requires that the whole binary is built with -mbackchain. 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 maintain the backchain.
-mpacked-stack,-mno-packed-stackโ Use (do not use) the packed stack layout. When-mno-packed-stackis specified, the compiler uses the all fields of the 96/160 byte 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 is reused for other purposes, allowing for more efficient use of the available stack space. However, when-mbackchainis also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain.
As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float.
The default is to not use the packed stack layout.
-msmall-exec,-mno-small-execโ Generate (or do not generate) code using thebrasinstruction to do subroutine calls. This only works reliably if the total executable size does not exceed 64k. The default is to use thebasrinstruction instead, which does not have this limitation. ๐ฅ-m64,-m31โ When-m31is specified, generate code compliant to the GNU/Linux for S/390 ABI. When-m64is specified, generate code compliant to the GNU/Linux for zSeries ABI. This allows GCC in particular to 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โ turn-mvxon and you're generating code with the instructions from the vector extension facility that showed up with the IBM z13 machine generation. Heads up bestie, this changes the ABI for some vector type values โ alignment and calling conventions, the whole thing. So if vector type values are chillin' in an ABI-relevant context, a GAS.gnu_attributecommand gets added to mark the resulting binary with the ABI it used.-mvxis enabled by default when you're using-march=z13. โจ-mzvector,-mno-zvectorโ this one unlocks vector language extensions and builtins using the instructions from that same vector extension facility from the IBM z13 machine generation. It adds support forvectorto be used as a keyword for defining vector type variables and arguments. But listen โvectoris only available when GNU extensions are enabled. It will not be expanded when you're 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. To actually use those builtins you need to include the header filevecintrin.h.-mzvectoris disabled by default. ๐-mmvcle,-mno-mvcleโ generate (or don't generate) code using themvcleinstruction to perform block moves. When-mno-mvcleis specified, amvcloop gets used instead. That's the default unless you're optimizing for size. ๐-mdebug,-mno-debugโ print (or don't print) extra debug info while compiling. Default is to not print debug info. No cap.-march=cpu-typeโ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. The possible values for cpu-type arez900/arch5,z990/arch6,z9-109,z9-ec/arch7,z10/arch8,z196/arch9,zEC12,z13/arch11,z14/arch12,z15/arch13,z16/arch14, andnative.
The default is -march=z900.
Specifying native as the cpu type can be used to select the best architecture option for the host processor. Note that -march=native has no effect if GCC does not recognize the processor. ๐ญ
-mtune=cpu-typeโ tune everything applicable about the generated code to cpu-type, 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) 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-traceso they point to specialized trace routines that give you the ability to selectively skip function trace entries for the TPF OS. This option is also 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's intended to identify functions that most probably cause a stack overflow, which makes it useful in an environment with limited stack size, e.g. the linux kernel. ๐ -mwarn-dynamicstackโ emit a warning if the function callsallocaor uses dynamically-sized arrays. Ngl, this is generally a bad idea when your stack size is limited. ๐ฌ-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, 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 help you debug stack overflow problems. The additionally emitted code causes only a little overhead, so it can also be used in production-like systems without greater performance degradation. The given values have to be exact powers of 2, and stack-size has to be greater than stack-guard without exceeding 64k. To be efficient, the extra code makes the assumption that the stack starts at an address aligned to the value given by stack-size. And the stack-guard option can only be used in conjunction with stack-size.- *
-mhotpatch=pre-halfwords*,post-halfwords โ if the hotpatch option is enabled, a "hot-patching" function prologue is generated for all functions in the compilation unit. The funtion label is prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label,2 * post-halfwordsbytes are appended, using the largest NOP like instructions the architecture allows (maximum 1000000).
If both arguments are zero, hotpatching is disabled.
This option can be overridden for individual functions with the "hotpatch" attribute. ๐
โจ SH Options โจ
These -m options are defined for the SH implementations, bestie:
-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 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โ generate code for SH4-200 in such a way that no double-precision floating-point operations are used.-m4-300โ generate code for SH4-300.-m4-300-nofpuโ generate code for SH4-300 in such a way that the floating-point unit is not used.-m4-300-singleโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-300-single-onlyโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-340โ generate code for SH4-340 (no MMU, no FPU).-m4-500โ generate code for SH4-500 (no FPU). 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โ generate code for the SH4a, in such a way that no double-precision floating-point operations are used.-m4a-singleโ generate code for the SH4a assuming the floating-point unit is in single-precision mode by default.-m4aโ generate code for the SH4a.-m4alโ same as-m4a-nofpu, except that it implicitly passes-dspto the assembler. GCC doesn't generate any DSP instructions at the moment. ๐ซถ-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. Careful though, this changes the calling conventions, and thus some functions from the standard C library do not work unless you recompile it first with-mdalign. ๐ญ-mrelaxโ shorten some address references at link time, when possible; uses the linker option-relax.-mbigtableโ use 32-bit offsets inswitchtables. The default is to use 16-bit offsets.-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,-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โ inlines the code that invalidates instruction cache entries after nested function trampolines get set up. But bestie, there's a catch: this option does nothing if-musermodeis in effect and the code generation option you picked (like-m4) doesn't let you use theicbiinstruction. And if your code generation option doesn't allowicbiwhile-musermodeis not in effect? Then the inlined code goes and messes with the instruction cache address array directly via an associative write. Which is giving "requires privileged mode at run time" energy โ and it also just fails if that cache line had been mapped via the TLB and has since become unmapped. ๐-misizeโ dumps instruction size and location straight into the assembly code. Receipts in the output, periodt.-mpadstructโ โ ๏ธ this one is deprecated. It pads structures out to multiples of 4 bytes, which is lowkey incompatible with the SH ABI. Not the vibe.-matomic-model=modelโ sets the model for atomic operations plus any extra parameters, all as a comma separated list. (For the deets on the atomic built-in functions themselves, go peek at__atomic Builtins.) Here's the full roster of models and parameters, no gatekeeping:noneโ disables compiler-generated atomic sequences entirely and emits library calls for atomic operations instead. This is the default when the target is notsh*-*-linux*.soft-gusaโ generates GNU/Linux-compatible gUSA software atomic sequences for the atomic built-in functions. Heads up: these sequences need extra support from the system's interrupt/exception handling code, and they're only suitable for SH3* and SH4* single-core systems. It's on by default when the target issh*-*-linux*and it's SH3* or SH4*. And if the target is SH4A, it also partially uses the hardware atomic instructionsmovli.landmovco.lto make more efficient code โ unless you specifystrict.soft-tcbโ generates software atomic sequences that use a variable in the thread control block. It's a variation of the gUSA sequences that also works on SH1* and SH2* targets. Same deal as before: these need extra support from the interrupt/exception handling code and are only suitable for single-core systems. When you use this model, you have to specify thegbr-offset=parameter too.soft-imaskโ generates software atomic sequences that temporarily disable interrupts by settingSR.IMASK = 1111. This model only works when the program runs in privileged mode, and it's only suitable for single-core systems. Good news: it doesn't need any extra support from the interrupt/exception handling code. It's the default when the target issh*-*-linux*and it's SH1* or SH2*.hard-llcsโ generates hardware atomic sequences usingmovli.landmovco.lonly. Only available on SH4A, and it's suitable for multi-core systems. Since those hardware instructions only support 32-bit atomic variable access, reading/writing 8- or 16-bit variables gets emulated with 32-bit accesses. Code compiled with this is also compatible with other software atomic model interrupt/exception handling systems when it runs on an SH4A system. This model needs no extra support from the system's interrupt/exception handling code.gbr-offset=โ this parameter sets the offset, in bytes, of the variable in the thread control block structure that the generated atomic sequences should use when you've selected thesoft-tcbmodel. For any other model, it's just ignored. The value has to be an integer multiple of four and land in the range 0-1020. Math checks out or it doesn't, bestie.strictโ this parameter stops you from mixing multiple atomic models, even compatible ones, and makes the compiler generate atomic sequences from the specified model only. No blending. Pick one. ๐
-mtasโ generates thetas.bopcode for__atomic_test_and_set. Quick PSA though: depending on your particular hardware and software config, this can degrade overall performance because of the operand cache line flushes thattas.bimplies. And on multi-core SH4A processors you've gotta usetas.bwith caution โ it can result in data corruption for certain cache configurations. Not the cute kind of chaos. ๐-mprefergotโ when generating position-independent code, emit function calls through the Global Offset Table instead of the Procedure Linkage Table.-musermode,-mno-usermodeโ don't allow (allow) the compiler to generate privileged mode code. Specifying-musermodealso implies-mno-inline-ic_invalidateif the inlined code wouldn't work in user mode.-musermodeis the default when the target issh*-*-linux*. And if the target is SH1* or SH2*,-musermodehas no effect, since there's no user mode to begin with. Mystery solved.-multcost=numberโ sets the cost to assume for a multiply insn.-mdiv=strategyโ sets the division strategy for integer division operations. strategy can be any of these:call-div1โ calls a library function that uses the single-step division instructiondiv1to do the thing. 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. If you specify this for targets that don't have a double precision FPU, it 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 doesn't trap. This is the default for SH4. Specifying this for targets without dynamic shift instructions defaults tocall-div1.
And if you never specified a division strategy? The default gets picked 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โ reserves space once for outgoing arguments in the function prologue instead of around each call. Generally a glow-up for both performance and size. Also needed for unwinding, so the stack frame doesn't change around conditional code.-mdivsi3_libfunc=nameโ sets 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 โ the compiler still expects the same sets of input/output/clobbered registers as if this option weren't there. Rename the vibe, not the contract.-mfixed-range=register-rangeโ generates code that treats the given register range as fixed registers. A fixed register is one the register allocator can't use โ super handy when you're compiling kernel code. A register range is two registers separated by a dash, and you can specify multiple ranges separated by a comma.-mbranch-cost=numโ assumes num is the cost for a branch instruction. Higher numbers make the compiler try to generate more branch-free code when it can. If you don't specify it, the value gets picked based on the processor type you're compiling for.-mzdcbranch,-mno-zdcbranchโ assume (don't assume) that the zero displacement conditional branch instructionsbtandbfare fast. If you specify-mzdcbranch, the compiler prefers zero displacement branch code sequences. It's enabled by default when generating code for SH4 and SH4A, and you can explicitly turn it off with-mno-zdcbranch.-mcbranch-force-delay-slotโ forces the usage of delay slots for conditional branches, which stuffs the delay slot with anopif no suitable instruction can be found. By default it's disabled. You can enable it to work around hardware bugs, like the ones found in the original SH7055. Bug workaround era. ๐ซถ-mfused-madd,-mno-fused-maddโ generate code that uses (doesn't use) the floating-point multiply and accumulate instructions. These get generated by default if hardware floating point is in use. The machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. Mapping era.-mfsca,-mno-fscaโ allow or disallow the compiler to emit thefscainstruction for sine and cosine approximations.-mfscamust be used together with-funsafe-math-optimizations. It's enabled by default when generating code for SH4A. And using-mno-fscadisables sine and cosine approximations even if-funsafe-math-optimizationsis in effect.-mfsrra,-mno-fsrraโ allow or disallow the compiler to emit thefsrrainstruction for reciprocal square root approximations.-mfsrramust be used together with-funsafe-math-optimizationsand-ffinite-math-only. It's enabled by default when generating code for SH4A. Using-mno-fsrradisables reciprocal square root approximations even if both-funsafe-math-optimizationsand-ffinite-math-onlyare in effect. Double-gated, bestie.-mpretend-cmoveโ prefers zero-displacement conditional branches for conditional move instruction patterns. This can result in faster code on the SH4 processor. โก-mfdpicโ generates code using the FDPIC ABI.
โ๏ธ Solaris 2 Options โ๏ธ
These -m options are the ones supported on Solaris 2, bestie:
-mclear-hwcapโ tells the compiler to remove the hardware capabilities generated by the Solaris assembler. You only need this when object files use ISA extensions that the current machine doesn't support, but they check at runtime whether or not to use them. Runtime vibe check, basically.-mimpure-textโ used in addition to-shared, this tells the compiler not to pass-z textto the linker when linking a shared object. With this option, you can link position-dependent code into a shared object. ๐-mimpure-textโ this one suppresses that "relocations remain against allocatable but non-writable sections" linker error message. Okay but bestie, listen: the relocations it needs trigger copy-on-write, so the shared object is not actually shared across processes. It's giving fake sharing ๐ญ. Instead of using-mimpure-text, you should compile all your source code with-fpicor-fPIC. Periodt.
Ok so these switches are supported in addition to the above on Solaris 2:
-pthreadsโ this is literally just a synonym for-pthread. Same energy, different spelling ๐
๐ธ SPARC Options โ๏ธ
These -m options are supported on the SPARC:
-mno-app-regs,-mapp-regsโ specify-mapp-regsand the compiler generates output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications. Just like global register 1, each global register 2 through 4 gets treated as an allocable register that gets clobbered by function calls. This is the default.
But if you wanna be fully SVR4 ABI-compliant and you're willing to eat some performance loss, specify -mno-app-regs. And fr fr, 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). That's the normal operating mode, nothing weird happening ๐ธ
-mfpu,-mhard-floatโ generate output containing floating-point instructions. This is the default. Slay โจ-mno-fpu,-msoft-floatโ generate output containing library calls for floating point.
โ ๏ธ Warning: the requisite libraries are not available for all SPARC targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. The embedded targetssparc-*-aoutandsparclite-*-*do provide software floating-point support.
Also important, -msoft-float changes the calling convention in the output file, so 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. No half measures, bestie ๐
-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. It's giving "we tried our best" ๐ญ
-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. Trade-offs, always trade-offs ๐
-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. Read the room before you use this one ๐-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. Vintage behaviour, iykyk ๐-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,leon3v7v8โsupersparc,hypersparc,leon,leon3,leon5sparcliteโf930,f934,sparclite86xsparcletโtsc701v9โultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7,m8
By default (unless configured otherwise), GCC generates code for the V7 variant of the SPARC architecture. With -mcpu=cypress, the compiler additionally optimizes it for the Cypress CY7C602 chip, as used in the SPARCStation/SPARCServer 3xx series. This is also appropriate for the older SPARCStation 1, 2, IPX etc.
With -mcpu=v8, GCC generates code for the V8 variant of the SPARC architecture. The only difference from V7 code is that the compiler emits the integer multiply and integer divide instructions which exist in SPARC-V8 but not in SPARC-V7. With -mcpu=supersparc, the compiler additionally optimizes it for the SuperSPARC chip, as used in the SPARCStation 10, 1000 and 2000 series.
With -mcpu=sparclite, GCC generates code for the SPARClite variant of the SPARC architecture. This adds the integer multiply, integer divide step and scan ("ffs") instructions which exist in SPARClite but not in SPARC-V7. With -mcpu=f930, the compiler additionally optimizes it for the Fujitsu MB86930 chip, which is the original SPARClite, with no FPU. With -mcpu=f934, the compiler additionally optimizes it for the Fujitsu MB86934 chip, which is the more recent SPARClite with FPU.
With -mcpu=sparclet, GCC generates code for the SPARClet variant of the SPARC architecture. This adds the integer multiply, multiply/accumulate, integer divide step and scan ("ffs") instructions which exist in SPARClet but not in SPARC-V7. With -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip.
With -mcpu=v9, GCC generates code for the V9 variant of the SPARC architecture. This adds 64-bit integer and floating-point move instructions, 3 additional floating-point condition code registers and conditional move instructions. With -mcpu=ultrasparc, the compiler additionally optimizes it for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, the compiler additionally optimizes it for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, the compiler additionally optimizes it for Sun UltraSPARC T1 chips. With -mcpu=niagara2, the compiler additionally optimizes it for Sun UltraSPARC T2 chips. With -mcpu=niagara3, the compiler additionally optimizes it for Sun UltraSPARC T3 chips. With -mcpu=niagara4, the compiler additionally optimizes it for Sun UltraSPARC T4 chips. With -mcpu=niagara7, the compiler additionally optimizes it for Oracle SPARC M7 chips. With -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips. So many chips, so little time ๐
-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 does.
The same values for -mcpu=cpu_type can be used for -mtune=cpu_type, but the only useful values are those that select a particular CPU implementation. Those are cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. With native Solaris and GNU/Linux toolchains, native can also be used.
-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. Lowkey iconic behaviour โจ-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. Combo deal ๐ซถ-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. It's giving inheritance, honestly ๐-mvis4,-mno-vis4โ turn on-mvis4and GCC will generate code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. The default is-mvis4when you're targeting a cpu that supports those instructions, likeniagara-7and later. Setting-mvis4also sets-mvis3,-mvis2and-mvis. ๐-mvis4b,-mno-vis4bโ with-mvis4b, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions, plus the additional VIS instructions introduced in the Oracle SPARC Architecture 2017. Default is-mvis4bwhen targeting a cpu that supports such instructions, likem8and 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, like 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, like 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. ๐-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, like 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, like 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). ๐ฉน-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. ๐ฉน
These -m options are supported in addition to the above on SPARC-V9 processors in 64-bit environments: ๐
-m32,-m64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. ๐ง-mcmodel=whichโ set the code model to one of:medlowโ the Medium/Low code model: 64-bit addresses, programs must be linked in the low 32 bits of memory. Programs can be statically or dynamically linked.medmidโ the Medium/Middle code model: 64-bit addresses, programs must be linked in the low 44 bits of memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.medanyโ the Medium/Anywhere code model: 64-bit addresses, programs may be linked anywhere in memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.embmedanyโ the Medium/Anywhere code model for embedded systems: 64-bit addresses, the text and data segments must be less than 2GB in size, both starting anywhere in memory (determined at link time). The global register%g4points to the base of the data segment. Programs are statically linked and PIC is not supported. ๐ซถ
-mmemory-model=mem-modelโ set the memory model in force on the processor to one of:defaultโ the default memory model for the processor and operating system.rmoโ Relaxed Memory Orderpsoโ Partial Store Ordertsoโ Total Store Orderscโ Sequential Consistency
These memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's "PSTATE.MM" field. ๐
-mstack-bias,-mno-stack-biasโ with-mstack-bias, GCC assumes that the stack pointer, and frame pointer if present, are offset by -2047 which 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: ๐
-Gโ create a shared object. It is recommended that-symbolicor-sharedbe used instead. ๐-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). ๐-YP,dirsโ search the directories dirs, and no others, for libraries specified with-l. ๐-Ym,dirโ look in the directory dir to find the M4 preprocessor. The assembler uses this option. ๐ ๏ธ
๐ V850 Options ๐
These -m options are defined for V850 implementations: ๐ฆ
-mlong-calls,-mno-long-callsโ treat all calls as being far away (near). If calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer. ๐-mno-ep,-mepโ do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into 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. ๐ค-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โ specify that the target processor is the V850E1. The preprocessor constants"__v850e1__"and"__v850e__"are defined if this option is used. ๐ป-mv850esโ specify that the target processor is the V850ES. This is an alias for the-mv850e1option. ๐ฏ-mv850eโ specify that the target processor is the V850E. The preprocessor constant"__v850e__"is defined if this option is used. ๐ป
If neither -mv850 nor -mv850e nor -mv850e1 nor -mv850e2 nor -mv850e2v3 nor -mv850e3v5 are defined then a default target processor is chosen and the relevant __v850*__ preprocessor constant is defined. ๐คท
The preprocessor constants "__v850" and "__v851__" are always defined, regardless of which processor variant is the target. ๐
-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. ๐ซ
This option is enabled by default when the RH850 ABI is in use (see -mrh850-abi), and disabled by default when the GCC ABI is in use. If "CALLT" instructions are being generated then the C preprocessor symbol "__V850_CALLT__" is defined. ๐ท๏ธ
-mrelax,-mno-relaxโ pass on (or do not pass on) the-mrelaxcommand-line option to the assembler. ๐-mlong-jumps,-mno-long-jumpsโ disable (or re-enable) the generation of PC-relative jump instructions. ๐ฆ-msoft-float,-mhard-floatโ disable (or re-enable) the generation of hardware floating point instructions. This 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. ๐
โ ๏ธ Heads up bestie โ -mloop is still experimental, so it's off by default for a reason. Don't come for me if it acts up. ๐
-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โ okay so this enables support for the old GCC version of the V850 ABI. With this version of the ABI, these 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 fordoubleandlong longtypes to be aligned on 8-byte boundaries. The default is to restrict the alignment of all objects to at most 4-bytes. When-m8byte-alignis in effect the C preprocessor symbol__V850_8BYTE_ALIGN__is defined. โจ-mbig-switchโ Generate code suitable for big switch tables. 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 (aobleqand 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.
-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_typewould.-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 frommain. 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 disablespragma 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-typeallows GCC to generate code that may not run at all on processors other than the one indicated. Specifying-march=cpu-typeimplies-mtune=cpu-type, except where noted otherwise.
The choices for cpu-type are:
nativeโ This selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines). Using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set.x86-64โ A generic CPU with 64-bit extensions.x86-64-v2,x86-64-v3,x86-64-v4โ These choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. On ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.
Since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. Specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value.
i386โ Original Intel i386 CPU.i486โ Intel i486 CPU. (No scheduling is implemented for this chip.)i586,pentiumโ Intel Pentium CPU with no MMX support.lakemontโ Intel Lakemont MCU, based on Intel Pentium CPU.pentium-mmxโ Intel Pentium MMX CPU, based on Pentium core with MMX instruction set support.pentiumproโ Intel Pentium Pro CPU.i686โ When used with-march, the Pentium Pro instruction set is used, so the code runs on all i686 family chips. When used 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โ 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โ 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โ 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โ Intel Haswell 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 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,XSAVESandSGXinstruction set support.bonnell๐ธ โ Intel Bonnell CPU with 64-bit extensions,MOVBE,MMX,SSE,SSE2,SSE3andSSSE3instruction set support.silvermont๐ฆ โ Intel Silvermont CPU with 64-bit extensions,MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,PCLMUL,PREFETCHWandRDRNDinstruction 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,CLFLUSHOPTandFSGSBASEinstruction set support.goldmont-plusโจ โ Intel Goldmont Plus 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,FSGSBASE,PTWRITE,RDPIDandSGXinstruction set support.tremont๐ซ โ Intel Tremont 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,FSGSBASE,PTWRITE,RDPID,SGX,CLWB,GFNI-SSE,MOVDIRI,MOVDIR64B,CLDEMOTEandWAITPKGinstruction set support.sierraforest๐ฒ โ Intel Sierra Forest 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,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKL,AVX-VNNI,AVXIFMA,AVXVNNIINT8,AVXNECONVERT,CMPCCXADD,ENQCMDandUINTRinstruction set support.grandridge๐๏ธ โ Intel Grand Ridge CPU 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,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.
lowkey the waysierraforestandgrandridgehave the exact same list and i still had to type it twice ๐ญ not me doing unpaid labour for a manpage
knl๐ โ Intel Knight's Landing 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,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1instruction set support.knm๐ โ Intel Knights Mill 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,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1,AVX5124VNNIW,AVX5124FMAPSandAVX512VPOPCNTDQinstruction 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,AVX512DQandAVX512CDinstruction set support.cannonlake๐ โ Intel Cannonlake 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,AVX512VL,AVX512BW,AVX512DQ,AVX512CD,PKU,AVX512VBMI,AVX512IFMAandSHAinstruction set support.icelake-client๐ง โ Intel Icelake Client 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,AVX512VL,AVX512BW,AVX512DQ,AVX512CD,PKU,AVX512VBMI,AVX512IFMA,SHA,AVX512VNNI,GFNI,VAES,AVX512VBMI2,VPCLMULQDQ,AVX512BITALG,RDPIDandAVX512VPOPCNTDQinstruction set support.icelake-server๐ง โ Intel Icelake 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,AVX512VL,AVX512BW,AVX512DQ,AVX512CD,PKU,AVX512VBMI,AVX512IFMA,SHA,AVX512VNNI,GFNI,VAES,AVX512VBMI2,VPCLMULQDQ,AVX512BITALG,RDPID,AVX512VPOPCNTDQ,PCONFIG,WBNOINVDandCLWBinstruction set support.cascadelake๐ โ Intel Cascadelake 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,AVX512CDandAVX512VNNIinstruction set support.cooperlake๐ โ Intel cooperlake 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,AVX512CD,AVX512VNNIandAVX512BF16instruction set support.tigerlake๐ฏ โ Intel Tigerlake 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,AVX512VL,AVX512BW,AVX512DQ,AVX512CDPKU,AVX512VBMI,AVX512IFMA,SHA,AVX512VNNI,GFNI,VAES,AVX512VBMI2,VPCLMULQDQ,AVX512BITALG,RDPID,AVX512VPOPCNTDQ,MOVDIRI,MOVDIR64B,CLWB,AVX512VP2INTERSECTandKEYLOCKERinstruction set support.
fr fr do not come for me aboutAVX512CDPKUup there โ that's exactly how the source has it, no comma, and i refuse to gaslight the manpage ๐
sapphirerapids๐ โ Intel sapphirerapids 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,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-FP16andAVX512BF16instruction set support.alderlake๐ โ Intel Alderlake 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,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKLandAVX-VNNIinstruction set support.rocketlake๐ โ Intel Rocketlake 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,AVX512F,AVX512VL,AVX512BW,AVX512DQ,AVX512CDPKU,AVX512VBMI,AVX512IFMA,SHA,AVX512VNNI,GFNI,VAES,AVX512VBMI2,VPCLMULQDQ,AVX512BITALG,RDPIDandAVX512VPOPCNTDQinstruction set support.graniterapids๐ชจ โ Intel graniterapids 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,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-FP16andPREFETCHIinstruction set support.graniterapids-d๐ชจ โ Intel graniterapids D 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,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,PREFETCHIandAMX-COMPLEXinstruction set support.
and now the AMD girlies get their moment ๐ because yes we stan a legacy king:
k6๐ซถ โ AMD K6 CPU withMMXinstruction set support.k6-2,k6-3๐ซถ โ Improved versions of AMD K6 CPU withMMXand3DNow!instruction set support.athlon,athlon-tbirdโ AMD Athlon CPU with MMX, 3dNOW!, enhanced 3DNow! and SSE prefetch instructions support. ๐athlon-4,athlon-xp,athlon-mpโ Improved AMD Athlon CPU with MMX, 3DNow!, enhanced 3DNow! and full SSE instruction set support. she's upgraded bestie โจ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 supersets MMX, SSE, SSE2, 3DNow!, enhanced 3DNow! and 64-bit instruction set extensions.)k8-sse3,opteron-sse3,athlon64-sse3โ Improved versions of AMD K8 cores with SSE3 instruction set support. ๐ฆamdfam10,barcelonaโ CPUs based on AMD Family 10h cores with x86-64 instruction set support. (This supersets MMX, SSE, SSE2, SSE3, SSE4A, 3DNow!, enhanced 3DNow!, ABM and 64-bit instruction set extensions.)bdver1โ CPUs based on AMD Family 15h cores with x86-64 instruction set support. (This supersets FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)bdver2โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)bdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)bdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, AVX2, XOP, LWP, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)znver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersets BMI, 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 supersets BMI, 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 supersets BMI, 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 supersets BMI, 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 and 64-bit instruction set extensions.) that list is LONG and she ate every single one ๐btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (This supersets MMX, SSE, SSE2, SSE3, SSSE3, SSE4A, CX16, ABM and 64-bit instruction set extensions.)btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includes MOVBE, F16C, BMI, AVX, PCLMUL, AES, SSE4.2, SSE4.1, CX16, ABM, SSE4A, SSSE3, SSE3, SSE2, SSE, MMX and 64-bit instruction set extensions.winchip-c6โ IDT WinChip C6 CPU, dealt in same way as i486 with additional MMX instruction set support. ๐ธwinchip2โ IDT WinChip 2 CPU, dealt in same way as i486 with additional MMX and 3DNow! instruction set support.c3โ VIA C3 CPU with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.)c3-2โ VIA C3-2 (Nehemiah/C5XL) CPU with MMX and SSE instruction set support. (No scheduling is implemented for this chip.)c7โ VIA C7 (Esther) CPU with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)samuel-2โ VIA Eden Samuel 2 CPU with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.)nehemiahโ VIA Eden Nehemiah CPU with MMX and SSE instruction set support. (No scheduling is implemented for this chip.)estherโ VIA Eden Esther CPU with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)eden-x2โ VIA Eden X2 CPU with x86-64, MMX, SSE, SSE2 and SSE3 instruction 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, AVX and AVX2 instruction set support. (No scheduling is implemented for this chip.)nanoโ Generic VIA Nano CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-1000โ VIA Nano 1xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-2000โ VIA Nano 2xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-3000โ VIA Nano 3xxx CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)nano-x2โ VIA Nano Dual Core CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)nano-x4โ VIA Nano Quad Core CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)lujiazuiโ ZHAOXIN lujiazui CPU with x86-64, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX, POPCNT, AES, PCLMUL, RDRND, XSAVE, XSAVEOPT, FSGSBASE, CX16, ABM, BMI, BMI2, F16C, FXSR, RDSEED instruction set support. โจgeodeโ AMD Geode embedded processor with MMX and 3DNow! instruction set support. ๐ซถ
-mtune=cpu-typeโ okay so this one tunes everything applicable about the generated code to cpu-type, except for the ABI and the set of available instructions. 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 use a-march=cpu-typeoption. For example, if GCC is configured fori686-pc-linux-gnuthen-mtune=pentium4generates code that is tuned for Pentium 4 but still runs on i686 machines. no cap, that's the whole vibe โ tuned, but still compatible ๐
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.
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 performs better on both Haswell and Silvermont, then you should use this option. Haswell and Silvermont besties, this one's for y'all ๐ฆ
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. โ ๏ธ she's old, she's retired, use-mtuneinstead bestie, periodt-mfpmath=unitโ Generate floating-point arithmetic for selected unit unit. The choices for unit are: ๐387โ okay so this is the standard 387 floating-point coprocessor that's present on the majority of chips and emulated otherwise. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, so you get 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.
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.
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,387,sse+387,bothโ 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. ๐
-masm=dialectโ output assembly instructions using selected dialect. Also affects which dialect is used for basicasmand extendedasm. Supported choices (in dialect order) areattorintel. The default isatt. Darwin does not supportintel. โจ-mieee-fp,-mno-ieee-fpโ control whether or not the compiler uses IEEE floating-point comparisons. These correctly handle the case where the result of a comparison is unordered. ๐ง-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.
-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.
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 thesin,cosandsqrtinstructions for the 387. Specify this option to avoid generating those instructions. This option is overridden when-marchindicates 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-optimizationsswitch. ๐ธ-malign-double,-mno-align-doubleโ control whether GCC alignsdouble,long double, andlong longvariables on a two-word boundary or a one-word boundary. Aligningdoublevariables on a two-word boundary produces code that runs somewhat faster on a Pentium at the expense of more memory.
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.
-m96bit-long-double,-m128bit-long-doubleโ these switches control the size oflong doubletype. The x86-32 application binary interface specifies the size to be 96 bits, so-m96bit-long-doubleis the default in 32-bit mode.
Modern architectures (Pentium and newer) prefer long double to be aligned to an 8- or 16-byte boundary. In arrays or structures conforming to the ABI, this 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.
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 oflong doubletype. A size of 64 bits makes thelong doubletype equivalent to thedoubletype. This is the default for 32-bit Bionic C library. A size of 128 bits makes thelong doubletype equivalent to the__float128type. This is the default for 64-bit Bionic C library.
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.
-malign-data=typeโ control how GCC aligns variables. Supported values for type arecompat, which uses increased alignment value compatible with GCC 4.8 and earlier;abi, which uses alignment value as specified by the psABI; andcacheline, which uses increased alignment value to match the cache line size.compatis the default. ๐-mlarge-data-threshold=thresholdโ when-mcmodel=mediumis specified, data objects larger than threshold are placed in the large data section. This value must be the same across all objects linked into the binary, and defaults to 65535. ๐ฅ-mrtdโ use a different function-calling convention, in which functions that take a fixed number of arguments return with theret numinstruction, which pops their arguments while returning. This saves one instruction in the caller since there is no need to pop the arguments there.
You can specify that an individual function is called with this calling sequence with the function attribute stdcall. You can also override the -mrtd option by using the function attribute cdecl.
Warning: this calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler. Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.)
-mregparm=numโ control how many registers are used to pass integer arguments. By default, no registers are used to pass arguments, and at most 3 registers can be used. You can control this behavior for a specific function by using the function attributeregparm.
Warning: if you use this switch, and num is nonzero, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules.
-msseregparmโ use SSE register passing conventions forfloatanddoublearguments and return values. You can control this behavior for a specific function by using the function attributesseregparm.
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.
-mvect8-ret-in-memโ return 8-byte vectors in memory instead of MMX registers. This is the default on VxWorks to match the ABI of the Sun Studio compilers until version 12. Only use this option if you need to remain compatible with existing code produced by those previous compiler versions or older versions of GCC. ๐-mpc32,-mpc64,-mpc80โ set 80387 floating-point precision to 32, 64 or 80 bits. When-mpc32is specified, the significands of results of floating-point operations are rounded to 24 bits (single precision);-mpc64rounds the significands of results of floating-point operations to 53 bits (double precision) and-mpc80rounds the significands of results of floating-point operations to 64 bits (extended double precision), which is the default. When this option is used, floating-point operations in higher precisions are not available to the programmer without setting the FPU control word explicitly. ๐
okay so real talk about rounding ๐ setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. but bestie, listen โ some mathematical libraries literally assume that extended-precision (80-bit) floating-point operations are enabled by default ๐ซถ routines in libraries like that could suffer significant loss of accuracy, typically through the so-called "catastrophic cancellation" ๐ญ, when this option is used to set the precision to less than extended precision. so like. know what you're doing, fr fr.
-mdaz-ftzโ the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in theMXCSRregister are used to control floating-point calculations โจ SSE and AVX instructions (including scalar and vector ones) 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โ realign 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, applicable to individual functions ๐-mpreferred-stack-boundary=num โ attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. if-mpreferred-stack-boundaryis not specified, the default is **4 (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 8 byte boundary. since x86-64 ABI require 16 byte stack alignment, this is ABI incompatible and intended to be used in controlled environment where stack space is important limitation ๐ฌ this option leads to wrong code when functions compiled with 16 byte stack alignment (such as functions from a standard library) are called with misaligned stack. in this 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 ๐ซ this includes the system libraries and startup modules.
- *
-mincoming-stack-boundary=num* โ assume the incoming stack is aligned to a 2 raised to num byte boundary. if-mincoming-stack-boundaryis not specified, the one specified by-mpreferred-stack-boundaryis used ๐
on Pentium and Pentium Pro, double and long double values should be aligned to an 8-byte boundary (see -malign-double) or suffer significant run time performance penalties ๐ on Pentium III, the Streaming SIMD Extension (SSE) data type __m128 may not work properly if it is not 16-byte aligned.
to ensure proper alignment of this 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 ๐ธ thus 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 is 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 is sensitive to stack space usage, such as embedded systems and operating system kernels, may want to reduce the preferred alignment to -mpreferred-stack-boundary=2 โจ
okay bestie, now the BIG one โ the extended instruction set switches ๐ all of these bad boys live together in one giant vibe check:
-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 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. (iykyk ๐)
-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 โ this option is used to do fine grain control of x86 code generation features โจ feature-list is a comma separated list of feature names. see also-mdump-tune-features. when specified, the feature is turned on if it is not preceded with^, otherwise, it is turned off.-mtune-ctrl=feature-list is 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 ๐-mno-defaultโ this option instructs GCC to turn off all tunable features. see also-mtune-ctrl=feature-list and-mdump-tune-features.-mcldโ this option instructs GCC to emit a"cld"instruction in the prologue of functions that use string instructions ๐ธ string instructions depend on the DF flag to select between autoincrement or autodecrement mode. while the ABI specifies the DF flag to be cleared on function entry, some operating systems violate this specification by not clearing the DF flag in their exception dispatchers ๐ญ the exception handler can be invoked with the DF flag set, which leads to 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. generation of"cld"instructions can be suppressed with the-mno-cldcompiler option in this case.-mvzeroupperโ this option instructs GCC to emit a"vzeroupper"instruction before a transfer of control flow out of the function to minimize the AVX to SSE transition penalty as well as remove unnecessary"zeroupper"intrinsics ๐ง-mprefer-avx128โ this option instructs GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer ๐ซ- *
-mprefer-vector-width=opt* โ this option instructs GCC to use opt-bit vector width in instructions instead of default on the selected platform. - *
-mmove-max=bits* โ this option instructs GCC to set the maximum number of bits can be moved from memory to memory efficiently to bits. the valid bits are128,256and512๐ - *
-mstore-max=bits* โ this option instructs GCC to set the maximum number of bits can be stored to memory efficiently to bits. the valid bits are128,256and512๐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โ this option enables GCC to generate"CMPXCHG16B"instructions in 64-bit code to implement compare-and-exchange operations on 16-byte aligned 128-bit objects ๐ฅ this is 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.-msahfโ this one turns on generation ofSAHFinstructions in 64-bit code. Okay so tea: early Intel Pentium 4 CPUs that had Intel 64 support, before the Pentium 4 G1 step showed up in December 2005, were missing theLAHFandSAHFinstructions that AMD64 supports. Those two are load and store instructions, respectively, for certain status flags. In 64-bit mode, theSAHFinstruction is used to optimize thefmod,drem, andremainderbuilt-in functions; see Other Builtins for the deets. ๐-mmovbeโ enables use of themovbeinstruction to implement__builtin_bswap32and__builtin_bswap64. cute little byte-swap glow-up โจ-mshstkโ the-mshstkoption enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). security era ๐-mcrc32โ enables built-in functions__builtin_ia32_crc32qi,__builtin_ia32_crc32hi,__builtin_ia32_crc32siand__builtin_ia32_crc32diso they generate thecrc32machine instruction. checksums but make it iconic ๐ฅ-mmwaitโ enables built-in functions__builtin_ia32_monitor, and__builtin_ia32_mwaitto generate themonitorandmwaitmachine instructions. bestie's just gonna sit here and wait ๐-mrecipโ enables use ofRCPSSandRSQRTSSinstructions (and their vectorized variantsRCPPSandRSQRTPS) with an extra Newton-Raphson step to bump precision, instead ofDIVSSandSQRTSS(and their vectorized variants) for single-precision floating-point arguments. These instructions only get generated when-funsafe-math-optimizationsis enabled together with-ffinite-math-onlyand-fno-trapping-math. Heads up though: 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 equals0.99999994). ๐ญ
Also 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.
And also note that GCC emits the above sequence with an 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 receipt, no cap ๐งพโจ
-mrecip=optโ this one 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. mix and match, main character energy ๐
-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 list is giving phonebook energy fr fr ๐ฎโ๐จ
-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 attributesms_abiandsysv_abi. pick ur fighter ๐ฅ-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. no shortcuts, we going the long way and it's precise ๐-mmanual-endbrโ insert ENDBR instruction at function entry only via thecf_checkfunction attribute. This is useful when used with the option-fcf-protection=branchto control ENDBR insertion at the function entry. you're the one holding the pen now ๐๏ธ-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. lowkey a glow-up for your switch statements ๐ก๏ธ-mcall-ms2sysv-xloguesโ 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. smaller functions, few extra instructions, that's the trade bestie ๐ค-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. bold choice, not always available ๐-mpush-args,-mno-push-argsโ use PUSH operations to store outgoing parameters. This method is shorter and usually equally fast as 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. on by default, but sometimes the off switch eats ๐-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 to 2. The drawback is a notable increase in code size. This switch implies-mno-push-args. speed demon but she's thicc ๐-mthreadsโ support thread-safe exception handling on MinGW. Programs that rely on thread-safe exception handling must compile and link all code with the-mthreadsoption. When compiling,-mthreadsdefines-D_MT; when linking, it links in a special thread helper library-lmingwthrdwhich cleans up per-thread exception-handling data. teamwork makes the dream work ๐ซถ-mms-bitfields,-mno-ms-bitfieldsโ enable/disable bit-field layout compatible with the native Microsoft Windows compiler.
If packed is used on a structure, or if bit-fields are used, it may be that the Microsoft ABI lays out the structure differently than the way GCC normally does. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
This option is enabled by default for Microsoft Windows targets. This behavior can also be controlled locally by use of variable or type attributes. For more information, see x86 Variable Attributes and x86 Type Attributes.
The Microsoft structure layout algorithm is fairly simple with the exception of the bit-field packing. The padding and alignment of members of structures and whether a bit-field can straddle a storage-unit boundary are determine 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
alignedattribute or thepackpragma), 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:
- 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,baris 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;
so for t2, bar lands at offset 2, not offset 1. that means t2 is 4 bytes big, periodt. and for t3? that zero-length bit-field does not touch the alignment of bar, and so it doesn't change the struct size either. slay.
okay bestie, given all that, here's the tea you actually need to remember:
- if a zero-length bit-field comes <em>after</em> a normal bit-field, the type of that zero-length bit-field can legitimately mess with the alignment of the whole struct. like,
t2is 4 bytes big because the zero-length bit-field follows a normal bit-field and it's typeshort. ๐ - even if a zero-length bit-field is <em>not</em> followed by a normal bit-field, it can still sway the struct's alignment:
struct
{
char foo : 6;
long : 0;
} t4;
here, t4 takes up 4 bytes. wild, i know.
- zero-length bit-fields that follow non-bit-field members? those get ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
here, t5 takes up 2 bytes. iconic.
-mno-align-stringopsโ do <em>not</em> align the destination of inlined string operations. this switch shrinks code size and actually speeds things up when the destination is already aligned but GCC has no idea about it. ๐-minline-all-stringopsโ by default GCC only inlines string ops when the destination is known to be aligned to at least a 4-byte boundary. this flips it on for everything: more inlining, bigger code, but maybe faster for code that lives on fastmemcpyandmemsetfor short lengths. bonus: it turns on inline expansion ofstrlenfor <em>all</em> pointer alignments. โจ-minline-stringops-dynamicallyโ for string ops of unknown size, it does run-time checks: inline code for small blocks, a library call for big ones. no cap.-mstringop-strategy=algโ overrides the internal decision heuristic for which algorithm gets used when inlining string ops. the allowed values for <em>alg</em> are:rep_byterep_4byterep_8byteโ expand using the i386repprefix of the specified size.byte_looploopunrolled_loopโ expand into an inline loop.libcallโ always use a library call.
-mmemcpy-strategy=strategyโ overrides the internal heuristic that decides whether__builtin_memcpyshould be inlined, and with which inline algorithm, when the expected size of the copy is known. <em>strategy</em> is a comma-separated list ofalg:max_size:dest_aligntriplets. <em>alg</em> is specified in-mstringop-strategy, <em>max_size</em> is the max byte size for which inline algorithm <em>alg</em> is allowed. for the last triplet, <em>max_size</em> has to be-1. and the <em>max_size</em> of the triplets in the list must go in increasing order. the minimal byte size for <em>alg</em> is 0 for the first triplet, andmax_size + 1of the preceding range after that.-mmemset-strategy=strategyโ same vibe as-mmemcpy-strategy=, except it controls__builtin_memsetexpansion instead. ๐-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. this skips the instructions that save, set up and restore frame pointers, and frees up an extra register in leaf functions. heads up:-fomit-leaf-frame-pointerdrops the frame pointer for leaf functions too, which might make debugging harder. ๐ญ-mtls-direct-seg-refs-mno-tls-direct-seg-refsโ controls whether TLS variables can be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer has to be added. whether that's even valid depends on your operating system and whether it maps the segment to cover the whole TLS area. for systems using the GNU C Library, the default is on.-msse2avx-mno-sse2avxโ tells the assembler to encode SSE instructions with a VEX prefix.-mavxturns this on by default. ๐ธ-mfentry-mno-fentryโ if profiling is active (-pg), put the profiling counter call <em>before</em> the prologue. note: on x86 architectures the attributems_hook_prologueisn't possible right now for-mfentryand-pg. ๐-mrecord-mcount-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection holding pointers to each profiling call. great for automatically patching and cutting out calls. ๐ฅ-mnop-mcount-mno-nop-mcountโ if profiling is active (-pg), generate the calls to the profiling functions as NOPs. useful when they're meant to be patched in later dynamically. honestly probably only useful together with-mrecord-mcount.-minstrument-return=typeโ instruments function exit in-pg -mfentryinstrumented functions with a call to the specified function. it only instruments <em>true</em> returns ending withret, not sibling calls ending withjump. valid <em>types</em> 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 is__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 what avoids unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or jump to a random location. GCC 4.4 or newer doesn't have those issues, regardless of the RAX register value. ๐ฑ
-m8bit-idiv-mno-8bit-idivโ on some processors, like Intel Atom, 8-bit unsigned integer divide is <em>way</em> faster than 32-bit/64-bit integer divide. this option generates a run-time check: if both dividend and divisor are within range of0to255, the 8-bit unsigned integer divide gets used instead of the 32-bit/64-bit one. ate. ๐-mavx256-split-unaligned-load-mavx256-split-unaligned-storeโ split 32-byte AVX unaligned load and store. ๐ฆ-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offsetโ generate stack protection code using the canary at <em>guard</em>. supported locations areglobalfor a global canary, ortlsfor a per-thread canary in the TLS block (that's the default). this option only does anything when-fstack-protectoror-fstack-protector-allis specified. with thetlschoice,-mstack-protector-guard-reg=regand-mstack-protector-guard-offset=offsetfurther specify which segment register (%fsor%gs) to use as the base register for reading the canary, and from what offset from that base register. the defaults for those are as specified in the relevant ABI. ๐-mgeneral-regs-onlyโ generate code that uses <em>only</em> the general-purpose registers. this stops the compiler from using floating-point, vector, mask and bound registers. no cap.-mrelax-cmpxchg-loopโ when emitting a compare-and-swap loop for__syncBuiltins and__atomicBuiltins that lack a native instruction, optimize for the highly contended case by issuing an atomic load before theCMPXCHGinstruction, and using thePAUSEinstruction to save CPU power when restarting the loop. ๐ง-mindirect-branch=choiceโ convert indirect call and jump with <em>choice</em>. the default iskeep, which leaves 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 by using the function attributeindirect_branch.
note that -mcmodel=large is incompatible with -mindirect-branch=thunk and -mindirect-branch=thunk-extern, since the thunk function may not be reachable in the large code model. ๐
note that -mindirect-branch=thunk-extern <em>is</em> compatible with -fcf-protection=branch, since the external thunk can be made to enable control-flow check. โจ
-mfunction-return=choiceโ convert function return with <em>choice</em>. the default iskeep, which leaves function return unmodified.thunkconverts function return to call and return thunk.thunk-inlineconverts function return to inlined call and return thunk.thunk-externconverts function return to external call and return thunk provided in a separate object file. you can control this behavior for a specific function by using the function attributefunction_return.
note that -mindirect-return=thunk-extern is compatible with -fcf-protection=branch, since 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, since the thunk function may not be reachable in the large code model. ๐ญ
-mindirect-branch-registerโ force indirect call and jump via register. ๐ฅ-mharden-sls=choiceโ generate code to mitigate against straight line speculation (SLS) with <em>choice</em>. the 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โ adds a CS prefix tocallandjmpto the indirect thunk when the branch target lives in ther8-r15registers ๐. The whole point is making thecallandjmpinstruction length exactly 6 bytes, so at run-time they can get swapped out forlfence; call *%r8-r15orlfence; jmp *%r8-r15. Length matters, bestie, it's giving precision ๐
These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments.
๐ x86-64 Environment & Code Model Options ๐
-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 for that it outputs the .code16gcc assembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode โจ
The -miamcu option generates code which conforms to Intel MCU psABI. It requires the -m32 option to be turned on.
-mno-red-zoneโ do not use a so-called "red zone" for x86-64 code ๐. The red zone is mandated by the x86-64 ABI; it's a 128-byte area beyond the location of the stack pointer that is not modified by signal or interrupt handlers, and therefore can be used for temporary data without adjusting the stack pointer. The flag-mno-red-zonedisables this red zone.-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-thresholdare put into large data or BSS sections and can be located above 2GB. Programs can be statically or dynamically linked.-mcmodel=largeโ generate code for the large model. This model makes no assumptions about addresses and sizes of sections ๐-maddress-mode=longโ generate code for long address mode. This is only supported for 64-bit and x32 environments. It is 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 is the default address mode for 32-bit and x32 environments.-mneeded,-mno-neededโ emitGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for Linux target to indicate the micro-architecture ISA level required to execute the binary ๐ง-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. Like, actually be careful here, bestie ๐ญ
-munroll-only-small-loopsโ controls conservative small loop unrolling. It is default enabled by O2, 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:
-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 thedllimportattribute 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 theUNICODEpreprocessor 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, as 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.datasection. This is necessary for older runtimes not supporting modification of.rdatasections 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 is enabled by default if GCC detects that the target assembler found during configuration supports the feature ๐
See also under x86 Options for standard options.
โก Xstormy16 Options โก
These options are defined for Xstormy16:
-msimโ choose startup files and linker script suitable for the simulator ๐
๐ฆ Xtensa Options ๐ฆ
These options are supported for Xtensa targets:
-mconst16,-mno-const16โ enable or disable use ofCONST16instructions for loading constant values. TheCONST16instruction is currently not a standard option from Tensilica. When enabled,CONST16instructions are always used in place of the standardL32Rinstructions. The use ofCONST16is enabled by default only if theL32Rinstruction is not available.-mfused-madd,-mno-fused-maddโ enable or disable use of fused multiply/add and multiply/subtract instructions in the floating-point option ๐. This has no effect if the floating-point option is not also enabled. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and add/subtract operations. This may be desirable in some cases where strict IEEE 754-compliant results are required: the fused multiply add/subtract instructions do not round the intermediate result, thereby producing results with more bits of precision than specified by the IEEE standard ๐ธ. Disabling fused multiply add/subtract instructions also ensures that the program output is not sensitive to the compiler's ability to combine multiply and add/subtract operations.-mserialize-volatile,-mno-serialize-volatileโ when this option is enabled, GCC insertsMEMWinstructions beforevolatilememory references to guarantee sequential consistency ๐ฅ. The default is-mserialize-volatile. Use-mno-serialize-volatileto omit theMEMWinstructions.-mforce-no-picโ for targets, like GNU/Linux, where all user-mode Xtensa code must be position-independent code (PIC), this option disables PIC for compiling kernel code ๐-mtext-section-literals,-mno-text-section-literalsโ these options control the treatment of literal pools ๐. The default is-mno-text-section-literals, which places literals in a separate section in the output file. This allows the literal pool to be placed in a data RAM/ROM, and it also allows the linker to combine literal pools from separate object files to remove redundant literals and improve code size โจ. With-mtext-section-literals, the literals are interspersed in the text section in order to keep them as close as possible to their references. This may be necessary for large assembly files. Literals for each function are placed right before that function.-mauto-litpools,-mno-auto-litpoolsโ these options control the treatment of literal pools ๐ฆ. The default is-mno-auto-litpools, which places literals in a separate section in the output file unless-mtext-section-literalsis used. With-mauto-litpoolsthe literals are interspersed in the text section by the assembler. Compiler does not produce explicit.literaldirectives and loads literals into registers withMOVIinstructions instead ofL32Rto let the assembler do relaxation and place literals as necessary ๐ . This option allows assembler to create several literal pools per function and assemble very big functions, which may not be possible with-mtext-section-literals.-mtarget-align,-mno-target-alignโ okay so when this is on, GCC tells the assembler to auto-align instructions, which cuts down branch penalties but costs you a lil code density, bestie. The assembler tries to widen density instructions so branch targets and the instructions right after call instructions line up nicely. But if there aren't enough preceding safe density instructions to align a target? No widening happens, periodt. The default is-mtarget-align. Also FYI these options don't touch auto-aligned instructions likeLOOPโ the assembler always aligns those, either by widening density instructions or by inserting NOP instructions. ๐-mlongcalls,-mno-longcallsโ when this one's enabled, GCC tells the assembler to turn direct calls into indirect calls, unless it can figure out that the target of a direct call is within the range the call instruction allows. This translation usually happens for calls to functions in other source files. Specifically, the assembler translates a directCALLinstruction into anL32Rfollowed by aCALLXinstruction. The default is-mno-longcalls. Use this in programs where the call target could potentially be out of range. Important tea though: this option lives in the assembler, not the compiler, so the assembly code GCC generates still shows direct call instructions โ go look at the disassembled object code to see the actual instructions. And note that the assembler uses an indirect call for every cross-file call, not just the ones that are actually out of range. ๐ญ-mabi=nameโ generate code for the ABI you name. The permissible values arecall0andwindowed. The default ABI gets chosen by the Xtensa core configuration. โจ-mabi=call0โ with this on, function parameters get 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โ with this on, function parameters get passed in registersa10througha15, and the called function rotates the register window by 8 registers on entry so that its arguments are found in registersa2througha7. Registera7may be used as a frame pointer. The register window gets rotated 8 registers back upon return. When this version of the ABI is enabled, the C preprocessor symbol__XTENSA_WINDOWED_ABI__is defined. ๐ฆ-mextra-l32r-costs=nโ specify an extra cost of instruction RAM/ROM access forL32Rinstructions, measured in clock cycles. This affects, when optimizing for speed, whether loading a constant from a literal pool usingL32Ror synthesizing the constant from a small one with a couple of arithmetic instructions. The default value is0. โญ
๐ zSeries Options ๐
These are listed under
โจ ENVIRONMENT โจ
okay bestie, this bit is all about the environment variables that change how GCC does its thing ๐
Some of them work by giving directories or prefixes to use when hunting for different kinds of files, and some are just here to set other aspects of the compilation environment. No cap.
Heads up: you can also tell GCC where to search with options like-B,-I, and-L. Those take precedence over places specified with environment variables, and environment variables in turn take precedence over whatever GCC was configured with. The order is iconic: options first, then env vars, then config. Periodt.
LANG / LC_CTYPE / LC_MESSAGES / LC_ALL
These cuties control how GCC uses localization info, so it can vibe with different national conventions ๐ GCC inspects the locale categories LC_CTYPE and LC_MESSAGES if it has been configured to do so. You can set those locale categories to any value your installation supports. A typical value is en_GB.UTF-8 for English in the United Kingdom encoded in UTF-8.
The LC_CTYPE environment variable specifies character classification. GCC uses it to determine the character boundaries in a string. This is needed for some multibyte encodings that contain quote and escape characters that are otherwise interpreted as a string end or escape. Literally so important.
The LC_MESSAGES environment variable specifies the language to use in diagnostic messages. So your compiler errors can speak your language, slay ๐
If the LC_ALL environment variable is set, it overrides the value of LC_CTYPE and LC_MESSAGES; otherwise, LC_CTYPE and LC_MESSAGES default to the value of the LANG environment variable. If none of these variables are set, GCC defaults to traditional C English behavior. Old school, but valid.
TMPDIR
If TMPDIR is set, it specifies the directory to use for temporary files. GCC uses temporary files to hold the output of one stage of compilation which is to be used as input to the next stage: for example, the output of the preprocessor, which is the input to the compiler proper. It's giving backstage pass energy ๐
GCC_COMPARE_DEBUG
Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. See the documentation of this option for more details. Nearly equivalent, bestie, not exactly โ read the docs for the full tea โ
GCC_EXEC_PREFIX
If GCC_EXEC_PREFIX is set, it specifies a prefix to use in the names of the subprograms executed by the compiler. No slash is added when this prefix is combined with the name of a subprogram, but you can specify a prefix that ends with a slash if you wish.
If GCC_EXEC_PREFIX is not set, GCC attempts to figure out an appropriate prefix to use based on the pathname it is invoked with.
If GCC cannot find the subprogram using the specified prefix, it tries looking in the usual places for the subprogram.
The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/ where prefix is the prefix to the installed compiler. In many cases prefix is the value of "prefix" when you ran the configure script.
Other prefixes specified with -B take precedence over this prefix.
This prefix is also used for finding files such as crt0.o that are used for linking.
In addition, the prefix is used in an unusual way in finding the directories to search for header files. For each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries replacing that beginning with the specified prefix to produce an alternate directory name. Thus, with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. If a standard directory begins with the configured prefix then the value of prefix is replaced by GCC_EXEC_PREFIX when looking for header files. She's complex but we love her ๐
COMPILER_PATH
The value of COMPILER_PATH is a colon-separated list of directories, much like PATH. GCC tries the directories thus specified when searching for subprograms, if it cannot find the subprograms using GCC_EXEC_PREFIX. So it's like a backup bestie list.
LIBRARY_PATH
The value of LIBRARY_PATH is a colon-separated list of directories, much like PATH. When configured as a native compiler, GCC tries the directories thus specified when searching for special linker files, if it cannot find them using GCC_EXEC_PREFIX. Linking using GCC also uses these directories when searching for ordinary libraries for the -l option (but directories specified with -L come first). -L stays winning, as she should ๐
LANG (yes, again ๐
)
This variable is used to pass locale information to the compiler. One way in which this information is used is to determine the character set to be used when character literals, string literals and comments are parsed in C and C++. When the compiler is configured to allow multibyte characters, the following values for LANG are recognized:
C-JIS
Recognize JIS characters.
C-SJIS
Recognize SJIS characters.
C-EUCJP
Recognize EUCJP characters.
If LANG is not defined, or if it has some other value, then the compiler uses "mblen" and "mbtowc" as defined by the default locale to recognize and translate multibyte characters. Default behavior coming through, no cap.
GCC_EXTRA_DIAGNOSTIC_OUTPUT
If GCC_EXTRA_DIAGNOSTIC_OUTPUT is set to one of the following values, then additional text will be emitted to stderr when fix-it hints are emitted. -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable. So those flags are the main characters here, fr fr.
fixits-v1
Emit parseable fix-it hints, equivalent to -fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.
fixits-v2
As "fixits-v1", but columns are expressed as display columns, as per -fdiagnostics-column-unit=display.
Some additional environment variables affect the behavior of the preprocessor. Preprocessor girlies, this one's for you ๐ซถ
CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH
Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.
The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include. Empty string, big power ๐
DEPENDENCIES_OUTPUT
If this variable is set, its value specifies how to output dependencies for Make based on the non-system header files processed by the compiler. System header files are ignored in the dependency output.
The value of DEPENDENCIES_OUTPUT can be just a file name, in which case the Make rules are written to that file, guessing the target name from the source file name. Or the value can have the form file target, in which case the rules are written to file 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 too. Combining options without even typing them? Iconic.
SUNPRO_DEPENDENCIES
This variable is the same as DEPENDENCIES_OUTPUT (see above), except that system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted. So close but not identical, bestie.
SOURCE_DATE_EPOCH
If this variable is set, its value specifies a UNIX timestamp to be used in replacement of the current date and time in the "__DATE__" and "__TIME__" macros, so that the embedded timestamps become reproducible. Reproducible builds are so valid ๐ฅ
The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00 represented in ASCII; 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 such as the last modification time of the source or package and it should be set by the build process. Don't just make up a number, bestie, set it properly ๐
๐ BUGS ๐
For instructions on reporting bugs, see <file:///usr/share/doc/gcc-13/README.Bugs>. Go snitch, but do it correctly ๐
๐ 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 are not necessary is innocuous.-sharedsuppresses the addition of startup code to alter the floating-point environment as done with-ffast-math,-Ofastor-funsafe-math-optimizationson some targets. Subtle defects? Not the vibe. Be careful ๐
๐ SEE ALSO ๐
gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1) and the Info entries for gcc, cpp, as, ld, binutils and gdb. The whole friend group, honestly ๐ซถ
โ๏ธ AUTHOR โ๏ธ
See the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC. Shoutout to the contributors, they ate ๐
ยฉ๏ธ COPYRIGHT ยฉ๏ธ
Copyright (c) 1988-2023 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page.
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.
and that's the whole manual, bestie ๐ this was gcc-13, dated 2024-09-04, from the GCC(1) page. mwah ๐ go compile something iconic, and remember: options first, env vars second, config third. periodt โจ
๐ฆ where this page comes from
- ubuntu noble: g++-13-mips64-linux-gnuabi64 13.3.0-6ubuntu2~24.04cross1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms