GCC(1)
๐ GCC(1) โ the GNU C and C++ compiler, but make it slay ๐
okay bestie, so like, this is the manual page for gcc, the GNU project C and C++ compiler. It's giving iconic compiler energy, no cap. Let's get into it. ๐ซถ
NAME
gcc - GNU project C and C++ compiler
SYNOPSIS
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Only the most useful options are listed here; see below for the remainder. g++ accepts mostly the same options as gcc.
DESCRIPTION
When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The "overall options" allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler.
Other options are passed on to one or more stages of processing. Some options control the preprocessor and others the compiler itself. Yet other options control the assembler and linker; most of these are not documented here, since you rarely need to use any of them.
Most of the command-line options that you can use with GCC are useful for C programs; when an option is only useful with another language (usually C++), the explanation says so explicitly. If the description for a particular option does not mention a source language, you can use that option with all supported languages.
The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead.
The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v.
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant.
Many options have long names starting with -f or with -W---for example, -fmove-loop-invariants, -Wformat and so on. Most of these have both positive and negative forms; the negative form of -ffoo is -fno-foo. This manual documents only one of these two forms, whichever one is not the default.
Some options take one or more arguments typically separated either by a space or by the equals sign (=) from the option name. Unless documented otherwise, an argument can be either numeric or a string. Numeric arguments must typically be small unsigned decimal or hexadecimal integers. Hexadecimal arguments must begin with the 0x prefix. Arguments to options that specify a size threshold of some sort may be arbitrarily large decimal or hexadecimal integers followed by a byte size suffix designating a multiple of bytes such as "kB" and "KiB" for kilobyte and kibibyte, respectively, "MB" and "MiB" for megabyte and mebibyte, "GB" and "GiB" for gigabyte and gigibyte, and so on. Such arguments are designated by byte-size in the following text. Refer to the NIST, IEC, and other relevant national and international standards for the full listing and explanation of the binary and decimal byte size prefixes.
OPTIONS
Option Summary
Here is a summary of all the options, grouped by type. Explanations are in the following sections.
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-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-fallow-parameterless-variadic-functions-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-fpermitted-flt-eval-methods=standard-fplan9-extensions-fsigned-bitfields-funsigned-bitfields-fsigned-char-funsigned-char-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-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-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-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|json]-fno-diagnostics-show-option-fno-diagnostics-show-caret-fno-diagnostics-show-labels-fno-diagnostics-show-line-numbers-fno-diagnostics-show-cwe-fdiagnostics-minimum-margin-width=width-fdiagnostics-parseable-fixits-fdiagnostics-generate-patch-fdiagnostics-show-template-tree-fno-elide-type-fdiagnostics-path-format=[none|separate-events|inline-events]-fdiagnostics-show-path-depths-fno-show-column-fdiagnostics-column-unit=[display|byte]-fdiagnostics-column-origin=origin-fdiagnostics-escape-format=[unicode|bytes]
โ ๏ธ Warning Options โ ๏ธ
okay bestie, deep breath, hydrate, sit up straight ๐ this is the warning fam in all its glory. every single one of them. we do not skip, we do not summarise, we do not play. if you were hoping I'd quietly drop the boring ones: no ma'am. not today. ๐ธ
here we go, in order, exactly as the page gives them:
-fsyntax-onlyโ just the syntax check, no extra anything ๐-fmax-errors=nโ caps it at n, everyone has a limit-Wpedanticโ the pedantic one. it said what it said-pedantic-errorsโ pedantic's dramatic sibling-wโ lowercase. tiny. suspicious. lowercase menace energy ๐-Wextraโ extra. just extra. as the name promises-Wallโ the big one, the main character ๐-Wabi=nโ abi with a value, iykyk-Waddressโ address, bestie-Wno-address-of-packed-memberโ the "no" version, and it's a long name, bless ๐ซถ-Waggregate-returnโ aggregates getting returned, apparently-Walloc-size-larger-than=byte-sizeโ takes a byte-size, very specific of it-Walloc-zeroโ alloc, zero-Wallocaโ allocaaaaaaaa-Walloca-larger-than=byte-sizeโ allocaaaaa but with a byte-size limit-Wno-aggressive-loop-optimizationsโ no aggressive loop optimizations, they're calming down-Warith-conversionโ arith conversion, arithmetic girlies rise ๐-Warray-boundsโ array bounds-Warray-bounds=nโ same but with an n-Warray-compareโ comparing arrays, we've all been there-Wno-attributesโ no attributes-Wattribute-alias=nโ attribute alias with an n-Wno-attribute-aliasโ the no version-Wno-attribute-warningโ no attribute warning-Wbidi-chars=[none|unpaired|any|ucn]โ bidi chars, and you get to pick: none, unpaired, any, or ucn โจ-Wbool-compareโ bool compare-Wbool-operationโ bool operation-Wno-builtin-declaration-mismatchโ no builtin declaration mismatch-Wno-builtin-macro-redefinedโ no builtin macro redefined-Wc90-c99-compatโ c90 to c99 compat, vintage behaviour-Wc99-c11-compatโ c99 to c11 compat-Wc11-c2x-compatโ c11 to c2x compat-Wc++-compatโ the C++ one, generically-Wc++11-compatโ c++11 compat-Wc++14-compatโ c++14 compat-Wc++17-compatโ c++17 compat-Wc++20-compatโ c++20 compat-Wno-c++11-extensionsโ no c++11 extensions-Wno-c++14-extensionsโ no c++14 extensions-Wno-c++17-extensionsโ no c++17 extensions-Wno-c++20-extensionsโ no c++20 extensions-Wno-c++23-extensionsโ no c++23 extensions-Wcast-alignโ cast align-Wcast-align=strictโ cast align but strict ๐ค-Wcast-function-typeโ cast function type-Wcast-qualโ cast qual-Wchar-subscriptsโ char subscripts-Wclobberedโ clobbered ๐-Wcommentโ comment-Wconversionโ conversion-Wno-coverage-mismatchโ no coverage mismatch-Wno-cppโ no cpp-Wdangling-elseโ dangling else, hanging there dramatically-Wdangling-pointerโ dangling pointer-Wdangling-pointer=nโ dangling pointer, with an n-Wdate-timeโ date time, timestamps in your feelings-Wno-deprecatedโ no deprecated-Wno-deprecated-declarationsโ no deprecated declarations-Wno-designated-initโ no designated init-Wdisabled-optimizationโ disabled optimization-Wno-discarded-array-qualifiersโ no discarded array qualifiers-Wno-discarded-qualifiersโ no discarded qualifiers-Wno-div-by-zeroโ no div by zero, very reasonable of it-Wdouble-promotionโ double promotion, get that bag ๐-Wduplicated-branchesโ duplicated branches, twinning fr-Wduplicated-condโ duplicated cond-Wempty-bodyโ empty body-Wno-endif-labelsโ no endif labels-Wenum-compareโ enum compare-Wenum-conversionโ enum conversion-Werrorโ oh she's serious ๐ญ-Werror=*โ error, wildcard edition, star of the show โญ-Wexpansion-to-definedโ expansion to defined-Wfatal-errorsโ FATAL. dramatic. love that for it ๐ฅ-Wfloat-conversionโ float conversion-Wfloat-equalโ float equal-Wformatโ format-Wformat=2โ format, level 2, we're levelling up-Wno-format-contains-nulโ no format contains nul-Wno-format-extra-argsโ no format extra args-Wformat-nonliteralโ format nonliteral-Wformat-overflow=nโ format overflow with an n-Wformat-securityโ format security ๐ก๏ธ-Wformat-signednessโ format signedness-Wformat-truncation=nโ format truncation with an n-Wformat-y2kโ format y2k, girl is nostalgic ๐ฆ-Wframe-addressโ frame address-Wframe-larger-than=byte-sizeโ frame larger than a byte-size-Wno-free-nonheap-objectโ no free nonheap object-Wno-if-not-alignedโ no if not aligned-Wno-ignored-attributesโ no ignored attributes-Wignored-qualifiersโ ignored qualifiers ๐-Wno-incompatible-pointer-typesโ no incompatible pointer types-Wimplicitโ implicit-Wimplicit-fallthroughโ implicit fallthrough-Wimplicit-fallthrough=nโ implicit fallthrough with an n-Wno-implicit-function-declarationโ no implicit function declaration-Wno-implicit-intโ no implicit int-Winfinite-recursionโ infinite recursion, going in circles bestie ๐-Winit-selfโ init self-Winlineโ inline-Wno-int-conversionโ no int conversion-Wint-in-bool-contextโ int in bool context-Wno-int-to-pointer-castโ no int to pointer cast-Wno-invalid-memory-modelโ no invalid memory model-Winvalid-pchโ invalid pch-Wjump-misses-initโ jump misses init-Wlarger-than=byte-sizeโ larger than a byte-size-Wlogical-not-parenthesesโ logical not parentheses-Wlogical-opโ logical op-Wlong-longโ long long, the name is a whole vibe ๐-Wno-lto-type-mismatchโ no lto type mismatch-Wmainโ main. the main character ๐-Wmaybe-uninitializedโ maybe uninitialized, the uncertainty is the point-Wmemset-elt-sizeโ memset elt size-Wmemset-transposed-argsโ memset transposed args-Wmisleading-indentationโ misleading indentation, gaslighting your eyes ๐-Wmissing-attributesโ missing attributes-Wmissing-bracesโ missing braces-Wmissing-field-initializersโ missing field initializers-Wmissing-format-attributeโ missing format attribute-Wmissing-include-dirsโ missing include dirs-Wmissing-noreturnโ missing noreturn-Wno-missing-profileโ no missing profile-Wno-multicharโ no multichar-Wmultistatement-macrosโ multistatement macros-Wnonnullโ nonnull-Wnonnull-compareโ nonnull compare-Wnormalized=[none|id|nfc|nfkc]โ normalized, and you choose: none, id, nfc, or nfkc โจ-Wnull-dereferenceโ null dereference-Wno-odrโ no odr-Wopenacc-parallelismโ openacc parallelism-Wopenmp-simdโ openmp simd-Wno-overflowโ no overflow-Woverlength-stringsโ overlength strings, she's long ๐ธ-Wno-override-init-side-effectsโ no override init side effects-Wpackedโ packed-Wno-packed-bitfield-compatโ no packed bitfield compat-Wpacked-not-alignedโ packed not aligned-Wpaddedโ padded-Wparenthesesโ parentheses, use them bestie-Wno-pedantic-ms-formatโ no pedantic ms format-Wpointer-arithโ pointer arith-Wno-pointer-compareโ no pointer compare-Wno-pointer-to-int-castโ no pointer to int cast-Wno-pragmasโ no pragmas-Wno-prio-ctor-dtorโ no prio ctor dtor-Wredundant-declsโ redundant decls, saying it twice ๐-Wrestrictโ restrict-Wno-return-local-addrโ no return local addr-Wreturn-typeโ return type-Wno-scalar-storage-orderโ no scalar storage order-Wsequence-pointโ sequence point-Wshadowโ shadow ๐ค-Wshadow=globalโ shadow but global-Wshadow=localโ shadow but local-Wshadow=compatible-localโ shadow but compatible-local-Wno-shadow-ivarโ no shadow ivar-Wno-shift-count-negativeโ no shift count negative-Wno-shift-count-overflowโ no shift count overflow-Wshift-negative-valueโ shift negative value-Wno-shift-overflowโ no shift overflow-Wshift-overflow=nโ shift overflow with an n-Wsign-compareโ sign compare-Wsign-conversionโ sign conversion-Wno-sizeof-array-argumentโ no sizeof array argument-Wsizeof-array-divโ sizeof array div-Wsizeof-pointer-divโ sizeof pointer div-Wsizeof-pointer-memaccessโ sizeof pointer memaccess-Wstack-protectorโ stack protector ๐ก๏ธ-Wstack-usage=byte-sizeโ stack usage, in byte-size-Wstrict-aliasingโ strict aliasing-Wstrict-aliasing=nโ strict aliasing with an n-Wstrict-overflowโ strict overflow-Wstrict-overflow=nโ strict overflow with an n-Wstring-compareโ string compare-Wno-stringop-overflowโ no stringop overflow-Wno-stringop-overreadโ no stringop overread-Wno-stringop-truncationโ no stringop truncation-Wsuggest-attribute=[pure|const|noreturn|format|malloc]โ suggests an attribute, and you pick from pure, const, noreturn, format, or malloc ๐-Wswitchโ switch-Wno-switch-boolโ no switch bool-Wswitch-defaultโ switch default-Wswitch-enumโ switch enum-Wno-switch-outside-rangeโ no switch outside range-Wno-switch-unreachableโ no switch unreachable-Wsync-nandโ sync nand-Wsystem-headersโ system headers-Wtautological-compareโ tautological compare, saying nothing with confidence ๐ญ-Wtrampolinesโ trampolines, bouncy ๐-Wtrigraphsโ trigraphs, ancient lore-Wtrivial-auto-var-initโ trivial auto var init-Wtsanโ tsan-Wtype-limitsโ type limits-Wundefโ undef-Wuninitializedโ uninitialized-Wunknown-pragmasโ unknown pragmas-Wunsuffixed-float-constantsโ unsuffixed float constants-Wunusedโ unused, the classic ๐-Wunused-but-set-parameterโ unused but set parameter-Wunused-but-set-variableโ unused but set variable-Wunused-const-variableโ unused const variable-Wunused-const-variable=nโ unused const variable with an n-Wunused-functionโ unused function-Wunused-labelโ unused label-Wunused-local-typedefsโ unused local typedefs-Wunused-macrosโ unused macros-Wunused-parameterโ unused parameter-Wno-unused-resultโ no unused result-Wunused-valueโ unused value-Wunused-variableโ unused variable-Wno-varargsโ no varargs-Wvariadic-macrosโ variadic macros-Wvector-operation-performanceโ vector operation performance, go off ๐-Wvlaโ vla-Wvla-larger-than=byte-sizeโ vla larger than a byte-size-Wno-vla-larger-thanโ no vla larger than-Wvolatile-register-varโ volatile register var-Wwrite-stringsโ write strings-Wzero-length-boundsโ zero length bounds
that's the whole roster, bestie. every last one. I told you we don't skip ๐
๐ Static Analyzer Options ๐
now THIS is the detective era ๐ต๏ธโโ๏ธโจ the static analyzer options. it's giving "I already know what you did". here's every single one:
-fanalyzerโ the analyzer itself, main character ๐-fanalyzer-call-summariesโ call summaries-fanalyzer-checker=nameโ pick your checker by name-fno-analyzer-feasibilityโ no analyzer feasibility-fanalyzer-fine-grainedโ fine grained, detail girlie ๐-fno-analyzer-state-mergeโ no analyzer state merge-fno-analyzer-state-purgeโ no analyzer state purge-fanalyzer-transitivityโ transitivity-fanalyzer-verbose-edgesโ verbose edges, talkative ๐ฃ๏ธ-fanalyzer-verbose-state-changesโ verbose state changes-fanalyzer-verbosity=levelโ verbosity, set your level-fdump-analyzerโ dump analyzer-fdump-analyzer-callgraphโ dump analyzer callgraph-fdump-analyzer-exploded-graphโ dump analyzer exploded graph ๐ฅ-fdump-analyzer-exploded-nodesโ dump analyzer exploded nodes-fdump-analyzer-exploded-nodes-2โ same but 2-fdump-analyzer-exploded-nodes-3โ same but 3, they really went there-fdump-analyzer-exploded-pathsโ dump analyzer exploded paths-fdump-analyzer-feasibilityโ dump analyzer feasibility-fdump-analyzer-jsonโ dump analyzer json ๐งพ-fdump-analyzer-state-purgeโ dump analyzer state purge-fdump-analyzer-stderrโ dump analyzer stderr-fdump-analyzer-supergraphโ dump analyzer supergraph, super indeed โญ-fdump-analyzer-untrackedโ dump analyzer untracked-Wno-analyzer-double-fcloseโ no analyzer double fclose-Wno-analyzer-double-freeโ no analyzer double free-Wno-analyzer-exposure-through-output-fileโ no analyzer exposure through output file-Wno-analyzer-file-leakโ no analyzer file leak-Wno-analyzer-free-of-non-heapโ no analyzer free of non-heap-Wno-analyzer-malloc-leakโ no analyzer malloc leak-Wno-analyzer-mismatching-deallocationโ no analyzer mismatching deallocation-Wno-analyzer-null-argumentโ no analyzer null argument-Wno-analyzer-null-dereferenceโ no analyzer null dereference-Wno-analyzer-possible-null-argumentโ no analyzer possible null argument-Wno-analyzer-possible-null-dereferenceโ no analyzer possible null dereference-Wno-analyzer-shift-count-negativeโ no analyzer shift count negative-Wno-analyzer-shift-count-overflowโ no analyzer shift count overflow-Wno-analyzer-stale-setjmp-bufferโ no analyzer stale setjmp buffer-Wno-analyzer-tainted-allocation-sizeโ no analyzer tainted allocation size-Wno-analyzer-tainted-array-indexโ no analyzer tainted array index-Wno-analyzer-tainted-divisorโ no analyzer tainted divisor-Wno-analyzer-tainted-offsetโ no analyzer tainted offset-Wno-analyzer-tainted-sizeโ no analyzer tainted size-Wanalyzer-too-complexโ analyzer too complex, relatable ๐ญ-Wno-analyzer-unsafe-call-within-signal-handlerโ no analyzer unsafe call within signal handler-Wno-analyzer-use-after-freeโ no analyzer use after free-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ no analyzer use of pointer in stale stack frame-Wno-analyzer-use-of-uninitialized-valueโ no analyzer use of uninitialized value-Wno-analyzer-write-to-constโ no analyzer write to const-Wno-analyzer-write-to-string-literalโ no analyzer write to string literal
๐ C and Objective-C-only Warning Options ๐
these ones are for the C and Objective-C girlies specifically, no gatekeeping, just vibes:
-Wbad-function-castโ bad function cast, we've all been bad ๐-Wmissing-declarationsโ missing declarations-Wmissing-parameter-typeโ missing parameter type-Wmissing-prototypesโ missing prototypes-Wnested-externsโ nested externs, nesting doll energy ๐ช-Wold-style-declarationโ old style declaration, vintage โจ-Wold-style-definitionโ old style definition-Wstrict-prototypesโ strict prototypes-Wtraditionalโ traditional, retro ๐-Wtraditional-conversionโ traditional conversion-Wdeclaration-after-statementโ declaration after statement-Wpointer-signโ pointer sign
๐ Debugging Options ๐
and now, the -g cinematic universe ๐ฌโจ all your debugging options, in order, no crumbs left:
-gโ the icon. the blueprint. the moment ๐-glevelโ g but with a level-gdwarfโ gdwarf-gdwarf-versionโ gdwarf with a version-gbtfโ gbtf-gctfโ gctf-gctflevelโ gctf with a level-ggdbโ ggdb, for the gdb besties ๐-grecord-gcc-switchesโ record gcc switches, receipts kept ๐งพ-gno-record-gcc-switchesโ no record gcc switches-gstabsโ gstabs-gstabs+โ gstabs but with a plus, extra โจ-gstrict-dwarfโ strict dwarf-gno-strict-dwarfโ no strict dwarf-gas-loc-supportโ gas loc support-gno-as-loc-supportโ no as loc support-gas-locview-supportโ gas locview support-gno-as-locview-supportโ no as locview support-gcolumn-infoโ column info-gno-column-infoโ no column info-gdwarf32โ dwarf32-gdwarf64โ dwarf64-gstatement-frontiersโ statement frontiers, exploring new lands ๐บ๏ธ-gno-statement-frontiersโ no statement frontiers-gvariable-location-viewsโ variable location views-gno-variable-location-viewsโ no variable location views-ginternal-reset-location-viewsโ internal reset location views-gno-internal-reset-location-viewsโ no internal reset location views-ginline-pointsโ inline points-gno-inline-pointsโ no inline points-gvmsโ gvms-gxcoffโ gxcoff-gxcoff+โ gxcoff with a plus, again extra-gz[=type]โ gz, with an optional type-gsplit-dwarfโ split dwarf, dividing the kingdom ๐ฆ-gdescribe-diesโ describe dies-gno-describe-diesโ no describe dies-fdebug-prefix-map=old=newโ maps old to new, remix era ๐ง-fdebug-types-sectionโ debug types section-fno-eliminate-unused-debug-typesโ no eliminate unused debug types-femit-struct-debug-baseonlyโ emit struct debug baseonly-femit-struct-debug-reducedโ emit struct debug reduced-femit-struct-debug-detailed[=spec-list]โ emit struct debug detailed, with an optional spec-list-fno-eliminate-unused-debug-symbolsโ no eliminate unused debug symbols-femit-class-debug-alwaysโ emit class debug always, always always ๐-fno-merge-debug-stringsโ no merge debug strings-fno-dwarf2-cfi-asmโ no dwarf2 cfi asm-fvar-trackingโ var tracking, she's watching ๐-fvar-tracking-assignmentsโ var tracking assignments
๐ฅ Optimization Options ๐ฅ
okay so this is the full optimization lineup โ every single flag in this family, written out exactly as it lives, nothing merged, nothing skipped, nothing "and the rest"-ed. It's the menu, bestie. Read it like a menu. ๐
-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 that's every last one of them, bestie. no "etc.", no "and friends", no sneaky "โฆ". fr fr. ๐ซถ
๐งช Program Instrumentation Options ๐งช
next up: the instrumentation crew. every flag here, in order, exactly as written โ no vibe checks skipped, no options ghosted. ๐
-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-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-exclude-function-list=sym,sym,...-finstrument-functions-exclude-file-list=file,file,...-fprofile-prefix-map=old=new
obsessed with how thorough this list is. nothing cut. ๐
๐ Preprocessor Options ๐
the preprocessor era โจ โ macros, includes, charsets, the whole crew. every single one, verbatim, in order. no skipping, iykyk. ๐ฆ
-Aquestion=answer-A-question[=answer]-C-CC-Dmacro[=defn]-dD-dI-dM-dN-dU-fdebug-cpp-fdirectives-only-fdollars-in-identifiers-fexec-charset=charset-fextended-identifiers-finput-charset=charset-flarge-source-files-fmacro-prefix-map=old=new-fmax-include-depth=depth-fno-canonical-system-headers-fpch-deps-fpch-preprocess-fpreprocessed-ftabstop=width-ftrack-macro-expansion-fwide-exec-charset=charset-fworking-directory-H-imacros file-include file-M-MD-MF-MG-MM-MMD-MP-MQ-MT-Mno-modules-no-integrated-cpp-P-pthread-remap-traditional-traditional-cpp-trigraphs-Umacro-undef-Wp,option-Xpreprocessor option
๐ง Assembler Options ๐ง
just two besties in this section and honestly? iconic. tiny roster, big energy. ๐
-Wa,option-Xassembler option
๐ Linker Options ๐
the linker era ๐ โ every single one of these, in order, no edits, no merges. periodt.
object-file-name-fuse-ld=linker-llibrary-nostartfiles-nodefaultlibs-nolibc-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 things live ๐ โ search paths and prefixes and sysroots, oh my. full list, nothing hidden. ๐ธ
-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 ๐๏ธ
codegen time ๐๏ธ โ registers, structs, enums, visibility, all of it. every flag, exactly as it appears. ๐
-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 ๐ ๏ธ
dev corner ๐ ๏ธ โ for the people who poke at the compiler's insides. every flag, unedited, no cap. iykyk. ๐ง
-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]-fprofile-report-frandom-seed=string-fsched-verbose=n-fsel-sched-verbose-fsel-sched-dump-cfg-fsel-sched-pipelining-verbose-fstats-fstack-usage-ftime-report-ftime-report-details-fvar-tracking-assignments-toggle-gtoggle-print-file-name=library-print-libgcc-file-name-print-multi-directory-print-multi-lib-print-multi-os-directory-print-prog-name=program-print-search-dirs-Q-print-sysroot-print-sysroot-headers-suffix-save-temps-save-temps=cwd-save-temps=obj-time[=file]
๐ป Machine-Dependent Options ๐ป
machine-dependent era ๐ป โ these shift depending on the machine you're aiming at. starting with the AArch64 crew. ๐
๐ง AArch64 Options ๐ง
the AArch64-specific ones, right here, every single flag, exactly as written: โจ
-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
and that's the whole machine-dependent roster for this round, bestie โ not a single one missing. ๐ซถ
โจ Adapteva Epiphany Options โจ
bestie these are the Epiphany knobs, all of them, zero gatekeeping:
-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 ๐
three options, tiny but mighty:
-march=gpu-mtune=gpu-mstack-size=bytes
๐ ARC Options ๐
the ARC menu is long bestie, sit down, hydrate, we're going in:
-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 ๐
okay ARM besties this is the list, it's giving extremely thorough:
-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
๐ฆ AVR Options ๐ฆ
microcontroller girlies rise, this one's for you:
-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-nodevicelib-nodevicespecs-Waddr-space-convert-Wmisspelled-isr
๐ซถ Blackfin Options ๐ซถ
every one of these, no cap:
-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 ๐ธ
short and sweet fr:
-mbig-endian-mlittle-endian-march=cpu-msim-msdata=sdata-type
โญ CRIS Options โญ
the whole vibe check, right here:
-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
๐ง CR16 Options ๐ง
seven little icons, obsessed:
-mmac-mcr16cplus-mcr16c-msim-mint32-mbit-ops-mdata-model=model
๐ C-SKY Options ๐
the full C-SKY set, main character energy:
-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 ๐
macOS besties, this list is enormous and honestly kinda iconic. note that a couple of these show up more than once in the list โ we're keeping it exactly as it is, no editing:
-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 ๐
old-school icon behaviour:
-mno-fp-regs-msoft-float-mieee-mieee-with-inexact-mieee-conformant-mfp-trap-mode=mode-mfp-rounding-mode=mode-mtrap-precision=mode-mbuild-constants-mcpu=cpu-type-mtune=cpu-type-mbwx-mmax-mfix-mcix-mfloat-vax-mfloat-ieee-mexplicit-relocs-msmall-data-mlarge-data-msmall-text-mlarge-text-mmemory-latency=time
๐ eBPF Options ๐
kernel-adjacent besties this one's yours:
-mbig-endian-mlittle-endian-mkernel=version-mframe-limit=bytes-mxbpf-mco-re-mno-co-re-mjmpext-mjmp32-malu32-mcpu=version
๐ FR30 Options ๐
just two, a minimalist moment:
-msmall-model-mno-lsim
โจ FT32 Options โจ
six options, short king energy:
-msim-mlra-mnodiv-mft32b-mcompress-mnopm
๐ฅ FRV Options ๐ฅ
big list, big vibes:
-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 ๐ง
picking your libc bestie, choose wisely:
-mglibc-muclibc-mmusl-mbionic-mandroid-tno-android-cc-tno-android-ld
๐ธ H8/300 Options ๐ธ
small stack of knobs, we love a tidy list:
-mrelax-mh-ms-mn-mexr-mno-exr-mint32-malign-300
๐ HPPA Options ๐
HP besties, this is your moment:
-march=architecture-type-mcaller-copies-mdisable-fpregs-mdisable-indexing-mfast-indirect-calls-mgas-mgnu-ld-mhp-ld-mfixed-range=register-range-mjump-in-delay-mlinker-opt-mlong-calls-mlong-load-store-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-msio-mwsio-munix=unix-std-nolibdld-static-threads
๐ฆ IA-64 Options ๐ฆ
Itanium girlies, the schedule flags go deep:
-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 โญ
five flags, all of them -enabled, we stan consistency:
-mbarrel-shift-enabled-mdivide-enabled-mmultiply-enabled-msign-extend-enabled-muser-enabled
๐ LoongArch Options ๐
the whole LoongArch lineup, no skips:
-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-mcmodel=code-model-mrelax-mpass-mrelax-to-as
๐ M32R/D Options ๐
here's the M32R/D set, fully intact:
-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 ๐ธ
three options, immaculate minimalism:
-mcpu=cpu-msim-memregs=number
๐ซถ M680x0 Options ๐ซถ
m68k besties the list is stacked:
-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 ๐
last but never least, the MCore menu:
-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
๐ MeP Options ๐
okay so MeP is here with a whole lil wardrobe, bestie. every single fit, no skips:
-mabsdiff-mall-opts-maverage-mbased=n-mbitops-mc=n-mclip-mconfig=name-mcop-mcop32-mcop64-mivc2-mdc-mdiv-meb-mel-mio-volatile-ml-mleadz-mm-mminmax-mmult-mno-opts-mrepeat-ms-msatur-msdram-msim-msimnovec-mtf-mtiny=n
๐ฆ MicroBlaze Options ๐ฆ
tiny soft core, HUGE option list. it's giving overachiever:
-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 main character of this whole chunk, fr fr. this list is long long. buckle up, we're going all the way down ๐ซถ
-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
okay phew. MIPS really said "here's my entire personality" and dumped it all on the table. we respect it tho ๐
๐ง MMIX Options ๐ง
Knuth's lil darling gets its moment, as it should:
-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, a lil snack:
-meb-mel-mmul.x-mno-crt0
โจ MSP430 Options โจ
the embedded bestie with the silicone tea โ (yes, errata is a whole thing here, but we're just listing, not spilling):
-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 ๐
three options, maximum confidence:
-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 โญ
the vintage icon, the OG, the way that it simply exists:
-mfpu-msoft-float-mac0-mno-ac0-m40-m45-m10-mint32-mno-int16-mint16-mno-int32-msplit-munix-asm-mdec-asm-mgnu-asm-mlra
๐ picoChip Options ๐
-mae=ae_type-mvliw-lookahead=N-msymbol-as-address-mno-inefficient-warnings
๐ซถ PowerPC Options ๐ซถ
okay so this one doesn't have its own list here, it just points you elsewhere:
See RS/6000 and PowerPC Options.
๐ PRU Options ๐
-mmcu=mcu-minrt-mno-relax-mloop-mabi=variant
๐ฅ RISC-V Options ๐ฅ
the new-gen baddie, obviously. here's every single flag, bestie:
-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-mmo-riscv-attribute-malign-data=type-mbig-endian-mlittle-endian-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset
๐ง 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 absolute unit. the "not me scrolling for ten years" list. every last one of them, periodt:
-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
and yes, that was all of them. every single one. we ate and left no crumbs ๐ฝ๏ธโจ
๐ธ 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 ๐ฆ
big iron, big vibes:
-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
๐ Score Options ๐
-meb-mel-mnhwloop-muls-mmac-mscore5-mscore5u-mscore7-mscore7d
๐ SH Options ๐
-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 ๐
and we're closing this chunk out with the Solaris set, bestie:
-mclear-hwcap-mno-clear-hwcap-mimpure-text-mno-impure-text-pthreads
โจ SPARC Options โจ
okay bestie, here comes the SPARC roster โ the whole thing, zero skips:
-mcpu=cpu-type -mtune=cpu-type -mcmodel=code-model
-mmemory-model=mem-model -m32 -m64 -mapp-regs -mno-app-regs
-mfaster-structs -mno-faster-structs -mflat -mno-flat -mfpu
-mno-fpu -mhard-float -msoft-float -mhard-quad-float
-msoft-quad-float -mstack-bias -mno-stack-bias -mstd-struct-return
-mno-std-struct-return -munaligned-doubles -mno-unaligned-doubles
-muser-mode -mno-user-mode -mv8plus -mno-v8plus -mvis -mno-vis
-mvis2 -mno-vis2 -mvis3 -mno-vis3 -mvis4 -mno-vis4 -mvis4b
-mno-vis4b -mcbcond -mno-cbcond -mfmaf -mno-fmaf -mfsmuld
-mno-fsmuld -mpopc -mno-popc -msubxc -mno-subxc -mfix-at697f
-mfix-ut699 -mfix-ut700 -mfix-gr712rc -mlra -mno-lra
โจ System V Options โจ
yep, just four. iconic minimalism tbh:
-Qy -Qn -YP,paths -Ym,dir
โจ TILE-Gx Options โจ
-mcpu=CPU -m32 -m64 -mbig-endian -mlittle-endian
-mcmodel=code-model
โจ TILEPro Options โจ
-mcpu=cpu -m32
โจ V850 Options โจ
look at this lineup, she's serving quantity ๐
-mlong-calls -mno-long-calls -mep -mno-ep
-mprolog-function -mno-prolog-function -mspace -mtda=n -msda=n
-mzda=n -mapp-regs -mno-app-regs -mdisable-callt
-mno-disable-callt -mv850e2v3 -mv850e2 -mv850e1 -mv850es -mv850e
-mv850 -mv850e3v5 -mloop -mrelax -mlong-jumps -msoft-float
-mhard-float -mgcc-abi -mrh850-abi -mbig-switch
โจ VAX Options โจ
-mg -mgnu -munix -mlra
โจ Visium Options โจ
-mdebug -msim -mfpu -mno-fpu -mhard-float
-msoft-float -mcpu=cpu-type -mtune=cpu-type -msv-mode -muser-mode
โจ VMS Options โจ
-mvms-return-codes -mdebug-main=prefix -mmalloc64
-mpointer-size=size
โจ VxWorks Options โจ
-mrtp -non-static -Bstatic -Bdynamic -Xbind-lazy
-Xbind-now
โจ x86 Options โจ
okay this one is a LOT. like, the x86 option list is the main character of option lists and I'm obsessed. every single one, no cap:
-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 -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 -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
โจ x86 Windows Options โจ
-mconsole -mcygwin -mno-cygwin -mdll
-mnop-fun-dllimport -mthread -municode -mwin32 -mwindows
-fno-set-stack-executable
โจ Xstormy16 Options โจ
-msim
โจ Xtensa Options โจ
-mconst16 -mno-const16 -mfused-madd -mno-fused-madd
-mforce-no-pic -mserialize-volatile -mno-serialize-volatile
-mtext-section-literals -mno-text-section-literals -mauto-litpools
-mno-auto-litpools -mtarget-align -mno-target-align -mlongcalls
-mno-longcalls -mabi=abi-type
โจ zSeries Options โจ
this one just points you elsewhere, bestie โ see S/390 and zSeries Options. ๐ซถ
๐ Options Controlling the Kind of Output ๐
okay so, this is the part where we talk about the actual JOURNEY a file goes on. Compilation can involve up to four stages: preprocessing, compilation proper, assembly and linking, and they always happen in that order. No skipping the queue, no cutting in line. ๐
GCC can preprocess and compile several files either into several assembler input files, or into one single assembler input file. Then each assembler input file produces an object file, and linking combines all the object files โ both the ones it just freshly compiled and the ones you handed it as input โ into an executable file.
For any given input file, the file name suffix is what decides which kind of compilation happens. It's giving "your name tag determines your whole destiny":
file.cโ C source code that must be preprocessed.file.iโ C source code that should not be preprocessed.file.iiโ C++ source code that should not be preprocessed.file.mโ Objective-C source code. Heads up bestie, you must link with thelibobjclibrary to make an Objective-C program work.file.miโ Objective-C source code that should not be preprocessed.file.mm,file.Mโ Objective-C++ source code. Note that you must link with thelibobjclibrary to make an Objective-C++ program work. Note that.Mrefers to a literal capital M.file.miiโ Objective-C++ source code that should not be preprocessed.file.hโ C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (that's the default), or a C, C++ header file to be turned into an Ada spec (via the-fdump-ada-specswitch).file.cc,file.cp,file.cxx,file.cpp,file.CPP,file.c++,file.Cโ C++ source code that must be preprocessed. Note that in.cxx, the last two letters must both be literallyx. Likewise,.Crefers to a literal capital C.file.mm,file.Mโ Objective-C++ source code that must be preprocessed.file.miiโ Objective-C++ source code that should not be preprocessed.file.hh,file.H,file.hp,file.hxx,file.hpp,file.HPP,file.h++,file.tccโ C++ header file to be turned into a precompiled header or Ada spec.file.f,file.for,file.ftnโ Fixed form Fortran source code that should not be preprocessed.file.F,file.FOR,file.fpp,file.FPP,file.FTNโ Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).file.f90,file.f95,file.f03,file.f08โ Free form Fortran source code that should not be preprocessed.file.F90,file.F95,file.F03,file.F08โ Free form Fortran source code that must be preprocessed (with the traditional preprocessor).file.goโ Go source code.file.dโ D source code.file.diโ D interface file.file.ddโ D documentation code (Ddoc).file.adsโ Ada source code file that contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). Such files are also called specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.file.sโ Assembler code.file.S,file.sxโ Assembler code that must be preprocessed.otherโ An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way. mystery file? straight to the linker. no questions asked. ๐
You can also specify the input language explicitly with the -x option:
-xlanguage โ Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next-xoption. Possible values for language are:
c c-header cpp-output
c++ c++-header c++-system-header c++-user-header c++-cpp-output
objective-c objective-c-header objective-c-cpp-output
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-xhas not been used at all). we're back to vibes-based detection, slay.
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. Note that some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all. literally nothing. a whole lot of nothing. iconic behaviour honestly. ๐
-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.
-Sโ Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified.
By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.
Input files that don't require compilation are ignored.
-Eโ Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. straight to stdout, no file, no ceremony, main character energy โจ
Input files that don't require preprocessing are ignored.
-o fileโ okay so this one drops your primary output into file, and it literally does not care what kind of output we're talking about: executable file, object file, assembler file, preprocessed C code, all of it. ๐
If you don't say -o, here's the default tea โ: an executable file lands in a.out, the object file for source.suffix goes in source.o, its assembler file goes in source.s, a precompiled header file goes in source.suffix.gch, and all preprocessed C source just vibes onto standard output.
So even though -o only names the primary output, bestie it also lowkey controls the naming of your auxiliary and dump outputs. See the examples below. Unless something overrides it, both auxiliary outputs and dump outputs get placed in the same directory as the primary output. In auxiliary outputs, the suffix of the input file gets replaced with the suffix of the auxiliary output file type; in dump outputs, the suffix of the dump file gets 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, gets combined with the input file name. And if both share the same base name (suffix disregarded, we don't care about it), the result of the combination is that base name โ otherwise they get concatenated with a dash in between. ๐
gcc -c foo.c ...
will use foo.o as the primary output, and place aux outputs and dumps right 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 all of 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 are named dir/foo.c.*. ๐
And listen โ 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. (We're getting to all of them, keep scrolling bestie.)
-dumpbase dumpbaseโ this sets the base name for auxiliary and dump output files. It does not touch the name of the primary output file, periodt.
Intermediate outputs, when they get preserved, are not regarded as primary outputs โ they're auxiliary outputs. Watch:
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) come with the input name suffix, and aux output files (those requested by other non-dump options, e.g. -save-temps, -gsplit-dwarf, -fcallgraph-info) come 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-ext auxdropsufโ when forming the name of an auxiliary (but not a dump) output file, drop the trailing auxdropsuf from dumpbase before appending any suffixes. If you don't specify it, 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 when 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.*. ๐
-dumpdir dumppfxโ 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 is explicitly specified. The goal is that the explicitly-specified dumppfx may contain the specified output name as part of the prefix, if desired; only an explicitly-specified -dumpbase would be combined with it, in order to avoid simply discarding a meaningful option. ๐
When compiling and then linking from a single input file, the linker output base name will only be appended to the default dumppfx as above if it does not share the base name with the single input file name. This has been covered in single-input linking cases above, but not with an explicit -dumpdir that inhibits the combination, even if overridden by -save-temps=*:
gcc foo.c -dumpdir alt/pfx- -o dir/main.exe -save-temps=cwd ...
Auxiliary outputs get named foo.*, and dump outputs get named foo.c.*, both landing in whatever the current working directory is โ whatever -save-temps=cwd ultimately asked for, basically.
Okay so the whole data flow, summed up (it's intuitive but ngl slightly imprecise, so don't quote me in a thesis): the primary output name gets split into a directory part and a basename part. dumppfx gets set to that directory part, unless something overrode it with -dumpdir or -save-temps=*, and dumpbase gets set to the basename part, unless -dumpbase overrode it. If there are multiple inputs, or if we're linking, this dumpbase can get combined with dumppfx and taken from each input file. For each input, the auxiliary output names are built by combining dumppfx, dumpbase minus its suffix, and the auxiliary output suffix. Dump output names are literally the same deal except the suffix from dumpbase is retained.
Now, when it comes to auxiliary and dump outputs made during LTO recompilation: a combo of dumppfx and dumpbase โ as given, or as derived from the linker output name but not from inputs, even in cases where that combo wouldn't otherwise be used as such โ gets passed down with a trailing period replacing the compiler-added dash (if there is one) as a -dumpdir option to lto-wrapper. And since it's involved in linking, this program doesn't normally get any -dumpbase and -dumpbase-ext, and it ignores them. ๐
When it runs sub-compilers, lto-wrapper appends LTO stage names to the received dumppfx, makes sure it contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers.
-vโ prints (to standard error output) the commands executed to run the stages of compilation. Also prints the version number of the compiler driver program, and of the preprocessor and the compiler proper. ๐-###โ like-v, except the commands are not executed and arguments get quoted unless they contain only alphanumeric characters or"./-_". Super useful for shell scripts that wanna capture the driver-generated command lines.--helpโ prints (to standard output) a description of the command-line optionsgccunderstands. If-vis also specified, then--helpalso gets passed on to the various processesgccinvokes, so they can show the command-line options they accept. And if-Wextrawas also specified (before the--helpoption), then command-line options with no documentation attached to them get displayed too.--target-helpโ prints (to standard output) a description of target-specific command-line options for each tool. For some targets, extra target-specific info may also be printed.--help={class|[^]qualifier}[,...]โ prints (to standard output) a description of the command-line options the compiler understands that fit into all the specified classes and qualifiers. Here are the supported classes:optimizersโ display all of the optimization options supported by the compiler. โจwarningsโ display all of the options controlling warning messages produced by the compiler. ๐ซถtargetโ display target-specific options. Unlike--target-helpthough, the target-specific options of the linker and assembler are not displayed, because those tools don't currently support the extended--help=syntax.paramsโ display the values recognized by the--paramoption.languageโ display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, you need to select thecommonclass.commonโ display the options that are common to all languages.
And these are the supported qualifiers:
undocumentedโ display only those options that are undocumented.joinedโ display options taking an argument that appears after an equal sign in the same continuous piece of text, like:--help=target.separateโ display options taking an argument that appears as a separate word following the original option, like:-o output-file.
So for example, to display all the undocumented target-specific switches the compiler supports, use:
--help=target,undocumented
You can flip the sense of a qualifier 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 don't 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, though it usually restricts the output so much that there's nothing left to display. One case where it does work, though, is when one of the classes is target. For example, to display all the target-specific optimization options, use:
--help=target,optimizers
The --help= option can be repeated on the command line. Each successive use displays its requested class of options, skipping the ones that have already been displayed. And if --help is also specified anywhere on the command line, then it takes precedence over any --help= option.
If the -Q option shows up on the command line before the --help= option, then the descriptive text displayed by --help= changes. Instead of describing the displayed options, you get an indication of whether the option is enabled, disabled, or set to a specific value (assuming the compiler knows this at the point where the --help= option is used).
Here's a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi= 2
-mabort-on-noreturn [disabled]
-mapcs [disabled]
The output is sensitive to the effects of previous command-line options, so for example you can find out which optimizations are enabled at -O2 by using:
-Q -O2 --help=optimizers
Or, 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
--versionโ display the version number and copyrights of the invoked GCC. ๐-pass-exit-codesโ normally thegccprogram exits with code1if any phase of the compiler returns a non-success return code. If you specify-pass-exit-codes, 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 can't read from a pipe; but the GNU assembler has no trouble at all. ๐ง-specs=fileโ process file after the compiler reads in the standard specs file, in order to override the defaults thegccdriver program uses when figuring out what switches to pass tocc1,cc1plus,as,ld, etc. More than one-specs=filecan be specified on the command line, and they get processed in order, from left to right.-wrapperโ invoke all subcommands under a wrapper program. The name of the wrapper program and its parameters get passed as a comma-separated list.
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 becomes gdb --args cc1 ....
-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. See also-fmacro-prefix-map,-fdebug-prefix-mapand-fprofile-prefix-map.-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โ in conjunction with-fdump-ada-spec[-slim]above, generate Ada specs as child units of parent unit.-fdump-go-spec=fileโ for input files in any language, generate corresponding Go declarations in file. This generates Go"const","type","var", and"func"declarations, which may be a useful way to start writing a Go interface to code written in some other language.@fileโ read command-line options from file. The options read get inserted in place of the original@fileoption. If file doesn't exist, or can't be read, then the option gets treated literally, and not removed.
Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively. ๐
๐ Compiling C++ Programs ๐
C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx; C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc; and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way you would for compiling C programs (usually with the name gcc). ๐ธ
Like, okay so โ just using gcc does not pull the C++ library in with it. It's not built for that, bestie. g++ is the program that calls GCC and automatically specifies linking against the C++ library. Iconic behaviour. It also treats .c, .h and .i files as C++ source files instead of C source files โ unless you use -x, obviously. And it's genuinely handy when you're precompiling a C header file with a .h extension so it can be used in C++ compilations. On lots of systems, g++ is also installed under the name c++. Same girl, different name. ๐
And when you compile C++ programs, you can specify a bunch of the same command-line options you'd use for compiling programs in literally any language, or command-line options that are meaningful for C and its related languages, or options that are meaningful only for C++ programs. Pick your fighter. โจ
๐ Options Controlling C Dialect ๐
These options control the dialect of C (or languages derived from C, like C++, Objective-C and Objective-C++) that the compiler accepts. Vibe check for your source files, basically.
-ansiโ In C mode this is equivalent to-std=c90. In C++ mode it's equivalent to-std=c++98.
What does that actually do tho? It turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or with standard C++ (when compiling C++ code) โ things like the asm and typeof keywords, and predefined macros like unix and vax that identify the type of system you're on. It also enables the undesirable and rarely used ISO trigraph feature. Yeah. Undesirable. I said what I said. And 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__ keep working despite -ansi. They don't care. You wouldn't want to use them in an ISO C program, obviously, but they're super useful to drop into header files that might get included in compilations done with -ansi. Alternate predefined macros such as __unix__ and __vax__ are also available, with or without -ansi.
And no, -ansi does not cause non-ISO programs to be rejected gratuitously. It's not that petty. For that you need -Wpedantic in addition to -ansi. Both. Together. Periodt.
The macro __STRICT_ANSI__ is predefined when the -ansi option is used. Some header files might 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 don't have semantics defined by ISO C (like 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 don't contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, like the asm and typeof keywords, but not other GNU extensions that don't have a meaning in ISO C90 โ such as omitting the middle term of a ?: expression. Letting you cook.
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. Not a bug, it's a lifestyle. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not.
A value for this option must be provided; possible values are:
c90,c89,iso9899:1990โ Support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as-ansifor C code.iso9899:199409โ ISO C90 as modified in amendment 1.c99,c9x,iso9899:1999,iso9899:199xโ ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). See<https://gcc.gnu.org/c99status.html>for more information. The namesc9xandiso9899:199xare deprecated. Old names, bestie, retire them.c11,c1x,iso9899:2011โ ISO C11, the 2011 revision of the ISO C standard. This standard is substantially completely supported, modulo bugs, floating-point issues (mainly but not entirely relating to optional C11 features from Annexes F and G) and the optional Annexes K (Bounds-checking interfaces) and L (Analyzability). The namec1xis deprecated.c17,c18,iso9899:2017,iso9899:2018โ ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is same as C11 except for corrections of defects (all of which are also applied with-std=c11) and a new value of__STDC_VERSION__, and so is supported to the same extent as C11. Basically C11's glow-up.c2xโ The next version of the ISO C standard, still under development. The support for this version is experimental and incomplete. Warning: construction zone ๐งgnu90,gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99,gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11,gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17,gnu18โ GNU dialect of ISO C17. This is the default for C code. ๐gnu2xโ The next version of the ISO C standard, still under development, plus GNU extensions. The support for this version is experimental and incomplete.c++98,c++03โ The 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code.gnu++98,gnu++03โ GNU dialect of-std=c++98.c++11,c++0xโ The 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11,gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14,c++1yโ The 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14,gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17,c++1zโ The 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17,gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code. The namegnu++1zis deprecated.c++20,c++2aโ The 2020 ISO C++ standard plus amendments. Support is experimental, and could change in incompatible ways in future releases. The namec++2ais deprecated.gnu++20,gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2b,c++23โ The next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases. Do not build your whole life on this one yet, fr fr.gnu++2b,gnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
-aux-infofilename โ 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. C only, sorry bestie.
Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration. Receipts for every declaration. Love that for you.
-fallow-parameterless-variadic-functionsโ Accept variadic functions without named parameters.
Although it is possible to define such a function, this is not very useful as it is not possible to read the arguments. This is only supported for C, as this construct is allowed by C++. So likeโฆ allowed, but why.
-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 is not affected by this switch. You may want to use the -fno-gnu-keywords flag instead, which disables typeof but not asm and inline. In C99 mode (-std=c99 or -std=gnu99), this switch only affects the asm and typeof keywords, since inline is a standard keyword in ISO C99. Context matters, bestie.
-fno-builtin,-fno-builtin-functionโ Don't recognize built-in functions that do not begin with__builtin_as prefix.
GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which 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. That's the tradeoff, no cap. In addition, 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. The compiler is watching. Always. ๐
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โ bestie, this lets you have conditional expressions with mismatched types in the second and third arguments. The value of such an expression isvoid. 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 the option-fgnu-tmis 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โ the option-fgnu89-inlinetells GCC to use the traditional GNU semantics forinlinefunctions when in C99 mode. Using this option is roughly equivalent to adding thegnu_inlinefunction attribute to all inline functions. The option-fno-gnu89-inlineexplicitly tells GCC to use the C99 semantics forinlinewhen in C99 or gnu99 mode (i.e., it specifies the default behavior). This option is not supported in-std=c90or-std=gnu90mode. The preprocessor macros__GNUC_GNU_INLINE__and__GNUC_STDC_INLINE__may be used to check which semantics are in effect forinlinefunctions.-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, bestie.-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.
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-vto show the list of configured offload targets underOFFLOAD_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++ 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.-fopenmp-simdโ enable handling of OpenMP's SIMD directives with#pragma ompin C/C++ and!$ompin Fortran. Other OpenMP directives are ignored.-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.-fpermitted-flt-eval-methodsspecifies whether the compiler should allow only the values ofFLT_EVAL_METHODspecified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3. style is eitherc11orts-18661-3as appropriate. The default when in a standards compliant mode (-std=c11or similar) is-fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11or 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โ let the typecharbe signed, likesigned char. Note that this is equivalent to-fno-unsigned-char, which is the negative form of-funsigned-char. Likewise, the option-fno-signed-charis equivalent to-funsigned-char.-funsigned-charโ let the typecharbe unsigned, likeunsigned char. Each kind of machine has a default for whatcharshould be. It is either likeunsigned charby default or likesigned charby default. Ideally, a portable program should always usesigned charorunsigned charwhen it depends on the signedness of an object. But many programs have been written to use plaincharand expect it to be signed, or expect it to be unsigned, depending on the machines they were written for. This option, and its inverse, let you make such a program work with the opposite default. The typecharis always a distinct type from each ofsigned charorunsigned char, even though its behavior is always just like one of those two.-fsso-struct=endiannessโ set the default scalar storage order of structures and unions to the specified endianness. The accepted values are big-endian, little-endian and native for the native endianness of the target (the default). This option is not supported for C++. Warning: the-fsso-structswitch 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.
โจ 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.
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. 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 โ first showed up in G++ 4.5, and it implements a standard mangling for vector types. slay.
- Version 5 โ debuted in G++ 4.6, and it fixes the mangling of attribute
const/volatileon function pointer types,decltypeof a plain decl, and using a function parameter in the declaration of another parameter. little glow-up โจ - Version 6 โ from G++ 4.7, correcting 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 โ G++ 4.8 era, and it treats
nullptr_tas a builtin type and corrects the mangling of lambdas in default argument scope. - Version 8 โ G++ 4.9, correcting the substitution behavior of function types with function-cv-qualifiers.
- Version 9 โ G++ 5.2, correcting the alignment of
nullptr_t. - Version 10 โ G++ 6.1, and it adds mangling of attributes that affect type identity, like ia32 calling convention attributes (e.g.
stdcall). okay werk ๐ - Version 11 โ G++ 7, correcting the mangling of
sizeof...expressions and operator names. Also: 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. And it implies-fnew-inheriting-ctors. - Version 12 โ G++ 8, correcting 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. not the accidental slay we wanted ๐ญ
- Version 13 โ G++ 8.2, and it fixes that accidental change in version 12. we love a redemption arc ๐ซถ
- Version 14 โ G++ 10, correcting the mangling of the
nullptrexpression. - Version 15 โ G++ 11, and it changes the mangling of
__alignof__so it's distinct from that ofalignof, plus dependent operator names.
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 tells it which ABI version to use for that alias. no cap.
With -fabi-version=0 (the default), this defaults to 11 (GCC 7 compatibility). If another ABI version is explicitly selected, this defaults to 0. And for compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option isn't provided but -Wabi=n is, that version gets used for compatibility aliases. If this option is provided along with -Wabi (no version on it), the version from this option is used for the warning.
-fno-access-controlโ turns off all access checking. Bestie this switch is mainly useful for working around bugs in the access control code, iykyk ๐-faligned-newโ enables support for C++17newof types that require more alignment thanvoid* ::operator new(std::size_t)provides. You can pass a numeric argument like-faligned-new=32to say how much alignment (in bytes) that function provides, but honestly few users will need to override the default ofalignof(std::max_align_t).
โจ This flag is enabled by default for -std=c++17. โจ
-fchar8_t-fno-char8_tโ enables support forchar8_tas adopted for C++20. That means: a whole newchar8_tfundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new__cpp_char8_tand__cpp_lib_char8_tfeature test macros. the full package deal ๐
This option lets functions be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
and it introduces new signatures for user-defined literals:
int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;
๐ Heads up: the change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. For example, the code below is well-formed under ISO C++11, but it's ill-formed when -fchar8_t is specified.
char ca[] = u8"xx"; // error: char-array initialized from wide
// string
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
-fcheck-newโ checks that the pointer returned byoperator newis non-null before it tries to modify the storage it allocated. Normally this check is unnecessary, because the C++ standard saysoperator newonly returns 0 if it's declaredthrow(), and in that case the compiler always checks the return value even without this option. In all other cases, whenoperator newhas a non-empty exception specification, memory exhaustion is signalled by throwingstd::bad_alloc. See alsonew (nothrow).-fconcepts-fconcepts-tsโ below-std=c++20,-fconceptsenables support for the C++ Extensions for Concepts Technical Specification, ISO 19217 (2015).
With -std=c++20 and above, Concepts are part of the language standard, so -fconcepts defaults to on. But the standard specification of Concepts differs significantly from the TS, so some constructs that were allowed in the TS but didn't make it into the standard can still be enabled by -fconcepts-ts.
-fconstexpr-depth=nโ sets the maximum nested evaluation depth for C++11constexprfunctions to n. A limit is needed so endless recursion during constant expression evaluation can be detected. The minimum specified by the standard is 512.-fconstexpr-cache-depth=nโ sets the maximum level of nested evaluation depth for C++11constexprfunctions that will be cached to n. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows very large from highly recursive evaluations). The default is 8. Very few users are likely to want to adjust it, but if your code does heavyconstexprcalculations you might want to experiment and find which value works best for you. ๐ง-fconstexpr-fp-exceptโ Annex F of the C standard specifies that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value. This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined.
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
-fconstexpr-loop-limit=nโ sets the maximum number of iterations for a loop in C++14constexprfunctions to n. A limit is needed to detect infinite loops during constant expression evaluation. The default is 262144 (1<<18).-fconstexpr-ops-limit=nโ sets the maximum number of operations during a singleconstexprevaluation. Even when the number of iterations of a single loop is limited with the above limit, if there are several nested loops and each has many iterations but still smaller than that limit, or if in the body of some loop โ or even outside a loop โ too many expressions need to be evaluated, the resultingconstexprevaluation might take too long. The default is 33554432 (1<<25).-fcoroutinesโ enables support for the C++ coroutines extension (experimental). ๐ฆ-fno-elide-constructorsโ the C++ standard allows an implementation to omit creating a temporary that's 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. It also makes G++ call trivial member functions which otherwise would be expanded inline.
๐ก In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.
-fno-enforce-eh-specsโ don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard, but it may be useful for reducing code size in production builds, much like definingNDEBUG. It 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. bestie, be careful with that one ๐ญ-fextern-tls-init,-fno-extern-tls-initโ okay so C++11 and OpenMP saidthread_localandthreadprivatevariables are allowed to have dynamic (runtime) initialization, and to make that work, literally every use of such a variable has to go through a lil wrapper function that does whatever init is needed. When the use and the definition live in the same translation unit, that overhead can get optimized away โ slay โ but when the use is in a different translation unit? Significant overhead, even if the variable genuinely doesn't need dynamic initialization. So if you, the programmer, are 100% sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because it's statically initialized, or because a use in the defining TU will run before any uses in another TU), you can skip that overhead with-fno-extern-tls-init. ๐
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that don't support symbol aliases, the default is -fno-extern-tls-init.
-ffold-simple-inlines,-fno-fold-simple-inlinesโ lets the C++ frontend fold calls tostd::move,std::forward,std::addressofandstd::as_const. And no, bestie, that's not the same as inlining โ the difference is that no debug information gets generated for these calls. Since these functions are rarely interesting to debug, the flag is on by default unless-fno-inlineis active. โจ-fno-gnu-keywordsโ don't recognizetypeofas a keyword, so your code can use that word as an identifier. You can still 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โ makes inline functions implicitly constexpr, if they satisfy the requirements for a constexpr function. Works in C++14 mode or later. This can make initialization flip from dynamic to static, plus other optimizations. we love a glow-up ๐ธ-fno-implicit-templatesโ never emit code for non-inline templates that get instantiated implicitly (i.e. by use). Only emit code for explicit instantiations. If you turn this on, you must be careful to structure your code so it includes all the necessary explicit instantiations, otherwise you get undefined symbols at link time. no cap, that linker error is on you ๐-fno-implicit-inline-templatesโ don't emit code for implicit instantiations of inline templates either. The default handles inlines differently so that compiles with and without optimization need the same set of explicit instantiations.-fno-implement-inlinesโ to save space, don't emit out-of-line copies of inline functions controlled by#pragma implementation. Heads up: this causes linker errors if those functions aren't inlined everywhere they're called. ๐-fmodules-ts,-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, since that's the default. And even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version.-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. That's different from traditional C++ behavior, and for good reasons. But it can make porting code a struggle, so this option makes such function definitions implicitly inline. The catch: it generates an ABI incompatibility, so you must use it everywhere or nowhere. (Those definitions outside of a named module stay implicitly inline regardless.)-fno-module-lazyโ disable lazy module importing and module mapper creation.-fmodule-mapper=[hostname]:port[?ident],-fmodule-mapper=|program[?ident] args...,-fmodule-mapper==socket[?ident],-fmodule-mapper=<>[inout][?ident],-fmodule-mapper=<in>out[?ident],-fmodule-mapper=file[?ident]โ this one's an oracle you query for module name to filename mappings. If you don't specify it, theCXX_MODULE_MAPPERenvironment variable gets used, and if that's unset too, an in-process default is provided. ๐ฎ-fmodule-onlyโ only emit the Compiled Module Interface, inhibiting any object file.-fms-extensionsโ disable-Wpedanticwarnings about constructs used in MFC, like implicitintand getting a pointer to member function via non-standard syntax.-fnew-inheriting-ctorsโ enable the P0136 adjustment to the semantics of C++11 constructor inheritance. It's part of C++17 but also considered a Defect Report against C++11 and C++14. This flag is enabled by default unless-fabi-version=10or lower is specified.-fnew-ttp-matchingโ enable the P0522 resolution to Core issue 150, template template parameters and default arguments: this lets a template with default template arguments be an argument for a template template parameter that has fewer template parameters. Enabled by default for-std=c++17.-fno-nonansi-builtinsโ disable built-in declarations of functions that aren't mandated by ANSI/ISO C. That list includesffs,alloca,_exit,index,bzero,conjf, and other related functions.-fnothrow-optโ treat athrow()exception specification as if it were anoexceptspecification, to reduce or eliminate the text size overhead compared to a function with no exception specification. Fun twist: if the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller, because the EH cleanups for those variables can be optimized away. The semantic effect is that an exception thrown out of a function with such an exception specification results in a call toterminaterather thanunexpected. ๐-fno-operator-namesโ don't treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms as keywords.-fno-optional-diagsโ disable diagnostics that the standard says a compiler doesn't need to issue. Currently the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class.-fpermissiveโ downgrade some diagnostics about nonconformant code from errors to warnings. So yeah,-fpermissivelets some nonconforming code actually compile. ๐ซถ-fno-pretty-templatesโ so normally, when an error message refers to a specialization of a function template, the compiler prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (e.g.void f(T) [with T = int]rather thanvoid f(int)) so it's clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of those behaviors makes the error message harder to understand instead of easier, you can use-fno-pretty-templatesto disable them. ๐-fno-rttiโ disable generation of information about every class with virtual functions, the info that the C++ run-time type identification features (dynamic_castandtypeid) use. If you don't use those parts of the language, this flag saves you some space. Note that exception handling uses the same information, but G++ generates it as needed. Thedynamic_castoperator can still be used for casts that don't require run-time type information, i.e. casts tovoid *or to unambiguous base classes.
Mixing code compiled with -frtti and code compiled with -fno-rtti may not work. For example, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. ๐
-fsized-deallocationโ enable the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
as introduced in C++14. Super useful for user-defined replacement deallocation functions that, say, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. And the flag -Wsized-deallocation warns about places that might want to add a definition. โจ
-fstrict-enumsโ let 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). Warning bestie: this assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. ๐ญ-fstrong-eval-orderโ evaluate member access, array subscripting, and shift expressions in left-to-right order, and evaluate 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โ set the max number of template instantiation notes for a single warning or error to n. Default value is10.-ftemplate-depth=nโ set the maximum instantiation depth for template classes to n. You need some limit on template instantiation depth 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, since the compiler can run out of stack space before hitting1024in some situations. ๐ฎโ๐จ-fno-threadsafe-staticsโ don't emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shrink your code size slightly in code that doesn't need to be thread-safe.-fuse-cxa-atexitโ register 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โ bestie, this one says do not touch the__cxa_get_exception_ptrruntime routine. The tradeoff? It makesstd::uncaught_exceptionlie to you (incorrect, periodt ๐). But if that runtime routine literally isn't available on your platform, you gotta do what you gotta do.-fvisibility-inlines-hiddenโ okay so this switch is declaring that nobody's out here comparing pointers to inline functions or methods where the addresses of those two functions get taken in different shared objects. That's the deal you're making. ๐ค
The glow-up: GCC can effectively mark inline methods with __attribute__ ((visibility ("hidden"))), so they don't show up in a DSO's export table and don't need a PLT indirection when used inside that DSO. And the way this can dramatically change load and link times for a DSO?? Because it massively shrinks the dynamic export table when the library is heavy on templates. It's giving iconic. โจ
Real talk though, this is not quite the same as marking the methods hidden directly โ because it doesn't touch static variables local to the function, and it doesn't make the compiler deduce that the function is defined in only one shared object.
You can mark a method with explicit visibility to negate the switch for that method. Say you genuinely want to compare pointers to one particular inline method โ mark it default visibility, slay. But marking the enclosing class with explicit visibility? No effect. Nada. ๐
Oh and explicitly instantiated inline methods are unaffected by this option, because their linkage might otherwise cross a shared library boundary.
-fvisibility-ms-compatโ this flag is out here trying to use visibility settings to make GCC's C++ linkage model match up with Microsoft Visual Studio's. Compatible besties, kind of.
Here's what it changes in 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.
For new code, honestly, just use -fvisibility=hidden and export the classes you actually want externally visible. That's the move. ๐
But unfortunately code can rely on the Visual Studio behavior, sometimes accidentally, and that's why this exists.
The consequences, and listen: 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 pointers to function members defined in different shared objects may not compare equal. Also, when this flag is given, it is a violation of the ODR to define types with the same name differently. So like, don't. ๐จ
-fno-weakโ do not use weak symbol support, even if the linker's got it. By default G++ uses weak symbols when they're available. This option exists only for testing, and end-users should not use it; it results in inferior code and has no benefits. Not me warning you twice. It may get removed in a future release of G++. ๐-fext-numeric-literals(C++ and Objective-C++ only) โ accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. Turn it off and those suffixes get treated as C++11 user-defined literal numeric suffixes instead. It's 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. It's off by default for ISO C++11 onwards (-std=c++11, ...).-nostdinc++โ don't search for header files in the standard directories specific to C++, but do still search the other standard directories. (This option is used when building the C++ library.) Selective search, we love to see it. ๐-flang-info-include-translate-flang-info-include-translate-not-flang-info-include-translate=headerโ these three are all about being informed of include translation events. The first notes accepted include translations, the second notes declined include translations. Theheaderform will inform you about include translations relating to that specific header. And ifheaderis of the formuseror<system>, it gets resolved to a specific user or system header using the include path. Gossip but make it compiler diagnostics. ๐ฆ-flang-info-module-cmi-flang-info-module-cmi=moduleโ these inform you of Compiled Module Interface pathnames. The first notes all read CMI pathnames. Themoduleform will note reading a specific module's CMI. Andmodulecan be a named module or a header-unit โ that latter one indicated by either being a pathname containing directory separators or being enclosed in<>or"".-stdlib=libstdc++,libc++โ when G++ is configured to support this option, it lets you specify alternate C++ runtime libraries. Two options are on the menu:libstdc++(the default, native C++ runtime for G++) andlibc++, which is the C++ runtime installed on some operating systems (e.g. Darwin versions from Darwin11 onwards). The option switches G++ to use the headers from the specified library and to emit-lstdc++or-lc++respectively, when a C++ runtime is required for linking. Pick your fighter. โ๏ธ
In addition, these warning options have meanings only for C++ programs:
-Wabi-tag(C++ and Objective-C++ only) โ warn when a type with an ABI tag is used in a context that doesn't have that ABI tag. See C++ Attributes for more about ABI tags. Context mismatch? Caught. ๐ต๏ธ-Wcomma-subscript(C++ and Objective-C++ only) โ warn about uses of a comma expression inside a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23. However, a comma expression wrapped in( )is not deprecated. Example:
void f(int *a, int b, int c) {
a[b,c]; // deprecated in C++20, invalid in C++23
a[(b,c)]; // OK
}
In C++23 it's valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that isn't valid in C++23 but used to be valid (though deprecated) in C++20, with a pedantic warning that you can disable with -Wno-comma-subscript.
Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated. Rules are rules. ๐
-Wctad-maybe-unsupported(C++ and Objective-C++ only) โ warn when you're doing class template argument deduction (CTAD) on a type with no explicitly written deduction guides. This warning points out cases where CTAD only succeeded because the compiler synthesized the implicit deduction guides โ which might not be what the programmer intended, bestie. Certain style guides allow CTAD only 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) { }
};
S(allow_ctad_t) -> S<void>; // guide with incomplete parameter type will never be considered
-Wctor-dtor-privacy(C++ and Objective-C++ only) โ warn when a class seems unusable because all the constructors or destructors in that class are private, and it has neither friends nor public static member functions. Also warns if there are no non-private methods, and there's at least one private member function that isn't a constructor or destructor. That class is giving locked-room mystery. ๐-Wdelete-non-virtual-dtor(C++ and Objective-C++ only) โ warn 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. Seriously, this one's not a vibe, it's a bug waiting to happen. ๐ญ-Wdeprecated-copy(C++ and Objective-C++ only) โ warn that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up. This warning is enabled by-Wextra. With-Wdeprecated-copy-dtor, also deprecate if the class has a user-provided destructor.-Wno-deprecated-enum-enum-conversion(C++ and Objective-C++ only) โ disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;
-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only) โ disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a floating-point type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
bool b = e <= 3.7;
-Wdeprecated-enum-float-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-init-list-lifetime(C++ and Objective-C++ only) โ do not warn 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.
- If a function returns a temporary
Dangling pointers are not the moment, bestie. Keep your arrays alive. ๐ซถ
- okay this one is a whole THING bestie, listen up ๐จ When an
initializer_listvariable gets assigned from a brace-enclosed initializer list, the temporary array made for the right side of that assignment only lives until the end of the full-expression โ so at the very next statement, yourinitializer_listvariable is holding a dangling pointer. it's giving haunted ๐ป
// 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
- and another one ๐ญ When a list constructor stores the
beginpointer from theinitializer_listargument, that does not 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. tragic. avoid. fr fr.
-Winvalid-imported-macrosโ verify all imported macro definitions are valid at the end of compilation. Not enabled by default, because it takes extra processing to figure out. But it's lowkey useful when you're prepping sets of header-units and wanna make sure the macros stay consistent. ๐-Wno-literal-suffix(C++ and Objective-C++ only) โ don't warn when a string or character literal is followed by a ud-suffix that doesn't begin with an underscore. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens, to keep backwards compatibility with code that uses formatting macros from<inttypes.h>. like so:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
int main() {
int64_t i64 = 123;
printf("My int64: %" PRId64"\n", i64);
}
In this case, PRId64 is treated as a separate preprocessing token. โจ
This option also controls the 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 don't get comfy with them.
These warnings are enabled by default. ๐
-Wno-narrowing(C++ and Objective-C++ only) โ for C++11 and later standards, narrowing conversions get diagnosed by default, as the standard demands. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but-Wno-narrowingsuppresses the diagnostic. ๐ข Heads up tho: this does not affect the meaning of well-formed code โ narrowing conversions are still considered ill-formed in SFINAE contexts. no cap.
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 happens inside { }, 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()ornoexcept) but is known by the compiler to never throw an exception. awkward!! ๐ซ-Wnoexcept-type(C++ and Objective-C++ only) โ warn if the C++17 feature makingnoexceptpart of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat.
example time ๐:
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>. the glow-up changed its whole name bestie ๐
-Wclass-memaccess(C++ and Objective-C++ only) โ warn when the destination of a call to a raw memory function likememsetormemcpyis 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 tomemsetbelow is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available. ๐ผ
std::string str = "abc";
memset (&str, 0, sizeof str);
The -Wclass-memaccess option is enabled by -Wall. Explicitly casting the pointer to the class object to void * or to a type that can be safely accessed by the raw memory function suppresses the warning. โจ
-Wnon-virtual-dtor(C++ and Objective-C++ only) โ warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class. in that case it's 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.-Wregister(C++ and Objective-C++ only) โ warn on uses of theregisterstorage class specifier, except when it's part of the GNU Explicit Register Variables extension. The use of theregisterkeyword as storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with-std=c++17. rip register, you had a good run ๐ชฆ-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. like:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for i and j to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall. the compiler said "i'll fix it but i'm telling on you" ๐ฃ
-Wno-pessimizing-move(C++ and Objective-C++ only) โ this warning warns when a call tostd::moveprevents 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. ๐ญ you sabotaged yourself bestie.
This warning is enabled by -Wall.
-Wno-redundant-move(C++ and Objective-C++ only) โ this warning warns about redundant calls tostd::move; that is, when a move operation would have been performed even without thestd::movecall. 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. ๐ doing the most for no reason.
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. small copy? fine. big copy? we're talking. ๐ฃ๏ธ
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. that's a lot of little ghosts per loop cycle ngl ๐ป
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 load-bearing ๐
-Wno-subobject-linkage(C++ and Objective-C++ only) โ do not warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage. If a type A depends on a type B with no or internal linkage, defining it in multiple translation units would be an ODR violation because the meaning of B is different in each translation unit. If A only appears in a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn't give this warning for types defined in the main.Cfile, as those are unlikely to have multiple definitions.-Wsubobject-linkageis enabled by default. ๐-Weffc++(C++ and Objective-C++ only) โ 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. ๐ง
-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. So like, if your catch blocks are in the wrong order, this warning would normally tell you โ but this flag says โnah, Iโm good.โ ๐
-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 vibes, bestie โ other compilers might side-eye you. ๐
-Wno-non-template-friend (C++ and Objective-C++ only) ๐ฆ
Disable warnings when non-template friend functions are declared within a template. In very old versions of GCC that predate implementation of the ISO standard, declarations such as friend int foo(int), where the name of the friend is an unqualified-id, could be interpreted as a particular specialization of a template function; the warning exists to diagnose compatibility problems, and is enabled by default. So this is like, a blast from the past, and the warning is on by default. ๐
-Wold-style-cast (C++ and Objective-C++ only) ๐
Warn if an old-style (C-style) cast to a non-void type is used within a C++ program. The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are less vulnerable to unintended effects and much easier to search for. So like, stop using the crusty C casts, bestie โ the new ones are iconic and safer. ๐
-Woverloaded-virtual (C++ and Objective-C++ only) ๐ฅ
Warn when a function declaration hides virtual functions from a base class. For example, in:
struct A {
virtual void f();
};
struct B: public A {
void f(int);
};
the A class version of f is hidden in B, and code like:
B* b;
b->f();
fails to compile. So like, the vibe is: Bโs f(int) is hiding Aโs f(), and thatโs a no-no. ๐ญ
-Wno-pmf-conversions (C++ and Objective-C++ only) ๐
Disable the diagnostic for converting a bound pointer to member function to a plain pointer. So like, if youโre doing that sketchy conversion, this flag tells GCC to chill. ๐ง
-Wsign-promo (C++ and Objective-C++ only) โจ
Warn when overload resolution chooses a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. So like, the standard said โweโre doing it this way now,โ and this warning is like, โhey, just so you know.โ ๐
-Wtemplates (C++ and Objective-C++ only) ๐
Warn when a primary template declaration is encountered. Some coding rules disallow templates, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also instantiate or specialize templates. So like, if your coding rule is โno templates,โ this is your enforcer, but it wonโt snitch on the STL. ๐ซถ
-Wmismatched-new-delete (C++ and Objective-C++ only) ๐
Warn for mismatches between calls to operator new or operator delete and the corresponding call to the allocation or deallocation function. This includes invocations of C++ operator delete with pointers returned from either mismatched forms of operator new, or from other functions that allocate objects for which the operator delete isnโt a suitable deallocator, as well as calls to other deallocation functions with pointers returned from operator new for which the deallocation function isnโt suitable.
For example, the delete expression in the function below is diagnosed because it doesnโt match the array form of the new expression the pointer argument was returned from. Similarly, the call to free is also diagnosed.
void f ()
{
int *a = new int[n];
delete a; // warning: mismatch in array forms of expressions
char *p = new char[n];
free (p); // warning: mismatch between new and free
}
The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete.
-Wmismatched-new-delete is included in -Wall. So like, if youโre using -Wall, you already got this. ๐ฅ
-Wmismatched-tags (C++ and Objective-C++ only) ๐
Warn for declarations of structs, classes, and class templates and their specializations with a class-key that does not match either the definition or the first declaration if no definition is provided.
For example, the declaration 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 as the example above shows. The -Wmismatched-tags option is intended to help achieve a consistent style of class declarations. In code that is intended to be portable to Windows-based compilers the warning helps prevent unresolved references due to the difference in the mangling of symbols declared with different class-keys. The option can be used either on its own or in conjunction with -Wredundant-tags. So like, itโs a style thing, but also a portability thing. ๐
-Wmultiple-inheritance (C++ and Objective-C++ only) ๐
Warn when a class is defined with multiple direct base classes. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use multiple inheritance. So like, if your rule is โno multiple inheritance,โ this is your girl. ๐ซถ
-Wvirtual-inheritance โจ
Warn when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use virtual inheritance. So like, same energy as above, but for virtual bases. ๐ฆ
-Wno-virtual-move-assign ๐
Suppress warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled. So like, this is dangerous, bestie โ donโt just silence it unless you know what youโre doing. ๐ญ
-Wnamespaces ๐
Warn when a namespace definition is opened. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also use using directives and qualified names. So like, if your coding rule says โno namespaces,โ this is your enforcer. ๐
-Wno-terminate (C++ and Objective-C++ only) โจ
Disable the warning about a throw-expression that will immediately result in a call to terminate. So like, if your throw is gonna hit terminate instantly, this flag says โI donโt wanna hear it.โ ๐
-Wno-vexing-parse (C++ and Objective-C++ only) ๐
Warn about the most vexing parse syntactic ambiguity. This warns about the cases when a declaration looks like a variable definition, but the C++ language requires it to be interpreted as a function declaration. For instance:
void f(double a) {
int i(); // extern int i (void);
int n(int(a)); // extern int n (int);
}
Another example:
struct S { S(int); };
void f(double a) {
S x(int(a)); // extern struct S x (int);
S y(int()); // extern struct S y (int (*) (void));
S z(); // extern struct S z (void);
}
The warning will suggest options how to deal with such an ambiguity; e.g., it can suggest removing the parentheses or using braces instead.
This warning is enabled by default. So like, itโs on by default, and itโs here to save you from the most vexing parse. ๐ญ
-Wno-class-conversion (C++ and Objective-C++ only) ๐
Do not warn when a conversion function converts an object to the same type, to a base class of that type, or to void; such a conversion function will never be called. So like, if itโs never gonna be called, why warn? This flag says โdonโt.โ ๐
-Wvolatile (C++ and Objective-C++ only) ๐ฅ
Warn about deprecated uses of the volatile qualifier. This includes postfix and prefix ++ and -- expressions of volatile-qualified types, using simple assignments where the left operand is a volatile-qualified non-class type for their value, compound assignments where the left operand is a volatile-qualified non-class type, volatile-qualified function return type, volatile-qualified parameter type, and structured bindings of a volatile-qualified type. This usage was deprecated in C++20.
Enabled by default with -std=c++20. So like, if youโre on C++20, you already got this warning. ๐
-Wzero-as-null-pointer-constant (C++ and Objective-C++ only) โจ
Warn when a literal 0 is used as null pointer constant. This can be useful to facilitate the conversion to nullptr in C++11. So like, stop using 0 as null, bestie โ use nullptr. ๐
-Waligned-new ๐ฆ
Warn about a new-expression of a type that requires greater alignment than the alignof(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. So like, if you need more alignment, this is your warning. ๐ซถ
-Wno-placement-new, -Wplacement-new=n ๐
Warn about placement new expressions with undefined behavior, such as constructing an object in a buffer that is smaller than the type of the object. For example, the placement new expression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large.
char buf [64];
new (buf) int[64];
This warning is enabled by default. So like, if youโre doing placement new into a too-small buffer, thatโs undefined behavior, and this warning will call it out. ๐ญ
-Wplacement-new=1โ this is the default level of-Wplacement-new, bestie ๐ At this level, the warning is not issued for some strictly undefined constructs that GCC allows as extensions for compatibility with legacy code. Like, 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โ level up, queen ๐ At this level, in addition to diagnosing all the same constructs as at level 1, a diagnostic is also issued for placement new expressions that construct an object in the last member of a structure whose type is an array of a single element and whose size is less than the size of the object being constructed. So the previous example would be diagnosed โ but the following construct makes use of the flexible member array extension to avoid the warning at level 2:
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
-Wcatch-value,-Wcatch-value=n(C++ and Objective-C++ only) โ warn about catch handlers that don't catch via reference ๐ฆ With-Wcatch-value=1(or just-Wcatch-valuefor short) it warns about polymorphic class types that are caught by value. With-Wcatch-value=2it warns about all class types caught by value. With-Wcatch-value=3it warns about all types that aren't caught by reference. And-Wcatch-valueis enabled by-Wall. ๐-Wconditionally-supported(C++ and Objective-C++ only) โ warns for conditionally-supported (C++11 [intro.defs]) constructs. iykyk โจ-Wno-delete-incomplete(C++ and Objective-C++ only) โ do NOT warn when deleting a pointer to incomplete type, which may cause undefined behavior at runtime ๐. This warning is enabled by default, so this flag is you turning it off on purpose. Be careful bestie.-Wextra-semi(C++, Objective-C++ only) โ warns about redundant semicolons after in-class function definitions. Not me leaving a stray;everywhere ๐-Wno-inaccessible-base(C++, Objective-C++ only) โ this option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. The warning is enabled by default. Note that the warning for ambiguous virtual bases is enabled by the-Wextraoption.
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ suppresses warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor. The warning is on by default because the ellipsis is not inherited. sneaky ellipsis behavior, honestly iconic ๐-Wno-invalid-offsetof(C++ and Objective-C++ only) โ suppresses warnings from applying theoffsetofmacro to a non-POD type. According to the 2014 ISO C++ standard, applyingoffsetofto a non-standard-layout type is undefined ๐ญ. In existing C++ implementations, however,offsetoftypically gives meaningful results. This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it.
The restrictions on offsetof may be relaxed in a future version of the C++ standard. so stay tuned, fr fr ๐
-Wsized-deallocation(C++ and Objective-C++ only) โ warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
without a definition of the corresponding sized deallocation function
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
or vice versa. Enabled by -Wextra along with -fsized-deallocation. gotta keep your deallocations matched, bestie ๐
-Wsuggest-final-typesโ warns about types with virtual methods where code quality would be improved if the type were declared with the C++11finalspecifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. devirtualization slay โจ This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete.-Wsuggest-final-methodsโ warns about virtual methods where code quality would be improved if the method were declared with the C++11finalspecifier, or, if possible, its type were declared in an anonymous namespace or with thefinalspecifier. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. It is recommended to first consider suggestions of-Wsuggest-final-typesand then rebuild with new annotations. order matters, bestie, do it in sequence ๐-Wsuggest-overrideโ warns about overriding virtual functions that are not marked with theoverridekeyword. just writeoverride!! ๐-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. The warning is enabled at all optimization levels but may yield different results with optimization than without. vibe check: it's always watching ๐-Wuse-after-free=1โ at level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call torealloc, regardless of whether or not the call resulted in an actual reallocation of memory. This includes double-freecalls as well as uses in arithmetic and relational expressions. Although undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.-Wuse-after-free=2โ at level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As before, uses in equality (or inequality) expressions are not diagnosed. For example, the second call tofreein the following function is diagnosed at this level:
struct A { int refcount; void *data; };
void release (struct A *p)
{
int refcount = --p->refcount;
free (p);
if (refcount == 0)
free (p->data); // warning: p may be used after free
}
-Wuse-after-free=3โ at level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined but equality tests sometimes appear after calls toreallocas an attempt to determine whether the call resulted in relocating the object to a different address. They are diagnosed at a separate level to aid legacy code gradually transition to safe alternatives. For example, the equality test in the function below is diagnosed at this level:
void adjust_pointers (int**, int);
void grow (int **p, int n)
{
int **q = (int**)realloc (p, n *= 2);
if (q == p)
return;
adjust_pointers ((int**)q, n);
}
To avoid the warning at this level, store offsets into allocated memory instead of pointers. This approach obviates needing to adjust the stored pointers after reallocation. offsets > pointers, periodt ๐
-Wuse-after-free=2is included in-Wall.
-Wuseless-cast(C++ and Objective-C++ only) โ warns when an expression is casted to its own type. casting something to what it already is? not the move, bestie ๐-Wno-conversion-null(C++ and Objective-C++ only) โ do not warn for conversions betweenNULLand non-pointer types.-Wconversion-nullis enabled by default. ๐ธ
โจ Options Controlling Objective-C and Objective-C++ Dialects โจ
(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves. we're just doing the compiler flags here ๐)
This section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs. You can also use most of the language-independent GNU compiler options. 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). it's giving "borrowed options" energy ๐
Here is a list of options that are only for compiling Objective-C and Objective-C++ programs:
-fconstant-string-class=class-nameโ use class-name as the name of the class to instantiate for each literal string specified with the syntax@"...". The default class name isNXConstantStringif the GNU runtime is being used, andNSConstantStringif the NeXT runtime is being used (see below). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption, if also present, overrides the-fconstant-string-classsetting and causes@"..."literals to be laid out as constant CoreFoundation strings. Note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. aliases upon aliases, iconic honestly ๐-fgnu-runtimeโ generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐-fnext-runtimeโ generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro__NEXT_RUNTIME__is predefined if (and only if) this option is used. only-if, bestie, don't forget โจ-fno-nil-receiversโ assume that all Objective-C message dispatches ([receiver message:arg]) in this translation unit ensure that the receiver is notnil. This allows for more efficient entry points in the runtime to be used. This option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. ๐ฆ-fobjc-abi-version=nโ pick version n of the Objective-C ABI for whichever runtime you've got going on. rn this one only works with the NeXT runtime, just so you know ๐. So: Version0is the traditional (32-bit) ABI, no support for properties and the other Objective-C 2.0 additions. Version1is the traditional (32-bit) ABI but with support for properties and those other Objective-C 2.0 additions. Version2is the modern (64-bit) ABI. And if you don't specify anything at all? Default is Version0on 32-bit target machines, and Version2on 64-bit target machines. no cap ๐-fobjc-call-cxx-cdtorsโ okay so for every Objective-C class, the compiler checks if any of its instance variables is a C++ object with a non-trivial default constructor. If yes, 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 vibe for destruction: it checks if 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. iconic tbh ๐ฆ
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 is the responsibility of the Objective-C runtime 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; the - (void) .cxx_destruct methods get invoked immediately before the runtime deallocates an object instance. the way that the runtime handles all this?? chef's kiss โจ
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โ allow fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. literally zooming ๐๏ธ-fobjc-exceptionsโ enables syntactic support for structured exception handling in Objective-C, similar to what C++ offers. This option is required to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. It's available with both the GNU runtime and the NeXT runtime โ but not in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier, bestie, so watch out for that one ๐-fobjc-gcโ enable 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 does not require special compiler flags. two different girlies, two different approaches ๐-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, check for anilreceiver 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 in this way, no matter what this flag is set to. And currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used. doing the most for no reason ๐ญ-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 this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that is not recognized by GCC 4.0 is rejected. super useful if you need to make sure your Objective-C code can be compiled with older versions of GCC. backwards compatibility queen ๐-freplace-objc-classesโ emit a special marker instructingld(1)not to statically link in the resulting object file, and allowdyld(1)to load it in at run time instead. This is used in conjunction 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, without the 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. live reloading before it was cool ๐ฅ-fzero-linkโ when compiling for the NeXT runtime, the compiler ordinarily replaces calls toobjc_getClass("...")(when the name of the class is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the-fzero-linkflag suppresses this behavior and causes calls toobjc_getClass("...")to be retained. This is useful in Zero-Link debugging mode, since it allows for individual class implementations to be modified during program execution. The GNU runtime currently always retains calls toobjc_get_class("...")regardless of command-line options. it's giving โจ flexible โจ-fno-local-ivarsโ by default, instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. This can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the-fno-local-ivarsflag disables this behavior, thus avoiding variable shadowing issues. no more identity theft fr fr ๐-fivar-visibility=[public|protected|private|package]โ set the default instance variable visibility to the specified option, so that instance variables declared outside the scope of any access modifier directives default to the specified visibility. pick your vibe ๐-gen-declsโ dump interface declarations for all classes seen in the source file to a file namedsourcename.decl. receipts, but make it a file ๐-Wassign-intercept(Objective-C and Objective-C++ only) โ warn whenever an Objective-C assignment is being intercepted by the garbage collector. not me getting intercepted ๐ณ-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. letting it slide, respectfully ๐คซ-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 is not implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the-Wno-protocoloption, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them. inherited counts now, we love to see it ๐ซถ-Wobjc-root-class(Objective-C and Objective-C++ only) โ warn 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)). main character energy, no parent required ๐-Wselector(Objective-C and Objective-C++ only) โ warn 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. final stage only, bestie, so don't be surprised when it ghosts you ๐-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warn 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. same size and alignment? we'll let it slide ๐-Wundeclared-selector(Objective-C and Objective-C++ only) โ warn 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. declare first, ask questions later โจ-print-objc-runtime-infoโ generate C header describing the largest structure that is passed by value, if any. the big one, if it exists ๐
โจ 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. rude of them tbh ๐ค
-fmessage-length=nโ try to format error messages so that 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. so if you like your errors long and unbroken, zero is your girl ๐
Note โ this option also affects the display of the #error and #warning pre-processor directives, and the deprecated function/type/variable attribute. It does not, however, affect the pragma GCC warning and pragma GCC error pragmas. specific much? yes. correct? also yes ๐
-fdiagnostics-plain-outputโ this option requests that diagnostic output look as plain as possible, which may be useful when runningdejagnuor other utilities that need to parse diagnostics output and prefer that it remain more stable over time.-fdiagnostics-plain-outputis currently equivalent to the following options:
-fno-diagnostics-show-caret
-fno-diagnostics-show-line-numbers
-fdiagnostics-color=never
-fdiagnostics-urls=never
-fdiagnostics-path-format=separate-events
In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list. no surprises, no chaos, just plain text ๐ธ
-fdiagnostics-show-location=onceโ okay so this one only matters in line-wrapping mode, no cap. It tells the diagnostic reporter to drop the source location once โ like, if the message is too long to fit on one physical line and has to wrap, the source location does not get repeated as a prefix over and over on the continuation lines. And bestie, this is literally the default behavior. ๐-fdiagnostics-show-location=every-lineโ also only meaningful in line-wrapping mode. This one says: yeah, emit that same source location info (as a prefix) for every physical line that comes out of breaking up a message that's too long for one line. ๐
๐ -fdiagnostics-color[=WHEN] and -fno-diagnostics-color ๐
Use color in diagnostics, periodt. ๐จ WHEN is never, always, or auto. The default depends on how the compiler was configured โ it can be any of those WHEN options, or also never if the GCC_COLORS environment variable isn't present in the environment, and auto otherwise. auto makes GCC use color only when standard error is a terminal, and when it's not executing in an emacs shell. ๐ฅ๏ธ The forms -fdiagnostics-color and -fno-diagnostics-color are aliases for -fdiagnostics-color=always and -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. (Go check the section in your text terminal's documentation for permitted values and what they mean as character attributes, iykyk.) 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
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.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, bestie. ๐ For example, when -fdiagnostics-show-option emits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option.
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when the standard error is a terminal, and when not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature, see below. ๐
The default depends on how the compiler has been configured. It can be any of the above WHEN options.
GCC can also be configured (via the --with-diagnostics-urls=auto-if-env configure-time option) so that the default is affected by environment variables. Under such a configuration, GCC defaults to using auto if either GCC_URLS or TERM_URLS environment variables are present and non-empty in the environment of the compiler, or never if neither are.
However, even with -fdiagnostics-urls=always the behavior is 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=n option 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@url{https://cwe.mitre.org/index.html, CWE}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-line-numbersโ By default, when printing source code (via-fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin. ๐ข- *
-fdiagnostics-minimum-margin-width=width* โ This option controls the minimum width of the left margin printed by-fdiagnostics-show-line-numbers. It defaults to6. ๐ -fdiagnostics-parseable-fixitsโ Emit fix-it hints in a machine-parseable format, suitable for consumption by IDEs. ๐ค For each fix-it, a line will be printed after the relevant diagnostic, starting with the stringfix-it:. For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of test.c are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as \\, tab as \t, newline as \n, double quotes as \", non-printable characters as octal (e.g. vertical tab as \013). ๐งผ
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. 45:3-45:3) indicates that the string is to be inserted at the given position. โ๏ธ
-fdiagnostics-generate-patchโ Print fix-it hints to stderr in unified diff format, after any diagnostics are printed. ๐ For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
void show_cb(GtkDialog *dlg)
{
- gtk_widget_showall(dlg);
+ gtk_widget_show_all(dlg);
}
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color). ๐จ
-fdiagnostics-show-template-treeโ In the C++ frontend, when printing diagnostics showing mismatching template types, such as:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
the -fdiagnostics-show-template-tree flag enables printing a tree-like structure showing the common and differing parts of the types, such as:
map<
[...],
vector<
[double != float]>>
๐ณโจ
The parts that differ are highlighted with color (that's "double" and "float" in this case). ๐
-fno-elide-typeโ okay so by default, when the C++ frontend prints diagnostics showing mismatching template types, the common parts of those types get printed as"[...]"to keep the error message cute and simplified. Like:
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. No more hiding the common bits, bestie. This flag also affects the output of the -fdiagnostics-show-template-tree flag. โจ
-fdiagnostics-path-format=KINDโ tells GCC how to print paths of control-flow events for diagnostics that have such a path attached to them.KINDisnone,separate-events, orinline-events, the default. ๐nonemeans to not print diagnostic paths at all. Ghosted. ๐separate-eventsmeans to print a separate"note"diagnostic for each event within the diagnostic. For example:
test.c:29:5: error: passing NULL as argument 1 to 'PyList_Append' which requires a non-NULL parameter
test.c:25:10: note: (1) when 'PyList_New' fails, returning NULL
test.c:27:3: note: (2) when 'i < count'
test.c:29:5: note: (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
inline-eventsmeans to print the events "inline" within the source code. This view attempts to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges within the source. ๐ซถ
For example, the same events as above might be printed as:
'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 is shown by grouping the events by stack frame, and using indentation to show how stack frames are nested, pushed, and popped. It's giving stack-trace but make it fashion. ๐
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 provides additional information when printing control-flow paths associated with a diagnostic. If this option is provided then the stack depth will be printed for each run of events within-fdiagnostics-path-format=separate-events.
This is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. So like, devs only, bestie. ๐ฉโ๐ป
-fno-show-columnโ do not print column numbers in diagnostics. This may be necessary if diagnostics are being scanned by a program that does not understand the column numbers, such asdejagnu. It's giving "please stop confusing my parser." ๐ญ-fdiagnostics-column-unit=UNITโ select the units for the column number. This affects traditional diagnostics (in the absence of-fno-show-column), as well as JSON format diagnostics if requested.
The default UNIT, display, considers the number of display columns occupied by each character. This may be larger than the number of bytes required to encode the character, in the case of tab characters, or it may be smaller, in the case of multibyte characters. For example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding requires two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding requires four bytes. ๐ง
Setting UNIT to byte changes the column number to the raw byte count in all cases, as was traditionally output by GCC prior to version 11.1.0. No cap, that's the old-school way.
-fdiagnostics-column-origin=ORIGINโ select the origin for column numbers, i.e. the column number assigned to the first column. The default value of1corresponds to traditional GCC behavior and to the GNU style guide. Some utilities may perform better with an origin of0; any non-negative value may be specified. So like, you can start counting from wherever, just keep it non-negative. ๐-fdiagnostics-escape-format=FORMATโ when GCC prints pertinent source lines for a diagnostic it normally attempts to print the source bytes directly. However, some diagnostics relate to encoding issues in the source file, such as malformed UTF-8, or issues with Unicode normalization. These diagnostics are flagged so that GCC will escape bytes that are not printable ASCII when printing their pertinent source lines.
This option controls how such bytes should be escaped.
The default FORMAT, unicode, displays Unicode characters that are not printable ASCII in the form <U+XXXX>, and bytes that do not correspond to a Unicode character validly-encoded in UTF-8-encoded will be 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 will display all non-printable-ASCII bytes in the form <XX>, thus showing the underlying encoding of non-ASCII Unicode characters. For the example above, the following will be printed:
before<CF><80><BF>after
-fdiagnostics-format=FORMATโ select a different format for printing diagnostics.FORMATistextorjson. The default istext.
The json format 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:
[
{
"kind": "warning",
"locations": [
{
"caret": {
"display-column": 3,
"byte-column": 3,
"column": 3,
"file": "misleading-indentation.c",
"line": 15
},
"finish": {
"display-column": 4,
"byte-column": 4,
"column": 4,
"file": "misleading-indentation.c",
"line": 15
}
}
],
"message": "this \u2018if\u2019 clause does not guard...",
"option": "-Wmisleading-indentation",
"option_url": "https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmisleading-indentation",
"children": [
{
"kind": "note",
"locations": [
{
"caret": {
"display-column": 5,
"byte-column": 5,
"column": 5,
"file": "misleading-indentation.c",
"line": 17
}
}
],
"escape-source": false,
"message": "...this statement, but the latter is ..."
}
]
"escape-source": false,
"column-origin": 1,
}
]
okay so bestie, in that little nest up there the "note" is literally a child of the "warning" ๐ โ like the warning is the mom and the note is the kid tagging along, iykyk.
So every diagnostic has a "kind". If that kind is "warning", then there's an "option" key describing the command-line option that controls the warning. the receipts are right there fr fr ๐งพ
A diagnostic can contain zero or more locations. Each location has an optional "label" string and up to three positions inside it: a "caret" position and optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers indicating a column position:
"display-column"counts display columns, accounting for tabs and multibyte characters. yes it's giving "I actually understand Unicode" energy โจ"byte-column"counts raw bytes. the raw, unfiltered truth ๐"column"is equal to one of the previous two, as dictated by the-fdiagnostics-column-unitoption. it's a pick-one situation, not both, no cap
All three columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but may be set, for instance, to 0 for compatibility with other utilities that number columns from 0. The column origin is recorded in the JSON output in the "column-origin" tag. In the remaining examples below, the extra column number outputs have been omitted for brevity. we're keeping it cute and short bestie ๐
For example, this error:
bad-binary-ops.c:64:23: error: invalid operands to binary + (have 'S' {aka
'struct s'} and 'T' {aka 'struct t'})
64 | return callee_4a () + callee_4b ();
| ~~~~~~~~~~~~ ^ ~~~~~~~~~~~~
| | |
| | T {aka struct t}
| S {aka struct s}
has three locations. Its primary location is at the + token at column 23. It has two secondary locations, describing the left and right-hand sides of the expression, which have labels. labeled, dressed, and ready to be perceived ๐
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 + ..."
}
next up: fix-its, aka the "here's how you fix it bestie" array ๐ซถ
If a diagnostic contains fix-it hints, it has a "fixits" array, consisting of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. For example, this diagnostic with a replacement fix-it hint:
demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
mean 'color'?
8 | return ptr->colour;
| ^~~~~~
| color
might be printed in JSON form as:
{
"children": [],
"fixits": [
{
"next": {
"column": 21,
"file": "demo.c",
"line": 8
},
"start": {
"column": 15,
"file": "demo.c",
"line": 8
},
"string": "color"
}
],
"kind": "error",
"locations": [
{
"caret": {
"column": 15,
"file": "demo.c",
"line": 8
},
"finish": {
"column": 20,
"file": "demo.c",
"line": 8
}
}
],
"escape-source": false,
"message": "\u2018struct s\u2019 has no member named ..."
}
where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value. read that again bestie: up to but NOT including. the next is exclusive, it's giving half-open interval realness โจ
- Deletions are expressed via an empty value for
"string". gone, deleted, blocked ๐ - Insertions by having
"start"equal"next". a little zero-width moment, we love to see it ๐ธ
now for the path girlies ๐ฃ๏ธ
If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing the events. Each event object has a "description" string, a "location" object, along with a "function" string and a "depth" number for representing interprocedural paths. The "function" represents the current function at that event, and the "depth" represents the stack depth relative to some baseline: the higher, the more frames are within the stack โ like, deeper in the call stack, deeper in the lore ๐ณ๏ธ
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
}
}
]
Last lil detail, and then we move on I promise: diagnostics have a boolean attribute "escape-source", hinting whether non-ASCII bytes should be escaped when printing the pertinent lines of source code ("true" for diagnostics involving source encoding issues). only for the encoding-issue girlies, very specific, very niche, very iconic ๐
โจ Options to Request or Suppress Warnings โจ
okay so warnings. what are they? they're diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error. ๐ธ like, technically legal but bestie... are we sure? ๐
The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC. they're the vibe-setters, not the specific-warning-enablers, okurrr ๐
-fsyntax-onlyโ Check the code for syntax errors, but don't do anything beyond that. literally just vibes-checking the syntax and then clocking out ๐-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. the drama: GCC says "I've had ENOUGH" and leaves the group chat ๐-wโ Inhibit all warning messages. full mute. not a single warning is getting through. blocked, unbothered, in my lane ๐-Werrorโ Make all warnings into errors. every warning gets a glow-up into a full-on error, no more soft launches bestie, it's giving consequences โจ๐ฅ
-Werror= ๐
Okay bestie, this one turns a specific warning into a full-on error. You append the specifier for the warning; so like -Werror=switch makes everything controlled by -Wswitch into an error instead of a lil warning. โจ
There's a negative form too, for when you want to un-error one specific thing โ -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is chugging along in the background being dramatic. ๐
Every controllable warning message literally tells you which option controls it. So you can just grab that option and pair it with -Werror= or -Wno-error= like we just said. (If you want that option printed in the message to stop, use -fno-diagnostics-show-option.) ๐
Not me reminding you:-Werror=fooautomatically implies-Wfoo. But-Wno-error=fooimplies nothing. Zero. Nada. No cap. ๐
-Wfatal-errors ๐
This makes the compiler just abort compilation on the very first error that shows up, instead of trying to keep going and printing a whole avalanche of further error messages. It's giving "we're done here" energy. ๐ซถ
You can request a ton of specific warnings with options starting with -W โ like -Wimplicit to ask for warnings on implicit declarations. And every single one of these specific warning options has a negative form starting with -Wno- to turn it off, like -Wno-implicit. ๐ธ
This manual only lists one of the two forms โ whichever one isn't the default. For more language-specific options you also wanna peek at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And you can get extra warnings by enabling the static analyzer. ๐
Some options, like -Wall and -Wextra, turn on other options, like -Wunused, which can turn on further options, like -Wunused-value. The combined effect of positive and negative forms is that more specific options win over less specific ones, no matter where they sit on 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 showed up at the end of the command line. ๐
When an unrecognized warning option is requested (e.g. -Wunknown-warning), GCC emits a diagnostic saying the option isn't recognized. But plot twist: if the -Wno- form is used, it's slightly different โ no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced anyway. This is so you can use new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option is present. ๐ฆ
Also, the effectiveness of some warnings depends on optimizations being enabled too. Like -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings might not be issued at all unless optimization is enabled. And while optimization generally improves the efficacy of control and data flow sensitive warnings, in some cases it may also cause false positives. ๐ญ
-Wpedantic
-pedantic ๐
Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, plus some other programs that don't follow ISO C and ISO C++. For ISO C, it follows the version of the ISO C standard specified by any -std option 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). However โ without this option, certain GNU extensions and traditional C and C++ features are supported too. With this option, they get rejected. โ
-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. So don't hold your breath, bestie. ๐ซถ
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 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. ๐
Careful: this is not equivalent to -Werror=pedantic, since there are errors enabled by this option and not enabled by the latter, and vice versa. Not interchangeable, bestie!
-Wall ๐
This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. 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++)-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-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=3-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-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-Wunusedor-Wall)-Wunused-but-set-parameter(only with-Wunusedor-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 so real talk โ even though the good people behind G++ tried to warn you about every single one of these cases, there are probably still some sneaky ones that slip through with no warning at all, even while G++ is out here generating code that just... isn't compatible. ๐ญ And yeah, the reverse happens too: sometimes you get yelled at by a warning even though the code it made is totally fine.
So if the thought of G++-generated code not being binary compatible with code from other compilers keeps you up at night, rewrite your code to dodge these warnings. That's the move. ๐
Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 all the way to 4.9) include:
- A template with a non-type template parameter of reference type got mangled wrong. Like this:
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 doesn't let you overload functions taking vectors of different sizes.
The mangling got changed in -fabi-version=4.
"__attribute ((const))"andnoreturnwere mangled as type qualifiers, anddecltypeof a plain declaration got folded away.
These mangling issues were fixed in -fabi-version=5.
- Scoped enumerators passed as arguments to a variadic function get promoted like unscoped enumerators do, which makes
va_argcomplain. On most targets this doesn't actually mess with the parameter passing ABI, since there's literally 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, since 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 โ like ia32 calling conventions on a function type (
stdcall,regparm, etc.) โ did not affect the mangled name, which led 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 turns on 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. Before GCC 4.4, that was not the case. For example:
union U {
long double ld;
int i;
};
union U is now always passed in memory.
๐ธ -Wchar-subscripts
Warns you if an array subscript has type char. This is a super common cause of errors, because programmers keep forgetting that this type is signed on some machines. ๐ญ This warning is enabled by -Wall.
๐ -Wno-coverage-mismatch
Warns you if feedback profiles don't match when you're using the -fprofile-use option. If a source file gets changed between compiling with -fprofile-generate and compiling with -fprofile-use, the files with the profile feedback can fail to match the source file, and then GCC can't use that profile feedback info. By default this warning is enabled and treated as an error. -Wno-coverage-mismatch disables the warning, or -Wno-error=coverage-mismatch disables the error. Turning off the error for this warning can give you poorly optimized code, and it's only useful for very minor changes like bug fixes to an existing codebase.
Completely disabling the warning is not recommended. bestie I am begging you, leave it on. ๐
๐ฆ -Wno-coverage-invalid-line-number
Warns you if a function ends earlier than it begins, because of invalid linenum macros. This warning is only emitted when --coverage is enabled.
By default this warning is enabled and treated as an error. -Wno-coverage-invalid-line-number disables the warning, or -Wno-error=coverage-invalid-line-number disables the error.
โจ -Wno-cpp (C, Objective-C, C++, Objective-C++ and Fortran only)
Suppresses warning messages emitted by "#warning" directives. like, quiet, bestie. ๐คซ
๐ -Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
Gives you a warning when a value of type float gets implicitly promoted to double. CPUs with a 32-bit "single-precision" floating-point unit implement float in hardware, but emulate double in software. On a machine like that, doing computations with double values is much more expensive, because of all the overhead that software emulation drags along. ๐ธ
It's genuinely so 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 does the entire computation with double, because the floating-point literal is a double. caught in 4K. ๐ธ
๐ -Wduplicate-decl-specifier (C and Objective-C only)
Warns you if a declaration has a duplicate const, volatile, restrict or _Atomic specifier. This warning is enabled by -Wall.
๐ -Wformat, -Wformat=n
Checks calls to printf and scanf, etc., to make sure the arguments you supplied have types that actually match the format string you specified, and that the conversions in the format string make sense. This covers standard functions, plus others specified by format attributes, across the printf, scanf, strftime and strfmon families (that last one is an X/Open extension, not in the C standard) โ or other target-specific families. Which functions get checked without format attributes having been specified depends on the standard version you selected, and those checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, plus features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used together with -Wformat, you get warnings about format features that aren't in the selected standard version (but not for strfmon formats, since those aren't in any version of the C standard). periodt.
-Wformat=1, -Wformat
Option -Wformat is equivalent to -Wformat=1, and -Wno-format is equivalent to -Wformat=0. Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull. Some aspects of this level of format checking can be disabled by these options: -Wno-format-contains-nul, -Wno-format-extra-args, and -Wno-format-zero-length. -Wformat is enabled by -Wall.
-Wformat=2
Enables -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
๐ -Wno-format-contains-nul
If -Wformat is specified, then do not warn about format strings that contain NUL bytes.
๐ง -Wno-format-extra-args
If -Wformat is specified, then do not warn about excess arguments to a printf or scanf format function. The C standard specifies that such arguments are ignored. so like, it's fine, it's giving "on purpose". ๐
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, warnings are normally still given, since the implementation couldn't know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, because the Single Unix Specification says such unused arguments are allowed.
โญ -Wformat-overflow, -Wformat-overflow=level
Warns about calls to formatted input/output functions like sprintf and vsprintf that might overflow the destination buffer. ๐ฑ When the exact number of bytes written by a format directive can't be determined at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. Enabling optimization will in most cases improve the accuracy of the warning, but it may also result in false positives. it's giving "trust me bro, but also maybe don't".
-Wformat-overflow, -Wformat-overflow=1
Level 1 of -Wformat-overflow (enabled by -Wformat) takes a conservative approach and warns only about calls that most likely overflow the buffer. At this level, numeric arguments to format directives with unknown values are assumed to have the value of one, and strings of unknown length are assumed to be empty. Numeric arguments known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive's precision or by a finite set of string literals, are assumed to take on the value within the range that results in the most bytes on output. For example, the call to sprintf below is diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') appended by the function to the destination buffer will be written past its end. Increasing the size of the buffer by a single byte is enough to avoid the warning, though it may not be enough to avoid the overflow.
void f (int a, int b)
{
char buf [13];
sprintf (buf, "a = %i, b = %i\n", a, b);
}
-Wformat-overflow=2 โจ
okay bestie, level 2 is where it gets extra ๐. It doesn't just warn about the obvious overflow โ it also warns about calls that might overflow the destination buffer if you give it an argument of sufficient length or magnitude. ๐ฅ
At level 2, unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string arguments whose length cannot be assumed to be bounded either by the directive's precision, or by a finite set of string literals they may evaluate to, or the character array they may point to, are assumed to be 1 character long. ๐ง
At level 2, the call in the example above is again diagnosed, but this time because with a equal to a 32-bit INT_MIN the first %i directive will write some of its digits beyond the end of the destination buffer. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC includes the minimum size of the buffer in an informational note following the warning. ๐
An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the short int type then using either the %hi format directive or casting the argument to short reduces the maximum required size of the buffer to 24 bytes. ๐ธ
void f (int a, int b)
{
char buf [23];
sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
-Wno-format-zero-length ๐
If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed. So like, chill, it's legal. ๐
-Wformat-nonliteral ๐ฆ
If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list. ๐
-Wformat-security ๐ฅ
If -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (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-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral.) ๐จ
-Wformat-signedness ๐
If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa. Like, pick a lane bestie. ๐
-Wformat-truncation ๐
-Wformat-truncation=level โญ
Warn about calls to formatted input/output functions such as snprintf and vsnprintf that might result in output truncation. 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. Except as noted otherwise, the option uses the same logic -Wformat-overflow. ๐ง
-Wformat-truncation-Wformat-truncation=1โ Level 1 of-Wformat-truncationenabled by-Wformatemploys a conservative approach that warns only about calls to bounded functions whose return value is unused and that will most likely result in output truncation.-Wformat-truncation=2โ Level 2 warns also 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 -Wformat is specified, also warn about strftime formats that may yield only a two-digit year. Y2K called, it wants its paranoia back. ๐
-Wnonnull ๐ซถ
Warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute. -Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option. ๐ซ
-Wnonnull-compare ๐
Warn when comparing an argument marked with the nonnull function 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 due to dereferencing a null pointer. This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used. ๐
-Winfinite-recursion ๐
Warn about infinitely recursive calls. The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions. -Winfinite-recursion is included in -Wall. ๐
-Winit-self (C, C++, Objective-C and Objective-C++ only) ๐ง
Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option. ๐คฏ
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 does not specify a type. This warning is enabled by default in C99 and later dialects of C, and also by -Wall. ๐
-Wno-implicit-function-declaration (C and Objective-C only) ๐ฆ
This option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by -Wall. The warning is made into an error by -pedantic-errors. โ ๏ธ
-Wimplicit (C and Objective-C only) ๐
Same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall. ๐ซถ
-Wimplicit-fallthrough ๐ธ
-Wimplicit-fallthrough is the same as -Wimplicit-fallthrough=3 and -Wno-implicit-fallthrough is the same as -Wimplicit-fallthrough=0. ๐
-Wimplicit-fallthrough=n ๐
Warn when a switch case falls through. For example:
switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;
case 3:
a = 3;
break;
}
This warning does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement or a call to function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.
switch (cond)
{
case 1:
if (i > 3) {
bar (5);
break;
} else if (i < 1) {
bar (0);
} else
return;
default:
...
}
Since there are occasions where a switch case fall through is desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that is 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 is also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:
-Wimplicit-fallthrough=0disables the warning altogether.-Wimplicit-fallthrough=1matches".*"regular expression, any comment is used as fallthrough comment.-Wimplicit-fallthrough=2case insensitively matches".*falls?[ \t-]*thr(ough|u).*"regular expression.-Wimplicit-fallthrough=3case 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=4case sensitively matches one of the following regular expressions:-fallthrough@fallthrough@lint -fallthrough[ \t]*[ \t]*FALLTHR(OUGH|U)[ \t]*
-Wimplicit-fallthrough=5doesn't recognize any comments as fallthrough comments, only attributes disable the warning.
The comment needs to be followed after optional whitespace and other comments by case or default keywords or by a user label that precedes some case or default label.
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra. โจ
-Wno-if-not-aligned(C, C++, Objective-C and Objective-C++ only) โ this one controls whether you get warned about stuff triggered by thewarn_if_not_alignedattribute. And bestie, these warnings are on by default, so if you're seeing them, that's why. โจ-Wignored-qualifiers(C and C++ only) โ warns you when a function's return type is carrying a type qualifier likeconst๐. In ISO C that qualifier literally does nothing, because the value a function returns isn't an lvalue โ it's giving "decorative, no function". In C++ the warning only fires for scalar types orvoid. And heads up: ISO C prohibits qualifiedvoidreturn types on function definitions, so those return types always get a warning even if you don't pass this option. no cap.
This warning is also enabled by -Wextra.
-Wno-ignored-attributes(C and C++ only) โ controls the warnings you get when an attribute gets ignored. This is different from the-Wattributesoption, because this one fires whenever the compiler decides to drop an attribute โ not when the attribute is unknown, used in the wrong place, etc. Enabled by default, iykyk. ๐-Wmainโ warns you if the type ofmainis looking sus ๐ญ.mainshould be a function with external linkage, returningint, and taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++, and it's enabled by either-Wallor-Wpedantic.-Wmisleading-indentation(C and C++ only) โ warns when your indentation does not match the actual block structure. Specifically, it fires forif,else,while, andforclauses whose guarded statement has no braces, followed by an unguarded statement sitting at the same indentation. The betrayal. ๐
In this example, the call to bar is misleadingly indented like it's guarded by the if conditional:
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
When you've got mixed tabs and spaces, the warning uses the -ftabstop= option to figure out if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic, like this:
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
And it's not issued after a #line directive either, because that usually means autogenerated code, and you can't make assumptions about the layout of the file that the directive points to. ๐คท
This warning is enabled by -Wall in C and C++.
-Wmissing-attributesโ warns when a declaration of a function is missing one or more attributes that a related function was declared with, where that absence might mess with the correctness or efficiency of the generated code. For example, it fires for declarations of aliases that use attributes specifying less restrictive requirements than their targets. That's typically a potential optimization opportunity, bestie โ free glow-up sitting right there. โจ 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. ๐ฌ
The attributes considered include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice.
In C++, the warning is issued when an explicit specialization of a primary template declared with attribute alloc_align, alloc_size, assume_aligned, format, format_arg, malloc, or nonnull is declared without it. Attributes deprecated, error, and warning suppress the warning..
You can use the copy attribute to apply the same set of attributes to a declaration as another declaration has, 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 uses both attribute malloc and alloc_size, the declaration of the explicit specialization of the template gets diagnosed because it's missing one of the attributes:
template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);
template <>
void* __attribute__ ((malloc)) // missing alloc_size
allocate<void> (size_t);
-Wmissing-bracesโ warns if an aggregate or union initializer isn't fully bracketed. In this example, the initializer foraisn't fully bracketed, but the one forbis:
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall.
-Wmissing-include-dirs(C, C++, Objective-C, Objective-C++ and Fortran only) โ warns if a user-supplied include directory doesn't actually exist. ๐ป This option is disabled by default for C, C++, Objective-C and Objective-C++. For Fortran, it's partially enabled by default โ it only warns for-Iand-J.-Wno-missing-profileโ this option controls warnings when feedback profiles are missing while you're using the-fprofile-useoption. It diagnoses those cases where a new function or a new file got added between compiling with-fprofile-generateand compiling with-fprofile-use, without regenerating the profiles. In those cases, the profile feedback data files don't contain any profile feedback info for the newly added function or file respectively. Also, when profile count data (.gcda) files get removed, GCC can't use any profile feedback information at all. In all these cases, warnings are issued to tell you a profile generation step is due. ๐
Ignoring the warning can result in poorly optimized code. -Wno-missing-profile can be used to disable the warning, but this is not recommended and should only be done when non-existent profile data is justified.
-Wmismatched-deallocโ warns for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn't a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of the attributemalloc. Unless it's disabled by the-fno-builtinoption, the standard functionscalloc,malloc,realloc, andfree, plus the corresponding forms of C++operator newandoperator delete, are implicitly associated as matching allocators and deallocators. In the following example,mydeallocis 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โ warns about unsafe multiple-statement macros that look like they're guarded by a clause likeif,else,for,switch, orwhile, when actually only the first statement is guarded after the macro expands. The audacity. ๐
For example:
#define DOIT x++; y++
if (c)
DOIT;
This will increment y unconditionally โ not just when c holds. ๐ญ This can usually be fixed by wrapping the macro in a do-while loop:
#define DOIT do { x++; y++; } while (0)
if (c)
DOIT;
This warning is enabled by -Wall in C and C++.
-Wparenthesesโ warns if parentheses are omitted in certain contexts, like when there's an assignment in a spot where a truth value is expected, or when operators get nested in ways whose precedence people often get confused about. ๐
It also warns if a comparison like x<=y<=z shows up; that's equivalent to (x<=y ? 1 : 0) <= z, which is a completely different interpretation from ordinary mathematical notation. math is not mathing here, bestie.
It also warns for dangerous uses of the GNU extension to ?: with the 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++ it 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.
-Wsequence-pointโ warns about code that may have undefined semantics because of violations of the sequence point rules in the C and C++ standards. ๐จ
The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order โ since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap.
ok so bestie, here's the tea on sequence points ๐ซ โ the standard does not say when between sequence points your modifications to object values actually kick in. If your program's whole vibe depends on that timing? undefined behavior, fr fr. The C and C++ standards literally spell it out: "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." Break those rules and literally any implementation can do whatever, and the results are entirely unpredictable. ๐ญ
Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs. (ngl that's a pretty good track record โจ)
The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this option will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++. (it's giving "we still care about your older codebases" energy ๐ )
The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at <https://gcc.gnu.org/readings.html>. ๐ฆ
This warning is enabled by -Wall for C and C++.
-Wno-return-local-addrโ Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (because that pointer is gonna be pointing at ghost data, bestie ๐ป)-Wreturn-typeโ Warn whenever a function is defined with a return type that defaults toint. Also warn about anyreturnstatement with no return value in a function whose return type is notvoid(falling off the end of the function body is considered returning without a value).
For C only, warn about a return statement with an expression in a function whose return type is void, unless the expression type is also void. As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used. Attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function is undefined.
Unlike in C, in C++, flowing off the end of a non-void function other than main results in undefined behavior even when the value of the function is not used. no cap, that one bites people
This warning is enabled by default in C++ and by -Wall otherwise.
-Wno-shift-count-negativeโ Controls warnings if a shift count is negative. This warning is enabled by default.-Wno-shift-count-overflowโ Controls warnings if a shift count is greater than or equal to the bit width of the type. This warning is enabled by default.-Wshift-negative-valueโ Warn if left shifting a negative value. This warning is enabled by-Wextrain C99 (and newer) and C++11 to C++17 modes.-Wno-shift-overflow-Wshift-overflow=nโ These options control warnings about left shift overflows.-Wshift-overflow=1โ This is the warning level of-Wshift-overflowand is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), as signed left shifts always wrap. slay, wrapping behavior โจ-Wshift-overflow=2โ This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
-Wswitchโ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration. (The presence of adefaultlabel prevents this warning.)caselabels outside the enumeration range also provoke warnings when this option is used (even if there is adefaultlabel). This warning is enabled by-Wall.-Wswitch-defaultโ Warn whenever aswitchstatement does not have adefaultcase. cover your bases, babe-Wswitch-enumโ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration.caselabels outside the enumeration range also provoke warnings when this option is used. The only difference between-Wswitchand this option is that this option gives a warning about an omitted enumeration code even if there is adefaultlabel. (so it's the extra-strict version ๐ )-Wno-switch-boolโ Do not warn when aswitchstatement has an index of boolean type and the case values are outside the range of a boolean type. It is possible to suppress this warning by casting the controlling expression to a type other thanbool. For example:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs.
-Wno-switch-outside-rangeโ This option controls warnings when aswitchcase has a value that is outside of its respective type range. This warning is enabled by default for C and C++ programs.-Wno-switch-unreachableโ Do not warn when aswitchstatement contains statements between the controlling expression and the first case label, which will never be executed. For example:
switch (cond)
{
i = 15;
...
case 5:
...
}
-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:
switch (cond)
{
int i;
...
case 5:
i = 5;
...
}
This warning is enabled by default for C and C++ programs. like, that code in there is literally never running, bestie ๐
-Wsync-nand(C and C++ only) โ Warn when__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions are used. These functions changed semantics in GCC 4.4. iykyk-Wtrivial-auto-var-initโ Warn when-ftrivial-auto-var-initcannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of aswitchstatement.-Wunused-but-set-parameterโ Warn whenever a function parameter is assigned to, but otherwise unused (aside from its declaration).
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused together with -Wextra.
-Wunused-but-set-variableโ Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-functionโ Warn 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โ Warn whenever a label is declared but not used. This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
-Wunused-local-typedefs(C, Objective-C, C++ and Objective-C++ only) โ Warn when a typedef locally defined in a function is not used. This warning is enabled by-Wall.-Wunused-parameterโ Warn whenever a function parameter is unused aside from its declaration.
To suppress this warning use the unused attribute.
-Wno-unused-resultโ Do not warn if a caller of a function marked with attributewarn_unused_resultdoes not use its return value. The default is-Wunused-result. (that return value was important, bestie, pls look at it ๐)-Wunused-variableโ Warn 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โ Warn whenever a constant static variable is unused aside from its declaration.-Wunused-const-variable=1is enabled by-Wunused-variablefor C, but not for C++. In C this declares variable storage, but in C++ this is not an error since const variables take the place of#defines. the way C and C++ handle const differentlyโฆ iconic ๐
To suppress this warning use the unused attribute.
-Wunused-const-variable=1โ This is the warning level that is enabled by-Wunused-variablefor C. It warns only about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header included.-Wunused-const-variable=2โ This warning level also warns for unused constant static variables in headers (excluding system headers). This is the warning level of-Wunused-const-variableand must be explicitly requested since in C++ this isn't an error and in C it might be harder to clean up all headers included. headers are a whole mess to clean, ngl
-Wunused-valueโ Warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression tovoid. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such asx[i,j]causes a warning, whilex[(void)i,j]does not. the comma operator ate and left no crumbs, but also no side effects ๐
This warning is enabled by -Wall.
-Wunusedโ All the above-Wunusedoptions combined. the whole squad in one flag โจ
In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter. yes, that one trips people up fr
-Wuninitializedโ Warn if an object with automatic or allocated storage duration is used without having been initialized. In C++, also warn if a non-static reference or non-staticconstmember appears in a class without constructors. bestie that memory is unhinged and uninitialized, do not trust it ๐
In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const-qualified argument of a built-in function that's known to read the object also gets diagnosed by this warning. (-Wmaybe-uninitialized is what gets issued for ordinary functions, bestie โ they're cousins.)
If you want a warning about code that uses the uninitialized value of the variable in its own initializer, that's a whole different option: -Winit-self.
These warnings pop off for individual uninitialized elements of structure, union or array variables, and for variables that are uninitialized as a whole. They do not happen for variables or elements declared volatile. And because these warnings depend on optimization, the exact variables or elements you get warned about depend on the precise optimization options and the version of GCC you're running. It's giving situational, fr fr.
Also lowkey important: there may be no warning about a variable that's only used to compute a value that itself is never used โ because those computations can get deleted by data flow analysis before the warnings even print. ๐
In C++, this warning also comes for using uninitialized objects in member-initializer-lists. Like, GCC warns about b being uninitialized in this lil snippet:
struct A {
int a;
int b;
A() : a(b) { }
};
-Wno-invalid-memory-modelโ this one controls warnings for invocations of__atomicBuiltins,__syncBuiltins, and the C11 atomic generic functions when the memory consistency argument is either invalid for the operation or outside the range of values of thememory_orderenumeration. For example, since the__atomic_storeand__atomic_store_nbuilt-ins are only defined for the relaxed, release, and sequentially consistent memory orders, this code right here gets diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default, bestie. It's just on. โจ
-Wmaybe-uninitializedโ okay so 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 for which the object is not initialized, the compiler emits a warning if it can't prove the uninitialized paths aren't executed at run time.
In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const-qualified function argument also gets diagnosed by this warning. (-Wuninitialized is what gets issued for built-in functions known to read the object.) Annotating the function with attribute access (none) says "hey, this argument isn't used to access the object," and that avoids the warning. ๐ซถ
These warnings are only possible in optimizing compilation, because otherwise GCC doesn't keep track of the state of variables. It literally can't see it.
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. Slap it in there. ๐
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 can't 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's in fact no problem, because longjmp can't in fact be called at the place that would cause a problem.
Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. ๐
This warning is enabled by-Wallor-Wextra.
-Wunknown-pragmasโ warns when a#pragmadirective is encountered that GCC doesn't understand. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. That's not the case if the warnings are only enabled by the-Wallcommand-line option. So like, this one goes harder than-Walldoes.-Wno-pragmasโ do not warn about misuses of pragmas, such as 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 beforemainis called or after it returns. The priority values must be greater than 100, because the compiler reserves priority values between 0--100 for the implementation. So yeah, that range is spoken for, bestie. ๐-Wstrict-aliasingโ this option is only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. The warning doesn't catch all cases, but it does attempt to catch the more common pitfalls. It's included in-Wall. It's equivalent to-Wstrict-aliasing=3.-Wstrict-aliasing=nโ same deal, only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules the compiler 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 don't 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 don't warn but
-Wstrict-overflow-Wstrict-overflow=nโ this option is only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Note that it doesn't warn about all 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. It's giving conditional, honestly.
An optimization that assumes signed overflow doesn't occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. So this warning can easily give a false positive: a warning about code that's not actually a problem. To help 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 simplifiesx + 1 > xto 1. This level of-Wstrict-overflowis enabled by-Wall; higher levels are not, and must be explicitly requested.-Wstrict-overflow=2โ also warn about other cases where a comparison is simplified to a constant. For example:abs (x) >= 0. This can only be simplified when signed integer overflow is undefined, becauseabs (INT_MIN)overflows toINT_MIN, which is less than zero.-Wstrict-overflow(with no level) is the same as-Wstrict-overflow=2.-Wstrict-overflow=3โ also warn about other cases where a comparison is simplified. For example:x + 1 > 1is simplified tox > 0.-Wstrict-overflow=4โ also warn about other simplifications not covered by the above cases. 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. For example:x + 2 > yis simplified tox + 1 >= y. 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โ warns for calls tostrcmpandstrncmpwhose result is determined to be either zero or non-zero in tests for such equality, owing to the length of one argument being 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 irrespective of the contents of 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");
}
-Wstring-compareis enabled by-Wextra.
-Wno-stringop-overflow,-Wstringop-overflow,-Wstringop-overflow=type โ bestie, this one yells at you when you call a string function likememcpyorstrcpyand it's dead obvious you're about to overflow the destination buffer. ๐ฅ The optional type argument is one greater than the type of Object Size Checking used to figure out how big the destination is. Heads up though: type only means anything for functions that work on character arrays โ raw memory functions likememcpyalways use Object Size type-0, periodt. This option also flags calls that pass a size bigger than the largest possible object, or at mostSIZE_MAX / 2bytes. It's giving its best results with optimization on, but ngl it can still catch a small subset of simple buffer overflows even without optimization in calls to GCC built-ins like__builtin_memcpythat line up with the standard functions. Anyway, the option only warns about a subset of the overflows that the matching overflow-checking built-ins would catch. โจ For example, it warns on thestrcpycall below because that copy moves at least 5 characters (the string"blue", NUL included) into a buffer of size 4:
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
static char buf [4];
const char *str;
switch (clr)
{
case blue: str = "blue"; break;
case purple: str = "purple"; break;
case yellow: str = "yellow"; break;
}
return strcpy (buf, str); // warning here
}
Option -Wstringop-overflow=2 is enabled by default. ๐
-Wstringop-overflow,-Wstringop-overflow=1โ this setting uses type-zero Object Size Checking to suss out the sizes of destination objects. At this level 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 could be one of several objects, it just assumes it's the biggest one of them. ๐ And on Linux systems, with optimization enabled at this setting, it warns for the exact same code as when the_FORTIFY_SOURCEmacro is defined to a non-zero value. iconic.-Wstringop-overflow=2โ this setting uses type-one Object Size Checking to determine destination object sizes. Here it warns about overflows when you write to members of the largest complete objects whose exact size is known. ๐ But it does not warn for excessive writes to those same members of unknown objects referenced by pointers, since those pointers might be pointing at arrays with unknown numbers of elements. This is the default setting of the option, btw.-Wstringop-overflow=3โ type-two Object Size Checking, bestie. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option, and heads up: it may result in warnings for safe code. ๐ญ-Wstringop-overflow=4โ type-three Object Size Checking to determine the sizes of destination objects. Here it warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest one of them to decide whether to warn. Just like-Wstringop-overflow=3, this setting may result in warnings for benign code. ๐
-Wno-stringop-overreadโ warns when you call string manipulation functions likememchrorstrcpyin a way that's determined to read past the end of the source sequence. ๐
Option -Wstringop-overread is enabled by default.
-Wno-stringop-truncationโ do not warn for calls to bounded string manipulation functions likestrncat,strncpy, andstpncpythat may either truncate the copied string or leave the destination unchanged. ๐
In this next example, the strncat call specifies a bound that's less than the length of the source string. So the copy of the source gets truncated and the call gets diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound:
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
And as another example, the following strncpy call copies to d only the characters before the terminating NUL, without appending the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call gets diagnosed. To avoid the warning when you don't expect the result to be NUL-terminated, call memcpy instead:
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
In the next one, the strncpy call passes the size of the destination buffer as the bound. If the source string's length is equal to or greater than that size, the result of the copy won't be NUL-terminated. So yeah, that call gets diagnosed too. ๐ฌ To avoid the warning, pass 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);
...
}
When a character array is meant to hold a sequence of bytes with no terminating NUL, you can annotate that array with the attribute nonstring to skip this warning. ๐ฆ But lowkey, those arrays are not suitable arguments for functions that expect NUL-terminated strings. To help catch accidental misuses of such arrays, GCC issues warnings unless it can prove the use is safe. ๐
-Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc]โ warns you when adding an attribute might be a good move. The attributes currently supported are listed below. ๐-Wsuggest-attribute=pure,-Wsuggest-attribute=const,-Wsuggest-attribute=noreturn,-Wmissing-noreturn,-Wsuggest-attribute=mallocโ warns about functions that might be candidates for the attributespure,const,noreturn, ormalloc. The compiler only warns for functions visible in other compilation units, or (forpureandconst) when it can't prove the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, callingabort, or trapping. This analysis needs option-fipa-pure-const, which is enabled by default at-Oand higher. Higher optimization levels make the analysis more accurate. ๐ฅ-Wsuggest-attribute=format,-Wmissing-format-attributeโ warns about function pointers that might be candidates forformatattributes. Note these are only possible candidates, not absolute ones, bestie. GCC guesses that function pointers withformatattributes used in assignment, initialization, parameter passing, or return statements should have a matchingformatattribute in the resulting type. I.e. the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have aformatattribute to avoid the warning. ๐
GCC also warns about function definitions that might be candidates for format attributes. Again โ only possible candidates. GCC 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 format attributes might not get detected at all. ๐
-Wsuggest-attribute=coldโ warns about functions that might be candidates for thecoldattribute. This is based on static detection and generally only warns about functions that always lead to a call to anothercoldfunction โ think wrappers of C++throw, or fatal error reporting functions that lead toabort. โ๏ธ
-Walloc-zeroโ warns about calls to allocation functions decorated with the attributealloc_sizethat specify zero bytes, including calls to the built-in forms ofaligned_alloc,alloca,calloc,malloc, andrealloc. Because the behavior of these functions with a zero size differs between implementations (and in the case ofreallocit's been deprecated ๐ณ), relying on it may cause subtle portability bugs and should be avoided. fr fr.-Walloc-size-larger-than=byte-size โ warns about calls to functions decorated with the attributealloc_sizethat try to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value ofPTRDIFF_MAXon the target.-Walloc-size-larger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be turned off either by specifying a byte-size ofSIZE_MAXor more, or with-Wno-alloc-size-larger-than. โจ-Wno-alloc-size-larger-thanโ disables-Walloc-size-larger-than=warnings. This option is equivalent to-Walloc-size-larger-than=SIZE_MAXor larger. ๐-Wallocaโ this option warns on every use ofallocain the source. all of them. every single one. ๐-Walloca-larger-than=byte-size โ this option warns on calls toallocawith an integer argument whose value is either zero, or that isn't bounded by a controlling predicate limiting its value to at most byte-size. It also warns for calls toallocawhere the bound value is unknown. 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);
}
So like, in the example above ๐ 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 you'd passed -Walloca-larger-than=500 instead, bestie, the compiler would absolutely emit a warning. ๐
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. Like this lil guy:
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. No cap. ๐ซถ
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 example above, n could be negative, causing a larger than expected argument to be implicitly cast into the alloca call. Sneaky. ๐
This option also warns when alloca is used in a loop. ๐
-Walloca-larger-than=PTRDIFF_MAX is enabled by default but is usually only effective when -ftree-vrp is active (default for -O2 and above).
See also -Wvla-larger-than=byte-size.
-Wno-alloca-larger-thanโ Disable-Walloca-larger-than=warnings. The option is equivalent to-Walloca-larger-than=SIZE_MAXor larger.-Warith-conversionโ Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from-Wconversion,-Wfloat-conversion, and-Wsign-conversion. โจ
void f (char c, int i)
{
c = c + i; // warns with B<-Wconversion>
c = c + 1; // only warns with B<-Warith-conversion>
}
-Warray-bounds,-Warray-bounds=n โ Warn about out of bounds subscripts or offsets into arrays. This warning is enabled by-Wall. It's more effective when-ftree-vrpis active (the default for-O2and above), but a subset of instances are issued even without optimization.-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 out of bounds accesses to trailing struct members of one-element array types and about the intermediate results of pointer arithmetic that may yield out of bounds values. Heads up: this warning level may give a larger number of false positives and is deactivated by default. โ ๏ธ
-Warray-compareโ Warn 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 โ Warn about redeclarations of functions involving arguments of array or pointer types of inconsistent kinds or forms, and enable 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โ Warn 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.
-Wattribute-alias is equivalent to -Wattribute-alias=1. This is the default. You can disable these warnings with either -Wno-attribute-alias or -Wattribute-alias=0.
-Wbidi-chars=[none|unpaired|any|ucn]โ Warn about possibly misleading UTF-8 bidirectional control characters in comments, string literals, character constants, and identifiers. ๐ณ Such characters can change left-to-right writing direction into right-to-left (and vice versa), which can cause confusion between the logical order and the visual order. This may be dangerous; for instance, it may seem that a piece of code is not commented out, whereas it in fact is. It's giving trap. ๐ฉ
There are three levels of warning supported by GCC. The default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the warning off. -Wbidi-chars=any warns 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โ Warn about boolean expression compared with an integer value different fromtrue/false. For instance, the following comparison is always false:
int n = 5;
...
if ((n > 1) == 2) { ... }
This warning is enabled by -Wall.
-Wbool-operationโ Warn 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โ Warn 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โ Warn 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โ Warn 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 aconst char *variable is passed to a function that takes achar *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 aconst int (*)[]variable is passed to a function that takes aint (*)[]parameter. This option can be used to suppress such a warning.-Wno-incompatible-pointer-types(C and Objective-C only) โ Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by-Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness.-Wno-int-conversion<span title="C and Objective-C only">(C and Objective-C only)</span> โ bestie, this one shuts off the warning about incompatible integerโpointer and pointerโinteger conversions. Important vibe check: this warning is about implicit conversions only. If you wanna silence the explicit ones (the ones where you literally wrote a cast), that's-Wno-int-to-pointer-castand-Wno-pointer-to-int-cast. Different flags, different jobs. ๐-Wzero-length-boundsโ warns you when you access elements of zero-length array members and those accesses might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because, fr fr, accesses to them are undefined. See
Okay so example time, because this one needs it. The first two stores in function bad get diagnosed because the array elements overlap the subsequent members b and c. The third store gets diagnosed by -Warray-bounds instead, because it's beyond the bounds of the whole 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
}
This option -Wzero-length-bounds is enabled by -Warray-bounds. โจ
-Wno-div-by-zeroโ do not warn about compile-time integer division by zero. Now floating-point division by zero? Not warned about at all, periodt โ because it can be a completely legitimate way of obtaining infinities and NaNs. ๐ฆ-Wsystem-headersโ prints warning messages for constructs found in system header files. Normally these warnings are suppressed, on the assumption that they usually don't indicate real problems and would only make the compiler output harder to read (real). Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code.
But heads up bestie: using-Walltogether with this option does not warn about unknown pragmas in system headers. For that,-Wunknown-pragmasmust also be used. Don't get caught out. ๐
-Wtautological-compareโ warns you if a self-comparison always evaluates to true or false. It catches all sorts of mistakes, like:
int i = 1;
...
if (i > i) { ... }
It also warns about bitwise comparisons that always evaluate to true or false, for instance:
if ((a & 16) == 10) { ... }
will always be false. ๐ญ This warning is enabled by -Wall.
-Wtrampolinesโ warns about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code that's created at run time on the stack when the address of a nested function is taken, and it's used to call that nested function indirectly. For some targets it's made up of data only, so it needs no special treatment. But for most targets it's made up of code, which means the stack has to be made executable for the program to work properly. ๐-Wfloat-equalโ warns if floating-point values are used in equality comparisons.
The idea behind this is that sometimes it's convenient (for the programmer, not for you, the person debugging it at 3am) to consider floating-point values as approximations to infinitely precise real numbers. If that's what you're doing, 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 too, but that's a different problem entirely). In particular, instead of testing for equality, you should check whether the two values have ranges that overlap; and that's done with the relational operators. So equality comparisons are probably mistaken. ๐
-Wtraditional<span title="C and Objective-C only">(C and Objective-C only)</span> โ warns about certain constructs that behave differently in traditional C versus ISO C. Also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. Buckle up, this list is long:- 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 didn't 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#doesn't appear as the first character on the line. It also suggests you hide directives like#pragmathat traditional C doesn't understand by indenting them. Some traditional implementations don't recognize#elif, so this option suggests avoiding it altogether. - A function-like macro that appears without arguments.
- The unary plus operator.
- The
Uinteger constant suffix, or theForLfloating-point constant suffixes. (Traditional C does support theLsuffix on integer constants.) Note: these suffixes appear in macros defined in the system headers of most modern systems, e.g. the_MIN/_MAXmacros in<limits.h>. Use of these macros in user code might normally lead to spurious warnings, however GCC's integrated preprocessor has enough context to avoid warning in these cases. - A function declared external in one block and then used after the end of the block.
- A
switchstatement has an operand of typelong. - A non-
staticfunction declaration follows astaticone. This construct is not accepted by some traditional C compilers. - The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
- Usage of ISO string concatenation is detected.
- Initialization of automatic aggregates.
- Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
- Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g.
__STDC__to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case. - Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use
-Wtraditional-conversion. - Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions, because these ISO C features appear in your code when using libiberty's traditional C compatibility macros,
PARAMSandVPARAMS. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
-Wtraditional-conversion<span title="C and Objective-C only">(C and Objective-C only)</span> โ warns if a prototype causes a type conversion that's different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument โ except when it's the same as the default promotion. ๐-Wdeclaration-after-statement<span title="C and Objective-C only">(C and Objective-C only)</span> โ warns when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90. ๐-Wshadowโ warns whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C), or whenever a built-in function is shadowed. Note that 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 includes also all instances of local shadowing. Which means-Wno-shadow=localand-Wno-shadow=compatible-localare ignored when-Wshadowis used. Same as-Wshadow=global. ๐-Wno-shadow-ivar<span title="Objective-C only">(Objective-C only)</span> โ do not warn whenever a local variable shadows an instance variable in an Objective-C method.-Wshadow=globalโ warns for any shadowing. Same as-Wshadow.-Wshadow=localโ warns when a local variable shadows another local variable or parameter.-Wshadow=compatible-localโ warns when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (in addition to-Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it's most likely intentional, not a bug or typo โ as shown in the following 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. 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. Use of this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means that shadowing const char *i by char *i does not emit a warning. ๐ฆ
This warning is also enabled by -Wshadow=local.
-Wlarger-than=byte-sizeโ warns whenever an object is defined whose size exceeds byte-size.-Wlarger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifying byte-size ofSIZE_MAXor more, or by-Wno-larger-than. ๐
Also, it's gonna yell at you for calls to bounded functions like memchr or strnlen when you hand them a bound that's bigger than the biggest object that could even exist โ which is PTRDIFF_MAX bytes by default. And the only way to shush these bad boys is -Wno-larger-than. That's it. That's the whole escape hatch. ๐ซถ
-Wno-larger-thanโ turns off the-Wlarger-than=warnings. Lowkey it's the same thing as saying-Wlarger-than=SIZE_MAXor even bigger. โจ-Wframe-larger-than=byte-sizeโ warns you when a function's frame gets bigger than byte-size. Okay bestie, heads up: the math it does to figure out the stack frame size is approximate and not conservative. So the real requirements might be a lil bit bigger than byte-size and it still won't warn you. ๐ And on top of that, anything you allocate withalloca, variable-length arrays, or related constructs is not counted by the compiler when it's deciding whether to warn.-Wframe-larger-than=PTRDIFF_MAXis on by default. You can kill these warnings by either passing a byte-size ofSIZE_MAXor more, or by using-Wno-frame-larger-than. ๐-Wno-frame-larger-thanโ disables-Wframe-larger-than=warnings. Same energy as-Wframe-larger-than=SIZE_MAXor larger. ๐-Wfree-nonheap-objectโ warns when you try to deallocate something that either wasn't allocated on the heap at all, or that you're freeing through a pointer that did not come back from a prior call to the matching allocation function. Classic example:stpcpyreturns a pointer to the terminating nul character, not to the start of the object, so thisfreedown here gets diagnosed:
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is included in -Wall. (so if you're on -Wall, surprise, you already have it ๐ญ)
-Wstack-usage=byte-sizeโ warns if a function's stack usage might go over byte-size. The computation here is conservative (opposite of the frame one, slay). Any space allocated viaalloca, variable-length arrays, or related constructs is included by the compiler when it's deciding whether to warn. ๐
The message matches what -fstack-usage spits out.
- If the stack usage is fully static but goes over the amount you specified, 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. You can disable these warnings by either specifying a byte-size of SIZE_MAX or more, or with -Wno-stack-usage.
-Wno-stack-usageโ disables-Wstack-usage=warnings. Equivalent to-Wstack-usage=SIZE_MAXor larger. ๐ธ-Wunsafe-loop-optimizationsโ warns if the loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. And with-funsafe-loop-optimizationsit warns if the compiler does make such assumptions. It's giving "damned if you do" ngl ๐-Wno-pedantic-ms-format(MinGW targets only) โ when you use this together with-Wformatand-pedanticwithout GNU extensions, it disables the warnings about non-ISOprintf/scanfformat width specifiersI32,I64, andIon Windows targets, since those depend on the MS runtime. ๐ฆ-Wpointer-arithโ warns about anything that depends on the "size of" a function type or ofvoid. GNU C gives these types a size of 1, for convenience when doing calculations withvoid *pointers and pointers to functions. In C++, it also warns when an arithmetic operation involvesNULL. This warning is also enabled by-Wpedantic. โจ-Wno-pointer-compareโ do not warn if a pointer is compared with a zero character constant. Usually that means the pointer was meant to be dereferenced. Like:
const char *p = foo ();
if (p == '\0')
return 42;
Note that the code above is invalid in C++11. ๐
This warning is enabled by default.
-Wtsanโ warns about unsupported features in ThreadSanitizer.
ThreadSanitizer does not support std::atomic_thread_fence and can report false positives.
This warning is enabled by default. ๐ง
-Wtype-limitsโ warns if a comparison is always true or always false because the data type's range is limited, but it does not warn for constant expressions. For example, it warns if an unsigned variable gets compared against zero with<or>=. This warning is also enabled by-Wextra. ๐-Wabsolute-value(C and Objective-C only) โ warns for calls to standard functions that compute the absolute value of an argument when a more appropriate standard function exists. For example, callingabs(3.14)triggers the warning, because the right function 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. You can suppress this warning with an explicit type cast, and it's also enabled by-Wextra. ๐-Wcomment-Wcommentsโ warns whenever a comment-start sequence/*appears inside a/*comment, or whenever a backslash-newline shows up in a//comment. This warning is enabled by-Wall. ๐-Wtrigraphsโ warns if any trigraphs are encountered that might change the meaning of the program. Trigraphs inside comments are not warned about โ except the ones that would form escaped newlines.
This option is implied by -Wall. If -Wall isn't given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but still get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs. ๐
-Wundefโ warns if an undefined identifier gets evaluated in an#ifdirective. Those identifiers get replaced with zero, bestie. ๐-Wexpansion-to-definedโ warns wheneverdefinedshows up in the expansion of a macro (including when the macro gets expanded by an#ifdirective). That usage is not portable. This warning is also enabled by-Wpedanticand-Wextra. โญ-Wunused-macrosโ warns about macros defined in the main file that go unused. A macro counts as used if it's expanded or tested for existence at least once. The preprocessor also warns if the macro hasn't been used by the time it's redefined or undefined.
Built-in macros, macros defined on the command line, and macros defined in include files are not warned about.
Note: if a macro is actually used, but only used inside skipped conditional blocks, then the preprocessor reports it as unused. To dodge the warning in that case, you might improve the scope of the macro's definition by, say, moving it into the first skipped block. Alternatively, you could provide a dummy use with something like:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsโ do not warn whenever an#elseor an#endifis followed by text. This sometimes happens in older programs with code shaped like this:
#if FOO
...
#else FOO
...
#endif FOO
That second and third FOO should be in comments. This warning is on by default. ๐ญ
-Wbad-function-cast(C and Objective-C only) โ warns when a function call is cast to a non-matching type. For example, it warns if a call to a function returning an integer type gets cast to a pointer type. ๐-Wc90-c99-compat(C and Objective-C only) โ warns about features that aren't in ISO C90 but are in ISO C99. Like, it warns about use of variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows__extension__. ๐ฆ-Wc99-c11-compat(C and Objective-C only) โ warns about features not present in ISO C99 but present in ISO C11. For instance, it warns about use of anonymous structures and unions, the_Atomictype qualifier, the_Thread_localstorage-class specifier, the_Alignasspecifier, theAlignofoperator, the_Generickeyword, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows__extension__. ๐ธ-Wc11-c2x-compat(C and Objective-C only) โ warns about features not present in ISO C11 but present in ISO C2X. For instance, it warns about omitting the string in_Static_assert, use of[[]]syntax for attributes, use of decimal floating-point types, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows__extension__. โจ-Wc++-compat(C and Objective-C only) โ warns about ISO C constructs that live outside the common subset of ISO C and ISO C++, e.g. a request for implicit conversion fromvoid *to a pointer to a non-voidtype. ๐-Wc++11-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g. identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011. This warning turns on-Wnarrowingand is enabled by-Wall. ๐-Wc++14-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. 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) โ do not warn about C++11 constructs in code being compiled with an older C++ standard. Even without this option, some C++11 constructs only get diagnosed if-Wpedanticis used. ๐-Wno-c++14-extensions(C++ and Objective-C++ only) โ do not warn about C++14 constructs in code being compiled with an older C++ standard. Even without this option, some C++14 constructs only get diagnosed if-Wpedanticis used. ๐ซถ-Wno-c++17-extensions(C++ and Objective-C++ only) โ pls stop telling me about C++17 stuff when I'm compiling with an older C++ standard bestie ๐ญ and like, even if you don't pass this, some C++17 constructs will still only get flagged if you're running-Wpedantic. so it's not a full muffle, iykyk.-Wno-c++20-extensions(C++ and Objective-C++ only) โ same energy, but for C++20 constructs in code being built with an older C++ standard. and again, even without this option, some C++20 constructs will only be diagnosed if-Wpedanticis in the mix. โจ-Wno-c++23-extensions(C++ and Objective-C++ only) โ you already know the vibe ๐ฆ this one silences C++23 constructs in code compiled under an older C++ standard. and yes, even without it, some C++23 constructs will only be diagnosed with-Wpedantic.
-Wcast-qualโ warns whenever a pointer gets cast in a way that removes a type qualifier from the target type. like, warn if a"const char *"gets cast to a plain old"char *". rude tbh.
it also warns when you make a cast that introduces a type qualifier in an unsafe way ๐ casting "char **" to "const char **" is unsafe, like so:
/* p is char ** value. */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK. */
*q = "string";
/* Now char** pointer points to read-only memory. */
**p = 'b';
-Wcast-alignโ warns whenever a pointer is cast so that the required alignment of the target gets increased. example: warn if a"char *"is cast to an"int *"on machines where integers can only be accessed at two- or four-byte boundaries. alignment girlies stay winning ๐-Wcast-align=strictโ same deal โ warn whenever a pointer cast increases the required alignment of the target โ except this one fires regardless of the target machine. no cap, it does not care where you're running. warn if a"char *"is cast to an"int *", periodt.-Wcast-function-typeโ warns when a function pointer gets cast to an incompatible function pointer. the deets ๐- 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, like
"int"vs."long"on ILP32 targets. - type qualifiers are also ignored.
- the function type
"void (*) (void)"is special and matches everything, which you can use to suppress this warning. iconic loophole ๐ - in a cast involving pointer to member types, this warns whenever the type cast is changing the pointer to member type.
this warning is enabled by -Wextra.
-Wwrite-stringsโ when compiling C, this gives string constants the type"const char[length]"so that copying the address of one into a non-"const""char *"pointer produces a warning. these warnings help you find, at compile time, code that can try to write into a string constant โ but only if you've been very careful about using"const"in declarations and prototypes. otherwise it's just a nuisance ๐ which is why-Walldoes not 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.
-Wclobberedโ warns for variables that might be changed by"longjmp"or"vfork". this warning is also enabled by-Wextra.-Wconversionโ warns for implicit conversions that may alter a value ๐ฅ this includes:- conversions between real and integer, like
"abs (x)"when"x"is"double"; - conversions between signed and unsigned, like
"unsigned ui = -1"; - and conversions to smaller types, like
"sqrtf (M_PI)".
- conversions between real and integer, like
it does not warn for explicit casts like "abs ((int) x)" and "ui = (unsigned) -1", or if the value isn't changed by the conversion like in "abs (2.0)". warnings about conversions between signed and unsigned integers can be turned off with -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.
-Wdangling-elseโ warns about constructions where there could be confusion about which"if"statement an"else"branch belongs to ๐ตโ๐ซ here's an example of exactly that mess:
{
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 the indentation above shows ๐ when there's potential for this confusion, GCC issues a warning when this flag is specified. to kill 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.
-Wdangling-pointerโ-Wdangling-pointer=nโ warns about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended ๐ป this includes local variables declared in nested blocks, compound literals and other unnamed temporary objects. on top of that, it warns about storing the address of such objects in escaped pointers. the warning is enabled at all optimization levels, but it may yield different results with optimization than without. ngl that's a little chaotic but okay.-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);
return p ? *p : 'x'; // warning: dangling pointer to a compound literal
}
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;
*p = &x; // warning: storing the address of a local variable in *p
}
-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;
}
strcat (s, ".tmp"); // warning: dangling pointer to may be used
...
}
-Wdangling-pointer=2 is included in -Wall. ๐
-Wdate-timeโ warns when macros"__TIME__","__DATE__"or"__TIMESTAMP__"are encountered, because they might prevent bit-wise-identical reproducible compilations ๐ฐ๏ธ no reproducible build for you, bestie.-Wempty-bodyโ warns if an empty body shows up in an"if","else"or"do while"statement. this warning is also enabled by-Wextra. like girl, is there a body in there or not ๐ญ-Wno-endif-labelsโ do not warn about stray tokens after"#else"and"#endif". minding my own business fr.-Wenum-compareโ warns 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.-Wenum-conversionโ warns when a value of enumerated type is implicitly converted to a different enumerated type. this warning is enabled by-Wextrain C.-Wjump-misses-init(C, Objective-C only) โ warns 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. it only warns about variables that are initialized when they're declared. this warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case ๐ซ
-Wjump-misses-init is included in -Wc++-compat. it can be disabled with the -Wno-jump-misses-init option.
-Wsign-compareโ warns 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's also enabled by-Wextra.-Wsign-conversionโ warns for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. an explicit cast silences the warning. in C, this option is enabled also by-Wconversion.-Wfloat-conversionโ warns 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.-Wno-scalar-storage-orderโ do not warn on suspicious constructs involving reverse scalar storage order. okay bestie, I'll look away ๐-Wsizeof-array-divโ warns 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 that case, the computation will not yield the number of elements in the array โ which is likely what the user actually wanted ๐ญ this warning warns e.g. about:
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
this warning is enabled by -Wall.
-Wsizeof-pointer-divโ bestie, this one clocks you dividing twosizeofexpressions where you're doing pointer-size รท element-size. That's the classic way to compute an array's length... and it does not work on pointers. So it'll call out stuff likesizeof (ptr) / sizeof (ptr[0])whenptris a pointer and not an array. ๐ Enabled by-Wall.-Wsizeof-pointer-memaccessโ this one side-eyes sus length arguments passed to certain string and memory built-in functions when the arg usessizeof. Like,memset (ptr, 0, sizeof (ptr));whenptris a pointer and not an array? Yeah, it flags that and even suggests a possible fix. Same energy formemcpy (&foo, ptr, sizeof (&foo));๐
It also warns about calls to bounded string copy functions like strncat or strncpy when the bound is a sizeof expression of the source array. Example time โ in this function the strncat call uses the size of the source string as the bound, which is almost certainly a mistake, so it gets diagnosed:
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
The -Wsizeof-pointer-memaccess option is enabled by -Wall. โจ
-Wno-sizeof-array-argumentโ do NOT warn when thesizeofoperator gets applied to a parameter that's declared as an array in a function definition. This warning is on by default for C and C++ programs. ๐ซถ-Wmemset-elt-sizeโ warns about suspicious calls to thememsetbuilt-in when 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. Translation: you forgot to multiply by the element size, bestie. ๐ญ Enabled by-Wall.-Wmemset-transposed-argsโ catches susmemsetbuilt-in calls where the second argument isn't zero and the third argument is zero. Like, the callmemset (buf, sizeof buf, 0)gets diagnosed because you so obviously meantmemset (buf, 0, sizeof buf)and just flipped them. ๐
Heads up: the diagnostic only fires if the third argument is a literal zero. If it's an expression that folds to zero, or a cast of zero to some type, then transposed args are way less likely and no warning is emitted.
Enabled by -Wall.
-Waddressโ warns about suspicious uses of address expressions. These include comparing the address of a function or a declared object to the null pointer constant, like:
void f (void);
void g (void)
{
if (!func) // warning: expression evaluates to false
abort ();
}
Comparisons of a pointer to a string literal, like:
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, like:
void f (const int *p, int i)
{
return p + i == NULL;
}
Uses like these typically mean the programmer messed up: the address of most functions and objects necessarily evaluates to true (the exception is weak symbols), so using one in a conditional might mean you're missing parentheses in a function call or a missing dereference in an array expression. ๐ง
The subset of this warning for object pointers can be suppressed by casting the pointer operand to an integer type such as inptr_t or uinptr_t. Comparisons against string literals result in unspecified behavior and are not portable, and they suggest the intent was to call strcmp. The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress warning is enabled by -Wall. ๐
-Wno-address-of-packed-memberโ don't warn when the address of a packed member of a struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default.-Wlogical-opโ warns about suspicious uses of logical operators in expressions, including using logical operators in contexts where a bit-wise operator is probably expected. Also warns when the operands of a logical operator are the same:
extern int a;
if (a < 0 && a < 0) { ... }
-Wlogical-not-parenthesesโ warns about logical not used on the left hand side operand of a comparison. It does not warn if the right operand is considered to be a boolean expression. Its whole purpose is catching suspicious code like this:
int a;
...
if (!a > 1) { ... }
You can suppress the warning by wrapping the LHS in parentheses:
if ((!a) > 1) { ... }
This warning is enabled by -Wall. ๐ธ
-Waggregate-returnโ warns if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.) ๐-Wno-aggressive-loop-optimizationsโ warns if, in a loop with a constant number of iterations, the compiler detects undefined behavior in some statement during one or more of the iterations.-Wno-attributesโ do not warn if an unexpected__attribute__is used, like unrecognized attributes, function attributes applied to variables, etc. Note: 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 warning about this declaration:
[[vendor::attr]] void f();
And you can disable warnings about all attributes in a namespace using -Wno-attributes=vendor::, which prevents warning about both of these declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Real talk:-Wno-attributes=does not imply-Wno-attributes.
-Wno-builtin-declaration-mismatchโ warns if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that 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 to bring the prototypes of built-in functions into scope. ๐
Example: the call to memset below gets diagnosed 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) โ warns if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if it's preceded by a declaration that specifies the argument types.)-Wold-style-declaration(C and Objective-C only) โ warns for obsolescent usages, according to the C Standard, in a declaration. Like, 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) โ warns if an old-style function definition is used. A warning is given 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) โ warns if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that don't have a matching prototype declaration in a header file. This option isn't 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โ warns if a global function is defined without a previous declaration. Does 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โ warns if a structure's initializer has some fields missing. For example, the following code causes such a warning, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so this modification doesn't trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
In C, this option doesn't warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
And in C++ this one stays quiet about the empty { } initializer too, bestie, like:
struct s { int f, g, h; };
s x = { };
It's folded into -Wextra ๐ so if you want the other -Wextra warnings but not this one, you go -Wextra -Wno-missing-field-initializers and you're golden โจ
-Wno-missing-requiresโ by default the compiler will clock you for a concept-id showing up as a C++20 simple-requirement, like this:
bool satisfied = requires { C<T> };
So here satisfied is true if C<T> is a valid expression โ which it is for every single T ๐ so like, that's probably not what you meant. Presumably the user meant to write:
bool satisfied = requires { requires C<T> };
so that satisfied is only true if concept C is satisfied for type T. Yes queen, that's the one ๐
You can turn this warning off with -Wno-missing-requires.
-Wno-missing-template-keywordโ the member access tokens.,->and::have to be followed by the"template"keyword whenever the parent object is dependent and the member being named is a template. Obsessed with that rule? No? Well:
template <class X>
void DoStuff (X x)
{
x.template DoSomeOtherStuff<X>(); // Good.
x.DoMoreStuff<X>(); // Warning, x is dependent.
}
In rare cases you can get false positives ๐ and to silence those, just wrap the expression in parentheses. For example, the following gets 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.
}
You can disable this warning with -Wno-missing-template-keyword.
-Wno-multicharโ don't warn if a multicharacter constant ('FOOF') gets used. Usually those are just a typo in the user's code, since they have implementation-defined values and should not be used in portable code ๐ซ-Wnormalized=[none|id|nfc|nfkc]โ okay so in ISO C and ISO C++, two identifiers are different if they're different sequences of characters. But sometimes, when you use characters outside the basic ASCII character set, you can end up with two different character sequences that look exactly the same ๐ญ To avoid that whole confusion, the ISO 10646 standard lays out some normalization rules that, when applied, make sure 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. Iconic โจ
There are four levels of warning supported by GCC:
- The default is
-Wnormalized=nfc, which warns about any identifier that isn't in the ISO 10646"C"normalized form, NFC. NFC is the recommended form for most uses, and 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. Which means there's literally no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC.
-Wnormalized=idsuppresses the warning for these characters. The hope is that future versions of the standards involved will fix this, which is why this option isn't the default ๐ - You can switch the warning off for all characters by writing
-Wnormalized=noneor-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 of 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 get 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โ don't 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 compiling with the-Werrorflag. two options, pick your fighter ๐-Wno-deprecatedโ don't warn about usage of deprecated features. simple as that, bestie ๐ซถ-Wno-deprecated-declarationsโ don't warn about uses of functions, variables, and types marked as deprecated by using the"deprecated"attribute.-Wno-overflowโ don't warn about compile-time overflow in constant expressions.-Wno-odrโ warn about One Definition Rule violations during link-time optimization. Enabled by default.-Wopenacc-parallelismโ warn about potentially suboptimal choices related to OpenACC parallelism. it's giving "girl, you could parallelize this better" โจ-Wopenmp-simdโ warn if the vectorizer cost model overrides the OpenMP simd directive set by the user. The-fsimd-cost-model=unlimitedoption can be used to relax the cost model ๐-Woverride-init(C and Objective-C only) โ warn if an initialized field without side effects gets overridden when using designated initializers.
This warning is included in -Wextra. To get the other -Wextra warnings without this one, use -Wextra -Wno-override-init.
-Wno-override-init-side-effects(C and Objective-C only) โ don't warn if an initialized field with side effects gets overridden when using designated initializers. This warning is enabled by default.-Wpackedโ warn if a structure is given the packed attribute, but that packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit ๐ฌ For instance, in this code, the variable"f.x"in"struct bar"is misaligned even though"struct bar"doesn't itself have the packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compatโ the 4.1, 4.2 and 4.3 series of GCC ignore the"packed"attribute on bit-fields of type"char". This got fixed in GCC 4.4, but the change can lead to differences in the structure layout. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there's no longer a 4-bit padding between field"a"and"b"in this structure:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warn if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning gets issued on"struct S", like,"warning: 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โ warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens you can rearrange the fields of the structure to reduce the padding and make the whole thing smaller ๐-Wredundant-declsโ warn 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โ warn when an object referenced by a"restrict"-qualified parameter (or, in C++, a"__restrict"-qualified parameter) gets aliased by another argument, or when copies between such objects overlap. For example, the call to the"strcpy"function below tries to truncate the string by replacing its initial characters with the last four. But because the call writes the terminating NUL into"a[4]", the copies overlap and the call gets diagnosed ๐ญ
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
The -Wrestrict option detects some instances of simple overlap even without optimization, but it works best at -O2 and above. It's included in -Wall โจ
-Wnested-externs(C and Objective-C only) โ warn if an"extern"declaration shows up inside a function. not the vibe ๐ซ-Winlineโ warn if a function that's declared as inline can't actually be inlined. Even with this option on, the compiler does not warn about failures to inline functions declared in system headers.
The compiler uses a whole variety of heuristics to figure out whether or not to inline a function. For example, it takes into account the size of the function being inlined and how much inlining has already been done in the current function. So like, seemingly insignificant changes in the source program can make the warnings produced by -Winline appear or disappear ๐ตโ๐ซ unpredictable queen
-Winterference-sizeโ warn about use of C++17"std::hardware_destructive_interference_size"without specifying its value with--param destructive-interference-size. It also warns about questionable values for that option ๐
This variable is intended to be used for controlling 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 intended to be far enough apart that stores to one won't require accesses to the other to reload the cache line ๐
okay so real talk, bestie โ by default, --param destructive-interference-size and --param constructive-interference-size get picked based on whatever -mtune you're rocking right now, usually the L1 cache line size for that specific target CPU, and sometimes a whole range if you're tuning for a generic target. โจ So like, every translation unit that depends on ABI compatibility for these variables has to be compiled with the same -mtune (or -mcpu). No mixing, it's giving monogamy.
If ABI stability matters to you โ say the use is in a header for a library โ you should probably just not use the hardware interference size variables at all. Not worth the drama. Or, alternatively, you can force a particular value with --param. Your call, bestie.
And if you're confident that your use of the variable doesn't affect ABI outside a single build of your project, you can turn off the warning with -Wno-interference-size. ๐
-Wint-in-bool-contextโ Warns when you use integer values somewhere booleans belong, and it's giving suspicious. Like conditional expressions (?:) using non-boolean integer constants in boolean context, for exampleif (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 casting to a pointer type from an integer of a different size. In C++, casting to a pointer type of smaller size is a straight-up error, not a vibe.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 chillin' in the search path but can't actually be used. It's there, it's just not serving.-Wlong-longโ Warns if thelong longtype is used. Enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. Wanna mute the messages? Use-Wno-long-long.-Wvariadic-macrosโ Warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. Enabled by either-Wpedanticor-Wtraditional. To 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 SIMD capabilities of the architecture. Mainly useful for performance tuning, iykyk. A vector operation can be implemented a few ways:- "piecewise" โ the scalar operation is performed on every vector element.
- "in parallel" โ the vector operation is implemented using scalars of a wider type, which normally is more performance efficient.
- "as a single scalar" โ the vector fits into a scalar type.
-Wvlaโ Warns if a variable-length array is used in the code. And-Wno-vlaprevents the-Wpedanticwarning about the variable-length array. ๐ซถ-Wvla-larger-than=byte-sizeโ With this option on, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that lets the array size exceed byte-size bytes. Same energy as how-Walloca-larger-than=byte-sizeworks, but for variable-length arrays. ๐
Lowkey important: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for those. ๐ญ
-Wvla-larger-than=PTRDIFF_MAX is enabled by default but is typically only effective when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=byte-size.
-Wno-vla-larger-thanโ Disables-Wvla-larger-than=warnings. This option is equivalent to-Wvla-larger-than=SIZE_MAXor larger. Bigger than big.-Wvla-parameterโ Warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enables detection of out-of-bounds accesses to such parameters by warnings such as-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 be diagnosed. ๐
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 specifies that the array argument must have at least n elements. In addition, calling f with the associated VLA bound parameter in excess of the actual VLA bound triggers a warning as well.
void f (int n, int[n]);
void f (int, int[]); // warning: argument 2 previously declared as a VLA
void g (int n)
{
if (n > 4)
return;
int a[n];
f (sizeof a, a); // warning: access to a by f may be out of bounds
...
}
-Wvla-parameter is included in -Wall. And the -Warray-parameter option triggers warnings for similar problems involving ordinary array arguments. โจ
-Wvolatile-register-varโ Warns if a register variable is declared volatile. And here's the tea: the volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. It's not the shield you think it is. This warning is enabled by-Wall.-Wdisabled-optimizationโ Warns if a requested optimization pass is disabled. This warning generally does not mean something is wrong with your code โ it just means GCC's optimizers can't handle the code effectively. Often the problem is that your code is too big or too complex. GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time. ๐ฎโ๐จ-Wpointer-sign(C and Objective-C only) โ Warns for pointer argument passing or assignment with different signedness. Only supported for C and Objective-C. It's implied by-Walland by-Wpedantic, which you can disable with-Wno-pointer-sign.-Wstack-protectorโ This one's only active when-fstack-protectoris active. It warns about functions that aren't protected against stack smashing. ๐-Woverlength-stringsโ Warns about string constants longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants way longer than the standard's minimum limit, but very portable programs should avoid using longer strings. ๐
The limit applies after string constant concatenation, and it doesn't count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 doesn't specify a normative minimum maximum, so we don't diagnose overlength strings in C++. Periodt.
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.
-Wunsuffixed-float-constants(C and Objective-C only) โ Issues a warning for any floating constant that doesn't have a suffix. When used together with-Wsystem-headersit warns about such constants in system header files too. This can be useful when preparing code to use with theFLOAT_CONST_DECIMAL64pragma from the decimal floating-point extension to C99. ๐-Wno-lto-type-mismatchโ During link-time optimization, don't warn about type mismatches in global declarations from different compilation units. Requires-fltoto be enabled. Enabled by default.-Wno-designated-init(C and Objective-C only) โ Suppresses warnings when a positional initializer is used to initialize a structure that's been marked with thedesignated_initattribute. ๐
โจ Options That Control Static Analysis โจ
-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. ๐ฅ
Heads up bestie: this analysis is much more expensive than other GCC warnings. Like, way more.
In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It's a bug-finding tool, not a tool for proving program correctness. No cap.
The analyzer is only suitable for use on C code in this release.
Enabling this option effectively enables the following warnings:
-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file -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-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-write-to-const
-Wanalyzer-write-to-string-literal
This option is only available if GCC was configured with analyzer support enabled. ๐ง
-Wanalyzer-too-complexโ If-fanalyzeris enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. ๐
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.
-Wno-analyzer-double-fcloseโ This warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-fcloseto disable it.
This diagnostic warns for paths through the code in which a FILE * can have fclose called on it more than once. Once is enough, babes.
-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. ๐ญ
-Wno-analyzer-exposure-through-output-fileโ bestie, this one needs-fanalyzerto even exist (that's what switches it on), so use-Wno-analyzer-exposure-through-output-fileto turn it back off. What it's clocking: paths through your code where a security-sensitive value gets written out to an output file. We're talking writing a password into a log file energy. ๐จ-Wno-analyzer-file-leakโ requires-fanalyzer, which enables it;-Wno-analyzer-file-leakdisables it. This diagnostic is watching for paths through the code where a"<stdio.h>""FILE *"stream object gets leaked. the way that file descriptor just wanders off into the void ๐ญ-Wno-analyzer-free-of-non-heapโ requires-fanalyzer, which enables it;-Wno-analyzer-free-of-non-heapdisables it. Catches paths through the code wherefreegets called on a non-heap pointer โ like an on-stack buffer, or a global. that's not your memory to free, queen ๐-Wno-analyzer-malloc-leakโ requires-fanalyzer, which enables it;-Wno-analyzer-malloc-leakdisables it. Flags paths through the code where a pointer allocated via an allocator is leaked: eithermalloc, or a function marked with attributemalloc. it's giving memory leak, and not the cute kind โจ-Wno-analyzer-mismatching-deallocationโ requires-fanalyzer, which enables it;-Wno-analyzer-mismatching-deallocationdisables it. Warns for paths through the code where the wrong deallocation function is called on a pointer value, based on which function allocated it in the first place. It'll call out mismatches betweenfree, scalardeleteand vectordelete[], and anything marked as allocator/deallocator pairs using attributemalloc. you can't just mix and match, that's not the vibe ๐-Wno-analyzer-possible-null-argumentโ requires-fanalyzer, which enables it;-Wno-analyzer-possible-null-argumentdisables it. This one sniffs out paths through the code where a possibly-NULL value gets passed to a function argument marked with__attribute__((nonnull))as requiring a non-NULL value. the audacity of a maybe-NULL fr fr-Wno-analyzer-possible-null-dereferenceโ requires-fanalyzer, which enables it;-Wno-analyzer-possible-null-dereferencedisables it. Warns for paths through the code where a possibly-NULL value is dereferenced. lowkey terrifying, highkey useful ๐-Wno-analyzer-null-argumentโ requires-fanalyzer, which enables it;-Wno-analyzer-null-argumentdisables it. 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. bestie we KNEW it was NULL ๐ญ-Wno-analyzer-null-dereferenceโ requires-fanalyzer, which enables it;-Wno-analyzer-null-dereferencedisables it. Flags paths through the code where a value known to be NULL gets dereferenced. not the dereference ๐-Wno-analyzer-shift-count-negativeโ requires-fanalyzer, which enables it;-Wno-analyzer-shift-count-negativedisables it. Catches paths through the code where a shift is attempted with a negative count. It's analogous to the-Wshift-count-negativediagnostic implemented in the C/C++ front ends, but it's implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. ๐-Wno-analyzer-shift-count-overflowโ requires-fanalyzer, which enables it;-Wno-analyzer-shift-count-overflowdisables it. Warns 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. Analogous to the-Wshift-count-overflowdiagnostic implemented in the C/C++ front ends, but implemented based on analyzing interprocedural paths rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. ๐-Wno-analyzer-stale-setjmp-bufferโ requires-fanalyzer, which enables it;-Wno-analyzer-stale-setjmp-bufferdisables it. This diagnostic warns for paths through the code wherelongjmpis called to rewind to ajmp_bufrelating to asetjmpcall in a function that has returned.
When setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. The stack frame becomes invalid when the function containing the setjmp call returns. Attempting to rewind to it via longjmp would reference a stack frame that no longer exists, and likely lead to a crash (or worse). ๐ฑ not "or worse", bestie, I'm scared
-Wno-analyzer-tainted-allocation-sizeโ this one needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-allocation-sizeto disable it. Warns for paths through the code where a value that could be under an attacker's control is used as the size of an allocation without being sanitized, so that an attacker could inject an excessively large allocation and potentially cause a denial of service attack. ๐ฅ
See @url{https://cwe.mitre.org/data/definitions/789.html, CWE-789: Memory Allocation with Excessive Size Value}.
-Wno-analyzer-tainted-array-indexโ requires both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-array-indexto disable it. Warns for paths through the code where a value that could be under an attacker's control is used as the index of an array access without being sanitized, so that an attacker could inject an out-of-bounds access. โจ
See @url{https://cwe.mitre.org/data/definitions/129.html, CWE-129: Improper Validation of Array Index}.
-Wno-analyzer-tainted-divisorโ requires both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-divisorto disable it. Warns for paths through the code where a value that could be under an attacker's control is used as the divisor in a division or modulus operation without being sanitized, so that an attacker could inject a division-by-zero. ๐-Wno-analyzer-tainted-offsetโ requires both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-offsetto disable it. Warns for paths through the code where a value that could be under an attacker's control is used as a pointer offset without being sanitized, so that an attacker could inject an out-of-bounds access. ๐
See @url{https://cwe.mitre.org/data/definitions/823.html, CWE-823: Use of Out-of-range Pointer Offset}.
-Wno-analyzer-tainted-sizeโ requires both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-sizeto disable it. Warns for paths through the code where a value that could be under an attacker's control is used as the size of an operation such asmemsetwithout being sanitized, so that an attacker could inject an out-of-bounds access. ๐-Wno-analyzer-unsafe-call-within-signal-handlerโ requires-fanalyzer, which enables it;-Wno-analyzer-unsafe-call-within-signal-handlerdisables it. Warns for paths through the code where a function known to be async-signal-unsafe (such asfprintf) is called from a signal handler. ma'am that is NOT signal-safe ๐ซ-Wno-analyzer-use-after-freeโ requires-fanalyzer, which enables it;-Wno-analyzer-use-after-freedisables it. Warns for paths through the code where a pointer is used after a deallocator is called on it: eitherfree, or a deallocator referenced by attributemalloc. you already let it go, stop texting it ๐-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ requires-fanalyzer, which enables it;-Wno-analyzer-use-of-pointer-in-stale-stack-framedisables it. Warns for paths through the code where a pointer is dereferenced that points to a variable in a stale stack frame. that frame is literally gone ๐-Wno-analyzer-write-to-constโ requires-fanalyzer, which enables it;-Wno-analyzer-write-to-constdisables it. Warns for paths through the code where the analyzer detects an attempt to write through a pointer to aconstobject. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. it said CONST, bestie ๐-Wno-analyzer-write-to-string-literalโ requires-fanalyzer, which enables it;-Wno-analyzer-write-to-string-literaldisables it. Warns for paths through the code where the analyzer detects an attempt to write through a pointer to a string literal. However, 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โ requires-fanalyzer, which enables it;-Wno-analyzer-use-of-uninitialized-valuedisables it. Warns for paths through the code where an uninitialized value is used. bestie you never gave it a value, of course it's confused ๐ญ
Pertinent parameters for controlling the exploration are: --param analyzer-bb-explosion-factor=value, --param analyzer-max-enodes-per-program-point=value, --param analyzer-max-recursion-depth=value, and --param analyzer-min-snodes-for-call-summary=value.
The following options control the analyzer.
-fanalyzer-call-summariesโ simplify interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return. iconic behaviour tbh ๐ซถ
If enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per --param analyzer-min-snodes-for-call-summary=value).
-fanalyzer-checker=nameโ restrict the analyzer to run just the named checker, and enable it.
Some checkers are disabled by default (even with -fanalyzer), such as the taint checker that implements -Wanalyzer-tainted-array-index, and this option is required to enable them.
Note: currently, -fanalyzer-checker=taint disables the following warnings from -fanalyzer:
-Wanalyzer-double-fclose,-Wanalyzer-double-free,-Wanalyzer-exposure-through-output-file,-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โ the analyzer warning squad, all listed together like a little friend group ๐ซถ
-fno-analyzer-feasibilityโ bestie, this one is for analyzer developers specifically, okay? ๐ฉโ๐ป
So by default the analyzer is like, wait, let me double-check that there's actually a feasible control flow path for every diagnostic it wants to emit โ like, are the conditions that hold actually not mutually exclusive? Because if there's no feasible path, the diagnostic gets rejected, periodt. This whole filtering vibe can be suppressed with -fno-analyzer-feasibility, which you'd do for debugging issues in this code.
-fanalyzer-fine-grainedโ also for analyzer developers โจ
Under the hood, the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. By default, one edge in this graph can hold the effects of a run of multiple statements inside a single basic block. But with -fanalyzer-fine-grained, every single statement gets its own edge. No sharing. No cap. ๐
-fanalyzer-show-duplicate-countโ yep, analyzer developers again ๐
If multiple diagnostics got detected as being duplicates of each other, this one emits a note when it reports the best diagnostic, telling you the number of additional diagnostics that got suppressed by the deduplication logic. Iconic little receipt. ๐งพ
-fno-analyzer-state-mergeโ analyzer developers, come through ๐
By default the analyzer tries to simplify analysis by merging sufficiently similar states at each program point as it builds its "exploded graph". With -fno-analyzer-state-merge that merging gets suppressed, for debugging state-handling issues.
-fno-analyzer-state-purgeโ analyzer developers, one more time ๐ธ
By default the analyzer tries 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, that purging gets suppressed, for debugging state-handling issues.
-fanalyzer-transitivityโ this one enables transitivity of constraints within the analyzer. Slay. ๐ฅ-fanalyzer-verbose-edgesโ analyzer developers only, bestie. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. ๐-fanalyzer-verbose-state-changesโ analyzer developers only too. It enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths. ๐-fanalyzer-verbosity=levelโ this controls the complexity of the control flow paths that get emitted for analyzer diagnostics. The level can be one of these:- At this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
freediagnostic, both calls tofreewill be shown. - As per the previous level, but also show events for the entry to each function.
- 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. โญ
- As per the previous level, but show all control flow events, not just significant ones.
- This level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
- At this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
-fdump-analyzerโ dumps internal details about what the analyzer is doing tofile.analyzer.txt. Heads up tho: this option is overridden by-fdump-analyzer-stderr. ๐-fdump-analyzer-stderrโ dumps internal details about what the analyzer is doing to stderr. And this option overrides-fdump-analyzer. So it's giving main character energy, lowkey. ๐-fdump-analyzer-callgraphโ dumps a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot. ๐-fdump-analyzer-exploded-graphโ dumps a representation of the "exploded graph" suitable for viewing with GraphViz tofile.eg.dot. Nodes are color-coded based on state-machine states to emphasize state changes. ๐-fdump-analyzer-exploded-nodesโ emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source. ๐-fdump-analyzer-exploded-nodes-2โ dumps a textual representation of the "exploded graph" tofile.eg.txt. ๐-fdump-analyzer-exploded-nodes-3โ dumps a textual representation of the "exploded graph" to one dump file per node, tofile.eg-id.txt. And bestie, this is typically a large number of dump files. Like, a LOT. ๐-fdump-analyzer-exploded-pathsโ dumps a textual representation of the "exploded path" for each diagnostic tofile.idx.kind.epath.txt. ๐ค๏ธ-fdump-analyzer-feasibilityโ dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the formfile.*.fg.dot,file.*.tg.dot, andfile.*.fpath.txt. ๐บ๏ธ-fdump-analyzer-jsonโ dumps a compressed JSON representation of analyzer internals tofile.analyzer.json.gz. The precise format is subject to change, so don't get too attached, ngl. ๐ฆ-fdump-analyzer-state-purgeโ as per-fdump-analyzer-supergraph, it dumps a representation of the "supergraph" suitable for viewing with GraphViz, but it annotates the graph with information on what state will be purged at each node. The graph is written tofile.state-purge.dot. ๐งน-fdump-analyzer-supergraphโ dumps representations of the "supergraph" suitable for viewing with GraphViz tofile.supergraph.dotand tofile.supergraph-eg.dot. These show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" and diagnostics associated with them. ๐ธ๏ธ-fdump-analyzer-untrackedโ emits custom warnings with internal details intended for analyzer developers. ๐ง
Options for Debugging Your Program ๐โจ
Okay so if you wanna tell GCC to emit extra information for use by a debugger, in almost all cases you literally just need to add -g to your other options. That's it, that's the whole vibe. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options. ๐ซถ
GCC allows you to use -g with -O. And the shortcuts taken by optimized code may occasionally be surprising, bestie โ I'm not gonna sugarcoat it:
- 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. ๐
If you are not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so that -Og may result in a better debugging experience. ๐
-gโ 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. So if you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -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. Bestie really said "give me everything". ๐-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. iykyk. ๐
-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. โจ-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. ๐
-gstabsโ okay so this one produces debugging info in stabs format (if that's even supported ๐ ), without GDB extensions. It's the format DBX uses on most BSD systems. But bestie, on MIPS, Alpha, and System V Release 4 systems this option produces stabs debugging output that DBX literally does not understand ๐ญ. And on System V Release 4 systems, this option requires the GNU assembler.-gstabs+โ same stabs format (if supported), but using GNU extensions understood only by the GNU debugger (GDB) ๐. The use of these extensions is likely to make other debuggers crash or refuse to read the program ๐. No cap.-gxcoffโ produces debugging info in XCOFF format (if that's supported). This is the format used by the DBX debugger on IBM RS/6000 systems. It's giving retro IBM energy โจ.-gxcoff+โ XCOFF format (if supported) with GNU extensions understood only by GDB. Using these is likely to make other debuggers crash or refuse to read the program, and may cause assemblers other than the GNU assembler (GAS) to fail with an error ๐ญ. So maybe don't unless you're built different.-gvmsโ produces debugging info in Alpha/VMS debug format (if supported). This is the format used by DEBUG on Alpha/VMS systems. Lowkey niche but iconic ๐ฆ.-glevel,-ggdblevel,-gstabslevel,-gxcofflevel,-gvmslevelโ request debugging information and also use level to specify how much info. Default level is2. Level0produces no debug info at all, so-g0negates-g. Level1produces minimal info, enough for making backtraces in parts of the program you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no info about local variables. Level3includes extra info, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use-g3. If you use multiple-goptions, with or without level numbers, the last such option is the one that is effective. Also,-gdwarfdoes not accept a concatenated debug level, to avoid confusion with-gdwarf-level. Instead use an additional-gleveloption to change the debug level for DWARF. Periodt ๐ .-fno-eliminate-unused-debug-symbolsโ by default, no debug info is produced for symbols that are not actually used. Use this option if you want debug info for all symbols. It's giving completionist energy ๐.-femit-class-debug-alwaysโ instead of emitting debugging info 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 info for classes, because using this option increases the size of debugging info by as much as a factor of two ๐ญ. So highkey use with caution.-fno-merge-debug-stringsโ direct the linker to not merge together strings in the debugging info that are identical in different object files. Merging is not supported by all assemblers or linkers. Merging decreases the size of the debug info in the output file at the cost of increasing link processing time. Merging is enabled by default. So this is the "leave my strings alone" option ๐.-fdebug-prefix-map=old=newโ when compiling files residing in directory old, record debugging info 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-map. It's giving path glow-up โจ.-fvar-trackingโ run variable tracking pass. It computes where variables are stored at each position in code. Better debugging info is then generated (if the debugging info format supports this info). It is enabled by default when compiling with optimization (-Os,-O,-O2, ...), debugging info (-g), and the debug info format supports it. Main character energy ๐.-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 info 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. So it's the "annotate everything" vibe ๐๏ธ.-gsplit-dwarfโ if DWARF debugging info is enabled, separate as much debugging info as possible into a separate output file with the extension.dwo. This option allows the build system to avoid linking files with debug info. To be useful, this option requires a debugger capable of reading.dwofiles. It's giving "separate but equal" for debug info ๐ฆ.-gdwarf32,-gdwarf64โ if DWARF debugging info is enabled,-gdwarf32selects the 32-bit DWARF format and-gdwarf64selects the 64-bit DWARF format. The default is target specific, on most targets it is-gdwarf32though. The 32-bit DWARF format is smaller, but can't support more than 2GiB of debug info in any of the DWARF debug info sections. The 64-bit DWARF format allows larger debug info and might not be well supported by all consumers yet. Choose your fighter ๐ฅ.-gdescribe-diesโ add description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. It's giving "name tags for the nameless" ๐ท๏ธ.-gpubnamesโ generate DWARF.debug_pubnamesand.debug_pubtypessections. Iconic โจ.-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. So niche but slay ๐ .-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 info. So it's a vibe check for your linker ๐ญ.-grecord-gcc-switches,-gno-record-gcc-switchesโ this switch causes the command-line options used to invoke the compiler that may affect code generation to be appended to theDW_AT_producerattribute in DWARF debugging info. The options are concatenated with spaces separating them from each other and from the compiler version. It is enabled by default. See also-frecord-gcc-switchesfor another way of storing compiler options into the object file. It's giving receipts for your compile flags ๐งพ.-gstrict-dwarfโ disallow using extensions of later DWARF standard version than selected with-gdwarf-version. On most targets using non-conflicting DWARF extensions from later standard versions is allowed. So this is the "no extras" option ๐ซ.-gno-strict-dwarfโ allow using extensions of later DWARF standard version than selected with-gdwarf-version. Let it be free ๐ฆ.-gas-loc-supportโ inform the compiler that the assembler supports.locdirectives. It may then use them for the assembler to generate DWARF2+ line number tables. This is generally desirable, because assembler-generated line-number tables are a lot more compact than those the compiler can generate itself. This option will be enabled by default if, at GCC configure time, the assembler was found to support such directives. It's giving "let the assembler cook" ๐ฉโ๐ณ.-gno-as-loc-supportโ force GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated. No outsourcing here ๐ช.-gas-locview-supportโ inform the compiler that the assembler supports "view" assignment and reset assertion checking in.locdirectives. This option will be enabled by default if, at GCC configure time, the assembler was found to support them. Fancy ๐ .-gno-as-locview-supportโ force GCC to assign view numbers internally, if-gvariable-location-viewsare explicitly requested. DIY vibes ๐ ๏ธ.-gcolumn-info,-gno-column-infoโ emit location column information into DWARF debugging info, rather than just file and line. This option is enabled by default. So you get the whole coordinate, not just the street ๐.-gstatement-frontiers,-gno-statement-frontiersโ this option causes GCC to create markers in the internal representation at the beginning of statements, and to keep them roughly in place throughout compilation, using them to guide the output ofis_stmtmarkers in the line number table. This is enabled by default when compiling with optimization (-Os,-O1,-O2, ...), and outputting DWARF 2 debug info at the normal level. It's giving statement boundary energy ๐ฉ.-gvariable-location-views,-gvariable-location-views=incompat5,-gno-variable-location-viewsโ augment variable location lists with progressive view numbers implied from the line number table. This enables debug info consumers to 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 will cause the compiler to 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 they can be consumed by debug info consumers that are not aware of these augmentations, but they won't derive any benefit from them either. This is enabled by default when outputting DWARF 2 debug info at the normal level, as long as there is assembler support,-fvar-tracking-assignmentsis enabled and-gstrict-dwarfis not. When assembler support is not available, this may still be enabled, but it will force GCC to output internal line number tables, and if-ginternal-reset-location-viewsis not enabled, that will most certainly lead to silently mismatching location views. So it's a whole saga ๐ญ.
There is a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, that can be enabled with -gvariable-location-views=incompat5. This option may be removed in the future, is only provided as a reference implementation of the proposed representation. Debug information consumers are not expected to support this extended format, and they would be rendered unable to decode location lists using it. ๐
-ginternal-reset-location-views-gno-internal-reset-location-viewsโ bestie, this one tries to figure out which location views can just be left out of location view lists. The catch? It needs the compiler to have very accurate insn length estimates, and likeโฆ that isn't always the case ๐ญ, and it may cause incorrect view lists to be generated silently when you're using an assembler that does not 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โ generate 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 information. You can enable this 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. iykyk ๐-gz[=type]โ produce compressed debug sections in DWARF format, if that is supported. If type is not given, the default type depends on the capabilities of the assembler and linker used. type may be one ofnone(don't compress debug sections),zlib(use zlib compression in ELF gABI format), orzlib-gnu(use zlib compression in traditional GNU format). If the linker doesn't support writing compressed debug sections, the option is rejected. Otherwise, if the assembler does not 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 file in which the struct is defined.
This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF debug output. ๐ง
-femit-struct-debug-reducedโ emit debug information for struct-like types only when the base name of the compilation source file matches the base name of file in which the type is defined, unless the struct is a template or defined in a system header.
This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF debug output. ๐ง
-femit-struct-debug-detailed[=spec-list]โ specify the struct-like types for which the compiler generates debug information. The whole point is to reduce duplicate struct debug information 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. fr fr.
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 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 are 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, however, this results in a significant amount of wasted space ๐ญ.
โจ Options That Control Optimization โจ
These options control various sorts of optimizations. ๐
Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code. 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. tradeoffs, bestie ๐
The compiler performs optimization based on the knowledge it has of the program. Compiling multiple files at once to a single output file mode allows the compiler to use information gained from all of the files when compiling each of them. iconic.
Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.
Most optimizations are completely disabled at -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified. Similarly, -Og suppresses many optimization passes.
Depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level. ๐ฆ
-O-O1โ Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.
With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O turns on the following optimization flags:
-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
-O2โ Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to-O, this option increases both compilation time and the performance of the generated code. slay ๐
-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp -fipa-cp -fipa-icf -fipa-ra -fipa-sra -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition -freorder-functions
-frerun-cse-after-loop -fschedule-insns -fschedule-insns2
-fsched-interblock -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos. โ ๏ธ
NOTE: In Ubuntu 8.10 and later versions,-D_FORTIFY_SOURCE=2, in Ubuntu 24.04 and later versions,-D_FORTIFY_SOURCE=3, is set by default, and is activated when-Ois set to 2 or higher. This enables additional compile-time and run-time checks for several libc functions. To disable, specify either-U_FORTIFY_SOURCEor-D_FORTIFY_SOURCE=0.
-O3โ Optimize yet more.-O3turns on all optimizations specified by-O2and also turns on the following optimization flags: ๐ฅ
-fgcse-after-reload
-fipa-cp-clone
-floop-interchange
-floop-unroll-and-jam
-fpeel-loops
-fpredictive-commoning
-fsplit-loops
-fsplit-paths
-ftree-loop-distribution
-ftree-partial-pre
-funswitch-loops
-fvect-cost-model=dynamic
-fversion-loops-for-strides
-O0โ okay so this one is the "we're literally not optimizing anything, we're just trying to get this to compile so we can debug it" vibe ๐ It cuts compilation time down and makes debugging actually produce the results you expect. And yeah, this is the default. Periodt.-Osโ Optimize for size. It switches on every-O2optimization except the ones that love to fatten up your code:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also turns on -finline-functions, makes the compiler tune for code size instead of execution speed, and runs even more optimizations that are all about shrinking your binary. Small and mighty, we love to see it ๐
-Ofastโ Disregard strict standards compliance. Not me enabling every single-O3optimization and then stacking on top optimizations that are not valid for all standard-compliant programs ๐ It flips on-ffast-math,-fallow-store-data-races, the Fortran-specific-fstack-arrays(unless-fmax-stack-var-sizeis specified), and-fno-protect-parens. And it turns off-fsemantic-interposition. If you need strict standards compliance, bestie, walk away ๐-Ogโ optimize the debugging experience, and honestly? This is the main character of the standard edit-compile-debug cycle โจ It gives you a reasonable level of optimization while keeping compilation fast and debugging good. It's a better pick than-O0for producing debuggable code, because some compiler passes that collect debug info are disabled at-O0.
Like -O0, -Og completely disables a number of optimization passes, so the individual options that control those passes just have no effect. Otherwise, -Og enables every -O1 optimization flag except the ones that might get in debugging's way:
-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. Heads up though: this can actually increase the number of instructions executed, if those instructions need fewer bytes to encode.-Ozacts a lot like-Os, including enabling most-O2optimizations. Shrink it down, we're packing light ๐ง
Okay so if you pass multiple -O options, with or without level numbers? The last one wins. That's the one that's effective. No mixing and matching, the compiler's not doing a vibe check on all of them.
Options of the form -fflag are your machine-independent flags. Most flags have both a positive and a negative form โ the negative form of -ffoo is -fno-foo. In the list below only one of the forms shows up (the one you'd typically use), and you can figure out the other by either removing no- or adding it. iykyk ๐
The next batch of options controls specific optimizations โ they're either turned on by the -O options, or they're related to ones that are. Use these flags in those rare moments when you want to "fine-tune" which optimizations actually happen. Fancy ๐
-fno-defer-popโ for machines that have to pop arguments after a function call, this always pops them the second each function returns. At-O1and higher,-fdefer-popis the default, which lets the compiler let arguments pile up on the stack across several function calls and then pop them all at once. Efficiency โจ-fforward-propagateโ runs a forward propagation pass on RTL. The pass tries to combine two instructions and checks whether the result can be simplified. If loop unrolling is active, two passes happen and the second one is scheduled after loop unrolling. This option is on by default at-O1,-O2,-O3,-Os.-ffp-contract=styleโ okay, three flavors bestie:-ffp-contract=offdisables floating-point expression contraction.-ffp-contract=fastenables floating-point expression contraction, like forming fused multiply-add operations when the target natively supports them.-ffp-contract=onenables floating-point expression contraction if the language standard allows it. This is currently not implemented and is treated equal to-ffp-contract=off.
The default is -ffp-contract=fast.
-fomit-frame-pointerโ omits the frame pointer in functions that don't need one ๐ซถ This dodges the instructions that save, set up and restore the frame pointer, and on many targets it also frees up an extra register.
On some targets this flag does literally nothing, because the standard calling sequence always uses a frame pointer, so it can't 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โ optimizes sibling and tail recursive calls. Enabled at-O2,-O3,-Os.-foptimize-strlenโ optimizes various standard C string functions (likestrlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives ๐ฅ Enabled at-O2,-O3.-fno-inlineโ do not expand any functions inline, apart from the ones marked with thealways_inlineattribute. This is the default when not optimizing. Individual functions can be exempted from inlining by marking them with thenoinlineattribute. Not me being picky about which functions get inlined ๐-finline-small-functionsโ integrates functions into their callers when their body is smaller than the expected function call code (so the overall size of the program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating this way. This inlining applies to all functions, even the ones not declared inline. Enabled at-O2,-O3,-Os.-findirect-inliningโ inlines indirect calls that get discovered to be known at compile time thanks to previous inlining. This option only does anything when inlining itself is turned on by-finline-functionsor-finline-small-functions. Enabled at-O2,-O3,-Os.-finline-functionsโ considers all functions for inlining, even if they aren't declared inline. The compiler heuristically decides which ones are worth integrating this way.
If every call to a given function gets integrated, and the function is declared static, then the function normally isn't output as assembler code in its own right.
Enabled at -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.
-finline-functions-called-onceโ considers allstaticfunctions called once for inlining into their caller, even if they aren't markedinline. If a call to a given function gets integrated, then the function isn't output as assembler code in its own right. Enabled at-O1,-O2,-O3and-Os, but not-Og.-fearly-inliningโ inlines functions marked byalways_inlineand functions whose body looks smaller than the function call overhead, early โ before doing-fprofile-generateinstrumentation and the real inlining pass. Doing this makes profiling significantly cheaper and usually makes inlining faster on programs with big chains of nested wrapper functions. Enabled by default. Get in early, slay ๐-fipa-sraโ does interprocedural scalar replacement of aggregates, removes unused parameters, and replaces parameters passed by reference with parameters passed by value. Enabled at-O2,-O3and-Os.-finline-limit=nโ by default, GCC limits how big a function can be for it to be inlined. This flag gives you coarse control over that limit.nis the size of functions that can be inlined, counted in number of pseudo instructions.
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 those parameters like this:
max-inline-insns-singleโ is set ton/2.max-inline-insns-autoโ is set ton/2.
See below for documentation of the individual parameters controlling inlining, and for the defaults of those parameters.
Note: there may be no value to -finline-limit that results in default behavior.
Note: in this particular context, pseudo instruction represents an abstract measurement of a function's size. It in no way represents a count of assembly instructions, and as such its exact meaning might change from one release to another. So don't @ me about it ๐ญ
-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, this emitsstaticfunctions that are declaredinlineinto the object file, even if the function has been inlined into all of its callers. This switch does not affect functions using theextern inlineextension in GNU C90. In C++, it emits any and all inline functions into the object file.-fkeep-static-functionsโ emitsstaticfunctions into the object file, even if the function is never used. Keeping it around for the plot ๐-fkeep-static-constsโ emits variables declaredstatic constwhen optimization isn't turned on, even if the variables aren't referenced. GCC enables this option by default. If you want to force the compiler to check whether a variable is referenced, regardless of whether or not optimization is turned on, use the-fno-keep-static-constsoption.-fmerge-constantsโ attempts 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-constantsto inhibit this behavior. Enabled at-O1,-O2,-O3,-Os.-fmerge-all-constantsโ attempts to merge identical constants and identical variables. This option implies-fmerge-constants. On top of that, it also considers things like even constant initialized arrays, or initialized constant variables with integral or floating-point types.
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. So like, be careful bestie ๐
-fmodulo-schedโ performs swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. Loops getting a little remix โจ-fmodulo-sched-allow-regmovesโ bestie, this one goes feral with the modulo scheduling. It does a more aggressive SMS-based modulo scheduling where register moves are allowed โจ. Setting this flag deletes certain anti-dependences edges, which triggers the generation of reg-moves based on the life-range analysis. Heads up tho: this option is effective only with-fmodulo-schedenabled ๐ซถ.-fno-branch-count-regโ turns off the optimization pass that scans for opportunities to use "decrement and branch" instructions 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. And no, bestie, the-fno-branch-count-regoption doesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes โ it's giving "I disabled one thing, not everything" ๐ญ.
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, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used. So like, if your weird little hack is throwing hands, here's your girl ๐.
The default is -ffunction-cse.
-fno-zero-initialized-in-bssโ okay so 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 audacity, honestly.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ performs optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found ๐ฅ. If so, the first branch is redirected 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. It's giving "why do twice what you can do once," periodt.
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, always tradeoffs.
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. She's just following the vibes.
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ this is similar to-fcse-follow-jumps, but 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. Iconic little shortcut behavior.
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-run common subexpression elimination after loop optimizations are performed ๐. Like, run it back, we missed something.
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-gcseto 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. She said "let's take this outside."
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, so you gotta ask for it directly, bestie.-fgcse-lasโ when-fgcse-lasis enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies) ๐ธ. Not enabled at any optimization level.-fgcse-after-reloadโ when-fgcse-after-reloadis enabled, a redundant load elimination pass is performed after reload ๐ . The purpose of this pass is to clean up redundant spilling. Enabled by-O3,-fprofile-useand-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. She's aggressive, it's in the name.-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. "We don't actually know how big this is" is a whole mood.-fcrossjumpingโ perform cross-jumping transformation ๐. This transformation unifies equivalent code and saves code size. The resulting code may or may not perform better than without cross-jumping โ no promises, bestie, it's giving "maybe faster, definitely smaller."
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.-fdceโ perform dead code elimination (DCE) on RTL โจ. Enabled by default at-O1and higher.-fdseโ perform dead store elimination (DSE) on RTL ๐. Enabled by default at-O1and higher.-fif-conversionโ attempt to transform conditional jumps into branch-less equivalents ๐. This includes use of conditional moves, min, max, set flags and abs instructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it is available is controlled by-fif-conversion2. Enabled at levels-O1,-O2,-O3,-Os, but not with-Og๐ซถ.-fif-conversion2โ use conditional execution (where available) to transform 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, which means two copies of the function. With this option, the base and complete variants are changed to be thunks that call a common implementation. De-dupe era ๐.
Enabled by -Os.
-fdelete-null-pointer-checksโ assume that programs cannot safely dereference null pointers, and that no code or data element resides at address zero ๐ฅ. This option enables simple constant folding optimizations at all optimization levels. In addition, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; these assume that a memory access to address zero always results in a trap, so that if a pointer is checked after it has already been dereferenced, it cannot be null.
Note however that in some environments this assumption is not true โ ๏ธ. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.
This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR, CR16, and MSP430, this option is completely disabled. Passes that use the dataflow information are enabled independently at different optimization levels.
-fdevirtualizeโ attempt to convert calls to virtual functions to direct calls โจ. This is done 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โ attempt to convert calls to virtual functions to speculative direct calls ๐ฎ. Based on the analysis of the type inheritance graph, determine for a given call the set of likely targets. If the set is small, preferably of size1, change the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, such as inlining. When they seem useless after further optimization, they are converted back into original form. She tries something bold, and if it flops, she pretends it never happened ๐.-fdevirtualize-at-ltransโ stream extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode ๐. This option enables more devirtualization but significantly increases the size of streamed data. For this reason it is disabled by default.-fexpensive-optimizationsโ perform a number of minor optimizations that are relatively expensive ๐ธ. Enabled at levels-O2,-O3,-Os.-freeโ attempt to remove redundant extension instructions ๐ธ. This is especially helpful for the x86-64 architecture, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. Enabled for Alpha, AArch64 and x86 at levels-O2,-O3,-Os.-fno-lifetime-dseโ okay so bestie, in C++ the value of an object is only affected by changes within its lifetime: when the constructor begins, the object has an indeterminate value, and any changes during the lifetime of the object are dead when the object is destroyed. Normally dead store elimination will take 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 (e.g. 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โ attempt to decrease register pressure through register live range shrinkage. This is helpful for fast processors with small or moderate size register sets. โจ-fira-algorithm=algorithmโ use the specified coloring algorithm for the integrated register allocator. The algorithm argument can bepriority, which specifies Chow's priority coloring, orCB, which specifies Chaitin-Briggs coloring. Chaitin-Briggs coloring is not implemented for all architectures, but for those targets that do support it, it is the default because it generates better code. ๐-fira-region=regionโ use specified regions for the integrated register allocator. The region argument should be one of the following:allโ use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set.mixedโ use all loops except for loops with small register pressure as the regions. This value usually gives the best results in most cases and for most architectures, and is enabled by default when compiling with optimization for speed (-O,-O2, ...).oneโ use all functions as a single region. This typically results in the smallest code size, and is enabled by default for-Osor-O0.
-fira-hoist-pressureโ use IRA to evaluate register pressure in the code hoisting pass for decisions to hoist expressions. This option usually results in smaller code, but it can slow the compiler down. This option is enabled at level-Osfor all targets. ๐ฆ-fira-loop-pressureโ use IRA to evaluate register pressure in loops for decisions to move loop invariants. This option usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down. This option is enabled at level-O3for some targets. ๐ฅ-fno-ira-share-save-slotsโ disable 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โ disable sharing of stack slots allocated for pseudo-registers. Each pseudo-register that does not get a hard register gets a separate stack slot, and as a result function stack frames are larger. ๐-flra-rematโ enable CFG-sensitive rematerialization in LRA. Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it is profitable. Enabled at levels-O2,-O3,-Os. โจ-fdelayed-branchโ if supported for the target machine, attempt 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, attempt to reorder instructions to eliminate execution stalls due to required data being unavailable. This helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating-point instruction is required. Enabled at levels-O2,-O3. ๐-fschedule-insns2โ similar to-fschedule-insns, but requests an additional pass of instruction scheduling after register allocation has been done. This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle. Enabled at levels-O2,-O3,-Os. ๐-fno-sched-interblockโ disable 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โ disable 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โ enable 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. Usage of this option can improve the generated code and decrease its size by preventing register pressure increase above the number of available hard registers and subsequent spills in register allocation. ๐-fsched-spec-loadโ allow 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โ allow 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โ define how many insns (if any) can be moved prematurely from the queue of stalled insns into the ready list during the second scheduling pass.-fno-sched-stalled-insnsmeans that no insns are moved prematurely,-fsched-stalled-insns=0means there is no limit on how many queued insns can be moved prematurely.-fsched-stalled-insnswithout a value is equivalent to-fsched-stalled-insns=1. ๐ฅ-fsched-stalled-insns-dep,-fsched-stalled-insns-dep=nโ define how many insn groups (cycles) are examined for a dependency on a stalled insn that is a candidate for premature removal from the queue of stalled insns. This has an effect only during the second scheduling pass, and only if-fsched-stalled-insnsis used.-fno-sched-stalled-insns-depis equivalent to-fsched-stalled-insns-dep=0.-fsched-stalled-insns-depwithout a value is equivalent to-fsched-stalled-insns-dep=1. ๐-fsched2-use-superblocksโ when scheduling after register allocation, use superblock scheduling. This allows motion across basic block boundaries, resulting in faster schedules. This option is experimental, as not all machine descriptions used by GCC model the CPU closely enough to avoid unreliable results from the algorithm. This only makes sense when scheduling after register allocation, i.e. with-fschedule-insns2or at-O2or higher. ๐ง-fsched-group-heuristicโ enable the group heuristic in the scheduler. This heuristic favors the instruction that belongs to a schedule group. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐-fsched-critical-path-heuristicโ enable the critical-path heuristic in the scheduler. This heuristic favors instructions on the critical path. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐ฅ-fsched-spec-insn-heuristicโ enable the speculative instruction heuristic in the scheduler. This heuristic favors speculative instructions with greater dependency weakness. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. โจ-fsched-rank-heuristicโ enable the rank heuristic in the scheduler. This heuristic favors the instruction belonging to a basic block with greater size or frequency. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐-fsched-last-insn-heuristicโ enable the last-instruction heuristic in the scheduler. This heuristic favors the instruction that is less dependent on the last instruction scheduled. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐ฆ-fsched-dep-count-heuristicโ enable the dependent-count heuristic in the scheduler. This heuristic favors the instruction that has more instructions depending on it. This is enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher. ๐-freschedule-modulo-scheduled-loopsโ modulo scheduling is performed before traditional scheduling. If a loop is modulo scheduled, later scheduling passes may change its schedule. Use this option to control that behavior. ๐-fselective-schedulingโ schedule instructions using selective scheduling algorithm. Selective scheduling runs instead of the first scheduler pass. ๐-fselective-scheduling2โ schedule instructions using selective scheduling algorithm. Selective scheduling runs instead of the second scheduler pass. ๐-fsel-sched-pipeliningโ enable 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 sounds cute until you realise it means: for symbols exported from the DSO, the compiler cannot do interprocedural propagation, inlining, and all the other glow-ups, because the function or variable in question might change on it. ๐ And like โ sure, this feature is genuinely useful, e.g. if you wanna rewrite memory allocation functions with a debugging implementation. But bestie, it is expensive in terms of code quality. With-fno-semantic-interposition, the compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Similarly, if interposition happens for variables, the constructor of the variable will be the same. This flag has no effect for functions explicitly declared inline (where it is never allowed for interposition to change semantics) and for symbols explicitly declared weak. periodt. โจ-fshrink-wrapโ emit function prologues only before the parts of the function that actually need it, instead of dumping them at the top of the function like a lil intro nobody asked for. This flag is enabled by default at-Oand higher. ๐-fshrink-wrap-separateโ shrink-wrap the separate parts of the prologue and epilogue separately, so those parts only get executed when needed. This option is on by default, but it does literally nothing unless-fshrink-wrapis also turned on and the target supports it. ๐ฆ-fcaller-savesโ enable allocation of values to registers that are 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. fr fr, only when it's actually worth it. ๐
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, then tries to find ways to combine them. Efficiency queen. ๐
Enabled by default at -O1 and higher.
-fipa-raโ use caller save registers for allocation if those registers are not used by any called function. In that case it is 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. no cap.
Enabled at levels -O2, -O3, -Os, however the option is disabled if generated code will be instrumented for profiling (-p, or -pg), or if the callee's register usage 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 tries to use less stack space, even if that makes the program slower. It's giving "I'll take the hit so the stack doesn't". ๐ญ This option implies setting thelarge-stack-frameparameter to100and thelarge-stack-frame-growthparameter to400.-ftree-reassocโ perform reassociation on trees. This flag is enabled by default at-O1and higher. ๐ธ-fcode-hoistingโ perform code hoisting. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at-O2and higher. โจ-ftree-preโ perform partial redundancy elimination (PRE) on trees. This flag is enabled by default at-O2and-O3. ๐ซถ-ftree-partial-preโ make partial redundancy elimination (PRE) more aggressive. This flag is enabled by default at-O3. She's not holding back. ๐-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. This option can cause excessive memory and compile-time usage on large compilation units. It is not enabled by default at any optimization level. like, none of them. ngl she's hungry. ๐ญ-fipa-profileโ perform interprocedural profile propagation. The functions called only from cold functions are marked as cold. Also functions executed once (such ascold,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โ perform function cloning to make interprocedural constant propagation stronger. When enabled, interprocedural constant propagation performs function cloning when an externally visible function can be called with constant arguments. Because this optimization can create multiple copies of functions, it may significantly increase code size (see--param ipa-cp-unit-growth=value). This flag is enabled by default at-O3. It is also enabled by-fprofile-useand-fauto-profile. ๐-fipa-bit-cpโ when enabled, perform interprocedural bitwise constant propagation. This flag is enabled by default at-O2and by-fprofile-useand-fauto-profile. It requires that-fipa-cpis enabled. ๐-fipa-vrpโ when enabled, perform interprocedural propagation of value ranges. This flag is enabled by default at-O2. It requires that-fipa-cpis enabled. ๐-fipa-icfโ perform Identical Code Folding for functions and read-only variables. The optimization reduces code size and may disturb unwind stacks by replacing a function by an equivalent one with a different name. The optimization works more effectively with link-time optimization enabled.
Although the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels and thus the optimizations are not the same โ there are equivalences that are found only by GCC and equivalences found only by Gold. two queens, different crowns. ๐
This flag is enabled by default at -O2 and -Os.
-flive-patching=levelโ control GCC's optimizations to produce output suitable for live-patching. ๐ฉน
If the compiler's optimization uses a function's body or information extracted from its body to optimize/change another function, the latter is called an impacted function of the former. If a function is patched, its impacted functions should be patched too.
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 enabled, the larger the number of impacted functions for each function. In order 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, therefore 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. As a result, when patching a static function, all its callers are impacted and so need to be patched as well.
In addition to all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables the following additional optimization flags: -fipa-cp-clone -fipa-sra -fpartial-inlining -fipa-cp
When -flive-patching is specified without any value, the default value is inline-clone. ๐
This flag is disabled by default.
heads up bestie โ-flive-patchingis not supported with link-time optimization (-flto). ๐
-fisolate-erroneous-paths-dereferenceโ bestie, this one sniffs out the paths where you're dereferencing a null pointer and therefore triggering erroneous or undefined behavior ๐. It isolates those little chaos paths away from the main control flow and turns the offending statement into a trap. It's on by default at-O2and higher, and it depends on-fdelete-null-pointer-checksalso being enabled, so no sneaky business there.-fisolate-erroneous-paths-attributeโ same energy, different trigger: this catches paths where a null value gets used in a way that's forbidden by areturns_nonnullornonnullattribute. It isolates them from the main control flow and turns that statement with erroneous or undefined behavior into a trap too ๐ชค. Heads up though: this is not currently enabled, but it may be enabled by-O2in the future.-ftree-sinkโ does forward store motion on trees. Enabled by default at-O1and higher โจ.-ftree-bit-ccpโ performs sparse conditional bit constant propagation on trees and propagates pointer alignment info. It only operates on local scalar variables, and it's enabled by default at-O1and higher โ except for-Og. It requires that-ftree-ccpis enabled first, so they're a little package deal ๐ซถ.-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees. Same deal: only touches local scalar variables, and it's enabled by default at-O1and higher.-fssa-backpropโ propagates info about how a value is used up the definition chain so it can simplify the definitions themselves. For example, it strips sign operations when the sign of a value literally never matters ๐. Enabled by default at-O1and higher.-fssa-phioptโ does pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at-O1and higher, except for-Og.-ftree-switch-conversionโ converts simple initializations inside a switch into initializations from a scalar array. Enabled by default at-O2and higher.-ftree-tail-mergeโ hunts for identical code sequences, and when it finds them, it replaces one with a jump to the other. This glow-up is known as tail merging or cross jumping โจ. Enabled by default at-O2and higher. The compilation time in this pass can be limited using themax-tail-merge-comparisonsparameter and themax-tail-merge-iterationsparameter, if you need to keep it from taking forever.-ftree-dceโ performs dead code elimination (DCE) on trees. Enabled by default at-O1and higher ๐ .-ftree-builtin-call-dceโ performs conditional dead code elimination (DCE) for calls to built-in functions that may seterrnobut are otherwise free of side effects. Enabled by default at-O2and higher if-Osis not also specified.-ffinite-loopsโ tells the compiler to assume that a loop with an exit will eventually take that exit and not loop forever โพ๏ธ๐ซ. That lets it remove loops that otherwise have no side-effects, since it's not counting "eventual endless looping" as a side effect. This option is enabled by default at-O2for C++ with-std=c++11or higher.-ftree-dominator-optsโ does a whole lil spa day of simple scalar cleanups based on a dominator tree traversal: constant/copy propagation, redundancy elimination, range propagation, and expression simplification ๐ง. It also performs jump threading (to reduce jumps to jumps). Enabled by default at-O1and higher.-ftree-dseโ performs dead store elimination (DSE) on trees. A dead store is a store into a memory location that gets overwritten later by another store with no intervening loads โ so the earlier store can just be deleted ๐๏ธ. Enabled by default at-O1and higher.-ftree-chโ performs loop header copying on trees. This is a win because it increases the effectiveness of code motion optimizations, and it also saves one jump ๐ฅ. Enabled by default at-O1and higher. It is not enabled for-Os, since it usually increases code size.-ftree-loop-optimizeโ performs loop optimizations on trees. Enabled by default at-O1and higher.-ftree-loop-linear,-floop-strip-mine,-floop-blockโ perform loop nest optimizations. Same as-floop-nest-optimize. To use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure ๐๏ธ.-fgraphite-identityโ enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using-fgraphite-identitywe can check the costs or benefits of theGIMPLE -> GRAPHITE -> GIMPLEtransformation ๐. Some minimal optimizations are also performed by the code generator isl, like index splitting and dead code elimination in loops.-floop-nest-optimizeโ enables the isl based loop nest optimizer. It's a generic loop nest optimizer based on the Pluto optimization algorithms, and it calculates a loop structure optimized for data-locality and parallelism. Heads up: 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 whether it's actually profitable to parallelize them ๐ญ. Bold. Iconic. No vibe check.-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. Warning bestie: this may severely limit the ability to debug an optimized program compiled with-fno-var-tracking-assignments๐. In its negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise.-ftree-loop-if-convertโ attempts to transform conditional jumps in the innermost loops into branch-less equivalents. The whole 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 can improve cache performance on big loop bodies and allows further loop optimizations (like parallelization or vectorization) to take place. For example, this loop:
DO I = 1, N
A(I) = B(I) + C
D(I) = E(I) * F
ENDDO
gets transformed to:
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
Enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile.
-ftree-loop-distribute-patternsโ performs loop distribution of patterns that can be code generated with calls to a library. Enabled by default at-O2and higher, and by-fprofile-useand-fauto-profile.
This pass distributes the initialization loops and generates a call to memset zero โจ. For example, this loop:
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
gets transformed to:
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and the initialization loop is transformed into 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 flag can improve cache performance on loop nests and allow further loop optimizations, like vectorization, to take place. For example, this loop:
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
is transformed to:
for (int i = 0; i < N; i++)
for (int k = 0; k < N; k++)
for (int j = 0; j < N; j++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
Enabled by default at -O3. It's 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 ๐. Enabled by default at-O3. It's 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 the 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 we can use just trivial invariantness analysis in loop unswitching ๐. The pass also includes store motion.-ftree-loop-ivcanonโ creates a canonical counter for the number of iterations in loops where figuring out the iteration count requires complicated analysis. Later optimizations may then 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 such that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, it replaces uses of the final value by that computation โ provided it's 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 โ parallelizes loops, i.e., splits their iteration space to run in n threads ๐งต. This is only possible for loops whose iterations are independent and can be arbitrarily reordered. Ngl, 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โ does function-local points-to analysis on trees โจ it's on by default at-O1and up, except when you're at-Og.-ftree-sraโ scalar replacement of aggregates, bestie ๐ this pass swaps out structure references for scalars so it doesn't commit your structs to memory too early. On by default at-O1and higher, except for-Og.-fstore-mergingโ merges narrow stores into consecutive memory addresses ๐ like, it takes contiguous stores of immediate values that are narrower than a word and squishes them into fewer wider stores so the instruction count goes down. Enabled by default at-O2and higher, plus-Os.-ftree-terโ temporary expression replacement during the SSA->normal phase ๐ธ single use/single def temporaries get replaced at their use location with their defining expression. This gives you non-GIMPLE code, but it hands the expanders way more complex trees to work with, which means better RTL generation. On by default at-O1and higher.-ftree-slsrโ straight-line strength reduction on trees โญ it spots related expressions involving multiplications and swaps them for cheaper calculations when it can. On by default at-O1and higher.-ftree-vectorizeโ vectorization on trees ๐ฆ this flag turns on-ftree-loop-vectorizeand-ftree-slp-vectorizeif you haven't explicitly specified them.-ftree-loop-vectorizeโ loop vectorization on trees ๐ on by default at-O2, and also enabled by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftree-slp-vectorizeโ basic block vectorization on trees ๐ on by default at-O2, and also enabled by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftrivial-auto-var-init=choiceโ initializes automatic variables with either a pattern or with zeroes ๐ซถ the whole point is bumping security and predictability by preventing uninitialized memory disclosure and use. Ngl though, GCC still considers an automatic variable with no explicit initializer as uninitialized, so-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still warn you about those. With this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. BUT โ the current implementation cannot initialize automatic variables 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.patterninitializes automatic variables with values that will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump, and aren't values programmers can rely on for useful program semantics. The current value is a byte-repeatable pattern with byte"0xFE". Heads up: the values used for pattern initialization might be changed in the future ๐zeroinitializes automatic variables with zeroes.
The default is uninitialized.
You can control this behavior for a specific variable by using the variable attribute uninitialized โจ
-fvect-cost-model=modelโ changes up the cost model used for vectorization ๐ model should be one ofunlimited,dynamic,cheap, orvery-cheap. Withunlimitedthe vectorized code-path is assumed to be profitable, while withdynamica runtime check guards the vectorized code-path so it only kicks in for iteration counts that'll likely run faster than the original scalar loop. Thecheapmodel disables vectorization of loops where doing so would be cost prohibitive โ say, because of required runtime checks for data dependence or alignment โ but otherwise it's equal todynamic. Thevery-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code being vectorized. Example: if each iteration of a vectorized loop could only handle exactly four iterations of the scalar loop,very-cheapwould 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โ changes the cost model for vectorization of loops marked with the OpenMP simd directive ๐ model should be one ofunlimited,dynamic,cheap. All values of model mean the same thing as described in-fvect-cost-model, and by default a cost model defined with-fvect-cost-modelis used.-ftree-vrpโ Value Range Propagation on trees โญ similar to the constant propagation pass, but instead of values it propagates ranges of values. This lets the optimizers remove unnecessary range checks like array bound checks and null pointer checks. On by default at-O2and higher. Null pointer check elimination only happens 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 from the first iteration โจ this breaks long dependency chains, which improves efficiency of the scheduling passes.
A combo of -fweb and CSE is often enough to get the same effect. However, that's not reliable when the loop body is more complicated than a single basic block. It also doesn't work at all on some architectures due to restrictions in the CSE pass.
This optimization is enabled by default.
-fvariable-expansion-in-unrollerโ with this one, the compiler makes 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โ inline parts of functions ๐ this option only has any effect when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
Enabled at levels -O2, -O3, -Os.
-fpredictive-commoningโ does predictive commoning optimization, i.e., reusing computations (especially memory loads and stores) performed in previous iterations of loops ๐ฅ
Enabled at level -O3. It's also enabled by -fprofile-use and -fauto-profile.
-fprefetch-loop-arraysโ if the target machine supports it, generates instructions to prefetch memory so loops that access large arrays run better ๐ธ
Ngl 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 the known return value of formatted output functions likesprintf,snprintf,vsprintf, andvsnprintf(but notprintforfprintf) ๐ this transformation lets GCC 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're implemented in the compiler; some targets use one, some use the other, a few use both.
-fpeephole is enabled by default. -fpeephole2 enabled 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're 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_expect info into account. The interactions between the heuristics and __builtin_expect can be complex, and in some cases it may be useful to disable the heuristics so the effects of __builtin_expect are easier to understand ๐
It's also possible to specify the expected probability of the expression with the __builtin_expect_with_probability built-in function.
The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.
-freorder-blocksโ reorders basic blocks in the compiled function to reduce the number of taken branches and improve code locality ๐
Enabled at levels -O1, -O2, -O3, -Os.
-freorder-blocks-algorithm=algorithmโ uses the specified algorithm for basic block reordering ๐ the algorithm argument can besimple, which doesn't increase code size (except sometimes due to secondary effects like alignment), orstc, the "software trace cache" algorithm, which tries to put all often executed code together, minimizing the number of branches executed by making extra copies of code.
The default is simple at levels -O1, -Os, and stc at levels -O2, -O3.
-freorder-blocks-and-partitionโ okay so this one doesn't just reorder basic blocks inside the compiled function to cut down taken branches (though it does do that, slay). It also splits hot and cold basic blocks into separate sections of the assembly and.ofiles, which helps paging and cache locality performance. It's giving glow-up for your memory hierarchy. โจ
Heads up though, this optimization gets automatically turned off when:
- there's exception handling or unwind tables around (on targets using
setjump/longjumpor a target specific scheme) - there are linkonce sections
- there are functions with a user-defined section attribute
- you're on any architecture that doesn't support named sections
And when -fsplit-stack is used, this option is not enabled by default (to avoid linker errors), but you can enable it explicitly โ if you're using a working linker. ๐ซถ
Enabled for x86 at levels -O2, -O3, -Os.
-freorder-functionsโ reorders functions in the object file to improve code locality. The way it works: it uses special subsections.text.hotfor the most frequently executed functions and.text.unlikelyfor the unlikely-executed ones. The linker does the actual reordering, so your object file format needs to support named sections and the linker has to place them in a reasonable way. no cap.
Lowkey this option does nothing for you unless you either provide profile feedback (peep -fprofile-arcs for the deets) or manually annotate functions with "hot" or "cold" attributes.
Enabled at levels -O2, -O3, -Os.
-fstrict-aliasingโ lets the compiler assume the strictest aliasing rules that apply to the language being compiled. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to live at the same address as an object of a different type โ unless the types are almost the same. Example: an"unsigned int"can alias an"int", but it can't alias a"void*"or a"double". A character type may alias any other type. ๐
Pay special attention to code like this:
union a_union {
int i;
double d;
};
int f() {
union a_union t;
t.d = 3.0;
return t.i;
}
Reading from a different union member than the one you most recently wrote to (this is called "type-punning", iykyk) is super common. And 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, like:
int f() {
double d = 3.0;
return ((union a_union *) &d)->i;
}
bestie this is the part where you read carefully. undefined behavior is not a vibe. ๐ญ
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-fipa-strict-aliasingโ controls whether the rules of-fstrict-aliasingget applied across function boundaries. Note that if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary. ๐ฆ
The -fipa-strict-aliasing option is enabled by default and is only effective in combination with -fstrict-aliasing.
โจ the alignment era โจ
-falign-functions-falign-functions=n-falign-functions=n:m-falign-functions=n:m:n2-falign-functions=n:m:n2:m2โ aligns the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes. This makes sure at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. ๐
If m isn't specified, it defaults to n.
Examples, because examples are everything:
-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 lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise it aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 isn't specified, it defaults to n2.
Some assemblers only support this flag when n is a power of two; in that case, it gets rounded up.
-fno-align-functions and -falign-functions=1 are equivalent and mean 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 enabled, the compiler tries to avoid unnecessarily overaligning functions. It attempts to instruct the assembler to align by the amount specified by-falign-functions, but not to skip more bytes than the size of the function. ๐ซถ-falign-labels-falign-labels=n-falign-labels=n:m-falign-labels=n:m:n2-falign-labels=n:m:n2:m2โ aligns all branch targets to a power-of-two boundary.
The parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean labels are not aligned.
If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.
If n is not specified or is zero, use a machine-dependent default โ which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-falign-loops-falign-loops=n-falign-loops=n:m-falign-loops=n:m:n2-falign-loops=n:m:n2:m2โ aligns loops to a power-of-two boundary. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. โจ
If -falign-labels is greater than this value, then its value is used instead.
Parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean 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โ aligns branch targets to a power-of-two boundary, for branch targets where the targets can only be reached by jumping. In this case, no dummy operations need be executed. ๐
If -falign-labels is greater than this value, then its value is used instead.
Parameters of this option are analogous to the -falign-functions option. -fno-align-jumps and -falign-jumps=1 are equivalent and mean 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. ๐-fallow-store-data-racesโ allows the compiler to perform optimizations that may introduce new data races on stores, without proving that the variable can't be concurrently accessed by other threads. Does not affect optimization of local data. It's safe to use this option if it's known that global data won't 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.-funit-at-a-timehas no effect, while-fno-unit-at-a-timeimplies-fno-toplevel-reorderand-fno-section-anchors.
Enabled by default.
-fno-toplevel-reorderโ do not reorder top-level functions, variables, and"asm"statements. Output them in the same order they appear in the input file. 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's 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.
-fwebโ constructs webs as commonly used for register allocation purposes and assigns each web its own individual pseudo register. This lets the register allocation pass operate on pseudos directly, and 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 the current compilation unit represents the whole program being compiled. All public functions and variables โ except"main"and those merged by attribute"externally_visible"โ become static functions, and in effect get optimized more aggressively by interprocedural optimizers. ๐
This option should not be used in combination with -flto. Instead, relying on a linker plugin should provide safer and more precise information.
-flto[=n]โ this option 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. ๐
So like, bestie, if you wanna use the link-time optimizer, you gotta pass -flto and your optimization options both at compile time and during the final link. The move is to compile all the files going into the same link with the same options, and also pass 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 save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. Then that final invocation reads the GIMPLE bytecode back out of foo.o and bar.o, merges the two files into a single internal image, and compiles the result like it always does. And because foo.o and bar.o are merged into one image, all the interprocedural analyses and optimizations in GCC work across both files as if they were literally one file. Which means, for example, the inliner can inline functions in bar.o into functions in foo.o and vice-versa. cross-file glow-up ๐
Another (simpler) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
That generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation, and optimizes them as usual to produce myprog. Iconic. โจ
The important thing to keep in mind โ and I mean keep in mind, bestie โ 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. you're the main character, you get to decide ๐ซถ
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. it just knows ๐ฆ
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. no negotiating on this one, it's giving fixed ๐ค
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 of 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.
To enable debug info generation you need to supply -g at compile time. If any of the input files at link time were built with debug info generation enabled the link will enable debug info generation as well. Any elaborate debug info settings like the dwarf level -gdwarf-5 need to be explicitly repeated at the linker command line and mixing different settings in different translation units is discouraged.
If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time. Similar diagnostics may be raised for other languages. still UB bestie, the warning is not a fix ๐
Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:
gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran
Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation. multilingual queen behavior ๐
If object files containing GIMPLE bytecode are stored in a library archive, say libfoo.a, it is possible to extract and use them in an LTO link if you are using a linker with plugin support. To create static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. At link time, use the flag -fuse-linker-plugin to ensure that the library 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 from libfoo.a and passes them on to the running GCC to make them part of the aggregated GIMPLE image to be optimized.
If you are not using a linker with plugin support and/or do not enable the linker plugin, then the objects inside libfoo.a are extracted and linked as usual, but they do not participate in the LTO optimization process. In order to make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.
Link-time optimizations do not require the presence of the whole program to operate. If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when linker plugin is active (see -fuse-linker-plugin).
The current implementation of LTO makes no attempt to generate bytecode that is portable between different types of hosts. The bytecode files are versioned and there is a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC. no time-traveling bytecode, sorry ๐ฐ๏ธ
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 is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used.
You can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. This is useful when the Makefile calling GCC is already executing in parallel. You must prepend a + to the command recipe in the parent Makefile for this to work. This option likely only works if MAKE is GNU make. Even without the option value, GCC tries to automatically detect a running GNU make's job server.
Use -flto=auto to use GNU make's job server, if available, or otherwise fall back to autodetection of the number of CPU threads present in your system. auto = the algorithm is algorithming โจ๐
-flto-partition=algโ bestie, this one picks the partitioning algorithm that the link-time optimizer uses, okay? The values are:1to1โ partition mirroring the original source files โจbalancedโ partitioning into equally sized chunks (whenever possible) ๐maxโ create a new partition for every symbol where possiblenoneโ disables partitioning and streaming completelyoneโ exactly one partition should be usednoneโ bypasses partitioning and executes the link-time optimization step directly from the WPA phase
The default value is balanced. While 1to1 can be used as an workaround for various code ordering issues, the max partitioning is intended for internal testing only ๐ญ so like, don't ship that one, fr fr.
-flto-compression-level=nโ this sets the level of compression used for 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:- For
zstd, valid values are0(no compression) to19(maximum compression) ๐ธ zlibsupports values from0to9
- For
Values outside this range are clamped to either minimum or maximum of the supported values, so no, you can't just make up a number, bestie ๐. If the option is not given, 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 ld2.21or newer.
This option enables the extraction of object files with GIMPLE bytecode out of library archives. This improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). 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). slay, it just works โจ
-ffat-lto-objectsโ okay so 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 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 plugin auto-load mechanism. Installing the linker plugin into$libdir/bfd-pluginshas the same effect as usage of the command wrappers (gcc-ar,gcc-nmandgcc-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โ so like, 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 train run are optimized agressively for size rather than speed ๐. In some cases it is not practical to train all possible hot paths in the program. (For example, program may contain functions specific for a given hardware and trianing may not cover all hardware configurations 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 train run is not representative but also leads to significantly bigger code. bigger code, bestie, you've been warned ๐-fprofile-use-fprofile-use=pathโ enable profile feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available ๐:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-reorder-functions
Before you can use this option, you must first generate profiling information โญ no shortcuts, girlie.
By default, GCC emits an error message if the feedback profiles do not match the source code. This error can be turned into a warning by using -Wno-error=coverage-mismatch. Note this may result in poorly optimized code ๐ฌ. Additionally, by default, GCC also emits a warning message if the feedback profiles do not exist (see -Wmissing-profile).
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
-fauto-profile-fauto-profile=pathโ enable sampling-based feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available ๐ธ:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-correction
path is the name of a file containing AutoFDO profile information. If omitted, it defaults to fbdata.afdo in the current directory ๐
Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more information, see <https://perf.wiki.kernel.org/>.
E.g.
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then use the create_gcov tool to convert the raw profile data to a format that can be used by GCC. You must also supply the unstripped binary for your program to this tool. See <https://github.com/google/autofdo>.
E.g.
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
The following options control compiler behavior regarding floating-point arithmetic ๐ . These options trade off between speed and correctness. All must be specifically enabled โ no auto-pilot here, bestie.
-ffloat-storeโ Do not store floating-point variables in registers, and inhibit other options that might change whether a floating-point value is taken from a register or memory ๐
This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. ๐ซถ
-fexcess-precision=styleโ this option allows further control over excess precision on machines where floating-point operations occur in a format with more precision or range than the IEEE standard and interchange floating-point types ๐. By default,-fexcess-precision=fastis in effect; this means that operations may be carried out in a wider precision than the types specified in the source if that would result in faster code, and it is unpredictable when rounding to the types specified in the source code takes place ๐ณ. When compiling C, if-fexcess-precision=standardis specified then excess precision follows the rules specified in ISO C99; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas-ffloat-storeonly affects assignments). This option is enabled by default for C if a strict conformance option such as-std=c99is used.-ffast-mathenables-fexcess-precision=fastby default regardless of whether a strict conformance option is used.
-fexcess-precision=standard is not implemented for languages other than C ๐ซ. On the x86, it has no effect if -mfpmath=sse or -mfpmath=sse+387 is specified; in the former case, IEEE semantics apply without excess precision, and in the latter, rounding is unpredictable. unpredictable rounding?? not the vibe ๐
-ffast-mathโ sets the options-fno-math-errno,-funsafe-math-optimizations,-ffinite-math-only,-fno-rounding-math,-fno-signaling-nans,-fcx-limited-rangeand-fexcess-precision=fast๐ฅ
This option causes the preprocessor macro __FAST_MATH__ to be defined โจ
This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions ๐ญ. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
-fno-math-errnoโ bestie, this one says: do not seterrnoafter calling math functions that run in a single instruction (thinksqrt). If your program relies on IEEE exceptions for math error handling, this flag is your girl for speed while keeping IEEE arithmetic compatibility. ๐
Not turned on by any -O option, because it can produce incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require those guarantees. ๐ฆ
The default is -fmath-errno.
On Darwin systems, the math library never sets errno. So there's literally no reason for the compiler to consider the possibility that it might โ and -fno-math-errno is the default there. ๐
-funsafe-math-optimizationsโ allowing 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 pull in 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 produce 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. It enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math. โจ
The default is -fno-unsafe-math-optimizations.
-fassociative-mathโ allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow โ so it cannot be used on code that relies on rounding behavior like(x + 2**52) - 2**52. It may also reorder floating-point comparisons, so it 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โ let the reciprocal of a value be used instead of dividing by the value, if that unlocks optimizations. For examplex / ycan be replaced withx * (1/y), which is useful if(1/y)is subject to common subexpression elimination. Heads up though: 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 produce incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require those guarantees.
The default is -fno-finite-math-only.
-fno-signed-zerosโ allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct+0.0and-0.0values, which then prohibits simplification of expressions such asx+0.0or0.0*x(even with-ffinite-math-only). This option implies that the sign of a zero result isn't significant. ๐
The default is -fsigned-zeros.
-fno-trapping-mathโ compile code assuming that floating-point operations cannot generate user-visible traps. Those traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that-fno-signaling-nansbe in effect. Setting it may allow faster code if you rely 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.
-frounding-mathโ disable transformations and optimizations that assume default floating-point rounding behavior. That's round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. Specify this option for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. It 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 to specify the default state for FENV_ACCESS. ๐ง
-fsignaling-nansโ compile code assuming that IEEE signaling NaNs may generate user-visible traps during floating-point operations. Setting this option disables optimizations that may change the number of exceptions visible with signaling NaNs. This option implies-ftrapping-math. โจ
It causes the preprocessor macro __SUPPORT_SNAN__ to be defined.
The default is -fno-signaling-nans.
This option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior.
-fno-fp-int-builtin-inexactโ do not allow the built-in functionsceil,floor,roundandtrunc, and theirfloatandlong doublevariants, to generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 allow these functions to raise theinexactexception, but ISO/IEC TS 18661-1:2014, the C bindings to IEEE 754-2008, as integrated into ISO C2X, does not allow these functions to do so. ๐ซถ
The default is -ffp-int-builtin-inexact, allowing the exception to be raised, unless C2X or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect.
Even if -fno-fp-int-builtin-inexact is used, if the functions generate a call to a library function then the inexact exception may be raised if the library implementation does not follow TS 18661.
-fsingle-precision-constantโ treat floating-point constants as single precision instead of implicitly converting them to double-precision constants. ๐ธ-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. The default is-fno-cx-limited-range, but it's enabled by-ffast-math. ๐
This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. Nevertheless, the option applies to all languages.
-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. ๐
The default is -fno-cx-fortran-rules.
The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code. ๐ญ๐
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilitiesto improve optimizations based on the number of 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. โจ
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 is 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. ๐
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โ runs a target-dependent glow-up pass over the instruction stream that schedules same-type instructions next to each other, because the target machine can literally execute them more efficiently when they're adjacent in the instruction flow. besties sitting together in the cafeteria energy ๐
Enabled at levels -O2, -O3, -Os.
-ftracerโ performs tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, which lets other optimizations do a better job. it's giving "clean up the room so everyone can find their stuff" โจ
Enabled by -fprofile-use and -fauto-profile.
-funroll-loopsโ unrolls 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 cap, it's a gamble ๐ฒ
Enabled by -fprofile-use and -fauto-profile.
-funroll-all-loopsโ unrolls all the loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. ๐ญ-funroll-all-loopsimplies the same options as-funroll-loops.-fpeel-loopsโ peels loops for which there is 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. Heads up: 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โ splits 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. one loop said "we're not the same" and honestly she was right ๐
Enabled by -fprofile-use and -fauto-profile.
-funswitch-loopsโ moves branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (modified according to result of the condition).
Enabled by -fprofile-use and -fauto-profile.
-fversion-loops-for-stridesโ if a loop iterates over an array with a variable stride, create another version of the loop that assumes the stride is always one. For example:
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
becomes:
if (stride == 1)
for (int i = 0; i < n; ++i)
x[i] = ...;
else
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
This is particularly useful for assumed-shape arrays in Fortran where (for example) it allows better vectorization assuming contiguous accesses. This flag is enabled by default at -O3. It 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.
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.
Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping).
On ELF/DWARF systems these options do not degenerate the quality of the debug information. There could be issues with other object files/debug info formats.
Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower. These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions. โ ๏ธ
-fstdarg-optโ optimize the prologue of variadic argument functions with respect to usage of those arguments.
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.
-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 calculates the addresses of all three variables, but if you compile it with -fsection-anchors, it accesses the variables from a common anchor point instead. The effect is similar to the following pseudocode (which isn't valid C):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
Not all targets support this option. ๐
-fzero-call-used-regs=choiceโ zero call-used registers at function return to increase program security by either mitigating Return-Oriented Programming (ROP) attacks or preventing information leakage through registers. ๐
The possible values of choice are the same as for the zero_call_used_regs attribute. The default is skip.
You can control this behavior for a specific function by using the function attribute zero_call_used_regs.
--param name=valueโ in some places, GCC uses various constants to control the amount of optimization that is done. For example, GCC does not inline functions that contain more than a certain number of instructions. You can control some of these constants on the command line using the--paramoption. ๐๏ธ
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases. fr fr, they can move on you.
In order to get minimal, maximal and default value of a parameter, one can use --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 branch is predicted to be taken with probability lower than this threshold (in percent), then it is considered well predictable.max-rtl-if-conversion-insnsโ RTL if-conversion tries to remove conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the maximum number of instructions in a block which should 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, making the compilation time increase with probably small improvement in executable size.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 number of passes, GCC factors computed gotos early in the compilation process, and unfactors them as late as possible. Only computed jumps at the end of a basic blocks with no more than max-goto-duplication-insns are unfactored.max-delay-slot-insn-searchโ the maximum number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions are searched, the time savings from filling the delay slot are minimal, so stop searching. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in execution time.max-delay-slot-live-searchโ when trying to fill delay slots, the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, increasing the 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 max amount of memory, inkB, that can be allocated to do the global common subexpression elimination optimization. If more memory than specified is required, the optimization is not done. ๐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. iykyk โจ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. fr fr, be careful. ๐max-inline-functions-called-once-loop-depthโ maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once. deep loops stay in their lane. ๐max-inline-functions-called-once-insnsโ maximal estimated size of functions produced while inlining functions called once. size check, bestie. ๐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 declared inline and methods implemented in a class declaration (C++). ๐max-inline-insns-autoโ when you use-finline-functions(included in-O3), a lot of functions that would otherwise not be considered for inlining by the compiler are investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto). it's giving selective. โจmax-inline-insns-smallโ this is bound applied to calls which are considered relevant with-finline-small-functions. small but mighty. ๐งmax-inline-insns-sizeโ this is bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization opportunities exposed by inlining. growth mindset, but make it size. ๐ฑuninlined-function-insnsโ number of instructions accounted by inliner for function overhead such as function prologue and epilogue. overhead is real. ๐ฎโ๐จuninlined-function-timeโ extra time accounted by inliner for function overhead such as time needed to execute function prologue and epilogue. time tax, literally. โณinline-heuristics-hint-percentโ the scale (in percents) applied toinline-insns-single,inline-insns-single-O2,inline-insns-autowhen inline heuristics hints that inlining is very profitable (will enable later optimizations). heuristics said yes. ๐uninlined-thunk-insns,uninlined-thunk-timeโ same as--param uninlined-function-insnsand--param uninlined-function-timebut applied to function thunks. thunk edition. ๐ฆinline-min-speedupโ when 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. speed demon behavior. ๐ฅ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. back end said no more. ๐large-function-growthโ specifies maximal growth of large function caused by inlining in percents. For example, parameter value100limits large function growth to2.0times the original size. math ate. โจlarge-unit-insnsโ the limit specifying 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 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. the way that this one explains itself, obsessed. ๐lazy-modulesโ maximum number of concurrently open C++ module files when lazy loading. lazy but organized. ๐inline-unit-growthโ specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value20limits unit growth to1.2times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size. cold functions don't count, periodt. โ๏ธipa-cp-unit-growthโ specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value10limits unit growth to1.1times the original size. IPA-CP said stay small. ๐ฑipa-cp-large-unit-insnsโ the size of translation unit that IPA-CP pass considers large. large according to IPA-CP. ๐ฆlarge-stack-frameโ the limit specifying large stack frames. While inlining the algorithm is trying to not grow past this limit too much. stack frame said respect my boundaries. ๐ซถlarge-stack-frame-growthโ specifies maximal growth of large stack frames caused by inlining in percents. For example, parameter value1000limits large stack frame growth to11times the original size. eleven times?! iconic. ๐max-inline-insns-recursive,max-inline-insns-recursive-autoโ specifies the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by performing recursive inlining.--param max-inline-insns-recursiveapplies to functions declared inline. For functions not declared inline, recursive inlining happens only when-finline-functions(included in-O3) is enabled;--param max-inline-insns-recursive-autoapplies instead. recursion? in this economy? ๐max-inline-recursive-depth,max-inline-recursive-depth-autoโ specifies the maximum recursion depth used for recursive inlining.--param max-inline-recursive-depthapplies to functions declared inline. For functions not declared inline, recursive inlining happens only when-finline-functions(included in-O3) is enabled;--param max-inline-recursive-depth-autoapplies instead. depth check, bestie. ๐min-inline-recursive-probabilityโ recursive inlining is profitable only for function having deep recursion in average and can hurt for function having little recursion depth by increasing the prologue size or complexity of function body to other optimizers. When profile feedback is available (see-fprofile-generate) the actual recursion depth can be guessed from the probability that function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents). probability said maybe. ๐ฒearly-inlining-insnsโ specify growth that the early inliner can make. In effect it increases the amount of inlining for code having a large abstraction penalty. early bird gets the inline. ๐ฆmax-early-inliner-iterationsโ limit of 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. early inliner has a limit, and she respects it. ๐comdat-sharing-probabilityโ probability (in percent) that C++ inline function with comdat visibility are shared across multiple compilation units. sharing is caring. ๐ซถmodref-max-bases,modref-max-refs,modref-max-accessesโ specifies the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. mod/ref said keep it capped. ๐modref-max-testsโ specifies the maximal number of tests 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. bigger than the others, no cap. ๐ฅmodref-max-depthโ specifies the maximum depth of DFS walk used by modref escape analysis. Setting to0disables the analysis completely. zero means off, periodt. ๐modref-max-escape-pointsโ specifies the maximum number of escape points tracked by modref per SSA-name. escape points? tracked. ๐ฆmodref-max-adjustmentsโ specifies the maximum number the access range is enlarged during modref dataflow analysis. range said expand, but only this much. ๐profile-func-internal-idโ a parameter to control whether to use function internal id in profile database lookup. If the value is0, the compiler uses an id that is based on function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. old profile data said be flexible. ๐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. vectorization said not yet. โกgcse-cost-distance-ratioโ scaling factor in calculation of 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 have cost less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions. hoisting said go big or go home. ๐gcse-unrestricted-costโ the cost (roughly: the cost of one typical machine instruction ๐ ) at which GCSE optimizations stop constraining how far an expression can travel. Right now this only works in the code hoisting pass, okurrr? The lesser the cost, the more feral and aggressive the code hoisting gets. Set it to0and every expression can travel unrestricted distances, no cap. โจmax-hoist-depthโ how deep we dig in the dominator tree looking for expressions to hoist ๐ต๏ธโโ๏ธ. This exists to dodge quadratic behavior in the hoisting algorithm (we do not have time for that). A value of0doesn't limit the search at all, but bestie be warned โ it may slow down compilation of huge functions. ๐max-tail-merge-comparisonsโ the max amount of similar bbs to compare a bb with. This is here to avoid quadratic behavior in tree tail merging. ๐ธmax-tail-merge-iterationsโ the max amount of iterations of the pass over the function. Used to keep compilation time in check during tree tail merging. โณstore-merging-allow-unalignedโ lets the store merging pass introduce unaligned stores, but only if it's legal to do so. Only if it's legal!! ๐max-stores-to-mergeโ the max number of stores it'll attempt to merge into wider stores in the store merging pass. ๐ฅmax-store-chains-to-trackโ the max number of store chains tracked at the same time while trying to merge them into wider stores in the store merging pass. ๐max-stores-to-trackโ the max number of stores tracked at the same time in the attempt to merge them into wider stores in the store merging pass. ๐max-unrolled-insnsโ the max number of instructions a loop may have for it to be unrolled. If a loop does get unrolled, this parameter also decides how many times the loop code gets unrolled. ๐max-average-unrolled-insnsโ same vibe as above but the max number of instructions is biased by the probabilities of their execution. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled. ๐ฆmax-unroll-timesโ the max number of unrollings of a single loop. periodt.max-peeled-insnsโ the max number of instructions a loop may have for it to be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled. ๐max-peel-timesโ the max number of peelings of a single loop. ๐งmax-peel-branchesโ the max number of branches on the hot path through the peeled sequence. ๐ฅmax-completely-peeled-insnsโ the max number of insns of a completely peeled loop. ๐max-completely-peel-timesโ the max number of iterations of a loop to be suitable for complete peeling. โจmax-completely-peel-loop-nest-depthโ the max depth of a loop nest suitable for complete peeling. ๐max-unswitch-insnsโ the max number of insns of an unswitched loop. ๐max-unswitch-levelโ the max number of branches unswitched in a single loop. โญlim-expensiveโ the minimum cost of an expensive expression in loop invariant motion. ๐ธmin-loop-cond-split-probโ when FDO profile information is available,min-loop-cond-split-probspecifies the minimum threshold for the probability of a semi-invariant condition statement to trigger loop split. ๐iv-consider-all-candidates-boundโ a bound on the number of candidates for induction variables. Below it, all candidates get 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 just give up on loops that contain more induction variable uses. she said "i'm out" ๐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โ average number of iterations of a loop. ๐dse-max-object-sizeโ 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โ 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โ bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down. ๐scev-max-expr-complexityโ bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer. ๐ญmax-tree-if-conversion-phi-argsโ maximum number of arguments in a PHI supported by TREE if conversion, unless the loop is marked with the simd pragma. ๐vect-max-version-for-alignment-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer. โvect-max-version-for-alias-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer. โvect-max-peeling-for-alignmentโ the maximum number of loop peels to enhance access alignment for the vectorizer. A value of-1means no limit. โพ๏ธmax-iterations-to-trackโ 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 denominator n of 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 that 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 upper 990 permilles โ or 99.0% โ of the profiled execution of the entire program.0means it is never considered hot. Used in LTO mode. ๐hot-bb-frequency-fractionโ the denominator n of 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 denominator n of 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โ or 5% โ 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 a known bound and another loop with an 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โ controls 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 the 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 limits superblock formation once the given percentage of executed instructions is covered. This limits unnecessary code size expansion. ๐
The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. The real profiles (as opposed to statically estimated ones) are much less balanced, which allows the threshold to be a larger value. โจ
tracer-max-code-growthโ stop tail duplication once code growth has reached the given percentage. This is a rather artificial limit, since most of the duplicates get 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 the best edge is less than this threshold (in percent). ๐tracer-min-branch-probability,tracer-min-branch-probability-feedbackโ stop forward growth if the best edge has probability lower than this threshold. โ
Similarly to tracer-dynamic-coverage, two parameters are provided. tracer-min-branch-probability-feedback is used for compilation with profile feedback, and tracer-min-branch-probability for compilation 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โ sets how big the OS-provided stack guard is, as 2 raised to num bytes. Bigger values might cut down how many explicit probes you need, but bestie, if you go bigger than the guard your OS actually gives you, your code is left vulnerable to stack clash style attacks. ๐ Don't do that.stack-clash-protection-probe-intervalโ stack clash protection means probing stack space as it gets allocated. This param controls the max distance between probes into the stack, again as 2 raised to num bytes. Higher values might mean fewer explicit probes, but same warning as above: a value larger than the OS-provided guard leaves code vulnerable to stack clash style attacks. ๐จmax-cse-path-lengthโ the max number of basic blocks on a path that CSE considers.max-cse-insnsโ the max number of instructions CSE processes before it flushes.ggc-min-expandโ GCC runs a garbage collector to manage its own memory allocation, and this parameter sets the minimum percentage by which the GC's heap is allowed to expand between collections. Tuning it may improve compilation speed, and it has no effect on code generation.
The default is 30% + 70% * (RAM/1GB), with an upper bound of 100% when RAM >= 1GB. If getrlimit is available, "RAM" means the smallest of actual RAM and RLIMIT_DATA or RLIMIT_AS. If GCC can't calculate RAM on a particular platform, the lower bound of 30% gets used. Setting this parameter and ggc-min-heapsize to zero makes a full collection happen at every opportunity โ which is extremely slow, but can be handy for debugging. ๐
ggc-min-heapsizeโ the minimum size of the garbage collector's heap before it even bothers collecting garbage. The first collection happens 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 of RAM/8, RLIMIT_RSS, or a limit that tries to make sure RLIMIT_DATA or RLIMIT_AS aren't exceeded โ but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). If GCC can't calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter and ggc-min-expand to zero causes a full collection at every opportunity. ๐
max-reload-search-insnsโ the max number of instructions reload should look backward for an equivalent register. Bigger values = more aggressive optimization, so compilation time goes up with probably slightly better performance. โจmax-cselib-memory-locationsโ the max number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making compilation time increase with probably slightly better performance.max-sched-ready-insnsโ the max number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass. Bigger values mean more thorough searches, making compilation time increase with probably little benefit. ๐max-sched-region-blocksโ the max number of blocks in a region considered for interblock scheduling.max-pipeline-region-blocksโ the max number of blocks in a region considered for pipelining in the selective scheduler.max-sched-region-insnsโ the max number of insns in a region considered for interblock scheduling.max-pipeline-region-insnsโ the max number of insns in a region 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 max number of iterations through CFG to extend regions. A value of0disables region extensions.max-sched-insn-conflict-delayโ the max 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 a store and a load targeting the same memory locations.selsched-max-lookaheadโ the max size of the lookahead window of selective scheduling. It's a depth of search for available instructions.selsched-max-sched-timesโ the max number of times 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 max number of best instructions in the ready list that get considered for renaming in the selective scheduler.sms-min-scโ the minimum value of stage count that swing modulo scheduler generates.max-last-value-rtlโ the max size, measured as number of RTLs, that can be recorded in an expression in combiner for a pseudo register as the last known value of that register.max-combine-insnsโ the max number of instructions the RTL combiner tries to combine.integer-share-limitโ small integer constants can share a data structure, which reduces the compiler's memory usage and increases its speed. This sets the max value of a shared integer constant. ๐ssp-buffer-sizeโ the minimum size of buffers (i.e. arrays) that receive stack smashing protection when-fstack-protectoris used.
This default before Ubuntu 10.10 was 8. Currently it's 4, to increase the number of functions protected by the stack protector.
min-size-for-stack-sharingโ the minimum size of variables taking part in stack slot sharing when not optimizing.max-jump-thread-duplication-stmtsโ max number of statements allowed in a block that needs to be duplicated when threading jumps.max-fields-for-field-sensitiveโ max number of fields in a structure treated in a field sensitive manner 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 this number may also lead to fewer streams being prefetched (seesimultaneous-prefetches).simultaneous-prefetchesโ max number of prefetches that can run at the same time.l1-cache-line-sizeโ the size of a cache line in L1 data cache, in bytes.l1-cache-sizeโ the size of L1 data cache, in kilobytes.l2-cache-sizeโ the size of L2 data cache, in kilobytes.prefetch-dynamic-stridesโ whether the loop array prefetch pass should issue software prefetch hints for strides that are non-constant. In some cases this may be beneficial, though the fact the stride is non-constant may make it hard to predict when there's a clear benefit to issuing these hints. ๐ฆ
Set to 1 if the prefetch hints should be issued for non-constant strides. Set to 0 if prefetch hints should be issued only 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 less than this threshold, prefetch hints won't be issued.
This setting is useful for processors that have hardware prefetchers, in which case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, it should be used here to improve the use of software prefetchers.
A value of -1 means we don't have a threshold, and therefore prefetch hints can be issued for any constant stride.
This setting is only useful for strides that are known and constant. โจ
destructive-interference-size,constructive-interference-sizeโ the values for the C++17 variablesstd::hardware_destructive_interference_sizeandstd::hardware_constructive_interference_size. The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.
The destructive interference size is intended to be used for layout, and thus has ABI impact. The default value is not expected to be stable, and on some targets varies with -mtune, so use of this variable in a context where ABI stability is important โ like the public interface of a library โ is strongly discouraged; if it is used in that context, users can stabilize the value using this option.
The constructive interference size is less sensitive, as it's typically only used in a static_assert to make sure that a type fits within a cache line.
See also -Winterference-size.
loop-interchange-max-num-stmtsโ the max number of stmts in a loop to be interchanged. ๐loop-interchange-stride-ratioโ the minimum ratio between the stride of two loops for interchange to be profitable. ๐min-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches to enable prefetching in a loop. โจprefetch-min-insn-to-mem-ratioโ same energy, different counter: the minimum ratio between the number of instructions and the number of memory references to enable prefetching in a loop. ๐ฆuse-canonical-typesโ whether the compiler should use the "canonical" type system. Should always be1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. However, if bugs in the canonical type system are causing compilation failures, set this value 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, consuming all of the memory available on the host machine. This parameter sets a limit on the length of the sets that are computed, which prevents the runaway behavior. Setting a value of0for this parameter allows an unlimited set length. ๐rpo-vn-max-loop-depthโ maximum loop depth that is value-numbered optimistically. When the limit hits the innermostrpo-vn-max-loop-depthloops and the outermost loop in the loop nest are value-numbered optimistically and the remaining ones not. ๐sccvn-max-alias-queries-per-accessโ maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit is hit the search is aborted and the load or store is not considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry. ๐ira-max-loops-numโ IRA uses regional register allocation by default. If a function contains more loops than the number given by this parameter, only at most the given number of the most frequently-executed loops form regions for regional register allocation. ๐ira-max-conflict-table-sizeโ although IRA uses a sophisticated algorithm to compress the conflict table, the table can still require excessive amounts of memory for huge functions. If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that does not require building a pseudo-register conflict table. ๐ตira-loop-reserved-regsโ IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (see-O3). The number of available registers reserved for some other purposes is given by this parameter. Default of the parameter is the best found from numerous experiments. ๐งชira-consider-dup-in-all-altsโ make IRA consider matching constraint (duplicated operand number) heavily in all available alternatives for preferred register class. If it is set as zero, it means IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, it means IRA will check all available alternatives for preferred register class even if it has found some choice with an appropriate register class and respect the found qualified matching constraint. ๐lra-inheritance-ebb-probability-cutoffโ LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance. EBB is used as a region to do this optimization. The parameter defines a minimal fall-through edge probability in percentage used to add BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64. ๐งฌloop-invariant-max-bbs-in-loopโ loop invariant motion can be very expensive, both in compilation time and in amount of needed compile-time memory, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them. ๐ซloop-max-datarefs-for-datadepsโ building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that are considered for data dependence analysis. These large loops are not handled by the optimizations using loop data dependencies. ๐ธ๏ธmax-vartrack-sizeโ sets a maximum number of hash table slots to use during variable tracking dataflow analysis of any function. If this limit is exceeded with variable tracking at assignments enabled, analysis for that function is retried without it, after removing all debug insns from the function. If the limit is exceeded even without debug insns, var tracking analysis is completely disabled for the function. Setting the parameter to zero makes it unlimited. ๐งmax-vartrack-expr-depthโ sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. This trades compilation time for more complete debug information. If this is set too low, value expressions that are available and could be represented in debug information may end up not being used; setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow. ๐max-debug-marker-countโ sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, such stmts will be dropped from the inlined copy of a function, and from its RTL expansion. ๐ฏmin-nondebug-insn-uidโ use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by-fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted. ๐ipa-sra-ptr-growth-factorโ IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter. ๐งฑipa-sra-max-replacementsโ maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it is also the maximum number of replacements of a formal parameter. ๐sra-max-scalarization-size-Ospeed,sra-max-scalarization-size-Osizeโ the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively. ๐งฎsra-max-propagationsโ the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation. ๐tm-max-aggregate-sizeโ when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. This option only applies when using-fgnu-tm. ๐งตgraphite-max-nb-scop-paramsโ to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. A variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP. ๐loop-block-tile-sizeโ loop blocking or strip mining transforms, enabled with-floop-blockor-floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using theloop-block-tile-sizeparameter. ๐งฉipa-jump-function-lookupsโ specifies number of statements visited during jump function offset discovery. ๐ต๏ธipa-cp-value-list-sizeโ IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization.ipa-cp-value-list-sizeis the maximum number of values and types it stores per one formal parameter of a function. ๐ipa-cp-eval-thresholdโ IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceedipa-cp-eval-threshold. โ๏ธipa-cp-max-recursive-depthโ maximum depth of recursive cloning for self-recursive function. ๐ipa-cp-min-recursive-probabilityโ recursive cloning only when the probability of call being executed exceeds the parameter. ๐ฒipa-cp-profile-count-baseโ when using-fprofile-useoption, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation. ๐ipa-cp-recursive-freq-factorโ the number of times interprocedural copy propagation expects recursive functions to call themselves. ๐ipa-cp-recursion-penaltyโ percentage penalty the recursive functions will receive when they are evaluated for cloning. ๐ipa-cp-single-call-penaltyโ the percentage penalty that functions which contain a single call to another function get hit with when they're being evaluated for cloning. โจipa-max-agg-itemsโ bestie, IPA-CP can also propagate a bunch of scalar values that are passed inside an aggregate ๐ซถ. This param controls the maximum number of such values per one parameter.ipa-cp-loop-hint-bonusโ when IPA-CP figures out that a cloning candidate would make the number of iterations of a loop known, it throws a bonus ofipa-cp-loop-hint-bonusonto that candidate's profitability score. slay ๐ipa-max-loop-predicatesโ the max number of different predicates IPA will use to describe when loops in a function have known properties.ipa-max-aa-stepsโ okay so while IPA-CP is analyzing function bodies it uses alias analysis to track values that function parameters point to ๐. But it's not about to waste its whole life on giant functions, so after it examinesipa-max-aa-stepsstatements that modify memory, it gives up and considers all memory clobbered. periodt.ipa-max-switch-predicate-boundsโ the maximal number of boundary endpoints of case ranges of a switch statement. For any switch that exceeds this limit, IPA-CP will not construct the cloning cost predicate (the thing it uses to estimate cloning benefit) for the default case of that switch statement.ipa-max-param-expr-opsโ IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit for cloning upon a certain constant value ๐ง . BUT if the number of operations in a parameter expression exceedsipa-max-param-expr-ops, that expression is treated as a complicated one and is not handled by IPA analysis. no cap.lto-partitionsโ specify the desired number of partitions produced during WHOPR compilation. Heads up: the number of partitions should exceed the number of CPUs used for compilation ๐lto-min-partitionโ the size of the minimal partition for WHOPR (measured in estimated instructions). This is what stops tiny little programs from getting split into way too many partitions and costing you a bag ๐ธ.lto-max-partitionโ the size of the max partition for WHOPR (in estimated instructions), there to provide an upper bound for the individual size of a partition. Meant to be used only with balanced partitioning ๐ธ.lto-max-streaming-parallelismโ the maximal number of parallel processes used for LTO streaming. go off, parallelism ๐ฅcxx-max-namespaces-for-diagnostic-helpโ the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. it's giving helpful bestie energy fr fr ๐sink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block that still allows statement sinking of a statement. Bigger numbers = more aggressive statement sinking ๐ค. A small positive adjustment gets applied for statements with memory operands, because those are even more profitable to sink.max-stores-to-sinkโ the maximum number of conditional store pairs that can be sunk. Set this to0if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled ๐ซ.case-values-thresholdโ the smallest number of different values for which it's best to use a jump-table instead of a tree of conditional branches. If the value is0, just use the default for the machine ๐ฅ๏ธ.jump-table-max-growth-ratio-for-sizeโ the maximum code size growth ratio when expanding into a jump table (in percent). This parameter is used when optimizing for size.jump-table-max-growth-ratio-for-speedโ the maximum code size growth ratio when expanding into a jump table (in percent). This parameter is used when optimizing for speed ๐๏ธ.tree-reassoc-widthโ sets the maximum number of instructions executed in parallel in a reassociated tree. This parameter overrides the target dependent heuristics used by default, if it has a non-zero value ๐.sched-pressure-algorithmโ pick between the two available implementations of-fsched-pressure:- Algorithm
1is the original implementation and is the more likely to prevent instructions from being reordered. - Algorithm
2was designed as a compromise between the relatively conservative approach of algorithm 1 and the rather aggressive approach of the default scheduler. It relies more heavily on having a regular register file and accurate register pressure classes. Seehaifa-sched.ccin the GCC sources for more details. The default choice depends on the target.
- Algorithm
max-slsr-cand-scanโ sets the maximum number of existing candidates that get considered when seeking a basis for a new straight-line strength reduction candidate ๐ช.asan-globalsโ enables buffer overflow detection for global objects ๐. This kind of protection is enabled by default if you're using-fsanitize=address. To disable global objects protection use--param asan-globals=0.asan-stackโ enables buffer overflow detection for stack objects ๐. This kind of protection is enabled by default when using-fsanitize=address. To disable stack protection use--param asan-stack=0.asan-instrument-readsโ enables buffer overflow detection for memory reads ๐. Enabled by default when using-fsanitize=address. To disable memory reads protection use--param asan-instrument-reads=0.asan-instrument-writesโ enables buffer overflow detection for memory writes โ๏ธ. Enabled by default when using-fsanitize=address. To disable memory writes protection use--param asan-instrument-writes=0.asan-memintrinโ enables detection for built-in functions. Enabled 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 ๐. This kind of protection is enabled by default when using the-fsanitize=addressoption. To disable it use--param asan-use-after-return=0.
Note: by default the check is disabled at run time. To enable it, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS.
asan-instrumentation-with-call-thresholdโ if the number of memory accesses in the function being instrumented is greater 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.hwasan-instrument-stackโ enables hwasan instrumentation of statically sized stack-allocated variables. Enabled by default when using-fsanitize=hwaddressand disabled by default when using-fsanitize=kernel-hwaddress. To disable stack instrumentation use--param hwasan-instrument-stack=0, and to enable it use--param hwasan-instrument-stack=1โจ.hwasan-random-frame-tagโ when using stack instrumentation, decide tags for stack variables using a deterministic sequence that begins at a random tag for each frame ๐ฒ. With this parameter unset, tags are chosen using the same sequence but beginning from1. 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. Enabled by default when using-fsanitize=hwaddressand disabled 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, 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โ maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.max-fsm-thread-lengthโ maximum number of basic blocks on a 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 where the parallelized version is preferred over the single-threaded one. And bestie, 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โ max recursion depth when we're querying the properties of SSA names in things like fold routines. One level of recursion = following one use-def chain. That's it, that's the unit. ๐max-speculative-devirt-maydefsโ the maximum number of may-defs we analyze when hunting for a must-def that pins down the dynamic type of an object invoking a virtual call we might be able to devirtualize speculatively.max-vrp-switch-assertionsโ the max number of assertions to add along the default edge of a switch statement during VRP.evrp-sparse-thresholdโ max number of basic blocks before EVRP starts using a sparse cache.evrp-modeโ says which mode Early VRP should operate in.vrp1-modeโ says which mode VRP pass 1 should operate in.vrp2-modeโ says which mode VRP pass 2 should operate in.ranger-debugโ picks the type of debug output to be issued for ranges.evrp-switch-limitโ the max number of switch cases before EVRP just ignores a switch entirely. ๐unroll-jam-min-percentโ the minimum percentage of memory references that have to be optimized away before the unroll-and-jam transformation counts as 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โ the maximum permissible cost for the sequence that the RTL if-conversion pass would generate for a branch that's considered unpredictable.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris used, this is the max number of times that any individual variable gets expanded during loop unrolling.partial-inlining-entry-probabilityโ maximum probability of the entry BB of a split region (in percent, relative to the entry BB of the function) for partial inlining to actually happen.max-tracked-strlensโ max number of strings the strlen optimization pass will track string lengths for.gcse-after-reload-partial-fractionโ the threshold ratio for doing partial redundancy elimination after reload.gcse-after-reload-critical-fractionโ the threshold ratio of critical edges execution count that permits doing redundancy elimination after reload.max-loop-header-insnsโ the max number of insns in a loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enable loop epilogue vectorization using a smaller vector size. โจvect-partial-vector-usageโ controls when the loop vectorizer even considers using partial vector loads and stores instead of 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. Also, this parameter only has an effect on targets that support partial vector loads and stores.vect-inner-loop-cost-factorโ the maximum factor 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โ max number of bits for which we avoid creating FMAs.sms-loop-average-count-thresholdโ a threshold on the average loop count considered by the swing modulo scheduler.sms-dfa-historyโ the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.graphite-allow-codegen-errorsโ whether codegen errors should be ICEs when-fchecking. ๐sms-max-ii-factorโ a factor for tuning the upper bound that the swing modulo scheduler uses for scheduling a loop.lra-max-considered-reload-pseudosโ the max number of reload pseudos considered while spilling a non-reload pseudo.max-pow-sqrt-depthโ maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant.max-dse-active-local-storesโ maximum number of active local stores in RTL dead store elimination.asan-instrument-allocasโ enable asan allocas/VLAs protection.max-iterations-computation-costโ a bound on the cost of an expression used to compute the number of iterations.max-isl-operationsโ maximum number of isl operations;0means unlimited.graphite-max-arrays-per-scopโ maximum number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of 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 when comparing to the number of (scaled) blocks.uninit-control-dep-attemptsโ maximum number of nested calls to search for control dependencies during uninitialized variable analysis.fsm-scale-path-blocksโ scale factor to apply to the number of blocks in a threading path when comparing to the number of (scaled) statements.sched-autopref-queue-depthโ hardware autoprefetcher scheduler model control flag. It's the number of lookahead cycles the model looks into; at' 'only enable instruction sorting heuristic.loop-versioning-max-inner-insnsโ the max number of instructions an inner loop can have before the loop versioning pass decides it's too big to copy.loop-versioning-max-outer-insnsโ the max number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy โ discounting any instructions in inner loops that directly benefit from versioning.ssa-name-def-chain-limitโ the maximum number ofSSA_NAMEassignments to follow when determining a property of a variable, like its value. This limits the number of iterations or recursive calls GCC performs when optimizing certain statements, or when determining their validity before 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 ofVALUEs handled during a singlefind_base_termcall.analyzer-max-enodes-per-program-pointโ the maximum number of exploded nodes per program point within the analyzer, before it terminates analysis of that point.analyzer-max-constraintsโ the maximum number of constraints per state.analyzer-min-snodes-for-call-summaryโ the minimum number of supernodes 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 show up in a dot dump before switching to a less verbose format.analyzer-max-recursion-depthโ the max number of times a callsite can appear in a call stack within the analyzer, before it terminates 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. ๐ฅranger-logical-depthโ maximum depth of logical expression evaluation the ranger will look through when evaluating outgoing edge ranges.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 for handling OpenACCkernelsconstructs. 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โ specify the mode of OpenACC privatization diagnostics for-fopt-info-omp-noteand applicable-fdump-tree-*-details. 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. ๐ฆ
aarch64-float-recp-precisionโ the number of Newton iterations used to calculate the reciprocal for float type. The precision of division is proportional to this param when division approximation is enabled. Default is1. ๐aarch64-double-recp-precisionโ same energy, but for double type. Number of Newton iterations for the reciprocal. Precision of division is proportional to this param when division approximation is enabled. Default is2. โจaarch64-autovec-preferenceโ force an ISA selection strategy for auto-vectorization, bestie. Accepts values from0to4, inclusive:0โ use the default heuristics.1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE. Prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE. Prefer SVE when the costs are deemed equal.
The default value is 0.
aarch64-loop-vect-issue-rate-nitersโ the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. If this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations. ๐ฆaarch64-vect-unroll-limitโ the vectorizer will use available tuning information to determine whether it would be beneficial to unroll the main vectorized loop, and by how much. This parameter sets the upper bound of how much the vectorizer will unroll the main loop. Default value is four.
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.
๐ Program Instrumentation Options ๐
GCC supports a number of command-line options that control adding run-time instrumentation to the code it normally generates. For example, one purpose of instrumentation is to collect profiling statistics for 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. 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. Periodt.
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). ๐
Note that if a command line directly links source files, the corresponding .gcda files will be prefixed with the unsuffixed name of the output file. E.g. gcc a.c b.c -o binary would generate binary-a.gcda and binary-b.gcda files.
--coverageโ this option is used to compile and link code instrumented for coverage analysis. The option is a synonym for-fprofile-arcs -ftest-coverage(when compiling) and-lgcov(when linking). See the documentation for those options for more details.- Compile the source files with
-fprofile-arcsplus optimization and code generation options. For test coverage analysis, use the additional-ftest-coverageoption. You do not need to profile every source file in a program. - Compile the source files additionally with
-fprofile-abs-pathto create absolute path names in the.gcnofiles. This allowsgcovto find the correct sources in projects where compilations occur with different working directories. - Link your object files with
-lgcovor-fprofile-arcs(the latter implies the former). - Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect,
forkcalls are detected and correctly handled without double counting.
- Compile the source files with
Moreover, an object file can be recompiled multiple times and the corresponding .gcda file merges as long as the source file and the compiler options are unchanged. ๐ซถ
- For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus
-fbranch-probabilities. - For test coverage analysis, use
gcovto produce human readable information from the.gcnoand.gcdafiles. Refer to thegcovdocumentation for further information.
With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. โจ
-ftest-coverageโ produce a notes file that thegcovcode-coverage utility can use to show program coverage. Each source file's note file is calledauxname.gcno. Refer to the-fprofile-arcsoption above for a description of auxname and instructions on how to generate test coverage data. 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 allowsgcovto find the correct sources in projects where compilations occur with different working directories. ๐-fprofile-dir=path โ set the directory to search for the profile data files in to path. This option affects only the profile data generated by-fprofile-generate,-ftest-coverage,-fprofile-arcsand used by-fprofile-useand-fbranch-probabilitiesand its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, thus the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of thesourcename.gcdafile and use it as the file name of a.gcdafile. See details about the file naming in-fprofile-arcs. See similar option-fprofile-note.
When an executable is run in a massive parallel environment, it is recommended to save profile to different folders. That can be done with variables in path that are exported during run-time:
%pโ process ID.%q{VAR}โ value of environment variableVAR.
-fprofile-generate-fprofile-generate=path โ enable options usually used for instrumenting application to produce profile useful for later recompilation with profile feedback based optimization. You must use-fprofile-generateboth when compiling and when linking your program.
The following options are enabled: -fprofile-arcs, -fprofile-values, -finline-functions, and -fipa-bit-cp.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
To optimize the program based on the collected profile information, use -fprofile-use. ๐ฅ
-fprofile-info-section-fprofile-info-section=name โ register the profile information in the specified section instead of using a constructor/destructor. The section name is name if it is specified, otherwise the section name defaults to.gcov_info. A pointer to the profile information generated by-fprofile-arcsis placed in the specified section for each translation unit. This option disables the profile information registration through a constructor and it disables the profile information processing through a destructor. This option is not intended to be used in hosted environments such as GNU/Linux. It targets free-standing environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. ๐ธ
The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:
.gcov_info :
{
PROVIDE (__gcov_info_start = .);
KEEP (*(.gcov_info))
PROVIDE (__gcov_info_end = .);
}
The program could dump the profiling information registered in this linker set for example like this:
#include <gcov.h>
#include <stdio.h>
#include <stdlib.h>
extern const struct gcov_info *__gcov_info_start[];
extern const struct gcov_info *__gcov_info_end[];
static void
filename (const char *f, void *arg)
{
puts (f);
}
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 *
allocate (unsigned length, void *arg)
{
return malloc (length);
}
static void
dump_gcov_info (void)
{
const struct gcov_info **info = __gcov_info_start;
const struct gcov_info **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()
{
dump_gcov_info();
return 0;
}
-fprofile-note=pathโ bestie, if you hand over apathhere, GCC drops the.gcnofile straight into thatpathlocation ๐พ. BUT heads up: if you combine this option with multiple source files, that.gcnofile gets overwritten. Like, poof. Gone. One file, one destiny. ๐ญ-fprofile-prefix-path=pathโ this one's a lil collab option, it works in combination withprofile-generate=profile_dirandprofile-use=profile_dirto tell GCC where the base directory of the built source tree is ๐๏ธ. By default,profile_diris gonna contain files with mangled absolute paths of all the object files in your built project โ and that's not it, that's lowkey a problem when the directory you used to build the instrumented binary is different from the directory you used to build the binary optimized with profile feedback, because then the profile data just won't be found during the optimized build ๐. In those setups,-fprofile-prefix-path=pathwithpathpointing to the base directory of the build strips out the irrelevant part of the path and keeps all the file names relative to the main build directory. Clean. Tidy. Slay. โจ-fprofile-prefix-map=old=newโ when you're compiling files that live in directory old, this records profiling information (with--coverage) describing them as if they actually lived in directory new instead ๐. Also peep-ffile-prefix-mapfor the same energy.-fprofile-update=methodโ this alters the update method for an app instrumented for profile feedback based optimization. Themethodargument should be one ofsingle,atomicorprefer-atomic๐. The first one (single) is the move for single-threaded applications, while the second (atomic) prevents profile corruption by emitting thread-safe code. Fr fr.
โ ๏ธ Warning: when an application does not properly join all threads (or creates a detached thread), a profile file can still get corrupted. Not a vibe.
Using prefer-atomic gets transformed either into atomic (when the target supports it) or into single otherwise ๐. And the GCC driver automatically selects prefer-atomic whenever -pthread is present in the command line. She's thoughtful like that ๐
.
-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 the C files starting with 'module'. Obsessed with the precision tbh.
-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. Not me skipping the whole /usr/ directory like it's a group chat I'm not in ๐.
-fprofile-reproducible=[multithreaded|parallel-runs|serial]โ controls the level of reproducibility of the profile gathered by-fprofile-generate๐ฏ. This makes it possible to rebuild a program with the same outcome, which is useful, for example, for distribution packages. Very much the "same fit every time" energy.
With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded, and profile data streaming is always done in the same order ๐งต. Note that profile streaming happens at the end of the program run but also before the fork function is invoked.
Note that it's quite common that execution counts of some part of programs depend, for example, on the length of temporary file names or memory space randomization (which may affect hash-table collision rate) ๐ตโ๐ซ. Such non-reproducible part of programs may be annotated by the no_instrument_function function attribute. gcov-dump with -l can be used to dump the gathered data and verify that they are indeed reproducible.
With -fprofile-reproducible=parallel-runs, the collected profile stays reproducible regardless of the order of streaming of the data into gcda files ๐. This setting makes it possible to run multiple instances of the instrumented program in parallel (such as with make -j). But lowkey a trade-off: this reduces the quality of the gathered data, in particular of indirect call profiling.
-fsanitize=addressโ enables AddressSanitizer, a fast memory error detector ๐ก๏ธ. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables-fsanitize-address-use-after-scope. Seehttps://github.com/google/sanitizers/wiki/AddressSanitizerfor more details. The run-time behavior can be influenced using theASAN_OPTIONSenvironment variable ๐ฑ. When set to"help=1", the available options are shown at startup of the instrumented program. Seehttps://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flagsfor a list of supported options. The option cannot be combined with-fsanitize=threador-fsanitize=hwaddress๐ซ. Note that the only target-fsanitize=hwaddressis currently supported on is AArch64.-fsanitize=kernel-addressโ enables AddressSanitizer for the Linux kernel ๐ง. Seehttps://github.com/google/kasanfor more details.-fsanitize=hwaddressโ enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer to allow the detection of memory errors with a low memory overhead โก. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables-fsanitize-address-use-after-scope. Seehttps://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.htmlfor more details. The run-time behavior can be influenced using theHWASAN_OPTIONSenvironment variable ๐ฑ. When set to"help=1", the available options are shown at startup of the instrumented program. The option cannot be combined with-fsanitize=threador-fsanitize=address, and is currently only available on AArch64 ๐ซ.-fsanitize=kernel-hwaddressโ enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel ๐งโก. Similar to-fsanitize=kernel-addressbut using an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences necessary for compiling the Linux kernel. These differences are to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte.
๐ Note: this option has different defaults to-fsanitize=hwaddress. Instrumenting the stack andallocacalls are not on by default but are still possible by specifying the command-line options--param hwasan-instrument-stack=1and--param hwasan-instrument-allocas=1respectively. Using a random frame tag is not implemented for kernel instrumentation.
-fsanitize=pointer-compareโ instruments comparison operations (<,<=,>,>=) with pointer operands ๐. The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread๐ซ.
๐ Note: by default the check is disabled at run time. To enable it, add"detect_invalid_pointer_pairs=2"to the environment variableASAN_OPTIONS. Using"detect_invalid_pointer_pairs=1"detects an invalid operation only when both pointers are non-null.
-fsanitize=pointer-subtractโ instruments subtraction with pointer operands ๐. The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread๐ซ.
๐ Note: by default the check is disabled at run time. To enable it, add"detect_invalid_pointer_pairs=2"to the environment variableASAN_OPTIONS. Using"detect_invalid_pointer_pairs=1"detects an invalid operation only when both pointers are non-null.
-fsanitize=shadow-call-stackโ enables ShadowCallStack, a security enhancement mechanism used to protect programs against return address overwrites (e.g. stack buffer overflows) ๐ก๏ธโจ. It works by saving a function's return address to a separately allocated shadow call stack in the function prologue and restoring the return address from the shadow call stack in the function epilogue. Instrumentation only occurs in functions that need to save the return address to the stack.
Currently it only supports the aarch64 platform ๐ป. It is specifically designed for Linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc. Users who want to use this feature in user space need to provide their own support for the runtime. It should be noted that this may cause the ABI rules to be broken ๐ฌ.
On aarch64, the instrumentation makes use of the platform register "x18" ๐. This generally means that any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18, otherwise functions compiled without -ffixed-x18 might clobber "x18" and so corrupt the shadow stack pointer. Do not skip that flag, bestie.
Also, because there is no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling ๐ซ. Use -fno-exceptions to turn off exceptions.
See https://clang.llvm.org/docs/ShadowCallStack.html for more details.
-fsanitize=threadโ bestie, meet ThreadSanitizer, the fast data race detector ๐โ๏ธ๐จ. It instruments memory access instructions so it can sniff out data race bugs like the little chaos gremlins they are. More deets at <https://github.com/google/sanitizers/wiki#threadsanitizer>. You can steer how it behaves at runtime with theTSAN_OPTIONSenvironment variable, and there's a whole list of supported options over at <https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags>. โ ๏ธ This one cannot be combined with-fsanitize=addressor-fsanitize=leak.
Heads up: sanitized atomic builtins cannot throw exceptions when they're operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions). Noted ๐
-fsanitize=leakโ turning on LeakSanitizer, aka the memory leak detector ๐ต๏ธโ๏ธ. Important vibe check: this option only matters for linking of executables, and the executable gets linked against a library that overridesmallocand other allocator functions. More info at <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>. Runtime behavior is influenced by theLSAN_OPTIONSenvironment variable. ๐ซ This one cannot be combined with-fsanitize=thread.-fsanitize=undefinedโ enabling UndefinedBehaviorSanitizer, the fast undefined behavior detector โจ. Various computations get instrumented to detect undefined behavior at runtime. More details at <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>. Runtime behavior is influenced by theUBSAN_OPTIONSenvironment variable. Current suboptions are:-fsanitize=shiftโ checks that the result of a shift operation is not undefined. Note that what exactly counts as undefined differs slightly between C and C++, and also between ISO C90 and C99, etc. This one has two suboptions:-fsanitize=shift-baseand-fsanitize=shift-exponent.-fsanitize=shift-exponentโ checks that the second argument of a shift operation is not negative and is smaller than the precision of the promoted first argument.-fsanitize=shift-baseโ if the second argument of a shift operation is within range, check that the result of the shift operation is not undefined. Same little caveat: what's exactly undefined differs slightly between C and C++, and between ISO C90 and C99, etc.-fsanitize=integer-divide-by-zeroโ detects integer division by zero. ๐-fsanitize=unreachableโ with this option, the compiler turns the__builtin_unreachablecall into a diagnostics message call instead. When you actually reach that__builtin_unreachablecall, the behavior is undefined. ๐-fsanitize=vla-boundโ instructs the compiler to check that the size of a variable length array is positive.-fsanitize=nullโ enables pointer checking ๐ซถ. Specifically, an application built with this turned on will throw an error message when it tries to dereference aNULLpointer, or if a reference (possibly an rvalue reference) is bound to aNULLpointer, or if a method is invoked on an object pointed to by aNULLpointer.-fsanitize=returnโ enables return statement checking. Programs built with this turned on will issue an error message when the end of a non-void function is reached without actually returning a value. This one works in C++ only.-fsanitize=signed-integer-overflowโ enables signed integer overflow checking. It checks that the result of+,*, and both unary and binary-does not overflow in signed arithmetics. It also detectsINT_MIN / -1signed division. Note: integer promotion rules must be taken into account. That is, the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ enables instrumentation of array bounds. Various out of bounds accesses are detected. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented.-fsanitize=bounds-strictโ enables strict instrumentation of array bounds ๐ฅ. Most out of bounds accesses are detected, including flexible array members and flexible array member-like arrays. Initializers of variables with static storage are not instrumented.-fsanitize=alignmentโ enables checking of alignment of pointers when they are dereferenced, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object.-fsanitize=object-sizeโ enables instrumentation of memory references using the__builtin_object_sizefunction. Various out of bounds pointer accesses are detected.-fsanitize=float-divide-by-zeroโ detects floating-point division by zero. Unlike other similar options,-fsanitize=float-divide-by-zerois not enabled by-fsanitize=undefined, because floating-point division by zero can be a legitimate way of obtaining infinities and NaNs. ๐-fsanitize=float-cast-overflowโ enables floating-point type to integer conversion checking. It checks that the result of the conversion does not overflow. Unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Also, this option does not work well withFE_INVALIDexceptions enabled.-fsanitize=nonnull-attributeโ enables instrumentation of calls, checking whether null values are not passed to arguments marked as requiring a non-null value by thenonnullfunction attribute.-fsanitize=returns-nonnull-attributeโ enables instrumentation of return statements in functions marked with thereturns_nonnullfunction attribute, to detect returning of null values from such functions.-fsanitize=boolโ enables instrumentation of loads from bool. If a value other than 0/1 is loaded, a run-time error is issued. ๐ฑ-fsanitize=enumโ enables 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.-fsanitize=vptrโ enables 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.-fsanitize=pointer-overflowโ enables instrumentation of pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued.-fsanitize=builtinโ enables instrumentation of arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing 0 as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and is diagnosed by this option.
So like, -ftrapv causes traps for signed overflows to be emitted, whereas -fsanitize=undefined gives a diagnostic message. This currently works only for the C family of languages.
-fno-sanitize=allโ this one disables all previously enabled sanitizers ๐งน. Note that-fsanitize=allis not allowed, since some sanitizers cannot be used together. Sorry bestie, them's the rules.-fasan-shadow-offset=numberโ forces GCC to use a custom shadow offset in AddressSanitizer checks. Super useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer ๐งช.-fsanitize-sections=s1,s2,...โ sanitize global variables in selected user-defined sections. Anysimay 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 keep 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 alter this behavior: only the first detected error is reported, and then the program exits with a non-zero exit code.
Currently this feature only works for -fsanitize=undefined (and its suboptions, except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all are also accepted โ the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.
Even if recovery mode is turned on the compiler side, it also needs to be enabled on the runtime library side, otherwise the failures are still fatal ๐ญ. The runtime library defaults to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. This can be overridden by setting the halt_on_error flag in the corresponding environment variable.
The 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โ enables sanitization of local variables to detect use-after-scope bugs ๐. The option sets-fstack-reuseto none.-fsanitize-undefined-trap-on-errorโ this option instructs the compiler to report undefined behavior using__builtin_traprather than alibubsanlibrary routine. The glow-up here is that thelibubsanlibrary is not needed and is not linked in, so this is usable even in freestanding environments ๐ฆ.-fsanitize-coverage=trace-pcโ turns on coverage-guided fuzzing instrumentation, bestie ๐ it drops a call to__sanitizer_cov_trace_pcinto every single basic block. every one. obsessed.-fsanitize-coverage=trace-cmpโ dataflow guided fuzzing instrumentation, and the way it works is so specific: it inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8when it's an integral comparison where both operands are variable, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8when it's an integral comparison with one operand constant, or__sanitizer_cov_trace_cmpf/__sanitizer_cov_trace_cmpdfor float or double comparisons, and__sanitizer_cov_trace_switchfor switch statements. the whole roster, no skips โจ-fcf-protection=[full|branch|return|none|check]โ enables instrumentation of control-flow transfers so your program is more secure, by checking that the target addresses of control-flow transfer instructions (think indirect function call, function return, indirect jump) are actually valid ๐ก๏ธ this stops anyone from diverting the flow of control to some unexpected target. it's built to protect against threats like Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP). iconic.
The value branch tells the compiler to check the validity of control-flow transfer at the point of indirect branch instructions, i.e. call/jmp instructions. The value return does the checking at the point of returning from a function. The value full is just an alias for specifying both branch and return. The value none turns the instrumentation off ๐ค
The value check is for the final link with link-time optimization (LTO). An error gets issued if LTO object files were compiled with different -fcf-protection values. And check is ignored at compile time, no cap.
The macro __CET__ is defined whenever -fcf-protection is used. The first bit of __CET__ is set to 1 for the value branch, and the second bit of __CET__ is set to 1 for return.
You can also use the nocf_check attribute to pick out which functions and calls should be skipped from instrumentation ๐
Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET) which works for i686 processor or newer.
-fharden-comparesโ for every logical test that survives gimple optimizations and isn't the condition in a conditional branch (like, conditions tested for conditional moves, or to store in boolean variables), it emits extra code to compute and verify the reversed condition, and to call__builtin_trapif the results don't match ๐ use it with-fharden-conditional-branchesto cover all conditionals.-fharden-conditional-branchesโ for every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and to call__builtin_trapif the result is unexpected ๐ณ use it with-fharden-comparesto cover all conditionals.
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.
-fstack-protectorโ emits extra code to check for buffer overflows, like 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 prints and the program exits ๐ only variables that are actually allocated on the stack count, so optimized-away variables or variables allocated in registers don't count.-fstack-protector-allโ same energy as-fstack-protectorexcept that all functions are protected. periodt.-fstack-protector-strongโ like-fstack-protectorbut it includes additional functions to be protected --- those that have local array definitions, or have references to local frame addresses. Only variables that are actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count ๐ธ-fstack-protector-explicitโ like-fstack-protectorbut it only protects those functions which have thestack_protectattribute. exclusive behavior, honestly kind of a vibe.-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.
Note that this switch doesn't actually cause checking to be done; the operating system or the language runtime has to do that. The switch causes generation of code to ensure that they see the stack being extended.
You can additionally 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 comes with these drawbacks, bestie, listen up:
- 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.
Most targets don't fully support stack clash protection. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. -fstack-clash-protection may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.
NOTE: In Ubuntu 19.10 and later versions,-fstack-clash-protectionis enabled by default for C, C++, ObjC, ObjC++, unless-fno-stack-clash-protectionis found.
-fstack-limit-register=reg-fstack-limit-symbol=sym-fno-stack-limitโ these generate code to make sure the stack doesn't grow beyond a certain value, either the value of a register or the address of a symbol ๐ 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. no stress.
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, because it's no longer necessary to calculate a good stack size to use for each thread. This is currently only implemented for the x86 targets running GNU/Linux.
When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run. If compiling all code, including library code, with -fsplit-stack is not an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later ๐
-fvtable-verify=[std|preinit|none]โ this one is only available when compiling C++ code, iykyk. it turns on (or off, if you're using-fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and hasn't been corrupted or overwritten ๐ if an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted. bye.
This option causes run-time data structures to be built at program startup, which are used for verifying the vtable pointers. The options std and preinit control the timing of when these data structures are built. In both cases the data structures are built before execution reaches main. Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized.
If this option appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std ๐
-fvtv-debugโ bestie this one only hits different when you're rolling with-fvtable-verify=stdor-fvtable-verify=preinit. When it's on, it makes the debug versions of the runtime functions for the vtable verification feature get called. It ALSO makes the compiler spill the tea on which vtable pointers it finds for each class, writing all of that to a file calledvtv_set_ptr_data.log, dropped into the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise.
โ ๏ธ Heads up girlypop: this feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one first. ๐
-fvtv-countsโ this is a debugging flag, ok? When used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, it makes the compiler keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts, and logs this information for each compilation unit. The compiler writes this to a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise. It ALSO counts the size of the vtable pointer sets for each class and writes that info tovtv_class_set_sizes.login the same directory. So many logs, so little time. ๐ซถ
โ ๏ธ Note again: this feature appends data to the log files. To get fresh log files, be sure to delete any existing ones. No cap.
-finstrument-functionsโ this generates instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions get called with the address of the current function and its call site:
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 may be looked up exactly in the symbol table. Iconic.
On some platforms, __builtin_return_address does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise. ๐
This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use extern inline in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.) Lucky you, I guess โจ
A function may be given the attribute no_instrument_function, in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory). Main character exception energy, honestly.
- *
-finstrument-functions-exclude-file-list=file*,file,... โ this sets the list of functions that are excluded from instrumentation (see the description of-finstrument-functions). If the file that contains a function definition matches with one of file, then that function is not instrumented. The match is done on substrings: if the file parameter is a substring of the file name, it's considered to be a match. Subtle but slay.
For example:
-finstrument-functions-exclude-file-list=/bits/stl,include/sys
excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.
And if, for some reason, you want to include the letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option). Yes it's cursed, no I don't make the rules. ๐
-finstrument-functions-exclude-function-list=sym,sym,... โ this is similar to-finstrument-functions-exclude-file-list, but this option sets the list of function names to be excluded from instrumentation. The function name to be matched is its user-visible name, such asvector<int> blah(const vector<int> &), *not the internal mangled name (e.g.,_Z4blahRSt6vectorIiSaIiEE). The match is done on substrings: if the *sym parameter is a substring of the function name, it's considered to be a match. For C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. Noted, bestie. ๐-fpatchable-function-entry=N[,M] โ generate N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to0, so the function entry points to the address just at the first NOP. These NOP instructions reserve extra space that can be used to patch in any desired instrumentation at run time, **provided that the code segment is writable. The amount of space is controllable indirectly via the number of NOPs; the NOP instruction used corresponds to the instruction emitted by the internal GCC back-end interfacegen_nop. This behavior is target-specific and may also depend on the architecture variant and/or other compilation options. Very much depends on the vibe check of your arch, lowkey.
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. This can be used to increase the area size or to remove it completely on a single function. 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.
The maximum value of N and M is 65535. That's the ceiling, periodt.
๐ธ Options Controlling the Preprocessor ๐ธ
These options control the C preprocessor, which is run on each C source file before actual compilation. Pre-gaming, basically. ๐ง
If you use the -E option, nothing is done except preprocessing. Some of these options make sense only together with -E because they cause the preprocessor output to be unsuitable for actual compilation.
In addition to the options listed here, there are a number of options to control search paths for include files documented in Directory Options. Options to control preprocessor diagnostics are listed in Warning Options.
-Dname โ predefine name as a macro, with definition1. Simple. Clean. Effective.- *
-D*name=definition โ the contents of definition are tokenized and processed as if they appeared during translation phase three in a#definedirective. In particular, the definition is truncated by embedded newline characters. Careful with that one fr fr.
If you're invoking the preprocessor from a shell or shell-like program, you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax.
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args...)=definition' works. There it is. ๐
-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. Order matters, always has. ๐
-Uname โ cancel any previous definition of name, either built in or provided with a-Doption. Undefine and move on.-includefile โ process file as if#include "file"appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If not found there, it's searched for in the remainder of the#include "..."search chain as normal.
If multiple -include options are given, the files are included in the order they appear on the command line.
-imacrosfile โ exactly like-include, except that any output produced by scanning file is thrown away. Macros it defines remain defined. This allows you to acquire all the macros from a header without also processing its declarations. Snatching the macros and ghosting the declarations, iconic behaviour honestly.
All files specified by -imacros are processed before all files specified by -include.
-undefโ do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined, so it's not a full wipe.-pthreadโ define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets.-Mโ instead of outputting the result of preprocessing, output a rule suitable formakedescribing the dependencies of the main source file. The preprocessor outputs onemakerule containing the object file name for that source file, a colon, and the names of all the included files, including those coming from-includeor-imacroscommand-line options. Dependency graph? Served. โจ
Unless specified explicitly (with -MT or -MQ), the object file name consists of the name of the source file with any suffix replaced with object file suffix and with any leading directory parts removed. If there are many included files then the rule is split into several lines using \-newline. The rule has no commands.
This option does not suppress the preprocessor's debug output, such as -dM. To avoid mixing such debug output with the dependency rules you should explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal. Don't mix your drinks bestie.
Passing -M to the driver implies -E, and suppresses warnings with an implicit -w.
-MMโ like-Mbut do not mention header files that are found in system header directories, nor header files that are included, directly or indirectly, from such a header. System headers stay in their lane. ๐ฆ
okay so real talk bestie: the choice between angle brackets and double quotes in an #include directive? it does not, all by itself, decide whether that header shows up in your -MM dependency output. periodt. ๐
-MF fileโ when it's vibing with-Mor-MM, this tells the compiler which file to write the dependencies to. no-MFswitch in sight? then the preprocessor just ships the rules off to the same place it would've sent preprocessed output. ๐ซถ
and when it's hanging out with the driver options -MD or -MMD, -MF overrides the default dependency output file.
oh and if file is -?? the dependencies get written to stdout. iconic.
-MGโ this one's a team player with stuff like-Mthat asks for dependency generation.-MGis like "aw, that missing header file? probably generated, no biggie" and it adds them to the dependency list without throwing an error. ๐ the dependency filename gets taken directly from the"#include"directive, no path prepended, no extra steps.-MGalso suppresses preprocessed output, because honestly a missing header file renders that useless anyway.
this feature is used in automatic updating of makefiles. iykyk.
-Mno-modulesโ disable dependency generation for compiled module interfaces. simple as that. ๐ฆ-MPโ this tells CPP to add a phony target for each dependency other than the main file, so each one depends on nothing. these dummy rules work around the errorsmakethrows at you when you delete header files without updating theMakefileto match. lowkey a lifesaver. ๐ญ
this is the typical output:
test.o: test.c test.h
test.h:
-MT targetโ changes the target of the rule that dependency generation emits. by default CPP grabs the name of the main input file, deletes any directory components and any file suffix like.c, then appends the platform's usual object suffix. boom, that's your target. โจ
an -MT option sets the target to be exactly the string you specify. want multiple targets? you can hand them over as a single argument to -MT, or just use multiple -MT options. your call, bestie.
for example, -MT '$(objpfx)foo.o' might give
$(objpfx)foo.o: foo.c
-MQ targetโ same as-MT, except it quotes any characters that are special to Make. so-MQ '$(objpfx)foo.o'gives
$$(objpfx)foo.o: foo.c
and the default target? it's automatically quoted, as if you'd given it with -MQ. ๐
-MDโ-MDis equivalent to-M -MF file, except that-Eis not implied. the driver figures out file based on whether an-ooption was given. if it was, the driver uses its argument but with a suffix of.d. otherwise it takes the name of the input file, strips any directory components and suffix, and slaps a.dsuffix on it. ๐
if -MD is used together with -E, any -o switch is understood to specify the dependency output file โ but if you use it without -E, each -o is understood to specify a target object file.
and since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process. sneaky but slay.
-MMDโ like-MDexcept it only mentions user header files, not system header files. keep it in the family. ๐-fpreprocessedโ tells the preprocessor that the input file has already been preprocessed. this suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. but it still recognizes and removes comments, so you can pass a file preprocessed with-Cto the compiler without any problems. ๐ซถ in this mode the integrated preprocessor is little more than a tokenizer for the front ends.
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. these are the extensions that GCC uses for preprocessed files created by -save-temps.
-fdirectives-onlyโ when preprocessing, handle directives, but do not expand macros.
the option's behavior depends on the -E and -fpreprocessed options. ๐
with -E, preprocessing is limited to handling directives such as "#define", "#ifdef", and "#error". other preprocessor operations, like macro expansion and trigraph conversion, are not performed. plus, the -dD option is implicitly enabled. โจ
with -fpreprocessed, predefinition of command line and most builtin macros is disabled. macros like "__LINE__", which are contextually dependent, are handled normally. this enables compilation of files previously preprocessed with "-E -fdirectives-only".
with both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. this enables full preprocessing of files previously preprocessed with "-E -fdirectives-only". ๐ธ
-fdollars-in-identifiersโ accept$in identifiers. yes really. ๐-fextended-identifiersโ accept universal character names and extended characters in identifiers. this option is enabled by default for C99 (and later C standard versions) and C++. ๐-fno-canonical-system-headersโ when preprocessing, do not shorten system header paths with canonicalization. leave those paths alone bestie. ๐-fmax-include-depth=depthโ sets the maximum depth of nested#include. the default is200. ๐-ftabstop=widthโ sets the distance between tab stops. this helps the preprocessor report correct column numbers in warnings or errors, even if tabs show up on the line. if the value is less than1or greater than100, the option is ignored. the default is8. โจ-ftrack-macro-expansion[=level]โ tracks locations of tokens across macro expansions. this lets the compiler emit a diagnostic about the current macro expansion stack when a compilation error happens inside a macro expansion. heads up though: using this option makes the preprocessor and the compiler consume more memory. ๐ญ the level parameter lets you choose the precision of token location tracking, so you can dial the memory consumption down if you need to. value0of level de-activates this option. value1tracks token locations in a degraded mode for the sake of minimal memory overhead โ in this mode all tokens resulting from the expansion of an argument of a function-like macro have the same location. value2tracks token locations completely, and this value is the most memory hungry. when this option is given with no argument, the default parameter value is2. ๐ซถ
note that "-ftrack-macro-expansion=2" is activated by default.
-fmacro-prefix-map=old=newโ when preprocessing files residing in directory old, expand the"__FILE__"and"__BASE_FILE__"macros as if the files resided in directory new instead. you can use this to change an absolute path into a relative one by using.for new, which can give you more reproducible builds that are location independent. โจ this option also affects"__builtin_FILE()"during compilation. see also-ffile-prefix-map.-fexec-charset=charsetโ sets the execution character set, used for string and character constants. the default isUTF-8. charset can be any encoding supported by the system's"iconv"library routine. ๐-fwide-exec-charset=charsetโ sets the wide execution character set, used for wide string and character constants. the default is one ofUTF-32BE,UTF-32LE,UTF-16BE, orUTF-16LEโ whichever corresponds to the width of"wchar_t"and the big-endian or little-endian byte order being used for code generation. same deal as-fexec-charset, charset can be any encoding supported by the system's"iconv"library routine. however, you will have problems with encodings that don't fit exactly in"wchar_t". not a vibe. ๐ฌ-finput-charset=charsetโ sets the input character set, used for translation from the character set of the input file to the source character set GCC uses. if the locale doesn't specify it, or GCC can't get that 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's"iconv"library routine. ๐ธ-fpch-depsโ when you're using precompiled headers, this flag makes the dependency-output flags also list the files from the precompiled header's dependencies. if you don't specify it, only the precompiled header itself gets listed, not the files used to create it โ because those files aren't consulted when a precompiled header is used. makes sense honestly. ๐ง-fpch-preprocessโ this option allows use of a precompiled header together with-E. it inserts a special"#pragma",#pragma GCC pch_preprocess "filename"in the output to mark the place where the precompiled header was found, and its filename. when-fpreprocessedis in use, GCC recognizes this"#pragma"and 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 option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory โ when it's present in the preprocessed input โ as the directory emitted as the current working directory in some debugging information formats. this option is implicitly enabled if debugging information is enabled, but that can be inhibited with the negated form-fno-working-directory. ๐ซถ and if the-Pflag is present on the command line, this option has no effect, since no"#line"directives are emitted whatsoever.-A predicate=answerโ make an assertion with the predicate predicate and answer answer. this form is preferred over the older form-A predicate(answer), which is still supported, because it doesn't use shell special characters. โจ-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. rip those ones. ๐ญ
You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #. ๐ yeah. chaos. but informed chaos.
-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. ๐ซถ
In addition to the side effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line. ๐ญ the way that would ruin your whole day...
The -CC option is generally used to support lint comments.
-Pโ Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers. โจ no linemarkers, no confusion, clean vibes.-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. ๐
Note that 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. ngl that's a real limitation, so read it twice bestie.
-trigraphsโ Support ISO C trigraphs. These are three-character sequences, all starting with??, that are defined by ISO C 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. ๐ retro problems, retro solutions.-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...!. ๐ the littlexvs!is giving detective energy, iykyk.-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. โ ๏ธ undefined behaviour, no cap, don't test it.-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. โจ iconic little trick honestly.
If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach. ๐ญ sneaky.
-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. names only, no lore attached.-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. ๐ฆ delayed output, main character timing.
-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. literally nothing, bestie.
-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. โ ๏ธ the way this is a "please don't" wrapped in a feature...-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 -Xpreprocessor twice, once for the option and once for the argument. twice!! don't forget the second one!! ๐
-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. ๐ซถ two passes, double the slay.-flarge-source-filesโ Adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage. ๐ญ the price is real.
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. โจ so many lines. so much room for activities.
๐ธ Passing Options to the Assembler ๐ธ
You can pass options to the assembler. yep, the assembler gets gifts too ๐
-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. yes bestie, twice again, same rules ๐
๐ 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. ๐ญ if there's no link step, they're just standing there, decorative.
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. ๐ the linker reads the vibes (contents) to tell them apart.-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. โ ๏ธ no linker, so no object file names as args, periodt.-flinker-output=typeโ This option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. For debugging the compiler and if incremental linking with a non-LTO object file is desired, it may be useful to control the type manually. ๐ฆ
If type is exec, code generation produces a static binary. In this case -fpic and -fpie are both disabled.
If type is dyn, code generation produces a shared library. In this case -fpic or -fPIC is preserved, but not enabled automatically. This 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 -fpie executable. This results in similar optimizations as exec except that -fpie is not disabled if specified at compilation time.
If type is rel, the compiler assumes that incremental linking is done. The sections containing intermediate code for link-time optimization are merged, pre-optimized, and output to the resulting object file. In addition, if -ffat-lto-objects is specified, binary code is produced for future non-LTO linking. The object file produced by incremental linking is smaller than a static library produced from the same object files. At link time the result of incremental linking also loads faster than a static library assuming that the majority of objects in the library are used. ๐
smaller AND faster, we love a glow-up.
Finally nolto-rel configures the compiler for incremental linking where code generation is forced, a final binary is produced, and the intermediate code for later link-time optimization is stripped. When multiple object files are linked together the resulting code is better optimized than with link-time optimizations disabled (for example, cross-module inlining happens), but most of benefits of whole program optimizations are lost. ๐ญ you win some, you lose the whole-program ones.
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. ๐ซถ a whole saga, honestly.
-fuse-ld=bfdโ Use thebfdlinker instead of the default linker.-fuse-ld=goldโ Use thegoldlinker instead of the default linker. โจ-fuse-ld=lldโ okay bestie, instead of the default linker, use the LLVMlldlinker. slay ๐-fuse-ld=moldโ orrrr use the Modern Linker (mold) instead of the default linker. literally so fast ๐ฆ-llibrary-l libraryโ search for the library named library when linking. (the second form, where library is a separate argument, exists only for POSIX compliance and is not recommended โ no cap, don't do it ๐)
The -l option gets passed directly to the linker by GCC. so like, go read your linker's docs for the exact deets โ the general description below is about the GNU linker specifically.
The linker hunts through a standard list of directories for the library. those directories include several standard system directories plus any you specify with -L. ๐
Static libraries are archives of object files and have names like liblibrary.a. some targets also support shared libraries, which typically have names like liblibrary.so. if it finds both static and shared versions, the linker gives preference to linking with the shared library โ unless you used -static. ๐
โ ๏ธ and this is the part everyone forgets: where you write this option in the command matters. the linker searches and processes libraries and object files in the order they are specified. so like:
foo.o -lz bar.o
searches library z after file foo.o but before bar.o. so if bar.o refers to functions in z, those functions may not be loaded. it's giving "order is everything" ๐
-lobjcโ you need this special case of the-loption in order to link an Objective-C or Objective-C++ program. that's the whole vibe. ๐-nostartfilesโ do not use the standard system startup files when linking. the standard system libraries are still used normally though, unless-nostdlib,-nolibc, or-nodefaultlibsis used. ๐-nodefaultlibsโ do not use the standard system libraries when linking. only the libraries you specify get passed to the linker, and options specifying linkage of the system libraries โ like-static-libgccor-shared-libgccโ are just ignored. the standard startup files are used normally, unless-nostartfilesis used.
heads up: the compiler may generate calls to memcmp, memset, memcpy and memmove. these entries are usually resolved by entries in libc. when this option is specified, those entry points should be supplied through some other mechanism. ๐ญ
-nolibcโ do not use the C library or system libraries tightly coupled with it when linking. it still links with the startup files,libgcc, or toolchain-provided language support libraries such aslibgnat,libgfortranorlibstdc++โ unless options preventing their inclusion are used as well. this typically removes-lcfrom the link command line, along with system libraries that normally go with it and become meaningless when absence of a C library is assumed, for example-lpthreador-lmin some configurations. this is intended for bare-board targets when there is indeed no C library available. main character energy for embedded girlies ๐ง-nostdlibโ do not use the standard system startup files or libraries when linking. no startup files, and only the libraries you specify get passed to the linker. and options specifying linkage of the system libraries, such as-static-libgccor-shared-libgcc, are ignored. ๐ซถ
same warning as before: 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.
๐ one of the standard libraries bypassed by-nostdliband-nodefaultlibsislibgcc.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 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.) literally iconic โจ
-e entry--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 step bestie ๐-no-pieโ don't produce a dynamically linked position independent executable. periodt. ๐-static-pieโ produce a static position independent executable on targets that support it. a static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. for predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option. ๐-pthreadโ link with the POSIX threads library. this option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. on some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking. no cap, use it on both sides ๐ฆ-rโ produce a relocatable object as output. this is also known as partial linking. lowkey a whole different mode ๐-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. it's giving "give me the full receipts" ๐-sโ remove all symbol table and relocation information from the executable. so small. so stripped. ๐-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 providelibgccas a shared library, these options force the use of either the shared or static version, respectively. if no shared version oflibgccwas built when the compiler was configured, these options have no effect. ๐
There are several situations in which an application should use the shared libgcc instead of the static version. the most common of these is when the application wishes to throw and catch exceptions across different shared libraries. in that case, each of the libraries as well as the application itself should use the shared libgcc.
Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do. slay ๐
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. if GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. this allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time. โจ
However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc. โ ๏ธ
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links againstlibasan. iflibasanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibasan. the-static-libasanoption directs the GCC driver to linklibasanstatically, without necessarily linking other libraries statically. ๐ฆ-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links againstlibtsan. iflibtsanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibtsan. the-static-libtsanoption directs the GCC driver to linklibtsanstatically, without necessarily linking other libraries statically. ๐-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links againstliblsan. ifliblsanis available as a shared library, and the-staticoption is not used, then this links against the shared version ofliblsan. the-static-liblsanoption directs the GCC driver to linkliblsanstatically, without necessarily linking other libraries statically. ๐-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links againstlibubsan. iflibubsanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibubsan. the-static-libubsanoption directs the GCC driver to linklibubsanstatically, without necessarily linking other libraries statically. ๐ธ-static-libstdc++โ when theg++program is used to link a C++ program, it normally automatically links againstlibstdc++. iflibstdc++is available as a shared library, and the-staticoption is not used, then this links against the shared version oflibstdc++. that is normally fine. however, it is sometimes useful to freeze the version oflibstdc++used by the program without going all the way to a fully static link. the-static-libstdc++option directs theg++driver to linklibstdc++statically, without necessarily linking other libraries statically. 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. iykyk ๐-Tscript โ bestie, this one uses script as the linker script. Most systems that rock the GNU linker support it. On some targets โ like bare-board targets with no operating system whatsoever โ you might actually need-Twhen linking, or else you get sad little references to undefined symbols. ๐ญ-Xlinkeroption โ pass option through as an option to the linker. Iconic for when you gotta hand over system-specific linker options that GCC doesn't even recognize. ๐
If you're passing an option that takes a separate argument, you must use -Xlinker twice โ once for the option, once for the argument. Like, to pass -assert definitions you write -Xlinker -assert -Xlinker definitions. Writing -Xlinker "-assert definitions" does not work, because that shoves the entire string in as a single argument, and that is not what the linker expects. ๐
When you're on the GNU linker, it's usually way comfier to pass arguments to linker options using the option=value syntax rather than as separate arguments. For example, you can say -Xlinker -Map=output.map instead of -Xlinker -Map -Xlinker output.map. Other linkers might not support that syntax for command-line options tho. ๐ฆ
-Wl,option โ pass option as an option to the linker. If option contains commas, it gets split into multiple options at the commas. You can use this syntax to pass an argument to the option. Example:-Wl,-Map,output.mappasses-Map output.mapto the linker. And with the GNU linker you can get the same effect with-Wl,-Map=output.map. โจ
NOTE: in Ubuntu 8.10 and later versions, forLDFLAGS, the option-Wl,-z,relrois used. To disable, use-Wl,-z,norelro.
-usymbol โ pretend the symbol symbol is undefined, which forces linking of library modules to define it. You can use-umultiple times with different symbols to force loading of extra library modules. ๐-zkeyword โ-zis passed directly on to the linker along with the keyword keyword. Peep the section in your linker's documentation for the permitted values and what they mean.
โจ Options for Directory Search โจ
These options specify the directories to search for header files, for libraries, and for parts of the compiler itself: ๐
-Idir,-iquotedir,-isystemdir,-idirafterdir โ add the directory dir to the list of directories searched for header files during preprocessing. If dir begins with=or$SYSROOT, then that=or$SYSROOTgets replaced by the sysroot prefix; see--sysrootand-isysroot. ๐ซถ
Directories you specify with -iquote apply only to the quote form of the directive, #include "file". Directories you specify with -I, -isystem, or -idirafter apply to lookup for both #include "file" and #include <file>. ๐ธ
You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order is, in this exact order:
- For the quote form of the include directive, the directory of the current file is searched first.
- For the quote form of the include directive, the directories specified by
-iquoteoptions are searched in left-to-right order, as they appear on the command line. - Directories specified with
-Ioptions are scanned in left-to-right order. - Directories specified with
-isystemoptions are scanned in left-to-right order. - Standard system directories are scanned.
- Directories specified with
-idirafteroptions are scanned in left-to-right order.
You can use -I to override a system header file, substituting your own version, since these directories get searched before the standard system header file directories. But you should not use this option to add directories that contain vendor-supplied system header files โ use -isystem for that. ๐
The -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment that's applied to the standard system directories.
If a standard system include directory, or a directory specified with -isystem, is also specified with -I, then the -I option is ignored. The directory is still searched, but as a system directory at its normal position in the system include chain. This is so GCC's procedure to fix buggy system headers and the ordering for the #include_next directive don't get inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options. ๐
-I-โ split the include path. This option has been deprecated. Please use-iquoteinstead for-Idirectories before the-I-, and 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 additional 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 directory of the current file as the first search directory for #include "file". And there is no way to override this effect of -I-. ๐ญ
-iprefixprefix โ specify prefix as the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final/.-iwithprefixdir,-iwithprefixbeforedir โ append dir to the prefix you 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. ๐ฆ-isysrootdir โ this option is like the--sysrootoption, but it applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the--sysrootoption for more info.-imultilibdir โ use dir as a subdirectory of the directory containing target-specific C++ headers.-nostdincโ do not search the standard system directories for header files. Only the directories explicitly specified with-I,-iquote,-isystem, and/or-idirafteroptions (and the directory of the current file, if that applies) are searched.-nostdinc++โ don't search for header files in the C++-specific standard directories, but do still search the other standard directories. (This option is used when building the C++ library.)-iplugindir=dir โ set the directory to search for plugins that are passed by-fplugin=nameinstead of-fplugin=path/name.so. This option is not meant to be used by the user โ it's only passed by the driver. ๐-Ldir โ add directory dir to the list of directories to be searched for-l.-Bprefix โ this option specifies where to find the executables, libraries, include files, and data files of the compiler itself. ๐
The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.
For each subprogram to be run, the compiler driver first tries the -B prefix, if there is one. 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 is 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 are tried, and that's all. The file is left out of the link if it isn't found by those means. ๐
Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.
As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it's 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 โ use dir as the logical root directory for headers and libraries. For example, if the compiler normally searches for headers in/usr/includeand libraries in/usr/lib, it instead searchesdir/usr/includeanddir/usr/lib.
If you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files.
The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker doesn't support this option, the header file aspect of --sysroot still works, but the library aspect does not. ๐ญ
--no-sysroot-suffixโ for some targets, a suffix gets added to the root directory specified with--sysroot, depending on the other options used, so that headers may for example be found indir/suffix/usr/includeinstead ofdir/usr/include. This option disables the addition of such a suffix. ๐ฆ
โจ Options for Code Generation Conventions โจ
These machine-independent options control the interface conventions used in code generation. ๐
Most of them have both 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 โ controls whether stack space gets recycled between user-declared local/auto variables and compiler-generated temporaries. reuse_level is one ofall,named_vars, ornone.all= reuse for everything (locals and temporaries),named_vars= only for user-defined locals that actually have names,none= no reuse at all, periodt. Default isall. ๐
You need this option when your program extends the lifetime of a scoped local variable โ or a compiler-generated temporary โ past the endpoint the language says it should die at. Like, once a variable's lifetime is over and it lives in memory, the optimizing compiler is fully allowed to hand its stack space over to other temporaries or scoped locals whose live range doesn't overlap with it. Legacy code that stretches local lifetimes is likely to break under the stack reuse optimization. ๐ญ
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?
}
A compiler-generated temporary's lifetime is fully well defined by the C++ standard, bestie. So when a temporary's lifetime ends and it lives in memory, the optimizing compiler gets to reuse its stack space with other temporaries or scoped locals whose live range doesn't overlap. BUT. Some legacy code relies on how older compilers behaved โ where temporaries' stack space was never reused โ and aggressive stack reuse can absolutely cause runtime errors. This option is the dial that controls the temporary stack reuse optimization. ๐
-ftrapvโ makes traps for signed overflow on addition, subtraction, and multiplication operations.-ftrapvand-fwrapvoverride each other, so passing-ftrapv -fwrapvon the command line means-fwrapvis the one that wins. And note โ only active options override, so-ftrapv -fwrapv -fno-wrapvon the command line means-ftrapvis what's effective. Sneaky but true. ๐-fwrapvโ tells the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag turns some optimizations on and others off. Same override tea as above:-ftrapvand-fwrapvoverride each other, so-ftrapv -fwrapvmeans-fwrapvwins; only active options override, so-ftrapv -fwrapv -fno-wrapvmeans-ftrapvwins. ๐-fwrapv-pointerโ tells the compiler to assume pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation. This flag disables some optimizations that assume pointer overflow is invalid. ๐ฆ-fstrict-overflowโ implies-fno-wrapv -fno-wrapv-pointer, and when negated implies-fwrapv -fwrapv-pointer. That's the whole vibe. โจ-fexceptionsโ enables exception handling, generating the extra code needed to propagate exceptions. On some targets this means GCC generates frame unwind information for all functions, which can produce significant data size overhead โ though it doesn't affect execution speed. If you don't specify this option, GCC turns it on by default for languages like C++ that normally need exception handling, and off for languages like C that normally don't. However โ you might need to enable it when compiling C code that has to interoperate properly with exception handlers written in C++. You may also want to disable it if you're compiling older C++ programs that don't use exception handling. ๐ซถ-fnon-call-exceptionsโ generates code that allows trapping instructions to throw exceptions. Note that this needs platform-specific runtime support that does not exist everywhere. And more importantly, it only lets trapping instructions throw exceptions โ i.e. memory references or floating-point instructions. It does not let exceptions be thrown from arbitrary signal handlers such asSIGALRM. This enables-fexceptions. ๐-fdelete-dead-exceptionsโ treats instructions that may throw exceptions but otherwise don't contribute to the program's execution as optimizable away. This doesn't affect calls to functions, except those with thepureorconstattributes. It's enabled by default for the Ada and C++ compilers, as the language specifications permit. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. ๐ธ-funwind-tablesโ similar to-fexceptions, except it only generates any needed static data and doesn't affect the generated code in any other way. You normally don't need to enable this yourself; a language processor that needs this handling enables it on your behalf. ๐ง-fasynchronous-unwind-tablesโ generates an unwind table in DWARF format, if the target machine supports it. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events โ think debugger or garbage collector. ๐ฅ-fno-gnu-uniqueโ on systems with a recent GNU assembler and C library, the C++ compiler uses theSTB_GNU_UNIQUEbinding to make sure that definitions of template static data members and static local variables in inline functions stay unique even in the presence ofRTLD_LOCAL. This is necessary to avoid problems with a library used by two differentRTLD_LOCALplugins that both depend on a definition in one of them and therefore disagree with the other about the binding of the symbol. But โ it causesdlcloseto be ignored for affected DSOs. So if your program relies on reinitialization of a DSO viadlcloseanddlopen, you can use-fno-gnu-unique. ๐ญ-fpcc-struct-returnโ returnsshortstructandunionvalues in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers โ particularly the Portable C Compiler (pcc). ๐
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the-fpcc-struct-returnswitch is not binary compatible with code compiled with the-freg-struct-returnswitch. Use it to conform to a non-default application binary interface.
-freg-struct-returnโ returnsstructandunionvalues in registers when possible. For small structures this is more efficient 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's 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. Iconic behavior honestly. ๐
Warning: code compiled with the-freg-struct-returnswitch is not binary compatible with code compiled with the-fpcc-struct-returnswitch. Use it to conform to a non-default application binary interface.
-fshort-enumsโ allocates to anenumtype only as many bytes as it needs for the declared range of possible values. Specifically, theenumtype becomes 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.
-fshort-wcharโ overrides the underlying type forwchar_tto beshort unsigned intinstead of the target's default. This option is useful for building programs to run under WINE. ๐
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
-fcommonโ in C code, this option controls where global variables defined without an initializer get placed โ those are known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with theexternkeyword, which do not allocate storage. ๐ฆ
The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker, so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit. ๐
-fcommon places uninitialized global variables in a common block instead. 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 it implies a speed and code size penalty on global variable references. It's mainly useful to let legacy code link without errors. ๐ซถ
-fno-identโ ignores the#identdirective. Short and sweet, bestie. โจ-finhibit-size-directiveโ bestie, this one says: do NOT emit a.sizeassembler directive, and nothing else that would start drama if the function gets chopped in half and the two halves get yeeted to wildly different spots in memory ๐ซ It's used when compilingcrtstuff.c, and like... you should not need it for anything else. Periodt.-fverbose-asmโ sprinkle extra commentary into the generated assembly so it's actually readable ๐ This is basically only for the girlies who genuinely need to read the assembly output (maybe you're debugging the compiler itself, iconic behavior).-fno-verbose-asm, the default, leaves all that extra info out, and it's useful when you're diffing two assembler files.
The added comments include:
- information on the compiler version and command-line options,
- the source code lines associated with the assembly instructions, in the form
FILENAME:LINENUMBER:CONTENT OF LINE, - hints on which high-level expressions correspond to the various assembly instruction operands.
So like, 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
The comments are intended for humans rather than machines, so the precise format of the comments is subject to change. Don't get attached, babe ๐ญ
-frecord-gcc-switchesโ this switch makes the command line you used to invoke the compiler get recorded into the object file it's creating ๐ It's only implemented on some targets, and the exact format of the recording depends on the target and the binary file format, but it usually takes the form of a section containing ASCII text. It's related to the-fverbose-asmswitch, except that one only records info in the assembler output file as comments, so it never reaches the object file. Also peep-grecord-gcc-switchesfor another way of storing compiler options into the object file ๐-fpicโ generate position-independent code (PIC) suitable for use in a shared library, if it's supported for the target machine โจ Such code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC โ it's part of the operating system, okay?). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker saying-fpicdoes not work; in that case, recompile with-fPICinstead. (These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit.)
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, slay ๐
When this flag is set, the macros __pic__ and __PIC__ are defined to 1.
-fPICโ if it's supported for the target machine, emit position-independent code suitable for dynamic linking, and avoiding any limit on the size of the global offset table ๐ This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Position-independent code requires special support, 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 like-fpicand-fPIC's little siblings ๐ similar vibe, but the generated position-independent code can only be linked into executables. Usually these get used to compile code that will be linked using the-pieGCC option.
-fpie and -fPIE both define the macros __pie__ and __PIE__. The macros have the value 1 for -fpie and 2 for -fPIE.
-fno-pltโ do not use the PLT for external function calls in position-independent code ๐ซ Instead, load the callee address at call sites from the GOT and branch to it. This leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures like 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives more register allocation freedom to the compiler. Lazy binding requires use of the PLT; with-fno-pltall external symbols are resolved at load time.
Alternatively, the function attribute noplt can be used to avoid calls through the PLT for specific external functions.
In position-dependent code, a few targets also convert calls to functions that are marked to not use the PLT to use the GOT instead.
-fno-jump-tablesโ do not use jump tables for switch statements even where it would be more efficient than other code generation strategies ๐ This one is of use in conjunction with-fpicor-fPICfor building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables don't require a GOT and this option is not needed.-fno-bit-testsโ do not use bit tests for switch statements even where it would be more efficient than other code generation strategies. Same energy, different mechanism ๐-ffixed-regโ treat the register named reg as a fixed register; generated code should never refer to it (except perhaps as a stack pointer, frame pointer or in some other fixed role) ๐
reg must be the name of a register. The register names accepted are machine-specific and are defined in the REGISTER_NAMES macro in the machine description macro file.
This flag does not have a negative form, because it specifies a three-way choice. Not everything in life has an opposite, bestie ๐คทโโ๏ธ
-fcall-used-regโ treat the register named reg as an allocable register that is clobbered by function calls. It may be allocated for temporaries or variables that do not live across a call. Functions compiled this way do not save and restore the register reg.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results ๐ญ
This flag does not have a negative form, because it specifies a three-way choice.
-fcall-saved-regโ treat the register named reg as an allocable register saved by functions. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the register reg if they use it ๐พ
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
A different sort of disaster results from the use of this flag for a register in which function values may be returned ๐
This flag does not have a negative form, because it specifies a three-way choice.
-fpack-struct[=n]โ without a value specified, pack all structure members together without holes ๐งณ When a value is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location.
Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch ๐ฑ Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.
-fleading-underscoreโ this option and its counterpart,-fno-leading-underscore, forcibly change the way C symbols are represented in the object file. One use is to help link with legacy assembly code ๐ฆ
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch.
-ftls-model=modelโ alter the thread-local storage model to be used ๐งต The model argument should be one ofglobal-dynamic,local-dynamic,initial-execorlocal-exec. Note that the choice is subject to optimization: the compiler may use a more efficient model for symbols not visible outside of the translation unit, or if-fpicis not given on the command line.
The default without -fpic is initial-exec; with -fpic the default is global-dynamic.
-ftrampolinesโ okay so for targets that normally need trampolines for nested functions, this makes them always generate trampolines instead of using descriptors. Otherwise, for targets that do not need them โ like, for example, HP-PA or IA-64 โ it does nothing. ๐
A trampoline is a small piece of 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. Therefore, it requires the stack to be made executable in order for the program to work properly. โ ๏ธ stack executable? yes bestie, that's the vibe.
-fno-trampolines is enabled by default on a language by language basis to let the compiler avoid generating them, if it computes that this is safe, and replace them with descriptors. 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.
Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care. ๐จ like, extreme extreme care. no cap.
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. so if you're not in Ada land, it's giving "no effect" energy.
-fvisibility=[default|internal|hidden|protected]โ Set the default ELF image symbol visibility to the specified option---all symbols are marked with this unless overridden within the code. 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. โจ slay โจ
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. The default if -fvisibility isn't specified 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 to marking things hidden when the default is public is to make the default hidden and mark things public. This is 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. This is a great boon to those working with cross-platform projects. fr fr, cross-platform besties are eating good with this one.
For those adding visibility support to existing code, you may find #pragma GCC visibility of use. This 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 as so to avoid PLT indirection overheads---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. no exceptions, literally.
Be aware that headers from outside your project, in particular system headers and headers from any other library you use, may not be expecting to be compiled with visibility other than the default. You may need to explicitly say #pragma GCC visibility push(default) before including any such headers. it's giving "please don't break my 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. iykyk.
Note that -fvisibility does affect C++ vague linkage entities. This means that, for instance, an exception class that is be thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. โ ๏ธ vague linkage? yes. mark it default or chaos.
An overview of these techniques, their benefits and how to use them is at <https://gcc.gnu.org/wiki/Visibility>. go read it, bestie.
-fstrict-volatile-bitfieldsโ This option should be used if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. For example, targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide; with this flag you can declare all peripheral bit-fields asunsigned short(assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access. so it's giving "respect my bit-field width, pls".
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. yikes, lowkey messy.
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. โ ๏ธ multiple accesses > faulting, periodt.
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. so like, define all the bits, bestie.
The default value of this option is determined by the application binary interface for the target processor. ABI decides, not you.
-fsync-libcallsโ This option controls whether any out-of-line instance of the__syncfamily of functions may be used to implement the C++11__atomicfamily of functions. so it's the sync-to-atomic pipeline, basically.
The default value of this option is enabled, thus the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library. libatomic said "I need this".
โจ 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. This includes options that produce debug dumps at various points in the compilation; that print statistics such as memory use and execution time; and that print information about GCC's configuration, such as where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. so like, devs only. main character energy for compiler nerds.
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. iykyk.
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 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. so many letters, but we love a naming convention.
-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. so many markers, so little time.
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. LTO said "not here".
-dletters,-fdump-rtl-pass,-fdump-rtl-pass=filenameโ Says to make debugging dumps during compilation at times specified byletters. This is used for debugging the RTL-based passes of the compiler. RTL besties, rise.
Some -dletters switches have different meaning when -E is used for preprocessing. โ ๏ธ different meaning alert.
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. alignments, slay.-fdump-rtl-asmconsโ Dump after fixing rtl statements that have unsatisfied in/out constraints. constraints? fixed.-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. auto inc/dec only, no cap.-fdump-rtl-barriersโ Dump after cleaning up the barrier instructions. barriers cleaned, iconic.-fdump-rtl-bbpartโ Dump after partitioning hot and cold basic blocks. hot and cold blocks, temperature check.-fdump-rtl-bbroโ Dump after block reordering. reorder, reorder, reorder.-fdump-rtl-btl1,-fdump-rtl-btl2โ-fdump-rtl-btl1and-fdump-rtl-btl2enable dumping after the two branch target load optimization passes. two passes, two dumps.-fdump-rtl-bypassโ Dump after jump bypassing and control flow optimizations. bypassing jumps like it's nothing.-fdump-rtl-combineโ dumps the tea right after the RTL instruction combination pass does its thing. โจ-fdump-rtl-compgotosโ dumps after the computed gotos get duplicated. ๐-fdump-rtl-ce1-fdump-rtl-ce2-fdump-rtl-ce3โ bestie these three are a set.-fdump-rtl-ce1,-fdump-rtl-ce2, and-fdump-rtl-ce3all enable dumping after the three if conversion passes. three passes, three flags, no notes. ๐-fdump-rtl-cprop_hardregโ dumps after hard register copy propagation. iconic behavior honestly. ๐-fdump-rtl-csaโ dumps after combining stack adjustments. ๐ธ-fdump-rtl-cse1-fdump-rtl-cse2โ-fdump-rtl-cse1and-fdump-rtl-cse2enable dumping after the two common subexpression elimination passes. โจ-fdump-rtl-dceโ dumps after the standalone dead code elimination passes. ๐ (literally, dead code, we love to see it)-fdump-rtl-dbrโ dumps after delayed branch scheduling. ๐-fdump-rtl-dce1-fdump-rtl-dce2โ-fdump-rtl-dce1and-fdump-rtl-dce2enable 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. the origin story fr fr. โญ-fdump-rtl-fwprop1-fdump-rtl-fwprop2โ-fdump-rtl-fwprop1and-fdump-rtl-fwprop2enable dumping after the two forward propagation passes. ๐ซถ-fdump-rtl-gcse1-fdump-rtl-gcse2โ-fdump-rtl-gcse1and-fdump-rtl-gcse2enable dumping after global common subexpression elimination. ๐-fdump-rtl-init-regsโ dumps after the initialization of the registers. main character setup energy. ๐-fdump-rtl-initvalsโ dumps after the computation of the initial value sets. โจ-fdump-rtl-into_cfglayoutโ dumps after converting to cfglayout mode. ๐ธ-fdump-rtl-iraโ dumps after iterated register allocation. ๐-fdump-rtl-jumpโ dumps after the second jump optimization. (the second one, iykyk) ๐ฅ-fdump-rtl-loop2โ-fdump-rtl-loop2enables dumping after the rtl loop optimization passes. ๐-fdump-rtl-machโ dumps after performing the machine dependent reorganization pass, if that pass exists. no cap, only if it exists. ๐-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. yes, the reverse of the earlier one, they're a matched pair bestie. ๐-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. โจ-fdump-rtl-sched1-fdump-rtl-sched2โ-fdump-rtl-sched1and-fdump-rtl-sched2enable dumping after the basic block scheduling passes. ๐-fdump-rtl-reeโ dumps after sign/zero extension elimination. ๐ธ-fdump-rtl-seqabstrโ dumps after common sequence discovery. ๐-fdump-rtl-shortenโ dumps after shortening branches. ๐-fdump-rtl-siblingโ dumps after sibling call optimizations. ๐-fdump-rtl-split1-fdump-rtl-split2-fdump-rtl-split3-fdump-rtl-split4-fdump-rtl-split5โ these options enable dumping after five rounds of instruction splitting. five. rounds. obsessed. ๐ฅ-fdump-rtl-smsโ dumps after modulo scheduling. > heads up bestie: this pass is only run on some architectures. ๐-fdump-rtl-stackโ dumps after conversion from GCC's "flat register file" registers to the x87's stack-like registers. > this pass is only run on x86 variants. ๐ง-fdump-rtl-subreg1-fdump-rtl-subreg2โ-fdump-rtl-subreg1and-fdump-rtl-subreg2enable dumping after the two subreg expansion passes. โญ-fdump-rtl-unshareโ dumps after all rtl has been unshared. ๐ฆ-fdump-rtl-vartrackโ dumps after variable tracking. ๐-fdump-rtl-vregsโ dumps after converting virtual registers to hard registers. the glow-up arc fr fr. ๐-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โ these dumps are defined but always produce empty files. not me getting excited over nothing ๐ญ literally empty. zero. nada. ๐-da-fdump-rtl-allโ produce all the dumps listed above. the whole buffet bestie, eat up. ๐โจ-dAโ annotate the assembler output with miscellaneous debugging information. ๐-dDโ dump all macro definitions, at the end of preprocessing, in addition to normal output. ๐-dHโ produce a core dump whenever an error occurs. > bestie this one is dramatic โ actual core dumps on error, be careful. ๐-dpโ annotate the assembler output with a comment indicating which pattern and alternative is used. the length and cost of each instruction are also printed. ๐ธ-dPโ dump the RTL in the assembler output as a comment before each instruction. also turns on-dpannotation. ๐ฆ-dxโ just generate RTL for a function instead of compiling it. usually used with-fdump-rtl-expand. โญ
-fdump-debugโ dump debugging information generated during the debug generation phase. ๐-fdump-earlydebugโ dump debugging information generated during the early debug generation phase. (yes it's the early one, they're different bestie) ๐ซถ-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. so diffable, so slay. โจ-freport-bugโ collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs. your crash gets receipts. ๐งพ๐-fdump-unnumberedโ when doing debugging dumps, suppress instruction numbers and address output. this makes it more feasible to usediffon debugging dumps for compiler invocations with different options, in particular with and without-g. ๐-fdump-unnumbered-linksโ when doing debugging dumps (see-doption above), suppress instruction numbers for the links to the previous and next instructions in a sequence. ๐-fdump-ipa-switch-fdump-ipa-switch-optionsโ control the dumping at various stages of inter-procedural analysis language tree to a file. the file name is generated by appending a switch specific suffix to the source file name, and the file is created in the same directory as the output file. the following dumps are possible:allโ enables all inter-procedural analysis dumps. ๐cgraphโ dumps information about call-graph optimization, unused function removal, and inlining decisions. ๐inlineโ dump after function inlining. ๐ฆ
additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized. โจ
for example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined. both. at once. ๐
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. ๐ธ-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. ๐งrawโ dump the raw internal tree data. > this option is applicable to C++ only. ๐
-fdump-passesโ print onstderrthe list of optimization passes that are turned on and off by the current command-line options. ๐-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. ๐-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. ๐ 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. ๐
detailsโ bestie this one makes the dumps give you MORE. Extra detail, plus it pulls in info from the optimization passes too. Heads up tho: not every dump option actually honors it ๐statsโ dumps a whole bunch of statistics about the pass. Very demure, very numbers. Again, not honored by every dump option, so don't come for me if one of them ghosts you ๐blocksโ shows you the basic block boundaries. Little fences between the blocks, love that for us. (It's disabled in raw dumps, fyi.)graphโ okay this one is iconic. For each of the other indicated dump files (-fdump-rtl-pass), it dumps a representation of the control flow graph that you can open with GraphViz, and it goes tofile.passid.pass.dot. Every function in the file gets pretty-printed as its own subgraph so GraphViz can render them all in a single plot. Chef's kiss โจ
Lowkey important: this option currently only works for RTL dumps, and the RTL is always dumped in slim form.
vopsโ shows the virtual operands for every single statement. Every. One. ๐ซถlinenoโ shows line numbers for statements. So you can actually find stuff instead of scrolling forever ๐ญuidโ shows the unique ID (DECL_UID) for each variable. Every variable gets its own little government name ๐verboseโ shows the tree dump for each statement. Wordy queen.ehโ shows the EH region number that holds each statement.scevโ shows scalar evolution analysis details. Fancy math moment fr fr ๐งoptimizedโ shows optimization information. Only available in certain passes, so don't be shocked when some passes give you nothing.missedโ shows missed optimization information. The "could've been iconic but wasn't" report ๐ญ Only available in certain passes.noteโ shows other detailed optimization information. Only available in certain passes.allโ turns on all the options, exceptraw,slim,verboseandlineno. Note the exceptions, bestie, they're doing heavy lifting.optallโ turns on all the optimization options, i.e.,optimized,missed, andnote.
Okay so to figure out what tree dumps are even available, or to find the dump for a pass you actually care about, follow these steps ๐
- Invoke GCC with
-fdump-passesand then, in the stderr output, go looking for a code that corresponds to the pass you're interested in. For example, the codestree-evrp,tree-vrp1, andtree-vrp2correspond to the three Value Range Propagation passes. The number at the end distinguishes distinct invocations of the same pass. So like... they're not the same pass, they're the same pass multiple times. Different vibes entirely. - To enable the creation of the dump file, append the pass code to the
-fdump-option prefix and invoke GCC with it. For example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the-fdump-tree-evrpoption. Optionally, you may specify the name of the dump file. If you don't specify one, GCC creates it as described below. - Find the pass dump in a file whose name is composed of three components separated by a period: the name of the source file GCC was invoked to compile, a numeric suffix indicating the pass number followed by the letter
tfor tree passes (and the letterrfor RTL passes), and finally the pass code. For example, the Early VRP pass dump might be in a file namedmyfile.c.038t.evrpin the current working directory.
Real talk: the numeric codes are not stable and may change from one version of GCC to another. Do not build your whole personality around them.
-fopt-info,-fopt-info-options,-fopt-info-options=filenameโ controls optimization dumps from all the various optimization passes. If you use the-optionsform, then options is a list of-separated option keywords that select the dump details and the optimizations. Okay so buckle up, because these options split into three groups:- options describing what kinds of messages should be emitted,
- options describing the verbosity of the dump, and
- options describing which optimizations should be included.
The options from each group can be freely mixed, since they're non-overlapping. But โ in case of any conflicts, the later options override the earlier options on the command line. Last one wins, periodt.
The following options control which kinds of messages get emitted:
optimizedโ prints information when an optimization is successfully applied. It's up to a pass to decide which information is relevant. For example, the vectorizer passes print the source location of loops which are successfully vectorized. Slay.missedโ prints information about missed optimizations. Individual passes control which information to include in the output.noteโ prints verbose information about optimizations, such as 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. (iykyk ๐ง)
One or more of the following option keywords can be used to 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, omitting messages that are treated as "internals".
If the filename is provided, then the dumps from all the applicable optimizations are concatenated into the filename. Otherwise the dump is output onto stderr. Though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored. ๐ซ
Note that the output filename is overwritten in case of multiple translation units. If you want a combined output from multiple translation units, use stderr instead.
In the following example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs a missed optimization report from all the passes into missed.all, and this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from vectorization passes on stderr. Note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter. Cute, right?
As another example,
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
Finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict, since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. So only vec.miss is produced, and it contains dumps from the vectorizer about missed opportunities. Sad for loop.opt, but rules are rules ๐
-fsave-optimization-recordโ writes aSRCFILE.opt-record.json.gzfile detailing what optimizations were performed, for those optimizations that support-fopt-info.
This option is experimental and the format of the data within the compressed JSON file is subject to change. Don't get attached.
It's roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, with the following additional data for each message:
- the execution count of the code being optimized, along with metadata about whether this was from actual profile data, or just an estimate, allowing consumers to 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. So it's giving... nested. ๐ธ
-fsched-verbose=nโ on targets that use instruction scheduling, this option controls the amount of debugging output the scheduler prints to the dump files.
For n greater than zero, -fsched-verbose outputs the same information as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also outputs basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info. So like, the higher the number, 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 use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead. Read that again bestie, this is dev-tools territory, not your everyday thing.-fdisable-ipa-passโ disable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.
-fdisable-rtl-pass,-fdisable-rtl-pass=range-listโ turn OFF the RTL pass called pass, bestie ๐ . pass is literally the pass name. Now, if that same pass gets statically invoked more than once in the compiler, you gotta append a sequential number to the pass name, starting from 1. And range-list? That's a comma-separated list of function ranges or assembler names. Each range is a number pair with a colon between them, and it's inclusive on BOTH ends. If a range is trivial you can just write it as a single number instead of a pair. So: if the function's call graph node's uid falls inside one of your ranges, the pass gets disabled for that function. The uid shows up in the function header of a dump file, and you can dump the pass names with-fdump-passes. iykyk โจ-fdisable-tree-pass,-fdisable-tree-pass=range-listโ disable the tree pass pass. Same energy as-fdisable-rtlfor the argument description, go read that one ๐-fenable-ipa-passโ turn ON the IPA pass pass. Again, pass is the pass name, and if the same pass is statically invoked multiple times in the compiler, tack on a sequential number starting from 1 ๐ธ-fenable-rtl-pass,-fenable-rtl-pass=range-listโ enable the RTL pass pass. For the argument description and examples, see-fdisable-rtl๐-fenable-tree-pass,-fenable-tree-pass=range-listโ enable the tree pass pass. Argument description? Yep,-fdisable-rtlagain, it's all there ๐
Here are some examples showing uses of these options, 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โ enables internal consistency checking ๐ง. The default depends on how your compiler was configured. And-fchecking=2cranks it up to even MORE internal consistency checking, the kind that might actually affect code generation. So like, highkey a thing to know ๐-frandom-seed=stringโ this gives GCC a seed to use instead of random numbers when it's generating certain symbol names that have to be different in every compiled file. It also places unique stamps in coverage data files and the object files that produce them. Bestie, the whole point: you can use-frandom-seedto produce reproducibly identical object files ๐
The string can be a number (decimal, octal or hex) or an arbitrary string โ and if it's arbitrary, it gets converted to a number by computing CRC32.
The string should be different for every file you compile. Fr fr, don't reuse it ๐
-save-tempsโ store the usual "temporary" intermediate files permanently ๐พ. They get named as auxiliary output files, as specified described under-dumpbaseand-dumpdir.
When you use it together with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file that has the same extension as an intermediate file. If you want that intermediate file anyway, rename the source file before using -save-temps โจ
-save-temps=cwdโ equivalent to-save-temps -dumpdir ./. ๐ซถ-save-temps=objโ equivalent to-save-temps -dumpdir outdir/, where outdir/ 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=objbehaves like-save-temps=cwd๐ธ-time[=file]โ report the CPU time taken by each subprocess in the compilation sequence โฑ๏ธ. For C source files, that's the compiler proper and the assembler (plus the linker, if linking is happening).
Without specifying an output file, the output looks like this:
# cc1 0.12 0.01
# as 0.00 0.01
The first number on each line is the "user time" โ that's time spent executing the program itself. The second number is "system time" โ time spent executing operating system routines on behalf of the program. Both numbers are in seconds, bestie ๐
With an output file specified, the output gets appended to that named file, and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
Notice the glow-up: the "user time" and the "system time" move before the program name, and the options passed to the program get displayed too โ so later you can tell exactly what file was being compiled, and with which options. iconic ๐
-fdump-final-insns[=file]โ dump the final internal representation (RTL) to file ๐. If you leave the optional argument out (or if file is"."), the dump file's name is determined by appending".gkd"to the dump base name โ see-dumpbase.-fcompare-debug[=opts]โ if no error happens 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 you omit the equal sign, 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 string is used for opts โ otherwise the default -gtoggle is used.
-fcompare-debug=, with the equal sign but no opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation AND the second compilation โ it even stops 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). Just want a warning instead? 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 requested by-fcompare-debug, along with options to silence warnings, and it omits other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files get renamed so they contain the".gk"additional extension during the second compilation, so the first compilation's versions don't get overwritten ๐
When this option is passed to the compiler driver, it causes the first compilation to be skipped โ which makes it useful for little other than debugging the compiler proper ๐
-gtoggleโ turn off generation of debug info, if leaving out this option generates it; or turn it on at level 2 otherwise ๐. Where it sits in the command line does not matter โ it takes effect after all other options are processed, and it only does so once, no matter how many times you give it. This is mainly intended to be used with-fcompare-debug๐-fvar-tracking-assignments-toggleโ toggles-fvar-tracking-assignments, in 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โ record the time consumed by infrastructure parts separately for each pass ๐-fira-verbose=nโ control the verbosity of the dump file for the integrated register allocator. Default value is 5. And if n is greater or equal to 10, the dump output is 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 ๐ซถ-fprofile-reportโ makes the compiler print some statistics about consistency of the (estimated) profile and the effect of individual passes ๐-fstack-usageโ makes the compiler output stack usage information for the program, on a per-function basis ๐. The filename for the dump is made by appending.suto the auxname. And auxname is generated from the name of the output file, if it's explicitly specified and it's not an executable โ otherwise it's the basename of the source file. Each entry is made up of three fields:- The name of the function.
- A number of bytes.
- One or more qualifiers:
"static","dynamic","bounded".
The qualifier "static" means that the function manipulates the stack statically: a fixed number of bytes are allocated for the frame on function entry and released on function exit, and no stack adjustments are otherwise made in the function. In that case, the second field is this fixed number of bytes ๐
The qualifier dynamic is saying the function is out here moving the stack around at runtime โ like, on top of the static allocation we just talked about, it also does stack adjustments inside the body of the function, for example pushing and popping arguments around function calls. And if the bounded qualifier is hanging out there too? Then the amount of those adjustments is bounded at compile time, and that second field is an upper bound of the total amount of stack the function uses. If bounded is NOT there, then the amount of adjustments is not bounded at compile time, and that second field is only representing the bounded part. ๐
-fstatsโ emits statistics about front-end processing at the end of the compilation. Heads up bestie: this option is supported only 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. The counter-value-list is a comma-separated list of
name:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...]
tuples, which sets the name of the counter and the list of closed intervals. The lower_bound is optional and is zero initialized if not set. For example, with -fdbg-cnt=dce:2-4:10-11,tail_call:10, dbg_cnt(dce) returns true only for the second, third, fourth, tenth and eleventh invocation. For dbg_cnt(tail_call) true is returned for the first 10 invocations. Slay, math. โจ
-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.-print-multi-directoryโ prints the directory name corresponding to the multilib selected by any other switches present in the command line. This directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ prints the mapping from multilib directory names to compiler switches that enable them. The directory name is separated from the switches by;, and each switch starts with an@instead of the-, with no spaces between multiple switches. This is supposed to ease shell processing, iykyk. ๐-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.. 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. Many paths, much wow. ๐-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 doesn'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 doesn't do anything else.-dumpmachineโ prints the compiler's target machine (for example,i686-pc-linux-gnu) โ and doesn't do anything else.-dumpversionโ prints the compiler version (for example,3.0,6.3.0or7) โ and doesn'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 doesn'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 doesn'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โ generates code for the specified data model. The 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. ๐ซ
-mbig-endianโ generates big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target.-mgeneral-regs-onlyโ generates 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โ generates little-endian code. This is the default when GCC is configured for anaarch64-*-*but not anaarch64_be-*-*target.-mcmodel=tinyโ generates 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โ generates 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โ generates 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 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โ uses TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default.-mtls-dialect=traditionalโ uses traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables.-mtls-size=sizeโ specifies 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 number 835769. 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 number 843419. 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โ enable or disable the square root approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of square root results to about 16 bits for single precision and to 32 bits for double precision. If enabled, it implies-mlow-precision-recip-sqrt.-mlow-precision-div-mno-low-precision-divโ enable or disable the division approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of division results to about 16 bits for single precision and to 32 bits for double precision.-mtrack-speculation,-mno-track-speculationโ turn the generation of extra code that tracks speculative execution through conditional branches ON or OFF. That tracking state is then available for the compiler to use when it expands calls to__builtin_speculation_safe_copy, which lets it spit out a more efficient code sequence. โจ-moutline-atomics,-mno-outline-atomicsโ turn calls to out-of-line helpers for implementing atomic operations ON or OFF. At runtime those helpers figure out whether the LSE instructions from ARMv8.1-A are usable; if they're not, the helpers fall back to the load/store-exclusive instructions that live in the base ARMv8.0 ISA. ๐ซถ
This option only matters when you're compiling for the base ARMv8.0 instruction set. If you're on a later revision โ like -march=armv8.1-a or -march=armv8-a+lse โ the ARMv8.1-Atomics instructions get used directly. Same deal with -mcpu= when the cpu you picked supports the lse feature. This option is on by default. ๐
- *
-march=name* โ name the target architecture you want, and optionally tack on one or more feature modifiers. The shape of this option is-march=arch{+[no]feature}*.
Here's the table of what values of arch are allowed and which features each one turns on by default:
armv8-a: Armv8-A :+fp,+simdarmv8.1-a: Armv8.1-A :armv8-a,+crc,+lse,+rdmaarmv8.2-a: Armv8.2-A :armv8.1-aarmv8.3-a: Armv8.3-A :armv8.2-a,+pautharmv8.4-a: Armv8.4-A :armv8.3-a,+flagm,+fp16fml,+dotprodarmv8.5-a: Armv8.5-A :armv8.4-a,+sb,+ssbs,+predresarmv8.6-a: Armv8.6-A :armv8.5-a,+bf16,+i8mmarmv8.7-a: Armv8.7-A :armv8.6-a,+ls64armv8.8-a: Armv8.8-a :armv8.7-a,+mopsarmv9-a: Armv9-A :armv8.5-a,+sve,+sve2armv8-r: Armv8-R :armv8-r
The value native is available on native AArch64 GNU/Linux and makes the compiler pick the architecture of the host system. This option has no effect if the compiler is unable to recognize the architecture of the host system,
The allowed values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers get specified, the right-most feature is the one that wins. ๐
GCC uses name to decide what kind of instructions it's allowed to emit when it generates assembly code. If you specify -march without also specifying either -mtune or -mcpu, the code gets tuned to perform well across a whole range of target processors implementing the target architecture.
- *
-mtune=name* โ name the target processor GCC should tune the performance of the code for. The permissible values here are:generic,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,cortex-a76,cortex-a76ae,cortex-a77,cortex-a65,cortex-a65ae,cortex-a34,cortex-a78,cortex-a78ae,cortex-a78c,ares,exynos-m1,emag,falkor,neoverse-512tvb,neoverse-e1,neoverse-n1,neoverse-n2,neoverse-v1,neoverse-v2,grace,qdf24xx,saphira,phecda,xgene1,vulcan,octeontx,octeontx81,octeontx83,octeontx2,octeontx2t98,octeontx2t96octeontx2t93,octeontx2f95,octeontx2f95n,octeontx2f95mm,a64fx,thunderx,thunderxt88,thunderxt88p1,thunderxt81,tsv110,thunderxt83,thunderx2t99,thunderx3t110,zeus,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53,cortex-a75.cortex-a55,cortex-a76.cortex-a55,cortex-r82,cortex-x1,cortex-x2,cortex-a510,cortex-a710,ampere1,ampere1a,cobalt-100andnative. ๐ฆ
The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 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, the option tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle and that can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). This is more general than tuning for a specific core like Neoverse V1 but it's more specific than the default tuning described below. โจ
Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. This option has no effect if the compiler is unable to recognize the processor of the host system.
Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.
This option cannot be suffixed by feature modifiers. ๐ซ
- *
-mcpu=name* โ name the target processor, optionally suffixed by one or more feature modifiers. The shape of this option is-mcpu=cpu{+[no]feature}*, and the permissible values for cpu are exactly the same as the ones available for-mtune. The permissible values for feature are documented in the sub-section onaarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers get specified, the right-most feature is the one that wins. ๐
GCC uses name to decide what kind of instructions it can emit when generating assembly code (as if by -march) and to decide the target processor to tune performance for (as if by -mtune). When you use this option alongside -march or -mtune, those options take precedence over the appropriate part of this option.
-mcpu=neoverse-512tvb is special because it doesn't refer to one specific core โ instead it refers 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. Unless -mtune overrides it, -mcpu=neoverse-512tvb tunes code in the same way as -mtune=neoverse-512tvb. ๐
- *
-moverride=string* โ override the tuning decisions the back-end makes in response to a-mtune=switch. The syntax, semantics, and accepted values for string in this option are not guaranteed to be consistent across releases. ๐ญ
This option is only intended to be useful when you're developing GCC. (Compiler-dev main character energy only, bestie. ๐ง)
-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files. This option exists for use in debugging the compiler. ๐-mpc-relative-literal-loads,-mno-pc-relative-literal-loadsโ enable or disable PC-relative literal loads. With this option, literal pools are accessed using a single instruction and emitted after each function. This limits the maximum size of functions to 1MB. It's enabled by default for-mcmodel=tiny. ๐-msign-return-address=scope โ pick 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. > Heads up: this option has been **deprecated by-mbranch-protection. ๐-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ pick which branch protection features to use.noneis the default and turns off all types of branch protection.standardturns on all types of branch protection features. If a feature has additional tuning options, thenstandardsets 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 argumentleafcan be used to extend the signing to include leaf functions. The optional argumentb-keycan be used to sign the functions with the B-key instead of the A-key.btiturns on the branch target identification mechanism. ๐- *
-mharden-sls=opts* โ enable compiler hardening against straight line speculation (SLS). opts is a comma-separated list of the following options:retbrblr
Also, -mharden-sls=all enables all SLS hardening while -mharden-sls=none disables all SLS hardening. ๐ฅ
- *
-msve-vector-bits=bits* โ specify how many bits are in an SVE vector register. This option only has an effect 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. > 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 ๐ธ
Feature modifiers used with -march and -mcpu can be any of the following and their inverses nofeature:
crcโ Enable CRC extension. This is on by default for-march=armv8.1-a. โจcryptoโ Enable Crypto extension. This also enables Advanced SIMD and floating-point instructions. ๐fpโ Enable floating-point instructions. This is on by default for all possible values for options-marchand-mcpu. ๐simdโ Enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for options-marchand-mcpu. ๐sveโ Enable Scalable Vector Extension instructions. This also enables Advanced SIMD and floating-point instructions. ๐lseโ Enable Large System Extension instructions. This is on by default for-march=armv8.1-a. ๐rdmaโ Enable Round Double Multiply Accumulate instructions. This is on by default for-march=armv8.1-a. ๐ซถfp16โ Enables the FP16 extension. This also enables floating-point instructions. โจfp16fmlโ Enables FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. This option is enabled by default for-march=armv8.4-a. Use of this option with architectures prior to Armv8.2-A is not supported. ๐rcpcโ Enables the RcPc extension. This does not change code generation from GCC, but is passed on to the assembler, enabling inline asm statements to use instructions from the RcPc extension. ๐dotprodโ Enables the Dot Product extension. This also enables Advanced SIMD instructions.aesโ Enables the Armv8-a aes and pmull crypto extension. This also enables Advanced SIMD instructions.sha2โ Enables the Armv8-a sha2 crypto extension. This also enables Advanced SIMD instructions.sha3โ Enables the sha512 and sha3 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.sm4โ Enables the sm3 and sm4 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.profileโ Enables the Statistical Profiling extension. This option 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. This option is only to enable the extension at the assembler level and 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. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.ssbsโ Enables the Armv8-a Speculative Store Bypass Safe instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.predresโ Enables the Armv8-a Execution and Data Prediction Restriction instructions. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.sve2โ Enables the Armv8-a Scalable Vector Extension 2. This also enables SVE instructions.sve2-bitpermโ Enables SVE2 bitperm instructions. This also enables SVE2 instructions.sve2-sm4โ Enables SVE2 sm4 instructions. This also enables SVE2 instructions.sve2-aesโ Enables SVE2 aes instructions. This also enables SVE2 instructions.sve2-sha3โ Enables SVE2 sha3 instructions. This also enables SVE2 instructions.tmeโ Enables the Transactional Memory Extension.i8mmโ Enables 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.f32mmโ Enables 32-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.f64mmโ Enables 64-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.bf16โ Enables brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.ls64โ Enables the 64-byte atomic load and store instructions for accelerators. This option is enabled by default for-march=armv8.7-a.mopsโ Enables the instructions to accelerate memory operations likememcpy,memmove,memset. This option is enabled by default for-march=armv8.8-aflagmโ Enables the Flag Manipulation instructions Extension.pauthโ Enables the Pointer Authentication Extension.
Oh and bestie, crypto implies aes, sha2, and simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. ๐
โจ Adapteva Epiphany Options โจ
These -m options are defined for Adapteva Epiphany:
-mhalf-reg-fileโ Don't allocate any register in the ranger32...r63. That allows code to run on hardware variants that lack these registers.-mprefer-short-insn-regsโ Preferentially allocate registers that allow short instruction generation. This can result in increased instruction count, so this may either reduce or increase overall code size.-mbranch-cost=numโ Set the cost of branches to roughly num "simple" instructions. This cost is only a heuristic and is not guaranteed to produce consistent results across releases.-mcmoveโ Enable the generation of conditional moves.-mnops=numโ Emit num NOPs before every other generated instruction.-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.-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. Note also that this option changes the ABI; compiling a program with a different stack offset than the libraries have been compiled with generally does not work. This option can be useful if you want to evaluate if a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate--with-stack-offset=numoption.
โ ๏ธ Bestie, this is an ABI change! Don't mix and match stack offsets with your libs, or it's gonna be a bad time. ๐
-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. 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.
mode can be set to one 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โ Code generation tweak that disables splitting of 32-bit loads.-mno-postincโ Code generation tweak that disables generation of post-increment addresses.-mno-postmodifyโ Code generation tweak that disables generation of post-modify addresses.
The defaults are msplit-lohi, -mpost-inc, and -mpost-modify.
-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. num may 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.-msplit-vecmove-earlyโ Split vector moves into single word moves before reload. In theory this can give better register allocation, but so far the reverse seems to be generally the case.-m1reg-regโ Specify a register to hold the constant -1, which makes loading small negative constants and certain bitmasks faster. Allowable values for reg arer43andr63, which specify use of that register as a fixed register, andnone, which means that no register is used for this purpose. The default is-m1reg-none.
๐ฎ AMD GCN Options ๐ฎ
These options are defined specifically for the AMD GCN port.
-march=gpu,-mtune=gpuโ Set architecture type or tuning for gpu. Supported values for gpu are:fijiโ Compile for GCN3 Fiji devices (gfx803).gfx900โ Compile for GCN5 Vega 10 devices (gfx900).gfx906โ Compile for GCN5 Vega 20 devices (gfx906).
-msram-ecc=on-msram-ecc=off-msram-ecc=anyโ compile binaries that'll behave on devices where the SRAM-ECC feature is on, off, or either way โจ On some devices you can flip this per-process, so like... the compiled code has to match whatever mode the device is actually in, no cap. Default isany, but only for the devices that support it ๐ซถ-mstack-size=bytesโ how many bytes of stack space each GPU thread (wave-front) gets to ask for ๐ธ Heads up bestie: there can be a lot of threads and the memory is limited, so don't go wild. Also the size of the stack allocation can lowkey affect run-time performance ๐ Default is32KBwhen you're using OpenACC or OpenMP, and1MBotherwise.-mxnackโ compile binaries that are suitable for devices with the XNACK feature enabled. Some devices always need XNACK, some let the user configure it, and the compiled code has to match the device mode, periodt. Default is-mno-xnack. And ngl, right now this option is just a placeholder for support that isn't implemented yet ๐
๐ ARC Options ๐
These ones control which architecture variant the code is getting compiled for, iykyk:
-mbarrel-shifterโ generate instructions that the barrel shifter supports ๐ This is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect.-mjli-alwaysโ force calling a function using thejli_sinstruction. Only valid for ARCv2 architecture, fr fr.-mcpu=cpuโ set the architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options 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.arc600_normโ compile for ARC 600 CPU with "norm" instructions enabled.arc600_mul32x16โ compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.arc601_normโ compile for ARC 601 CPU with "norm" instructions enabled.arc601_mul32x16โ compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring reduced register set.
-mdpfp-mdpfp-compactโ generate double-precision FPX instructions, tuned for the compact implementation ๐-mdpfp-fastโ generate double-precision FPX instructions, tuned for the fast implementation โก-mno-dpfp-lrsrโ disable thelrandsrinstructions 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. Heads up: 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โ okay so this option is ignored; it's provided for compatibility purposes only ๐ Software floating-point code is emitted by default, and that default can be overridden by the 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, periodt.
-mfpu=fpuโ enables support for specific floating-point hardware extensions for ARCv2 cores โจ Supported values for fpu are:fpusโ enables support for single-precision floating-point hardware extensions.fpudโ enables support for double-precision floating-point hardware extensions. The single-precision floating-point extension is also enabled. Not available for ARC EM.fpudaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point extension is also enabled. This option is only available for ARC EM.fpuda_divโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point, square-root, and divide extensions are also enabled. This option is only available for ARC EM.fpuda_fmaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point and fused multiply and add hardware extensions are also enabled. This option is only available for ARC EM.fpuda_allโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. All single-precision floating-point hardware extensions are also enabled. This option is only available for ARC EM.fpus_divโ enables support for single-precision floating-point, square-root and divide hardware extensions.fpud_divโ enables support for double-precision floating-point, square-root and divide hardware extensions. This option includes optionfpus_div. Not available for ARC EM.fpus_fmaโ enables support for single-precision floating-point and fused multiply and add hardware extensions.fpud_fmaโ enables support for double-precision floating-point and fused multiply and add hardware extensions. This option includes optionfpus_fma. Not available for ARC EM.fpus_allโ enables support for all single-precision floating-point hardware extensions.fpud_allโ enables support for all single- and double-precision floating-point hardware extensions. Not available for ARC EM.
-mirq-ctrl-saved=register-range, blink, lp_countโ specifies general-purpose registers that the processor automatically saves/restores on interrupt entry and exit ๐ register-range is specified as two registers separated by a dash. The register range always starts withr0, and the upper limit is thefpregister. blink and lp_count are optional. This option is only valid for ARC EM and ARC HS cores, bestie.-mrgf-banked-regs=numberโ okay so when you roll into a fast interrupt (and bestie, fast interrupts are the ones at the highest priority level, P0 โจ), this tells the compiler how many registers get replicated in the second register bank. These interrupts only savePCandSTATUS32, so they can dodge memory transactions during interrupt entry and exit โ iconic efficiency tbh ๐ . Reach for this when you're doing fast interrupts on an ARC V2 family processor. Allowed values are literally just4,8,16, and32. no in-between, no vibes-based numbers ๐-mlpc-width=widthโ sets the width of thelp_countregister. Valid widths:8,16,20,24,28,32bits. The default width is locked to 32 bits. Here's the tea though: if the width is under 32, the compiler won't try to turn your loops into the zero-delay loop mechanism unless it knowslp_countcan hold the loop-counter value you need. Depending on what width you picked, the compiler and the run-time library might still use the loop mechanism for various other needs. Also, 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. It defines the__ARC_RF16__preprocessor macro ๐ฆ-mbranch-indexโ turns on use ofbiorbihinstructions to implement jump tables ๐ฅ
The next batch? These get passed through to the assembler, and they define preprocessor macro symbols. two-for-one, we love a multitasker ๐
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol__Xdsp_packa. Heads up: this one is deprecated ๐-mdvbfโ passed down to the assembler to enable the dual Viterbi butterfly extension. Also sets the preprocessor symbol__Xdvbf. Deprecated, bestie ๐-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. Deprecated ๐-mmac-24โ passed down to the assembler. Also sets the preprocessor symbol__Xxmac_24. Deprecated ๐-mrtscโ passed down to the assembler to enable the 64-bit time-stamp counter extension instruction. Also sets the preprocessor symbol__Xrtsc. 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. Deprecated ๐-mxyโ passed down to the assembler to enable the XY memory extension. Also sets the preprocessor symbol__Xxyโจ
Next up: how the assembly code gets annotated. aesthetic decisions, basically ๐
-misizeโ annotates assembler instructions with estimated addresses ๐-mannotate-alignโ explains what alignment considerations led to the decision to make an instruction short or long. like, it spills the reasoning ๐ซถ
And these ones get passed straight through to the linker:
-marclinuxโ passed through to the linker to specify use of thearclinuxemulation. This option is on by default in tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets when profiling is not requested ๐-marclinux_profโ passed through to the linker to specify use of thearclinux_profemulation. This one is on by default in tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets when profiling is requested ๐
Now we're in the semantics of generated code. the personality of your binary, if you will ๐
-mlong-callsโ generates calls as register indirect calls, which gives you access to the full 32-bit address range ๐-mmedium-callsโ don't use less than a 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. Conditional execution of function calls gets suppressed so you can use the 25-bit range instead of the 21-bit range with conditional branch-and-link. This is the default for tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets โญ-G numโ puts definitions of externally-visible data in a small data section if that data is no bigger than num bytes. Default num is4for any ARC configuration, or8when there are double load/store operations ๐ฆ-mno-sdataโ don't generate sdata references. This is the default for tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets ๐-mvolatile-cacheโ use ordinarily cached memory accesses for volatile references. This is the default โจ-mno-volatile-cacheโ enable cache bypass for volatile references ๐
And here come the fine-tuners, the little knobs for code generation ๐๏ธ
-malign-callโ does nothing. Preserved for backward compatibility. it's giving decorative ๐-mauto-modify-regโ enable the use of pre/post modify with register displacement ๐ง-mbbit-peepholeโ enable bbit peephole2 ๐-mno-brccโ disables a target-specific pass inarc_reorgto generate compare-and-branch (brcc) instructions. It has no effect on generation of these instructions driven by the combiner pass โ ๏ธ-mcase-vector-pcrelโ use PC-relative switch case tables to enable case table shortening. This is the default for-Os๐-mcompact-casesiโ enable the compactcasesipattern. This is the default for-Os, and it's only available for ARCv1 cores. This option is deprecated ๐-mno-cond-execโ disable the ARCompact-specific pass that generates conditional execution instructions.
Okay so the long version, because this one's actually interesting: due to delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass to generate conditional execution is often lacking. So the ARC port kept a special pass around that hunts for more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling are done. This pass generally โ but not always โ improves performance and code size, at the cost of extra compilation time. That's exactly why there's an option to switch it off. And if you're hitting a problem where call instructions blow past their allowable offset range because they got conditionalized? You should consider using -mmedium-calls instead ๐ซถ
-mearly-cbranchsiโ enable pre-reload use of thecbranchsipattern ๐ฑ-mexpand-adddiโ expandadddi3andsubdi3at RTL generation time intoadd.f,adcetc. This option is deprecated ๐-mindexed-loadsโ enable the use of indexed loads. Careful, because this can be problematic: some optimizers will then assume that indexed stores exist, and they do not ๐ญ-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 using a call to a special function in libgcc; this is called a millicode call. Since these calls can cause performance issues, and/or linking issues when you're linking in a nonstandard way, this option exists so you can turn millicode call generation on or off ๐๏ธ-mcode-density-frameโ lets the compiler emitenterandleaveinstructions. These are only valid for CPUs with the code-density feature ๐-mmixed-codeโ does nothing. Preserved for backward compatibility. another decorative icon ๐-mq-classโ this option is deprecated. Enables q instruction alternatives. This is the default for-Osโจ-mRcqโ enable Rcq constraint handling. Most short code generation depends on this. This is the default ๐-mRcwโ enable Rcw constraint handling. Most ccfsm condexec mostly depends on this. This is the default ๐-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, when this isn't set, the behavior is equivalent to level 1 ๐
-mtune=cpuโ set instruction scheduling parameters for cpu, overriding anything implied by-mcpu=. Supported values for cpu are:ARC600โ tune for ARC600 CPU.ARC601โ tune for ARC601 CPU.ARC700โ tune for ARC700 CPU with standard multiplier block.ARC700-xmacโ tune for ARC700 CPU with XMAC block.ARC725Dโ tune for ARC725D CPU.ARC750Dโ tune for ARC750D CPU.
-mmultcost=numโ the cost to assume for a multiply instruction, with4being equal to a normal instruction โ๏ธ-munalign-prob-threshold=probabilityโ does nothing. Preserved for backward compatibility ๐
โ ๏ธ bestie listen. The next batch is kept around for backward compatibility, but it's deprecated and will be removed in a future release. Do not build your whole personality on these ๐
-margonautโ obsolete FPX ๐ชฆ-mbig-endian,-EBโ compile code for big-endian targets. Use of these options is now deprecated. Big-endian code is supported by configuring GCC to buildarceb-elf32andarceb-linux-uclibctargets, for which big endian is the default ๐-mlittle-endian,-ELโ compile code for little-endian targets. Use of these options is now deprecated. Little-endian code is supported by configuring GCC to 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. the underscore era is OVER bestie ๐-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 have been replaced byARC600,ARC601,ARC700andARC700-xmacrespectively. glow-up szn โจ-multcost=numโ replaced by-mmultcost.
๐ฆ ARM Options ๐ฆ
ok so these -m options are the ones defined for the ARM port, and there are a LOT of them so grab a snack ๐
-mabi=nameโ generate code for the ABI you name. 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 when it's not strictly necessary for the code to run correctly. heads up: if you also pass-fomit-frame-pointerwith this, then stack frames won't be generated for leaf functions. the default is-mno-apcs-frame. > โ ๏ธ this option is deprecated โ it's giving legacy, don't build your whole personality on it.-mapcsโ this is just a synonym for-mapcs-frame, and yeah, it's deprecated too.-mthumb-interworkโ generate code that supports calling between the ARM and Thumb instruction sets. without this option, on pre-v5 architectures, you literally cannot reliably use the two instruction sets inside one program, no cap ๐ญ. the default is-mno-thumb-interwork, because specifying-mthumb-interworkgenerates slightly larger code. in AAPCS configurations this option is meaningless (vibe check: it does nothing there).-mno-sched-prologโ stop the reordering of instructions in the function prologue, and stop them merging with the instructions in the function's body. what that buys you: every function starts with a recognizable set of instructions (or honestly just one from a small choice of different function prologues), and that info can be used to locate where functions start inside an executable piece of code. the default is-msched-prolog.-mfloat-abi=nameโ tells GCC which floating-point ABI to use. permissible values are:soft,softfpandhard.softmakes GCC generate output that contains library calls for floating-point operations.softfpallows generating code that uses hardware floating-point instructions, but it still uses the soft-float calling conventions.hardallows generation of floating-point instructions and uses FPU-specific calling conventions.
the default depends on the specific target configuration. ๐ข note well: the hard-float and soft-float ABIs are not link-compatible; you have to compile your entire program with the same ABI and link with a compatible set of libraries. do not mix, it will not slay, it will just break ๐ซ
-mgeneral-regs-onlyโ generate code that uses only the general-purpose registers. this stops the compiler from using floating-point and Advanced SIMD registers, but it puts no restrictions on the assembler.-mlittle-endianโ generate code for a processor running in little-endian mode. this is the default for all standard configurations. main character default energy ๐-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, pick between BE8 and BE32 formats. this option has no effect for little-endian images and is ignored. the default depends on the selected target architecture: for ARMv6 and later architectures the default is BE8, and for older architectures the default is BE32. > ๐ BE32 format has been deprecated by ARM.-march=name[+extension...]โ this specifies the name of the target ARM architecture. GCC uses this name to figure out what kind of instructions it can emit when generating assembly code. you can use this option together 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. you add them by appending +extension to the architecture name. extension options get processed in order and capabilities accumulate. an extension will also enable any necessary base extensions that it depends on โ for example, the +crypto extension will always enable the +simd extension. the one exception to the additive construction is for extensions prefixed with +no...: those disable the specified option and any other extensions that may depend on that extension being present.
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 comes after it. the way that ordering MATTERS ๐ค
most extension names are generically named, but their effect depends on the architecture you apply them to. for example, the +simd option can be applied to both armv7-a and armv8-a architectures, but it enables 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 it 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, with 16 double-precision registers.+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers.+neonโ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extension+neon-vfpv3can be used as an alias for this extension.+neon-fp16โ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.+nosimdโ disable the Advanced SIMD instructions (does not disable floating point).+nofpโ disable the floating-point and Advanced SIMD instructions.
armv8-a+crcโ the Cyclic Redundancy Check (CRC) instructions.+simdโ the ARMv8-A Advanced SIMD and floating-point instructions.+cryptoโ the cryptographic instructions.
+nocryptoโ Disable the cryptographic instructions. Bye bye crypto, not today. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. It's giving "no math, no vectors, no crypto" energy. ๐+sbโ Speculation Barrier Instruction. Slay that speculation. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. Keeping predictions on a leash, periodt. ๐armv8.1-aโ okay bestie, this architecture is iconic and here's what you can toggle:+simdโ The ARMv8.1-A Advanced SIMD and floating-point instructions. Vector math? Obsessed. โจ+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions. Crypto plus SIMD plus FP? A whole meal. ๐+nocryptoโ Disable the cryptographic instructions. Not me turning crypto off. ๐+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. It's giving "none of that, thanks". ๐+sbโ Speculation Barrier Instruction. No cap, keep it safe. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. Restrict those predictions, bestie. ๐
armv8.2-aโ this one is just here, living its best life. No extra+toggles listed in this stretch. ๐ธarmv8.3-aโ okay this one ate and left no crumbs. Here's the whole menu:+fp16โ The half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions. Half precision? More like half the storage, double the slay. ๐+fp16fmlโ The half-precision floating-point fmla extension. This also enables the half-precision floating-point extension and Advanced SIMD and floating-point instructions. FML? Not today, this is fmla. ๐ญ+simdโ The ARMv8.1-A Advanced SIMD and floating-point instructions. SIMD girlies rise. โจ+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions. Crypto + SIMD + FP, a trio. ๐+dotprodโ Enable the Dot Product extension. This also enables Advanced SIMD instructions. Dot product? She's multiplying and she's proud. ๐งฎ+nocryptoโ Disable the cryptographic extension. Crypto off, peace out. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. No FP, no SIMD, no crypto. A clean slate. ๐+sbโ Speculation Barrier Instruction. Speculation barrier? She's a wall. ๐งฑ+predresโ Execution and Data Prediction Restriction Instructions. Restrict the predictions, periodt. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. 8-bit matrix math? She's smart. ๐ง+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. Brain float? Literally brainy. ๐ง
armv8.4-aโ this one is stacked, bestie. Here's the tea:+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. That's a lot of enabling, and she's doing it flawlessly. ๐+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. SIMD plus dot product? A combo meal. ๐+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. Crypto bringing friends. ๐+nocryptoโ Disable the cryptographic extension. Crypto off. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. No FP, no SIMD, no crypto. ๐+sbโ Speculation Barrier Instruction. Barrier up. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. Restrict those predictions. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. Matrix multiply? She's doing math. ๐งฎ+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. Brainy float. ๐ง
armv8.5-aโ another iconic arch, but check the list, because it's slightly different:+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. Half precision, full slay. ๐+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. SIMD and dot product, a dynamic duo. โจ+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. Crypto with the entourage. ๐+nocryptoโ Disable the cryptographic extension. No crypto. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. No FP, no SIMD, no crypto. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. 8-bit matrix math. ๐ง+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. Brain float, literally. ๐ง
armv8.6-aโ same energy as 8.5-a, bestie. Here we go:+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. Half precision, full send. ๐+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. SIMD and dot product. โจ+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. Crypto plus friends. ๐+nocryptoโ Disable the cryptographic extension. Crypto off. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. No FP, no SIMD, no crypto. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. Matrix multiply. ๐งฎ+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. Brain float. ๐ง
armv7-rโ okay bestie, this one is giving classic ARM vibes. Here's the list:+fp.spโ The single-precision VFPv3 floating-point instructions. The extension+vfpv3xdcan be used as an alias for this extension. Single precision? She's precise. ๐ฏ+fpโ The VFPv3 floating-point instructions with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension. 16 double-precision registers? That's a lot of storage. ๐พ+vfpv3xd-d16-fp16โ The single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. A whole mouthful, but she ate. ๐+vfpv3-d16-fp16โ The VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. VFPv3 plus half precision? Okay. โจ+nofpโ Disable the floating-point extension. No FP. ๐ซ+idivโ The ARM-state integer division instructions. Integer division? She's dividing. โ+noidivโ Disable the ARM-state integer division extension. No integer division. ๐ซ
armv7e-mโ embedded vibes, bestie. Here's what's on the menu:+fpโ The single-precision VFPv4 floating-point instructions. Single precision VFPv4. ๐ฏ+fpv5โ The single-precision FPv5 floating-point instructions. FPv5, single precision. โจ+fp.dpโ The single- and double-precision FPv5 floating-point instructions. Single and double precision? Versatile. ๐+nofpโ Disable the floating-point extensions. No FP extensions. ๐ซ
armv8.1-m.mainโ M-profile main character energy. Here's the tea:+dspโ The DSP instructions. DSP, she's processing signals. ๐ถ+mveโ The M-Profile Vector Extension (MVE) integer instructions. MVE integer, vector vibes. โจ+mve.fpโ The M-Profile Vector Extension (MVE) integer and single precision floating-point instructions. MVE plus single precision FP. ๐+fpโ The single-precision floating-point instructions. Single precision FP. ๐ฏ+fp.dpโ The single- and double-precision floating-point instructions. Single and double FP. ๐+nofpโ Disable the floating-point extension. No FP. ๐ซ+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. CDE on coprocessors 0 through 7, pick your fighter. ๐ฎ
armv8-m.mainโ another M-profile baddie. Here's the list:+dspโ The DSP instructions. DSP. ๐ถ+nodspโ Disable the DSP extension. No DSP. ๐ซ+fpโ The single-precision floating-point instructions. Single precision FP. ๐ฏ+fp.dpโ The single- and double-precision floating-point instructions. Single and double FP. ๐+nofpโ Disable the floating-point extension. No FP. ๐ซ+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. CDE on coprocessors 0 to 7. ๐ฎ
armv8-rโ real-time vibes, bestie. Here's what you can toggle:+crcโ The Cyclic Redundancy Check (CRC) instructions. CRC, checking that redundancy. ๐+fp.spโ The single-precision FPv5 floating-point instructions. Single precision FPv5. ๐ฏ+simdโ The ARMv8-A Advanced SIMD and floating-point instructions. ARMv8-A SIMD and FP. โจ+cryptoโ The cryptographic instructions. Crypto. ๐+nocryptoโ Disable the cryptographic instructions. No crypto. ๐ซ+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. No FP, no SIMD, no crypto. ๐
-march=nativeโ causes the compiler to auto-detect the architecture of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. So if it doesn't work, it just shrugs and does nothing. ๐คทโโ๏ธ-mtune=nameโ bestie, this one picks which target ARM processor GCC should tune the code's performance for. Some ARM implementations just run better when you tell the compiler to aim at them. 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-x1,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,xgene1.
And likeโฆ plot twist ๐ซถ this option can ALSO say "tune for a big.LITTLE system." Permissible names for that are: cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55.
-mtune=generic-arch means "tune for a whole blend of processors inside architecture arch." The goal is code that runs well on the current most popular processors โ balancing optimizations that help some CPUs in the range while dodging the performance pitfalls of the others. Heads up tho: what this option actually does may shift in future GCC versions, because CPU models come and go. It's giving main character energy that keeps evolving ๐
-mtune accepts the same extension options as -mcpu, but those extension options do not affect the tuning of the generated code. Just so we're clear.
-mtune=native makes the compiler auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful, the option has no effect. (No effect at all. It justโฆ sits there. ๐)
-mcpu=name[+extension...]โ this one names the target ARM processor. GCC uses the name to derive the target ARM architecture (as if you'd written-march) and the ARM processor type to tune performance for (as if you'd written-mtune). Where this option is used in conjunction with-marchor-mtune, those options take precedence over the appropriate part of this option. Precedence, bestie. It's a whole thing.
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 the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions. Whew. Okay. So many moving parts, but we got this โจ
For example, cortex-a9 can be found in three major configurations: integer only, with just a floating-point unit, or with floating-point and Advanced SIMD. The default is to enable all the instructions, but the extensions +nosimd and +nofp can be used to disable just the SIMD, or both the SIMD and floating-point instructions respectively.
Permissible names for this option are the same as those for -mtune. (Same list, different job. Slay.)
The following extension options are common to the listed CPUs:
+nodspโ Disable the DSP instructions oncortex-m33,cortex-m35p.+nofpโ Disables the floating-point instructions onarm9e,arm946e-s,arm966e-s,arm968e-s,arm10e,arm1020e,arm1022e,arm926ej-s,arm1026ej-s,cortex-r5,cortex-r7,cortex-r8,cortex-m4,cortex-m7,cortex-m33andcortex-m35p. Disables the floating-point and SIMD instructions ongeneric-armv7-a,cortex-a5,cortex-a7,cortex-a8,cortex-a9,cortex-a12,cortex-a15,cortex-a17,cortex-a15.cortex-a7,cortex-a17.cortex-a7,cortex-a32,cortex-a35,cortex-a53andcortex-a55.+nofp.dpโ Disables the double-precision component of the floating-point instructions oncortex-r5,cortex-r7,cortex-r8,cortex-r52,cortex-r52plusandcortex-m7.+nosimdโ Disables the SIMD (but not floating-point) instructions ongeneric-armv7-a,cortex-a5,cortex-a7andcortex-a9.+cryptoโ Enables the cryptographic instructions oncortex-a32,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,exynos-m1,xgene1,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53andcortex-a75.cortex-a55.
Additionally, the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a.
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information.
-mcpu=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful, the option has no effect. (Again! It just does nothing. Iconic behavior honestly ๐
)
-mfpu=nameโ specifies what floating-point hardware (or hardware emulation) is available on the target. Permissible names are:auto,vfpv2,vfpv3,vfpv3-fp16,vfpv3-d16,vfpv3-d16-fp16,vfpv3xd,vfpv3xd-fp16,neon-vfpv3,neon-fp16,vfpv4,vfpv4-d16,fpv4-sp-d16,neon-vfpv4,fpv5-d16,fpv5-sp-d16,fp-armv8,neon-fp-armv8andcrypto-neon-fp-armv8. Note thatneonis an alias forneon-vfpv3andvfpis an alias forvfpv2.
The setting auto is the default and is special. It causes the compiler to select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.
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. Why? 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. ๐ซฃ Yes bestie, precision loss. Real talk.
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. No type for you. Bye ๐
-mstructure-size-boundary=nโ The sizes of all structures and unions get rounded up to a multiple of the number of bits set by this option. Permissible values are8,32and64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is8. A value of64is only allowed if the underlying ABI supports it.
Specifying a larger number can produce faster, more efficient code, but 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. ๐จ Mixing values = chaos. Be careful.
This option is deprecated. It's giving legacy. It's giving "we don't do this anymore." ๐ฅ
-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. Like, sir, you said you'd never return, and yet. ๐ค
-mlong-calls-mno-long-calls
Tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction.
Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the "short_call" attribute, functions that are inside the scope of a "#pragma no_long_calls" directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the "long_call" attribute or the "section" attribute, and functions that are within the scope of a "#pragma long_calls" directive are always turned into long calls. So many exceptions, so little time ๐
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a "#pragma long_calls_off" directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers. Nope. Zero. None.
-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. That's on you, runtime bestie ๐ซถ
-mpic-register=regโ Specify the register to be used for PIC addressing. For standard PIC base case, the default is any suitable register determined by compiler. For single PIC base case, the default isR9if target is EABI based or stack-checking is enabled, otherwise the default isR10.-mpic-data-is-text-relativeโ bestie, this one says: assume the gap between the text segment and the data segment is locked in at static link time. That means we can use PC-relative addressing to grab stuff we already know lives in the data segment. For non-VxWorks RTP targets this is on by default. And the tea is: if you turn it off on those targets, it quietly turns on-msingle-pic-basefor you. ๐ซถ-mpoke-function-nameโ writes the name of every function right into the text section, sitting directly in front of the function prologue. The generated code looks like this:
t0
.ascii "arm_poke_function_name", 0
.align
t1
.word 0xff000000 + (t1 - t0)
arm_poke_function_name
mov ip, sp
stmfd sp!, {fp, ip, lr, pc}
sub fp, ip, #4
So when you're doing a stack backtrace, the code can peek at 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 before that location, and its length is ((pc[-3]) & 0xff000000). โจ
-mthumb,-marmโ pick your fighter: do you want code that runs in ARM state or Thumb state? For most configurations the default is ARM state, but that default can be changed by configuring GCC with the--with-mode=stateconfigure option.
You can also override ARM vs Thumb per-function using the target("thumb") and target("arm") function attributes or pragmas. Slay. ๐
-mflip-thumbโ flips between ARM and Thumb modes on alternating functions. This one exists purely for regression testing of mixed Thumb/ARM codegen. Not for ordinary compiling, bestie, it's giving lab-coat energy, not production energy. ๐งช-mtpcs-frameโ generates a stack frame that's compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that doesn't call any other functions.) The default is-mno-tpcs-frame.-mtpcs-leaf-frameโ generates a stack frame that's compliant with the Thumb Procedure Call Standard for all leaf functions. (A leaf function is one that does not call any other functions.) The default is-mno-apcs-leaf-frame.-mcallee-super-interworkingโ gives every externally visible function in the file being compiled an ARM instruction set header that switches to Thumb mode before running the rest of the function. This lets those functions get called from non-interworking code. Heads up: this option is not valid in AAPCS configurations, because interworking is already enabled by default there. ๐-mcaller-super-interworkingโ lets calls through function pointers (virtual functions included) execute correctly whether or not the target code was compiled for interworking. The catch: there's a small overhead cost when executing a function pointer if this is enabled. Also not valid in AAPCS configurations, because interworking is enabled by default there. ๐-mtp=nameโ specify the access model for the thread local storage pointer. Valid models are:softโ generates calls to__aeabi_read_tpcp15โ fetches the thread pointer straight fromcp15(supported in the arm6k architecture)autoโ uses the best available method for the selected processor
Default setting is auto. ๐
-mtls-dialect=dialectโ specify which dialect to use for accessing thread local storage. Two are supported:gnuandgnu2. Thegnudialect picks the original GNU scheme for supporting local and global dynamic TLS models. Thegnu2dialect picks the GNU descriptor scheme, which gives 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 that restriction, and whenever-fpicor-fPICis specified. This option conflicts with-mslow-flash-data.-mfix-cortex-m3-ldrdโ some Cortex-M3 cores can cause data corruption whenldrdinstructions with overlapping destination and base registers get used. This option avoids generating those instructions. Enabled by default when-mcpu=cortex-m3is specified. ๐ก๏ธ-mfix-cortex-a57-aes-1742098,-mno-fix-cortex-a57-aes-1742098,-mfix-cortex-a72-aes-1655431,-mno-fix-cortex-a72-aes-1655431โ enable (or 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 16- and 32-bit values from addresses that aren't 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 isn't enabled, words in packed data structures get accessed one byte at a time.
The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending on the setting of this option. And if unaligned access is enabled, 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 vibe. ๐-mslow-flash-dataโ assume loading data from flash is slower than fetching instructions. So literal loads get minimized for better performance. Only supported when compiling for ARMv7 M-profile, and off by default. It conflicts with-mword-relocations.-masm-syntax-unifiedโ assume inline assembler is using unified asm syntax. The default is currently off, which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated. ๐-mrestrict-itโ restricts generation of IT blocks so they conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. On by default for ARMv8-A Thumb mode.-mprint-tune-infoโ print CPU tuning info as a comment in the assembler file. This is only for regression testing of the compiler and is not intended for ordinary use in compiling code. Disabled by default. ๐งช-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files. Provided for use in debugging the compiler.-mpure-codeโ do not allow constant data to be placed in code sections. Also, when compiling for ELF object format, give all text sections the ELF processor-specific section attributeSHF_ARM_PURECODE. 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 you can find at <https://developer.arm.com/documentation/ecm0359818/latest/>. ๐-mfix-cmse-cve-2021-35465โ mitigate against a potential security issue with theVLLDMinstruction in some M-profile devices when using CMSE (CVE-2021-365465). This option is enabled by default when the option-mcpu=is used withcortex-m33,cortex-m35porcortex-m55. You can use-mno-fix-cmse-cve-2021-35465to disable the mitigation. ๐ก๏ธ-mstack-protector-guard=guard,-mstack-protector-guard-offset=offsetโ generate stack protection code using a 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 forarm-*-uclinuxfdpiceabitargets, this option is on by default and implies-fPIEif none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and you should explicitly provide the PIC/PIE-related options as needed.
Note that static linking is not supported, because it would still involve the dynamic linker when the program self-relocates. If such behavior is acceptable, use -static and -Wl,-dynamic-linker options.
The opposite -mno-fdpic option is useful (and required) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs. ๐ง
โจ AVR Options โจ
These options are defined for AVR implementations:
-mmcu=mcuโ specify Atmel AVR instruction set architectures (ISA) or MCU type.
The default for this option is avr2.
GCC supports the following AVR devices and ISAs:
"avr2"โ "Classic" devices with up to 8 KiB of program memory.- mcu =
"attiny22","attiny26","at90s2313","at90s2323","at90s2333","at90s2343","at90s4414","at90s4433","at90s4434","at90c8534","at90s8515","at90s8535".
- mcu =
"avr25"โ "Classic" devices with up to 8 KiB of program memory and with theMOVWinstruction.- mcu =
"attiny13","attiny13a","attiny24","attiny24a","attiny25","attiny261","attiny261a","attiny2313","attiny2313a","attiny43u","attiny44","attiny44a","attiny45","attiny48","attiny441","attiny461","attiny461a","attiny4313","attiny84","attiny84a","attiny85","attiny87","attiny88","attiny828","attiny841","attiny861","attiny861a","ata5272","ata6616c","at86rf401".
- mcu =
"avr3"โ "Classic" devices with 16 KiB up to 64 KiB of program memory.- mcu =
"at76c711","at43usb355".
- mcu =
"avr31"โ "Classic" devices with 128 KiB of program memory.- mcu =
"atmega103","at43usb320".
- mcu =
"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 is supported for assembler only ๐ซ . mcu ="attiny11","attiny12","attiny15","attiny28","at90s1200".
-mabsdataโ bestie, this one tells the compiler to assume that literally all data in static storage can be reached withLDS/STSinstructions. It only does anything on reduced Tiny devices like ATtiny40. Also peep the"absdata"AVR Variable Attributes variable attribute โจ.-maccumulate-argsโ stack space for outgoing function arguments gets accumulated, and the needed room for those outgoing args is acquired/released once in the function prologue/epilogue. Without this flag, outgoing arguments are pushed right before calling a function and popped right after. On AVR, popping the args after the call can be pricey, so accumulating the stack space might give you smaller executables โ because arguments don't need to be removed from the stack after such a call. This one can shrink code size for functions that make several calls to functions that take their arguments on the stack, like calls to printf-like functions. ate, no crumbs ๐ .-mbranch-cost=costโ sets the branch cost for conditional branch instructions to cost. Reasonable values for cost are small, non-negative integers. The default branch cost is0.-mcall-prologuesโ function prologues/epilogues get expanded as calls to the appropriate subroutines. Code size is smaller ๐.-mdouble=bits-mlong-double=bitsโ set the size (in bits) of the"double"or"long double"type, respectively. Possible values for bits are32and64. Whether a specific value for bits is even allowed depends on the--with-double=and--with-long-double=configure options (https://gcc.gnu.org/install/configure.html#avr), and the same goes for the default values of these options.-mgas-isr-prologuesโ interrupt service routines (ISRs) may use the"__gcc_isr"pseudo instruction supported by GNU Binutils. If this option is on, you can still disable the feature for individual ISRs by way of the AVR Function Attributes"no_gccisr"function attribute. This feature is activated per default if optimization is on (but not with-Og,@pxref{Optimize Options}), and if GNU Binutils supports PR21683 (https://sourceware.org/PR21683).-mint8โ assume"int"is an 8-bit integer. This affects the sizes of all the types: a"char"is 1 byte, an"int"is 1 byte, a"long"is 2 bytes, and"long long"is 4 bytes. Heads up bestie, this option does not conform to the C standards, but it results in smaller code size ๐.-mmain-is-OS_taskโ do not save registers in"main". The effect is the same as attaching the AVR Function Attributes"OS_task"attribute to"main". It's activated per default if optimization is on.-mn-flash=numโ assume the flash memory has a size of num times 64 KiB.-mno-interruptsโ the generated code is not compatible with hardware interrupts. Code size is smaller ๐ฆ.-mrelaxโ try to replace the"CALL"(resp."JMP") instruction with the shorter"RCALL"(resp."RJMP") instruction if applicable. Setting-mrelaxjust adds the--mlink-relaxoption to the assembler's command line and the--relaxoption to the linker's command line.
Jump relaxing is 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.
-mrmwโ assume the device supports the Read-Modify-Write instructions"XCH","LAC","LAS"and"LAT".-mshort-callsโ assume that"RJMP"and"RCALL"can target the whole program memory.
This option is used internally for multilib selection. It is not an optimization option, and you don't need to set it by hand ๐.
-msp8โ treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. In general, you don't need to set this option by hand.
This option is used internally by the compiler to select and build multilibs for architectures "avr2" and "avr25". These architectures mix devices with and without "SPH". For any setting other than -mmcu=avr2 or -mmcu=avr25 the compiler driver adds or removes this option from the compiler proper's command line, because the compiler then knows if the device or architecture has an 8-bit stack pointer and thus no "SPH" register or not. ๐ซถ
-mstrict-Xโ use address register"X"in a way proposed by the hardware. This means that"X"is only used in indirect, post-increment or pre-decrement addressing.
Without this option, the "X" register may be used in the same way as "Y" or "Z" which then is emulated by additional instructions. For example, loading a value with "X+const" addressing with a small non-negative "const < 64" to a register Rn is performed as
adiw r26, const ; X += const
ld <Rn>, X ; <Rn> = *X
sbiw r26, const ; X -= const
-mtiny-stackโ only change the lower 8 bits of the stack pointer. ๐-mfract-convert-truncateโ allow to use truncation instead of rounding towards zero for fractional fixed-point types.-nodevicelibโ don't link against AVR-LibC's device specific library"lib<mcu>.a".-nodevicespecsโ don't add-specs=device-specs/specs-mcuto the compiler driver's command line. The user takes responsibility for supplying the sub-processes like compiler proper, assembler and linker with appropriate command line options. This means that the user has to supply her private device specs file by means of-specs=path-to-specs-file. There is no more need for option-mmcu=mcu.
This option can also serve as a replacement for the older way of specifying custom device-specs files that needed -B some-path to point to a directory which contains a folder named "device-specs" which contains a specs file named "specs-mcu", where mcu was specified by -mmcu=mcu.
-Waddr-space-convertโ warn about conversions between address spaces in the case where the resulting address space is not contained in the incoming address space.-Wmisspelled-isrโ warn if the ISR is misspelled, i.e. without__vectorprefix. Enabled by default.
โจ "EIND" and Devices with More Than 128 Ki Bytes of Flash โจ
Pointers in the implementation are 16 bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can target any code address in the range of 64 Ki words.
In order to facilitate indirect jump on devices with more than 128 Ki bytes of program memory space, there is a special function register called "EIND" that serves as most significant part of the target address when "EICALL" or "EIJMP" instructions are used.
Indirect jumps and calls on these devices are handled as follows by the compiler and are subject to some limitations:
- The compiler never sets
"EIND". - The compiler uses
"EIND"implicitly in"EICALL"/"EIJMP"instructions or might read"EIND"directly in order to emulate an indirect call/jump by means of a"RET"instruction. - The compiler assumes that
"EIND"never changes during the startup code or during the application. In particular,"EIND"is not saved/restored in function or interrupt service routine prologue/epilogue. - For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads sometimes also called trampolines. Thus, the indirect call/jump jumps to such a stub. The stub contains a direct jump to the desired address.
- Linker relaxation must be turned on so that the linker generates the stubs correctly in all situations. See the compiler option
-mrelaxand the linker option--relax. There are corner cases where the linker is supposed to generate stubs but aborts without relaxation and without a helpful error message. ๐ญ - The default linker script is arranged for code with
"EIND = 0". If code is supposed to work for a setup with"EIND != 0", a custom linker script has to be used in order to place the sections whose name start with".trampolines"into the segment where"EIND"points 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 on"EIND", see the AVR-LibC user manual ("http://nongnu.org/avr-libc/user-manual/"). - It is legitimate for user-specific startup code to set up
"EIND"early, 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 sets"EIND"to 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
"gs"modifier (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
"gs"modifiers for code labels in the following situations:- Taking address of a function or code label.
- Computed goto.
- If prologue-save function is used, see
-mcall-prologuescommand-line option. - Switch/case dispatch tables. If you do not want such dispatch tables you can specify the
-fno-jump-tablescommand-line option. - C and C++ constructors/destructors called during startup/shutdown.
- If the tools hit a
gs()modifier explained above.
- Jumping to non-symbolic addresses like so is not supported:
int main (void)
{
/* Call function at word address 0x2 */
return ((int(*)(void)) 0x2)();
}
Instead, a stub has to be set up, i.e. the function has to be called through a symbol ("func_4" in the example):
int main (void)
{
extern int func_4 (void);
/* Call function at byte address 0x4 */
return func_4();
}
and the application be linked with -Wl,--defsym,func_4=0x4. Alternatively, "func_4" can be defined in the linker script.
๐ Handling of the "RAMPD", "RAMPX", "RAMPY" and "RAMPZ" Special Function Registers ๐
Some AVR devices support memories larger than the 64 KiB range that can be accessed with 16-bit pointers. To access memory locations outside this 64 KiB range, the content of a "RAMP" register is used as 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
"RAMP"special function registers with zero. - If a AVR Named Address Spaces, named address space other than generic or
"__flash"is used, then"RAMPZ"is set as needed before the operation. - If the device supports RAM larger than 64 KiB and the compiler needs to change
"RAMPZ"to accomplish an operation,"RAMPZ"is reset to zero after the operation. - If the device comes with a specific
"RAMP"register, 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
"RAMP"registers, you must reset it to zero after the access.
๐ฆ AVR Built-in Macros ๐ฆ
GCC defines several built-in macros so that the user code can test for the presence or absence of features. Almost any of the following built-in macros are deduced from device capabilities and thus triggered by the -mmcu= command-line option.
For even more AVR-specific built-in macros see AVR Named Address Spaces and AVR Built-in Functions.
"__AVR_ARCH__"โ build-in macro that resolves to a decimal number that identifies the architecture and depends on the-mmcu=mcuoption. Possible values are:2,25,3,31,35,4,5,51,6
for mcu="avr2", "avr25", "avr3", "avr31", "avr35", "avr4", "avr5", "avr51", "avr6", respectively, and
100,102,103,104,105,106,107
for mcu="avrtiny", "avrxmega2", "avrxmega3", "avrxmega4", "avrxmega5", "avrxmega6", "avrxmega7", respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4.
"__AVR_Device__"โ setting-mmcu=devicedefines this built-in macro which reflects the device's name. For example,-mmcu=atmega8defines the built-in macro"__AVR_ATmega8__",-mmcu=attiny261adefines"__AVR_ATtiny261A__", etc.
The built-in macros' names follow the scheme "__AVR_Device__" where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase.
If device is not a device but only a core architecture like avr51, this macro is not defined.
"__AVR_DEVICE_NAME__"โ setting-mmcu=devicedefines this built-in macro to the device's name. For example, with-mmcu=atmega8the macro is defined 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_ELPM__"โ the device has the"ELPM"instruction."__AVR_HAVE_ELPMX__"โ the device has the"ELPM Rn,Z"and"ELPM Rn,Z+"instructions."__AVR_HAVE_MOVW__"โ the device has the"MOVW"instruction to perform 16-bit register-register moves.__AVR_HAVE_LPMX__โ bestie your device ships with theLPM Rn,ZandLPM Rn,Z+instructions. iconic.__AVR_HAVE_MUL__โ the device has a hardware multiplier ๐__AVR_HAVE_JMP_CALL__โ the device hasJMPandCALL. this is the vibe for devices with more than 8 KiB of program memory.__AVR_HAVE_EIJMP_EICALL____AVR_3_BYTE_PC__โ the device hasEIJMPandEICALL. that's the case for devices with more than 128 KiB of program memory. and lowkey this also means 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 gets treated as an 8-bit respectively 16-bit register by the compiler. ngl the definition of these macros is affected by-mtiny-stack.__AVR_HAVE_SPH____AVR_SP8__โ the device has the SPH (high part of stack pointer) special function register, or has an 8-bit stack pointer, respectively ๐ซถ the definition of these macros is affected by-mmcu=, and in the cases of-mmcu=avr2and-mmcu=avr25also by-msp8.__AVR_HAVE_RAMPD____AVR_HAVE_RAMPX____AVR_HAVE_RAMPY____AVR_HAVE_RAMPZ__โ the device has theRAMPD,RAMPX,RAMPY,RAMPZspecial function register, respectively โจ__NO_INTERRUPTS__โ this macro is literally just reflecting the-mno-interruptscommand-line option.__AVR_ERRATA_SKIP____AVR_ERRATA_SKIP_JMP_CALL__โ some AVR devices (AT90S8515, ATmega103) must not skip 32-bit instructions because of a hardware erratum ๐ญ the skip instructions areSBRS,SBRC,SBIS,SBICandCPSE. the second macro is only defined if__AVR_HAVE_JMP_CALL__is also set.__AVR_ISA_RMW__โ the device has Read-Modify-Write instructions (XCH, LAC, LAS and LAT) ๐ฅ__AVR_SFR_OFFSET__=offsetโ instructions that can address I/O special function registers directly, likeIN,OUT,SBI, etc., may use a different address than if they were addressed by an instruction to access RAM likeLDorSTS. this offset depends on the device architecture and has to be subtracted from the RAM address in order to get the respective I/O address. no cap, that's the whole deal.__AVR_SHORT_CALLS__โ the-mshort-callscommand line option is set.__AVR_PM_BASE_ADDRESS__=addrโ some devices support reading from flash memory by means ofLD*instructions ๐ the flash memory is seen in the data address space at an offset of__AVR_PM_BASE_ADDRESS__. if this macro is not defined, this feature is not available. if it is defined, the address space is linear and there is no need to put.rodatainto RAM. this is handled by the default linker description file, and it's currently available foravrtinyandavrxmega3. even more convenient: there's no need to use address spaces like__flashor features like attributeprogmemandpgm_read_*. obsessed.__WITH_AVRLIBC__โ the compiler is configured to be used together with AVR-Libc. see the--with-avrlibcconfigure option.__HAVE_DOUBLE_MULTILIB__โ defined if-mdouble=acts as a multilib option.__HAVE_DOUBLE32____HAVE_DOUBLE64__โ defined if the compiler supports 32-bit double resp. 64-bit double. the actual layout is specified by option-mdouble=.__DEFAULT_DOUBLE__โ the size in bits ofdoubleif-mdouble=is not set. to test the layout ofdoublein a program, use the built-in macro__SIZEOF_DOUBLE__๐__HAVE_LONG_DOUBLE32____HAVE_LONG_DOUBLE64____HAVE_LONG_DOUBLE_MULTILIB____DEFAULT_LONG_DOUBLE__โ same as above, but forlong doubleinstead ofdouble.__WITH_DOUBLE_COMPARISON__โ reflects the--with-double-comparison={tristate|bool|libf7}configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to 2 or 3.__WITH_LIBF7_LIBGCC____WITH_LIBF7_MATH____WITH_LIBF7_MATH_SYMBOLS__โ reflects the--with-libf7={libgcc|math|math-symbols}configure option (https://gcc.gnu.org/install/configure.html#avr).
๐ Blackfin Options ๐
-mcpu=cpu[-sirevision]โ tells GCC the name of the target Blackfin processor ๐ right now, cpu can be one ofbf512,bf514,bf516,bf518,bf522,bf523,bf524,bf525,bf526,bf527,bf531,bf532,bf533,bf534,bf536,bf537,bf538,bf539,bf542,bf544,bf547,bf548,bf549,bf542m,bf544m,bf547m,bf548m,bf549m,bf561,bf592.
the optional sirevision specifies the silicon revision of the target Blackfin processor. any workarounds available for the targeted silicon revision get 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.
heads up bestie: support forbf561is incomplete. forbf561, only the preprocessor macro is defined. ๐
-msimโ says the program will be run on the simulator. this causes the simulator BSP provided by libgloss to be linked in. it only has effect for the 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. slay.-mspecld-anomalyโ when enabled, the compiler makes sure the generated code does not contain speculative loads after jump instructions. if this option is used,__WORKAROUND_SPECULATIVE_LOADSis defined.-mno-specld-anomalyโ don't generate extra code to prevent speculative loads from occurring.-mcsync-anomalyโ when enabled, the compiler makes sure the generated code does not contain CSYNC or SSYNC instructions too soon after conditional branches. if this option is used,__WORKAROUND_SPECULATIVE_SYNCSis defined.-mno-csync-anomalyโ don't generate extra code to prevent CSYNC or SSYNC instructions from occurring too soon after a conditional branch.-mlow64kโ when enabled, the compiler is free to take advantage of the knowledge that the entire program fits into the low 64k of memory โจ-mno-low64kโ assume that the program is arbitrarily large. this is the default.-mstack-check-l1โ do stack checking using information placed into L1 scratchpad memory by the uClinux kernel ๐ซถ-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. this allows for execute in place and shared libraries in an environment without virtual memory management. this option implies-fPIC. with 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.-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 that the data segment follows the text segment. this is the default.-mlong-calls-mno-long-callsโ tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. this switch is needed if the target function lies outside of the 24-bit addressing range of the offset-based version of subroutine call instruction ๐ฅ
this feature is not enabled by default. specifying -mno-long-calls restores the default behavior. note these switches have no effect on how the compiler generates code to handle function calls via function pointers.
-mfast-fpโ link with the fast floating-point library. this library relaxes some of the IEEE floating-point standard's rules for checking inputs against Not-a-Number (NAN), in the interest of performance. bestie that's the trade-off, fr fr.-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โ makes a standalone app for Core A of the BF561 when you're doing the one-application-per-core thing ๐ . It pulls in the proper start files and link scripts for Core A, and it defines the macro"__BFIN_COREA". Heads up though: this one only works alongside-mmulticore, bestie. No solo runs.-mcorebโ same energy but for Core B of BF561, again in the one-app-per-core model ๐. Proper start files and link scripts for Core B get used, and"__BFIN_COREB"gets defined. Small plot twist: when you use this, you gotta usecoreb_maininstead ofmain. And yes, it can only be used with-mmulticore. Periodt.-msdramโ builds a standalone app for SDRAM โจ. Proper start files and link scripts get used to drop the application into SDRAM, and the macro"__BFIN_SDRAM"is defined. Lowkey important: the loader should initialize SDRAM before loading the application, okay?-micplbโ assumes ICPLBs are enabled at run time ๐ธ. This matters because it changes how certain anomaly workarounds behave. For Linux targets the default is to assume ICPLBs are on; for standalone applications the default is off. Iykyk.
๐ C6X Options ๐
-march=nameโ tells GCC the name of the target architecture ๐ฆ. GCC uses this name to figure out what kind of instructions it can emit while generating assembly code. The permissible names are:c62x,c64x,c64x+,c67x,c67x+,c674x.-mbig-endianโ generate code for a big-endian target. Go big or go home ๐ซถ.-mlittle-endianโ generate code for a little-endian target. This is the default, so if you say nothing, this is the vibe ๐.-msimโ choose startup files and a linker script suitable for the simulator โจ.-msdata=defaultโ put small global and static data in the.neardatasection, which is pointed to by register"B14"๐. Small uninitialized global and static data goes in.bss, which sits right next to.neardata. Small read-only data goes into.rodata. And the sections used for the big pieces of data are.fardata,.farand.const.-msdata=allโ put all data into the sections reserved for small data, not just the small objects, and access them using addressing relative to the"B14"register ๐ฅ.-msdata=noneโ make no use of the small-data sections at all, and use absolute addresses to access all data ๐. All initialized global and static data goes in.fardata, all uninitialized data goes in.far, and all constant data goes into.const.
๐ง CRIS Options ๐ง
These options are defined specifically for the CRIS ports, bestie. Very niche, very slay.
-march=architecture-type,-mcpu=architecture-typeโ generate code for the specified architecture ๐. The choices for architecture-type arev3,v8andv10, for ETRAX 4, ETRAX 100, and ETRAX 100 LX respectively. The default isv0.-mtune=architecture-typeโ tune everything applicable about the generated code to architecture-type, 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โ warns you when the stack frame of a function exceeds n bytes ๐.-metrax4,-metrax100โ these two are just synonyms for-march=v3and-march=v8respectively. Same thing, different name, iconic.-mmul-bug-workaround,-mno-mul-bug-workaroundโ works around a bug in the"muls"and"mulu"instructions for the CPU models where it applies ๐. This option is disabled by default.-mpdebugโ enables CRIS-specific verbose debug-related information in the assembly code ๐. It also has the effect of turning off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file. Not me reading assembly for fun, but here we are.-mcc-initโ do not use condition-code results from previous instructions; always emit compare and test instructions before using 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 (and theirno-counterparts) arrange (or eliminate the arrangement) 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, so no worries there.-m32-bit,-m16-bit,-m8-bitโ similar to the stack-, data- and const-align options above, these arrange for the 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 that 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 when storage for local variables needs to be allocated. You are on your own. Fr fr.
-melfโ legacy no-op option. It's giving historical artifact ๐.-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 it passes linker options to locate initialized data at0x40000000and zero-initialized data at0x80000000๐.
๐ CR16 Options ๐
These options are defined specifically for the CR16 ports.
-mmacโ enables the use of multiply-accumulate instructions โจ. Disabled by default.-mcr16cplus,-mcr16cโ generate code for the CR16C or CR16C+ architecture ๐. CR16C+ is the default, so that's the main character.-msimโ links the librarylibsim.a, which is compatible with the simulator ๐. Applicable to ELF compiler only.-mint32โ choose integer type as 32-bit wide.-mbit-opsโ generates"sbit"/"cbit"instructions for bit manipulations ๐ .-mdata-model=modelโ choose a data model ๐. The choices for model arenear,farormedium, andmediumis the default. However,faris not valid with-mcr16c, because the CR16C architecture does not support the far data model. Sorry bestie, that's just the rules.
๐ C-SKY Options ๐
GCC supports these options when compiling for C-SKY V2 processors. Let's gooo.
-march=archโ specify the C-SKY target architecture ๐ฆ. Valid values for arch are:ck801,ck802,ck803,ck807, andck810. The default isck810.-mcpu=cpuโ specify the C-SKY target processor ๐. Valid values for cpu are:ck801,ck801t,ck802,ck802t,ck802j,ck803,ck803h,ck803t,ck803ht,ck803f,ck803fh,ck803e,ck803eh,ck803et,ck803eht,ck803ef,ck803efh,ck803ft,ck803eft,ck803efht,ck803r1,ck803hr1,ck803tr1,ck803htr1,ck803fr1,ck803fhr1,ck803er1,ck803ehr1,ck803etr1,ck803ehtr1,ck803efr1,ck803efhr1,ck803ftr1,ck803eftr1,ck803efhtr1,ck803s,ck803st,ck803se,ck803sf,ck803sef,ck803seft,ck807e,ck807ef,ck807,ck807f,ck810e,ck810et,ck810ef,ck810eft,ck810,ck810v,ck810f,ck810t,ck810fv,ck810tv,ck810ft, andck810ftv. That's a whole alphabet of processors, I know ๐ญ.-mbig-endian,-EB,-mlittle-endian,-ELโ select big- or little-endian code ๐ธ. The default is little-endian.-mfloat-abi=nameโ specifies which floating-point ABI to use. The permissible values are:soft,softfpandhard.softcauses GCC to generate output containing library calls for floating-point operations ๐ซถ.softfpallows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions โจ.hardallows generation of floating-point instructions and uses FPU-specific calling conventions ๐ฅ.
The default depends on the specific target configuration. 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. No mixing, bestie, it will not end well ๐.
-mhard-float,-msoft-floatโ select hardware or software floating-point implementations ๐. The default is soft float.-mdouble-float,-mno-double-floatโ when-mhard-floatis in effect, enable generation of double-precision float instructions ๐. This is the default except when compiling for CK803.-mfdivdu,-mno-fdivduโ when-mhard-floatis in effect, enable generation of"frecipd","fsqrtd", and"fdivd"instructions โจ. This is the default except when compiling for CK803.-mfpu=fpuโ select the floating-point processor ๐. This option can only be used with-mhard-float. The values for fpu arefpv2_sf(equivalent to-mno-double-float -mno-fdivdu),fpv2(-mdouble-float -mno-divdu), andfpv2_divd(-mdouble-float -mdivdu).-melrw,-mno-elrwโ enable the extended"lrw"instruction ๐. This option defaults to on for CK801 and off otherwise.-mistack,-mno-istackโ enable interrupt stack instructions; the default is off.
The-mistackoption is required to handle the"interrupt"and"isr"function attributes. Don't skip it if you need those, fr fr.
-mmpโ enable multiprocessor instructions; the default is off ๐ .-mcpโ enable coprocessor instructions; the default is off.-mcacheโ enable coprocessor instructions; the default is off. (Yes, that's what it says, bestie, I'm just the messenger ๐.)-msecurityโ enable C-SKY security instructions; the default is off ๐.-mtrustโ enable C-SKY trust instructions; the default is off ๐ก๏ธ.-mdsp,-medsp,-mvdspโ enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively โจ. All of these options default to off.-mdiv,-mno-divโ generate divide instructions. Default is off.-msmart,-mno-smartโ generate code for Smart Mode, using only registers numbered0-7to allow use of 16-bit instructions ๐. This option is ignored for CK801, where this is the required behavior, and it defaults to on for CK802. For other targets, the default is off.-mhigh-registers,-mno-high-registersโ generate code using the high registers numbered16-31๐. This option is not supported on CK801, CK802, or CK803, and it's enabled by default for other processors.-manchor,-mno-anchorโ generate code using global anchor symbol addresses โ.-mpushpop,-mno-pushpopโ generate code using"push"and"pop"instructions ๐ . This option defaults to on.-mmultiple-stld,-mstm,-mno-multiple-stld,-mno-stmโ bestie, this one makes the compiler spit out code that usesstmandldminstructions. Heads up though: it's not supported on CK801, but it's on by default everywhere else. ๐-mconstpool,-mno-constpoolโ build constant pools inside the compiler instead of handing that job off to the assembler. This is the default, and it's literally required for correct code generation on CK801 and CK802. On other processors? Optional, do what you want. โจ-mstack-size,-mno-stack-sizeโ emit.stack_sizedirectives for every single function in the assembly output. Defaults to off, no cap. ๐-mccrt,-mno-ccrtโ generate code for the C-SKY compiler runtime instead oflibgcc. Defaults to off. ๐ฆ-mbranch-cost=nโ set the branch costs to roughly n instructions. Default is1. ๐ธ-msched-prolog,-mno-sched-prologโ allow scheduling of function prologue and epilogue sequences.
โ ๏ธ Okay so, real talk: using this can produce code that is not compliant with the C-SKY V2 ABI prologue requirements, and that code cannot be debugged or backtraced. It's disabled by default for a reason, 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.
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 pulls that off by running the compiler or linker multiple times and joining the results together with lipo. ๐
The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can be used to override this.
The Darwin tools vary in their behavior when presented with an ISA mismatch. The assembler, as, only permits instructions to be used that are valid for the subtype of the file it is generating, so you cannot put 64-bit instructions in a ppc750 object file. The linker for shared libraries, /usr/bin/libtool, fails and prints an error if asked to create a shared library with a less restrictive subtype than its input files (for instance, trying to put a ppc970 object file in a ppc7400 library). The linker for executables, ld, quietly gives the executable the most restrictive subtype of any of its input files. ๐ญ
-Fdirโ add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by-Ioptions and are scanned in a left-to-right order.
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. the way that it just... gives you everything ๐ซถ-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. See manld(1)for more information. ๐-arch_errors_fatalโ cause the errors having to do with files that have the wrong architecture to be fatal. ๐ญ-bind_at_loadโ causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.-bundleโ produce a Mach-o bundle format file. See manld(1)for more information. ๐-bundle_loader executableโ this option specifies the executable that will load the build output file being linked. See manld(1)for more information.-dynamiclibโ when passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand. ๐-force_cpusubtype_ALLโ this causes GCC's output file to have theALLsubtype, instead of one controlled by the-mcpuor-marchoption. โญ-allowable_client client_name-client_name-compatibility_version-current_version-dead_strip-dependency-file-dylib_file-dylinker_install_name-dynamic-exported_symbols_list-filelist-flat_namespace-force_flat_namespace-headerpad_max_install_names-image_base-init-install_name-keep_private_externs-multi_module-multiply_defined-multiply_defined_unused-noall_load-no_dead_strip_inits_and_terms-nofixprebinding-nomultidefs-noprebind-noseglinkedit-pagezero_size-prebind-prebind_all_twolevel_modules-private_bundle-read_only_relocs-sectalign-sectobjectsymbols-whyload-seg1addr-sectcreate-sectobjectsymbols-sectorder-segaddr-segs_read_only_addr-segs_read_write_addr-seg_addr_table-seg_addr_table_filename-seglinkedit-segprot-segs_read_only_addr-segs_read_write_addr-single_module-static-sub_library-sub_umbrella-twolevel_namespace-umbrella-undefined-unexported_symbols_list-weak_reference_mismatches-whatsloaded
These options are passed to the Darwin linker. The Darwin linker man page describes them in detail. ๐ฆ
๐ธ DEC Alpha Options ๐ธ
These -m options are defined for the DEC Alpha implementations:
-mno-soft-float,-msoft-floatโ use (do not use) the hardware floating-point instructions for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. Unless they are replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulations routines, these routines issue floating-point operations. If you are compiling for an Alpha without floating-point operations, you must ensure that the library is built so as not to call them.
Note that Alpha implementations without floating-point operations are required to have floating-point registers. ๐ญ
-mfp-reg,-mno-fp-regsโ generate code that uses (does not use) the floating-point register set.-mno-fp-regsimplies-msoft-float. If the floating-point register set is not used, floating-point operands are passed in integer registers as if they were integers and floating-point results are passed in$0instead of$f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with-mno-fp-regsmust also be compiled with that option. ๐
A typical use of this option is building a kernel that does not use, and hence need not save and restore, any floating-point registers. ๐
-mieeeโ okay so bestie, the Alpha architecture has floating-point hardware that's optimized for maximum performance and is mostly compliant with the IEEE floating-point standard. Mostly. ๐ For full compliance you need software assistance, and that's literally what this flag is. It generates code that's fully IEEE-compliant except that the inexact-flag is not maintained (peep below for the version that does). Turning it on defines the preprocessor macro_IEEE_FPduring compilation. The code it spits out is less efficient but it can correctly handle denormalized numbers and those exceptional IEEE values like not-a-number and plus/minus infinity. Other Alpha compilers call this option-ieee_with_no_inexact.
DEBIAN SPECIFIC: this one is on by default foralpha-linux-gnu, unless-ffinite-math-only(which is part of the-ffast-mathset) is specified โ because the software functions in the GNU libc math libraries generate denormalized numbers, NaNs, and infs, and all of those will cause a program toSIGFPEwhen it tries to use the results without-mieee. ๐ so like, keep that in mind.
-mieee-with-inexactโ same energy as-mieeeexcept the generated code also maintains the IEEE inexact-flag. Turning this on makes the generated code implement fully-compliant IEEE math, periodt. On top of_IEEE_FP, it also defines_IEEE_FP_EXACTas a preprocessor macro. On some Alpha implementations the resulting code may run significantly slower than the default code. And since there's very little code that actually depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this one-ieee_with_inexact.- *
-mfp-trap-mode=trap-mode* โ controls which floating-point related traps are enabled. Other Alpha compilers call this-fptmtrap-mode. The trap mode can be one of four values:nโ the default (normal) setting. The only traps enabled are the ones that cannot be disabled in software (e.g., division by zero trap).uโ on top of the traps enabled byn, underflow traps are enabled too.suโ likeu, but the instructions are marked to be safe for software completion (see the Alpha architecture manual for the deets).suiโ likesu, but inexact traps are enabled as well.
- *
-mfp-rounding-mode=rounding-mode* โ picks the IEEE rounding mode. Other Alpha compilers call this-fprmrounding-mode. The rounding-mode can be one of:nโ normal IEEE rounding mode. Floating-point numbers get 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. So unless your program modifies thefpcr,dcorresponds to round towards plus infinity.
- *
-mtrap-precision=trap-precision* โ in the Alpha architecture, floating-point traps are imprecise. Which 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 helps operating system trap handlers figure out the exact location that caused a floating-point trap. Depending on what your application needs, 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โ marks the generated code as IEEE conformant. ๐ You must not use this option unless you also specify-mtrap-precision=iand either-mfp-trap-mode=suor-mfp-trap-mode=sui. Its only effect is to emit the line.eflag 48in the function prologue of the generated assembly file.-mbuild-constantsโ normally GCC examines a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it 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 for building a shared library dynamic loader โ itself a shared library, it has to relocate itself in memory before it can find the variables and constants in its own data segment. iconic 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 (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, and using those macros does not allow optimal instruction scheduling. GNU binutils as of version 2.12 supports a new syntax that lets the compiler explicitly mark which relocations should apply to which instructions. This option is mostly useful for debugging, since 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 lets the variables 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,-mlarge-textโ when-msmall-textis used, the compiler assumes that the code of the entire program (or shared library) fits in 4MB, and is thus reachable with a branch instruction. When-msmall-datais used, the compiler can assume that all local symbols share the same$gpvalue, and thus reduce the number of instructions required for a function call from 4 to 1. The default is-mlarge-text.- *
-mcpu=cpu_type* โ sets the instruction set and instruction scheduling parameters for machine typecpu_type. You can specify either the EV style name or the corresponding chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors and chooses the default values for the instruction set from the processor you specify. If you don't specify a processor type, GCC defaults to the processor on which the compiler was built.
Supported values for cpu_type are:
ev4,ev45,21064โ schedules as an EV4 and has no instruction set extensions.ev5,21164โ schedules as an EV5 and has no instruction set extensions.ev56,21164aโ schedules as an EV5 and supports the BWX extension.pca56,21164pc,21164PCโ schedules as an EV5 and supports the BWX and MAX extensions.ev6,21264โ schedules as an EV6 and supports the BWX, FIX, and MAX extensions.ev67,21264aโ schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions.
Native toolchains also support the 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 typecpu_type. The instruction set is not changed. Native toolchains also support the valuenative, which selects the best architecture option for the host processor.-mtune=nativehas no effect if GCC does not recognize the processor. - *
-mmemory-latency=time* โ sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. Valid options fortimeare:numberโ a decimal number representing clock cycles.L1,L2,L3,mainโ the compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note thatL3is only valid for EV5.
โจ eBPF Options โจ
- *
-mframe-limit=bytes* โ specifies the hard limit for frame sizes, in bytes. Currently, the value that can be specified should be less than or equal to32767. Defaults to whatever limit is imposed by the version of the Linux kernel targeted. no cap ๐ซถ - *
-mkernel=version* โ specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to determine which instructions to use, what kernel helpers to allow, etc. Currently,versioncan be one of4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9,4.10,4.11,4.12,4.13,4.14,4.15,4.16,4.17,4.18,4.19,4.20,5.0,5.1,5.2,latestandnative. ๐ธ -mbig-endianโ make code for a big-endian target ๐ซถ-mlittle-endianโ make code for a little-endian target. this one is the default, bestie ๐-mjmpextโ turn on generation of the extra conditional-branch instructions โจ enabled for CPU v2 and above.-mjmp32โ turn on 32-bit jump instructions ๐ฆ enabled for CPU v3 and above.-malu32โ turn on 32-bit ALU instructions ๐ธ enabled for CPU v3 and above.-mcpu=versionโ this tells the compiler which version of the eBPF ISA to target ๐ newer versions might not be supported by every kernel, so likeโฆ vibe check your kernel first. the default isv3.
the supported values for version are:
v1โ the very first stable eBPF ISA, no special features, no extensions, just pure vibes โจv2โ supports the jump extensions, as in-mjmpext๐ซv3โ everything fromv2, plus:- 32-bit jump operations, as in
-mjmp32 - 32-bit ALU operations, as in
-malu32
- 32-bit jump operations, as in
-mco-reโ turn on BPF Compile Once - Run Everywhere (CO-RE) support ๐ it requires-gbtfand is implied by-gbtftoo.-mno-co-reโ turn off BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is on by default when you're 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 ๐ฆ namely:- save and restore callee-saved registers at function entry and exit, respectively.
๐ FR30 Options ๐
these options are defined specifically for the FR30 port, no cap ๐
-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, so there's no need to include the simulator library (libsim.a) on the linker command line ๐
๐ฆ FT32 Options ๐ฆ
these options are defined specifically for the FT32 port, periodt โจ
-msimโ says the program will be run on the simulator ๐ง this makes an alternate runtime startup and library get linked. you must not use this option when generating programs that will run on real hardware; you have to provide your own runtime library for whatever I/O functions are needed.
okay so this one is a hard no for real hardware, bestie ๐
-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 you're 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, bestie ๐-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โ enable the use of conditional execution (default) ๐ธ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-cond-execโ disable the use of conditional execution ๐ซ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mvliw-branchโ run a pass to pack branches into VLIW instructions (default) ๐
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-vliw-branchโ do not run a pass to pack branches into VLIW instructions ๐ซ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mmulti-cond-execโ enable optimization of"&&"and"||"in conditional execution (default) ๐
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-multi-cond-execโ disable optimization of"&&"and"||"in conditional execution ๐ซ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mnested-cond-execโ enable nested conditional execution optimizations (default) ๐ฆ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-nested-cond-execโ disable nested conditional execution optimizations ๐ซ
this switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-moptimize-membarโ this switch removes redundant"membar"instructions from the compiler-generated code ๐งน it is enabled by default.-mno-optimize-membarโ this switch disables the automatic removal of redundant"membar"instructions from the generated code ๐ซ-mtomcat-statsโ causegasto print out tomcat statistics ๐ฑ๐-mcpu=cpuโ select the processor type for which to generate code ๐ the possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple.
๐ง GNU/Linux Options ๐ง
these -m options are defined for GNU/Linux targets:
-mglibcโ use the GNU C library ๐ this is the default except on*-*-linux-*uclibc*,*-*-linux-*musl*and*-*-linux-*android*targets.-muclibcโ use 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 Bionic C library ๐ค this is the default on*-*-linux-*android*targets.-mandroidโ compile code compatible with the Android platform ๐ฑ this is the default on*-*-linux-*android*targets.
when compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. when linking, this option makes the GCC driver pass Android-specific options to the linker. and finally, this option causes the preprocessor macro "__ANDROID__" to be defined ๐
-tno-android-ccโ disable compilation effects of-mandroid, i.e., do not enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default ๐ซ-tno-android-ldโ disable 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โ bestie, this one generates code for the H8/300H. that's the whole vibe. โจ-msโ generates code for the H8S. ๐-mnโ generates code for the H8S and H8/300H in the normal mode. this switch must be used either with-mhor-ms, no solo runs allowed. ๐-ms2600โ generates code for the H8S/2600. this switch must be used with-ms. periodt.-mexrโ extended registers are stored on stack before execution of function with monitor attribute. default option is-mexr. this option is valid only for H8S targets. ๐ซถ-mno-exrโ extended registers are not stored on stack before execution of function with monitor attribute. default option is-mno-exr. this option is valid only for H8S targets. ๐-mint32โ makes"int"data 32 bits by default. iconic.-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. no cap. ๐-mpa-risc-1-0,-mpa-risc-1-1,-mpa-risc-2-0โ synonyms for-march=1.0,-march=1.1, and-march=2.0respectively. slay. โจ-mcaller-copiesโ the caller copies function arguments passed by hidden reference. this option should be used 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. ๐ง-mjump-in-delayโ this option is ignored and provided for compatibility purposes only. it's giving ghost. ๐ป-mdisable-fpregsโ prevent floating-point registers from being used in any manner. this is necessary for compiling kernels that perform lazy context switching of floating-point registers. if you use this option and attempt to perform floating-point operations, the compiler aborts. ๐-mdisable-indexingโ prevent the compiler from using indexing address modes. this avoids some rather obscure problems when compiling MIG generated code under MACH. lowkey a lifesaver. ๐ซถ-mno-space-regsโ generate 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. โจ
-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. ๐-mlong-load-storeโ generate 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. ๐-mportable-runtimeโ use the portable calling conventions proposed by HP for ELF systems. ๐-mgasโ enable the use of assembler directives only GAS understands. iykyk.-mschedule=cpu-typeโ schedule code according to the constraints for the machine type cpu-type. the choices for cpu-type are7007100,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. periodt. ๐ฅ-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. ๐ญ-msoft-floatโ generate output containing library calls for floating point. warning: the requisite libraries are not available for all HPPA targets. normally the facilities of the machine's usual C compiler 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. ๐ซถ
-msioโ generate 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. โจ-mgnu-ldโ use options specific to GNU ld. this passes-sharedto ld when building a shared library. it is the default when GCC is configured, explicitly or implicitly, with the GNU linker. this option does not affect which ld is called; it only changes what parameters are passed to that ld. the ld that 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 HP ld. this passes-bto ld when building a shared library and passes+Accept TypeMismatchto ld on all links. it is the default when GCC is configured, explicitly or implicitly, with the HP linker. this option does not affect which ld is called; it only changes what parameters are passed to that ld. the ld that 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*. ๐-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. ๐ญ
-munix=unix-stdโ generate compiler predefines and select a startfile for the specified UNIX standard. the choices for unix-std are93,95and98.93is supported on all HP-UX versions.95is available on HP-UX 10.10 and later.98is available on HP-UX 11.11 and later. the default values are93for HP-UX 10.00,95for HP-UX 10.10 though to 11.00, and98for HP-UX 11.11 and later.
-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for "XOPEN_UNIX" and "_XOPEN_SOURCE_EXTENDED", and the startfile unix95.o. -munix=98 provides additional predefines for "_XOPEN_UNIX", "_XOPEN_SOURCE_EXTENDED", "_INCLUDE__STDC_A1_SOURCE" and "_INCLUDE_XOPEN_SOURCE_500", and the startfile unix98.o.
it is important to note that this option changes the interfaces for various library routines. it also affects the operational behavior of the C library. 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โ suppress the generation of link options to searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later. ๐ซ-staticโ the HP-UX implementation ofsetlocalein libc has 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 with libdld.sl when the -static option is specified. this causes the resulting binary to be dynamic. on the 64-bit port, the linkers generate dynamic binaries by default in any case. the -nolibdld option can be used to prevent the GCC driver from adding these link options. ๐
-threadsโ add support for multithreading with the dce thread library under HP-UX. this option sets flags for both the preprocessor and linker. ๐ฅ
๐ฆ IA-64 Options ๐ฆ
these are the -m options defined for the Intel IA-64 architecture.
-mbig-endianโ generate code for a big-endian target. this is the default for HP-UX. ๐-mlittle-endianโ generate code for a little-endian target. this is the default for AIX5 and GNU/Linux. โจ-mgnu-as,-mno-gnu-asโ generate (or don't) code for the GNU assembler. this is the default. ๐-mgnu-ld,-mno-gnu-ldโ generate (or don't) code for the GNU linker. this is the default. ๐-mno-picโ bestie, this one generates code that does not use a global pointer register ๐ so the result is not position independent code, and it straight up violates the IA-64 ABI. periodt.-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, which is giving helpful honestly.-mno-sdata-msdataโ disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs ๐ iykyk.-mconstant-gpโ generate code that uses a single constant global pointer value. Super useful when compiling kernel code ๐-mauto-picโ generate code that is self-relocatable. This implies-mconstant-gp. Useful when compiling firmware code ๐-minline-float-divide-min-latencyโ generate code for inline divides of floating-point values using the minimum latency algorithm.-minline-float-divide-max-throughputโ generate code for inline divides of floating-point values using the maximum throughput algorithm.-mno-inline-float-divideโ do not generate inline code for divides of floating-point values.-minline-int-divide-min-latencyโ generate code for inline divides of integer values using the minimum latency algorithm.-minline-int-divide-max-throughputโ generate code for inline divides of integer values using the maximum throughput algorithm.-mno-inline-int-divideโ do not generate inline code for divides of integer values.-minline-sqrt-min-latencyโ generate code for inline square roots using the minimum latency algorithm.-minline-sqrt-max-throughputโ generate code for inline square roots using the maximum throughput algorithm.-mno-inline-sqrtโ do not generate inline code forsqrt.-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, bestie, so it's already on unless you say otherwise.-mno-dwarf2-asm-mdwarf2-asmโ don't (or do โจ) generate assembler code for the DWARF line number debugging info. This may be useful when you're not using the GNU assembler.-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 honestly it does not always do so ๐ญ-mfixed-range=register-rangeโ generate code treating the given register range as fixed registers. A fixed register is one that the register allocator cannot use. 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โ specify bit size of immediate TLS offsets. Valid values are14,22, and64โญ-mtune=cpu-typeโ tune the instruction scheduling for a particular CPU. Valid values areitanium,itanium1,merced,itanium2, andmckinley.-milp32-mlp64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. These are HP-UX specific flags ๐-mno-sched-br-data-spec-msched-br-data-specโ (dis/en)able data speculative scheduling before reload. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is disabled.-msched-ar-data-spec-mno-sched-ar-data-specโ (en/dis)able data speculative scheduling after reload. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is enabled.-mno-sched-control-spec-msched-control-specโ (dis/en)able control speculative scheduling. This feature is available only during region scheduling (i.e. before reload). This results in generation of theld.sinstructions and the corresponding check instructionschk.s. The default setting is disabled.-msched-br-in-data-spec-mno-sched-br-in-data-specโ (en/dis)able speculative scheduling of the instructions that are dependent on the data speculative loads before reload. This is effective only with-msched-br-data-specenabled. The default setting is enabled.-msched-ar-in-data-spec-mno-sched-ar-in-data-specโ (en/dis)able speculative scheduling of the instructions that are dependent on the data speculative loads after reload. This is effective only with-msched-ar-data-specenabled. The default setting is enabled.-msched-in-control-spec-mno-sched-in-control-specโ (en/dis)able speculative scheduling of the instructions that are dependent on the control speculative loads. This is effective only with-msched-control-specenabled. The default setting is enabled.-mno-sched-prefer-non-data-spec-insns-msched-prefer-non-data-spec-insnsโ if enabled, data-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the data speculation much more conservative. The default setting is disabled.-mno-sched-prefer-non-control-spec-insns-msched-prefer-non-control-spec-insnsโ if enabled, control-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the control speculation much more conservative. The default setting is disabled.-mno-sched-count-spec-in-critical-path-msched-count-spec-in-critical-pathโ if enabled, speculative dependencies are considered during computation of the instructions priorities. This makes the use of the speculation a bit more conservative. The default setting is disabled.-msched-spec-ldcโ use a simple data speculation check. This option is on by default โจ-msched-control-spec-ldcโ use a simple check for control speculation. This option is on by default โจ-msched-stop-bits-after-every-cycleโ place a stop bit after every cycle when scheduling. This option is on by default โจ-msched-fp-mem-deps-zero-costโ assume that floating-point stores and loads are not likely to cause a conflict when placed into the same instruction group. This option is disabled by default.-msel-sched-dont-check-control-specโ generate checks for control speculation in selective scheduling. This flag is disabled by default.-msched-max-memory-insns=max-insnsโ limit on the number of memory insns per instruction group, giving lower priority to subsequent memory insns attempting to schedule in the same instruction group. Frequently useful to prevent cache bank conflicts. The default value is1.-msched-max-memory-insns-hard-limitโ makes the limit specified bymsched-max-memory-insnsa hard limit, disallowing more than that number in an instruction group. Otherwise, the limit is "soft", meaning that non-memory operations are preferred when the limit is reached, but memory operations may still be scheduled.
๐ฎ LM32 Options ๐ฎ
These -m options are defined for the LatticeMico32 architecture, bestie:
-mbarrel-shift-enabledโ enable barrel-shift instructions ๐ซ-mdivide-enabledโ enable divide and modulus instructions โ-mmultiply-enabledโ enable multiply instructions โ๏ธ-msign-extend-enabledโ enable sign extend instructions.-muser-enabledโ enable user-defined instructions ๐
๐ LoongArch Options ๐
These command-line options are defined for LoongArch targets:
-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.loongarch64โ a generic CPU with 64-bit extensions.la464โ LoongArch LA464 CPU with LBT, LSX, LASX, LVZ.
-mtune=cpu-typeโ optimize the output for the given processor, specified by microarchitecture name ๐-mabi=base-abi-typeโ generate code for the specified calling convention. base-abi-type can be one of:lp64dโ uses 64-bit general purpose registers and 32/64-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits.lp64fโ uses 64-bit general purpose registers and 32-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits.lp64sโ uses 64-bit general purpose registers and no floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits.
-mfpu=fpu-typeโ generate code for the specified FPU type, which can be one of:64โ allow the use of hardware floating-point instructions for 32-bit and 64-bit operations.32โ allow the use of hardware floating-point instructions for 32-bit operations.none0โ prevent the use of hardware floating-point instructions.
-msoft-floatโ force-mfpu=noneand prevents the use of floating-point registers for parameter passing. This option may change the target ABI ๐-msingle-floatโ force-mfpu=32and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI ๐-mdouble-floatโ force-mfpu=64and allow the use of 32/64-bit floating-point registers for parameter passing. This option may change the target ABI ๐-mbranch-cost=nโ sets how expensive a branch is, roughly measured in n instructions. ๐ธ-mcheck-zero-division,-mno-check-zero-divisonโ trap (or don't trap) when someone tries to divide an integer by zero. ๐จ The default is-mcheck-zero-divisionfor-O0or-Og, and-mno-check-zero-divisionfor every other optimization level.-mcond-move-int,-mno-cond-move-intโ conditional moves for integral data in general-purpose registers: on (off). Default is-mcond-move-int. ๐-mcond-move-float,-mno-cond-move-floatโ conditional moves for floating-point registers: on (off). Default is-mcond-move-float. โจ-mmemcpy,-mno-memcpyโ force (or don't force) usingmemcpyfor non-trivial block moves. The default is-mno-memcpy, which lets GCC inline most constant-sized copies, no cap. ๐ซถ Bumping the optimization level to-Osalso forces the use ofmemcpy, but-mno-memcpymay override that behavior if you explicitly specify it โ regardless of the order these options appear on the command line. Sneaky but true.-mstrict-align,-mno-strict-alignโ avoid (or allow) generating memory accesses that might not be aligned on a natural object boundary as described in the architecture specification. 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). Default value is0.-mmax-inline-memcpy-size=nโ inline every block move (stuff like calls tomemcpyor structure copies) that's less than or equal to n bytes. Default value of n is1024. ๐ฆ-mcmodel=code-modelโ picks the code model. Pick from:- tiny-static ๐ฃ
- local symbol and global strong symbol: the data section must be within +/-2MiB addressing space. The text section must be within +/-128MiB addressing space.
- global weak symbol: the got table must be within +/-2GiB addressing space.
- tiny
- local symbol: the data section must be within +/-2MiB addressing space. The text section must be within +/-128MiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
- normal
- local symbol: the data section must be within +/-2GiB addressing space. The text section must be within +/-128MiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
- large
- local symbol: the data section must be within +/-2GiB addressing space. The text section must be within +/-128GiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
- extreme(Not implemented yet) ๐
- local symbol: the data and text section must be within +/-8EiB addressing space.
- global symbol: the data got table must be within +/-8EiB addressing space.
- tiny-static ๐ฃ
The default code model is normal.
-mrelax,-mno-relaxโ take (or don't take) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option also gets passed down to the assembler. The default is decided at GCC build-time by detecting the corresponding assembler support:-mrelaxif the assembler supports both the-mrelaxoption and conditional branch relaxation (this is required, bestie โ otherwise the.aligndirectives and conditional branch instructions in the assembly code GCC outputs 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 along to the assembler. The default is determined at GCC build-time by detecting the corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption,-mno-pass-mrelax-to-asotherwise. This one is mostly useful for debugging, or for interoperating with assemblers that aren't the build-time one. ๐ง
๐ M32C Options ๐
-mcpu=nameโ select the CPU to generate code for. name can be one ofr8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series. ๐-msimโ says the program is gonna run on the simulator, so an alternate runtime library gets linked in that supports, like, file I/O and stuff. ๐ฅ๏ธ You must not use this option when generating programs that will run on real hardware; you have to provide your own runtime library for whatever I/O functions are needed. Real talk.-memregs=numberโ specifies how many memory-based pseudo-registers GCC uses during code generation. These pseudo-registers act like real registers, so there's a whole tradeoff between GCC's ability to fit the code into available registers and the performance penalty of using memory instead of registers. โ๏ธ Heads up: every module 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 defined for Renesas M32R/D architectures:
-m32r2โ generate code for the M32R/2.-m32rxโ generate code for the M32R/X.-m32rโ generate code for the M32R. This is the default. โญ-mmodel=smallโ assumes all objects live in the lower 16MB of memory (so their addresses can be loaded with theld24instruction), and assumes all subroutines are reachable with theblinstruction. This is the default.
The addressability of a particular object can be set with the model attribute.
-mmodel=mediumโ assumes objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assumes all subroutines are reachable with theblinstruction.-mmodel=largeโ assumes objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assumes subroutines may not be reachable with theblinstruction (so the compiler generates the much slowerseth/add3/jlinstruction sequence ๐).-msdata=noneโ disables use of the small data area. Variables go into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default.
The small data area consists of sections .sdata and .sbss. Objects may be explicitly placed in the small data area with the section attribute using one of these sections.
-msdata=sdataโ put small global and static data in the small data area, but don't generate special code to reference them.-msdata=useโ put small global and static data in the small data area, and generate special instructions to reference them. ๐ฅ-G numโ put global and static objects 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 at all, fr.
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 when debugging programs. ๐-malign-loopsโ align all loops to a 32-byte boundary.-mno-align-loopsโ do not enforce a 32-byte alignment for loops. This is the default.-missue-rate=numberโ issue number instructions per cycle. number can only be1or2.-mbranch-cost=numberโ number can only be1or2. If it's1, branches are preferred over conditional code; if it's2, the opposite applies. ๐-mflush-trap=numberโ specifies the trap number used to flush the cache. The default is12. Valid numbers are between0and15inclusive.-mno-flush-trapโ specifies that the cache cannot be flushed by using a trap.-mflush-func=nameโ specifies the name of the operating system function to call to flush the cache. The default is_flush_cache, but a function call is only used if a trap is not available.-mno-flush-funcโ indicates that there is no OS function for flushing the cache.
๐ M680x0 Options ๐
These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below. ๐ง
-march=archโ generate code for a specific M680x0 or ColdFire instruction set architecture. Permissible values of arch for M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures are selected according to Freescale's ISA classification and the permissible values are:isaa,isaaplus,isabandisac.
GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above. ๐
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture.
-mcpu=cpuโ generate code for a specific M680x0 or ColdFire processor. The M680x0 cpus are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire cpus are given by the table below, which also classifies the CPUs into families: ๐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 combos of-mcpuand-marchget rejected, bestie, they don't play nice together.
GCC defines the macro __mcf_cpu_cpu when a ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family comes from the table above. ๐
-mtune=tune โ tune the code for a particular microarchitecture, but 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's 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's 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's equivalent to-march=68020.-m68030โ generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It's equivalent to-march=68030.-m68040โ generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It's 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 doesn't 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's 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 doesn't 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's 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's equivalent to-mcpu=5206, and is now deprecated in favor of that option.
Use this option for a microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
-m5206eโ generate output for a 5206e ColdFire CPU. This option is now deprecated in favor of the equivalent-mcpu=5206e.-m528xโ generate output for a member of the ColdFire 528X family. This option is now deprecated in favor of the equivalent-mcpu=528x.-m5307โ generate output for a ColdFire 5307 CPU. This option is now deprecated in favor of the equivalent-mcpu=5307.-m5407โ generate output for a ColdFire 5407 CPU. This 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; use library calls instead. This is the default for68000,68010and68832targets. It's also the default for ColdFire devices that have no FPU.-mdiv-mno-divโ generate (do not generate) ColdFire hardware divide and remainder instructions. If-marchis used without-mcpu, the default isonfor ColdFire architectures andofffor M680x0 architectures. Otherwise, the default is taken from the target CPU (either the default CPU, or the one specified by-mcpu). For example, the default isofffor-mcpu=5206andonfor-mcpu=5206e. ๐ซ
GCC defines the macro __mcfhwdiv__ when this option is enabled.
-mshortโ consider typeintto be 16 bits wide, likeshort int. Additionally, parameters passed on the stack are also aligned to a 16-bit boundary, even on targets whose API mandates promotion to 32-bit.-mno-shortโ do not consider typeintto be 16 bits wide. This is the default.-mnobitfield-mno-bitfieldโ do not use the bit-field instructions. The-m68000,-mcpu32and-m5200options imply-mnobitfield.-mbitfieldโ do use the bit-field instructions. The-m68020option implies-mbitfield. This is the default if you use a configuration designed for a 68020.-mrtdโ use a different function-calling convention, in which functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. This saves one instruction in the caller, since there's no need to pop the arguments there. ๐
This calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler.
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. ๐ญ
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.)
The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.
The default is -mno-rtd.
-malign-int-mno-align-intโ control whether GCC alignsint,long,long long,float,double, andlong doublevariables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory.
Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k. ๐
Use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors.
-mno-strict-align-mstrict-alignโ do not (do) assume that unaligned memory references are handled by the system.-msep-dataโ generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies-fPIC. โจ-mno-sep-dataโ generate code that assumes that the data segment follows the text segment. This is the default.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies-fPIC.-mno-id-shared-libraryโ generate code that doesn't assume ID-based shared libraries are being used. This is the default.- *
-mshared-library-id=n* โ specifies the identification number of the ID-based shared library being compiled. Specifying a value of0generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option. -mxgot-mno-xgotโ when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors, this option is not needed;-fPICsuffices. ๐ฆ
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
Okay so if that happens, bestie, you literally just recompile your code with -mxgot and it should work with very large GOTs. But lowkey there's a catch โ code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol. ๐ญ Not ideal but it works.
Also ngl, some linkers (including newer versions of the GNU linker) can create multiple GOTs and sort GOT entries. If you've got one of those fancy linkers, you should only need -mxgot when you're compiling a single object file that accesses more than 8192 GOT entries. And likeโฆ very few do. ๐
Heads up: these options have no effect unless GCC is generating position-independent code. Fr fr, they do nothing otherwise.
-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. iykyk.
-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, so it's the moment.)-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 that need 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. ๐
๐ฆ MeP Options ๐ฆ
-mabsdiffโ enables theabsinstruction, which is the absolute difference between two registers.-mall-optsโ enables all the optional instructions---average, multiply, divide, bit operations, leading zero, absolute difference, min/max, clip, and saturation. The whole buffet, no cap.-maverageโ enables theaveinstruction, which computes the average of two registers.-mbased=nโ variables of size n bytes or smaller are placed in the.basedsection by default. Based variables use the$tpregister as a base register, and there is a 128-byte limit to the.basedsection.-mbitopsโ enables the bit operation instructions---bit test (btstm), set (bsetm), clear (bclrm), invert (bnotm), and test-and-set (tas).-mc=nameโ selects which section constant data is placed in. name may betiny,near, orfar.-mclipโ enables theclipinstruction. Note that-mclipis not useful unless you also provide-mminmax. They're a package deal, bestie. ๐ซถ-mconfig=nameโ selects one of the built-in core configurations. Each MeP chip has one or more modules in it; each module has a core CPU and a variety of coprocessors, optional instructions, and peripherals. TheMeP-Integratortool, not part of GCC, provides these configurations through this option; using this option is the same as using all the corresponding command-line options. The default configuration isdefault.-mcopโ enables the coprocessor instructions. By default, this is a 32-bit coprocessor. Note that the coprocessor is normally enabled via the-mconfig=option.-mcop32โ enables the 32-bit coprocessor's instructions.-mcop64โ enables the 64-bit coprocessor's instructions.-mivc2โ enables IVC2 scheduling. IVC2 is a 64-bit VLIW coprocessor.-mdcโ causes constant variables to be placed in the.nearsection.-mdivโ enables thedivanddivuinstructions.-mebโ generate big-endian code.-melโ generate little-endian code.-mio-volatileโ tells the compiler that any variable marked with theioattribute is to be considered volatile.-mlโ causes variables to be assigned to the.farsection by default.-mleadzโ enables theleadz(leading zero) instruction.-mmโ causes variables to be assigned to the.nearsection by default.-mminmaxโ enables theminandmaxinstructions.-mmultโ enables the multiplication and multiply-accumulate instructions.-mno-optsโ disables all the optional instructions enabled by-mall-opts.-mrepeatโ enables therepeatanderepeatinstructions, used for low-overhead looping. Loop era. โจ-msโ causes all variables to default to the.tinysection. Note that there is a 65536-byte limit to this section. Accesses to these variables use the%gpbase register.-msaturโ enables the saturation instructions. Note that the compiler does not currently generate these itself, but this option is included for compatibility with other tools, likeas.-msdramโ link the SDRAM-based runtime instead of the default ROM-based runtime.-msimโ link the simulator run-time libraries.-msimnovecโ link the simulator runtime libraries, excluding built-in support for reset and exception vectors and tables.-mtfโ causes all functions to default to the.farsection. Without this option, functions default to the.nearsection.-mtiny=nโ variables that are n bytes or smaller are allocated to the.tinysection. These variables use the$gpbase register. The default for this option is4, but note that there's a 65536-byte limit to the.tinysection.
๐ 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. Valid models are:executableโ normal executable (default), uses startup codecrt0.o.xmdstubโ for use with Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent calledxmdstub. This uses startup filecrt1.oand sets the start address of the program to0x800.bootstrapโ for applications that are loaded using a bootloader. This model uses startup filecrt2.owhich does not contain a processor reset vector handler. This is suitable for transferring control on a processor reset to the bootloader rather than the application.novectorsโ for applications that do not require any of the MicroBlaze vectors. This option may be useful for applications running within a monitoring application. This model usescrt3.oas a startup file.
Option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model. (Yes, the -mxl-mode-app-model vibe has an old-school cousin. Do not use the cousin.)
-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โ generate code that runs on arch, which can be the name of a generic MIPS ISA, or the name of a particular processor. The ISA names are:mips1,mips2,mips3,mips4,mips32,mips32r2,mips32r3,mips32r5,mips32r6,mips64,mips64r2,mips64r3,mips64r5andmips64r6. The processor names are:4kc,4km,4kp,4ksc,4kec,4kem,4kep,4ksd,5kc,5kf,20kc,24kc,24kf2_1,24kf1_1,24kec,24kef2_1,24kef1_1,34kc,34kf2_1,34kf1_1,34kn,74kc,74kf2_1,74kf1_1,74kf3_2,1004kc,1004kf2_1,1004kf1_1,i6400,i6500,interaptiv,loongson2e,loongson2f,loongson3a,gs464,gs464e,gs264e,m4k,m14k,m14kc,m14ke,m14kec,m5100,m5101,octeon,octeon+,octeon2,octeon3,orion,p5600,p6600,r2000,r3000,r3900,r4000,r4400,r4600,r4650,r4700,r5900,r6000,r8000,rm7000,rm9000,r10000,r12000,r14000,r16000,sb1,sr71000,vr4100,vr4111,vr4120,vr4130,vr4300,vr5000,vr5400,vr5500,xlrandxlp. The special valuefrom-abiselects the most compatible architecture for the selected ABI (that is,mips1for 32-bit ABIs andmips3for 64-bit ABIs).
The native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
In processor names, a final 000 can be abbreviated as k (for example, -march=r2k). Prefixes are optional, and vr may be written r. โจ
- Names of the form nf2_1 = processors with FPUs clocked at half the rate of the core ๐ names of the form nf1_1 = FPUs clocked at the same rate as the core โจ and names of the form nf3_2 = FPUs clocked at a ratio of 3:2 with respect to the core ๐ For compatibility reasons (the way legacy never dies ๐ญ), 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, and bestie they are:
_MIPS_ARCHโ gives the name of target architecture, as a string โจ_MIPS_ARCH_fooโ where foo is the capitalized value of_MIPS_ARCH๐
So like, for example, -march=r2000 sets _MIPS_ARCH to "r2000" and defines the macro _MIPS_ARCH_R2000 ๐ฅ periodt.
- Note that 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โ optimize for arch. Among other things, this option controls the way instructions are scheduled, and the perceived cost of arithmetic operations. The list of arch values is the same as for-march๐- When this option is not used, GCC optimizes for the processor specified by
-march. By using-marchand-mtunetogether, it is possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family ๐ iconic. -mtunedefines the macros_MIPS_TUNEand_MIPS_TUNE_foo, which work in the same way as the-marchones described above ๐
โจ the mips-level shortcut era โจ
okay so these are all just little nicknames, no cap:
-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 era ๐
-mips16,-mno-mips16โ generate (do not generate) MIPS16 code ๐ If GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE.- MIPS16 code generation can also be controlled on a per-function basis by means of
"mips16"and"nomips16"attributes ๐ -mflip-mips16โ generate MIPS16 code on alternating functions ๐ฆ This option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code โ it's giving "test lab only, bestie, don't touch" ๐
๐ interlink era ๐
-minterlink-compressed,-mno-interlink-compressedโ require (do not require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa ๐- For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump.
-minterlink-compressedtherefore 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 ๐ซถ the elders stay respected.
๐ธ the ABI section, we're so back ๐ธ
-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
-mgp32to get 32-bit code instead โจ - For information about the O64 ABI, see <https://gcc.gnu.org/projects/mipso64-abi.html> ๐
- GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. You can select this combination with
-mabi=32 -mfp64. This ABI relies on themthc1andmfhc1instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors ๐ฅ no cap. - 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
$f0only, not a$f0/$f1pair ๐ 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 ๐ง iconic behaviour honestly.
๐ abicalls & shared ๐
-mabicalls,-mno-abicallsโ generate (do not generate) code that is suitable for SVR4-style dynamic objects.-mabicallsis the default for SVR4-based systems ๐-mshared,-mno-sharedโ generate (do not generate) code that is fully position-independent, and that can therefore be linked into shared libraries ๐ This option only affects-mabicalls.- All
-mabicallscode has traditionally been position-independent, regardless of options like-fPICand-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-shareddepends 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-sharedgenerally makes executables both smaller and quicker ๐ฅ slay.-msharedis the default โจ-mplt,-mno-pltโ assume (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
-mpltthe default by configuring GCC with--with-mips-plt. The default is-mno-pltotherwise ๐
๐ฆ GOT problems? we've all been there ๐ฆ
-mxgot,-mno-xgotโ lift (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 ๐ญ the price of power, bestie. - Note that some linkers can create multiple GOTs. If you have such a linker, you should only need to use
-mxgotwhen 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 ๐ธ
โจ register width vibes โจ
-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 ๐ (mysterious, main character energy fr)
๐ float 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. ๐ญ be careful bestie, that's a whole disaster arc.
-msingle-floatโ assume that the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ assume that the floating-point coprocessor supports double-precision operations. This is the default โจ-modd-spreg,-mno-odd-spregโ enable the use of odd-numbered single-precision floating-point registers for the o32 ABI ๐ This is the default for processors that are known to support these registers. When using the o32 FPXX ABI,-mno-odd-spregis set by default ๐
๐ NaN treatment: abs & neg ๐
-mabs=2008,-mabs=legacyโ these options control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with theabs.fmtandneg.fmtmachine instructions ๐- By default or when
-mabs=legacyis used the legacy treatment is selected. In this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead unless the-ffinite-math-onlyoption has also been specified ๐ฆ - The
-mabs=2008option selects the IEEE 754-2008 treatment. In this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN โจ These instructions are therefore always used for the respective operations ๐ฅ -mnan=2008,-mnan=legacyโ these options control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data ๐-mnan=legacyโ this one picks the legacy NaN encoding, bestie. So quiet NaNs (qNaNs, the chill ones) are marked by the first bit of their trailing significand field being 0, and signaling NaNs (sNaNs, the dramatic ones that love to throw exceptions) are marked by that first bit being 1. โจ-mnan=2008โ and this one picks the IEEE 754-2008 encoding instead. Now it's flipped: qNaNs get the first bit of their trailing significand field set to 1, and sNaNs get it set to 0. ๐
The default is-mnan=legacyunless GCC has been configured with--with-nan=2008. No cap.
-mllsc,-mno-llscโ use (or don't use) thell,sc, andsyncinstructions to implement atomic memory built-in functions. If you don't say either one, GCC just uses the instructions whenever the target architecture supports them. ๐ซถ
Lowkey -mllsc is the move when your runtime environment can emulate those instructions, and -mno-llsc hits different when you're compiling for nonstandard ISAs. You can make either one the default by configuring GCC with --with-llsc or --without-llsc respectively. Fun fact: --with-llsc is already the default for some configurations โ peep the installation documentation for the details. ๐
-mdsp,-mno-dspโ use (or don't use) revision 1 of the MIPS DSP ASE. This option defines the preprocessor macro__mips_dsp. It also defines__mips_dsp_revto 1. ๐-mdspr2,-mno-dspr2โ use (or don't use) revision 2 of the MIPS DSP ASE. This one defines the preprocessor macros__mips_dspand__mips_dspr2, and it also defines__mips_dsp_revto 2. ๐ฆ-msmartmips,-mno-smartmipsโ use (or don't use) the MIPS SmartMIPS ASE. That's it, that's the whole vibe.-mpaired-single,-mno-paired-singleโ use (or don't use) paired-single floating-point instructions. Heads up tho: this option requires hardware floating-point support to be enabled. ๐-mdmx,-mno-mdmxโ use (or don't use) MIPS Digital Media Extension instructions. Plot twist: this option can only be used when generating 64-bit code, and it also requires hardware floating-point support to be enabled. ๐-mips3d,-mno-mips3dโ use (or don't use) the MIPS-3D ASE. And btw,-mips3dimplies-mpaired-single. It's giving package deal. ๐-mmicromips,-mno-micromipsโ generate (or don't generate) microMIPS code.
You can also control microMIPS code generation on a per-function basis with the micromips and nomicromips attributes. So granular, we love that for you. โจ
-mmt,-mno-mtโ use (or don't use) MT Multithreading instructions.-mmcu,-mno-mcuโ use (or don't use) the MIPS MCU ASE instructions.-meva,-mno-evaโ use (or don't use) the MIPS Enhanced Virtual Addressing instructions.-mvirt,-mno-virtโ use (or don't use) the MIPS Virtualization (VZ) instructions.-mxpa,-mno-xpaโ use (or don't use) the MIPS eXtended Physical Address (XPA) instructions.-mcrc,-mno-crcโ use (or don't use) the MIPS Cyclic Redundancy Check (CRC) instructions.-mginv,-mno-ginvโ use (or don't use) the MIPS Global INValidate (GINV) instructions.-mloongson-mmi,-mno-loongson-mmiโ use (or don't use) the MIPS Loongson MultiMedia extensions Instructions (MMI).-mloongson-ext,-mno-loongson-extโ use (or don't use) the MIPS Loongson EXTensions (EXT) instructions.-mloongson-ext2,-mno-loongson-ext2โ use (or don't use) the MIPS Loongson EXTensions r2 (EXT2) instructions. Three Loongson options in a row, iconic behavior honestly. ๐-mlong64โ forcelongtypes to be 64 bits wide. For the lore on what the default is and how pointer size gets decided, go read-mlong32. ๐-mlong32โ forcelong,int, and pointer types to be 32 bits wide.
So here's the tea: 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, and so does the 64-bit EABI; the others use 32-bit longs. Pointers are the same size as longs โ or the same size as integer registers, whichever is smaller. ๐ง
-msym32,-mno-sym32โ assume (or don't assume) that all symbols have 32-bit values, regardless of the selected ABI. This option is useful in combination with-mabi=64and-mno-abicalls, because it lets GCC generate shorter and faster references to symbolic addresses. Speed AND efficiency? Ate. ๐ฅ-Gnum โ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. Then GCC can generate more efficient accesses to that data โ check-mgpoptfor the deets.
The default -G option depends on the configuration. ๐
-mlocal-sdata,-mno-local-sdataโ extend (or don't extend) the-Gbehavior to local data too, like static variables in C.-mlocal-sdatais the default for all configurations. ๐ซถ
If the linker starts complaining that an application is using too much small data, you might wanna try rebuilding the less performance-critical parts with -mno-local-sdata. You might also wanna build large libraries with -mno-local-sdata, so the libraries leave more room for the main program. Sharing is caring.
-mextern-sdata,-mno-extern-sdataโ assume (or don't 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.
Okay this next part is important, so listen up. If you compile a module Mod with-mextern-sdata -Gnum-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-Gsetting or attach asectionattribute to Var's definition. If Var is common, you must link the application with a high-enough-Gsetting. Don't skip this, bestie. ๐ญ
The easiest way of satisfying these restrictions is to compile and link every module with the same -G option. But maybe you wanna build a library that supports several different small data limits โ that's valid. You can do it 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 (or don't use) GP-relative accesses for symbols that are known to be in a small data section; peep-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations. โจ
-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.)
And -mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. The domino effect, fr fr. ๐ข
-membedded-data,-mno-embedded-dataโ allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. This gives slightly slower code than the default, but it reduces the amount of RAM required when executing โ so it may be preferred for some embedded systems. Trade-offs, baby. โ๏ธ-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ put uninitializedconstvariables in the read-only data section. Quick note: this option is only meaningful in conjunction with-membedded-data. It doesn't do anything on its own. ๐-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's also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM. Very specific, very slay. ๐-mcode-readable=noโ instructions must not access executable sections. This option can be useful on targets that are configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM. So close but not quite. ๐ญ
-msplit-addresses,-mno-split-addressesโ enable (or disable) use of the%hi()and%lo()assembler relocation operators. Heads up: this option has been superseded by-mexplicit-relocsbut is retained for backwards compatibility. It's giving legacy support, respect the elders. ๐-mexplicit-relocs,-mno-explicit-relocsโ use (or don't use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by-mno-explicit-relocs, is to use assembler macros instead.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators. ๐
-mcheck-zero-division,-mno-check-zero-divisionโ trap (or don't trap) on integer division by zero.
The default is -mcheck-zero-division. โ ๏ธ
-mdivide-traps,-mdivide-breaksโ MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but it's only supported on MIPS II and later. Also, some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE). Yikes. Use-mdivide-trapsto allow conditional traps on architectures that support them, and-mdivide-breaksto force the use of breaks. ๐
The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. And if you want them gone entirely, divide-by-zero checks can be completely disabled using -mno-check-zero-division. ๐ซถ
-mload-store-pairs,-mno-load-store-pairsโ enable (or disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default, but it only takes effect when the selected architecture is known to support bonding. Otherwise it's just vibing. โจ-munaligned-access,-mno-unaligned-accessโ enable (or disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So-mno-unaligned-accessmay be needed by kernel. Kernel besties, this one's for you. ๐-mmemcpy,-mno-memcpyโ force (or don't force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. Inlining stays winning. ๐ฅ-mlong-calls,-mno-long-callsโ okay so-mlong-callsturns OFF the use of thejalinstruction, and-mno-long-callsis the "do not disable it" twin ๐ . Usingjalto call functions is more efficient, but it comes with a whole situationship: the caller and the callee have to live in the same 256 megabyte segment. That's it, that's the deal.
No cap: this option does nothing on abicalls code. The default is -mno-long-calls.
-mmad,-mno-madโ enable (or disable) use of themad,maduandmulinstructions, as provided by the R4650 ISA โจ.-mimadd,-mno-imaddโ enable (or disable) use of themaddandmsubinteger instructions. The default is-mimaddon architectures that supportmaddandmsubโ except for the 74k architecture, where it was found to generate slower code ๐ญ (the 74k said "not today").-mfused-madd,-mno-fused-maddโ enable (or disable) use of the floating-point multiply-accumulate instructions, whenever they're available. Default is-mfused-madd๐ซถ.
Heads up bestie: 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. That 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.
-nocppโ tell the MIPS assembler to not run its preprocessor over user assembler files (the ones with a.ssuffix) when assembling them ๐.-mfix-24k,-mno-fix-24kโ work around the 24K E48 errata (lost data on stores during refill) ๐. These workarounds are implemented by the assembler, not by GCC.-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.
-mfix-r5900,-mno-fix-r5900โ do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer, and always schedule anopinstruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip ๐. The workaround is implemented by the assembler rather than by GCC.-mfix-rm7000,-mno-fix-rm7000โ work around the RM7000dmult/dmultuerrata. The workarounds are implemented by the assembler rather than by GCC.-mfix-vr4120,-mno-fix-vr4120โ work around certain VR4120 errata:dmultudoes not always produce the correct result.divandddivdo not always produce the correct result if one of the operands is negative.
The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the mips64vr*-elf configurations โจ.
Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. These errata are handled by the assembler, not by GCC itself.
-mfix-vr4130โ work around the VR4130mflo/mfhierrata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids usingmfloandmfhiif the VR4130macc,macchi,dmaccanddmacchiinstructions are available instead ๐-mfix-sb1,-mno-fix-sb1โ work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2F1andF2floating-point errata.)-mr10k-cache-barrier=settingโ specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors ๐ง.
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 at all ๐ซ. If called, the function must take the same arguments as the common_flush_funcโ that is, the address of the memory range for which the cache is being flushed, the size of the memory range, and the number3(to flush both caches). The default depends on the target GCC was configured for, but commonly is either_flush_funcor__cpu_flush๐ธ.mbranch-cost=numโ set the cost of branches to roughly num "simple" instructions. (Yes bestie, the manpage really does write it without the leading dash. I don't make the rules, I just transcribe them exactly. ๐ ) This cost is only a heuristic and is not guaranteed to produce consistent results across releases. A zero cost redundantly selects the default, which is based on the-mtunesetting.-mbranch-likely,-mno-branch-likelyโ enable or disable use of Branch Likely instructions, regardless of the default for the selected architecture. By default, Branch Likely instructions may be generated if they are supported by the selected architecture. An exception is for the MIPS32 and MIPS64 architectures and processors that implement those architectures; for those, Branch Likely instructions are not be generated by default because the MIPS32 and MIPS64 architectures specifically deprecate their use ๐ค.-mcompact-branches=never,-mcompact-branches=optimal,-mcompact-branches=alwaysโ these options control which form of branches will be generated. The default is-mcompact-branches=optimalโจ.
The -mcompact-branches=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. If a compact branch instruction is not available, a delay slot form of the branch will be used instead.
This option is supported from MIPS Release 6 onwards ๐.
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.
-mfp-exceptions,-mno-fp-exceptionsโ specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled ๐ซถ.
For instance, on the SB-1, if FP exceptions are disabled, and we are emitting 64-bit code, then we can use both FP pipes. Otherwise, we can only use one FP pipe ๐ฅฒ.
-mvr4130-align,-mno-vr4130-alignโ the VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel ๐ฏ.
This option only has an effect when optimizing for the VR4130. It normally makes code faster, but at the expense of making it bigger. It is enabled by default at optimization level -O3 ๐ฅ.
-msynci,-mno-synciโ enable (or disable) generation ofsynciinstructions on architectures that support it. Thesynciinstructions (if enabled) are generated when__builtin___clear_cacheis compiled ๐.
This option defaults to -mno-synci, but the default can be overridden by configuring GCC with --with-synci.
Careful bestie: when compiling code for single processor systems, it is generally safe to use synci. However, on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior ๐.
-mrelax-pic-calls/-mno-relax-pic-callsโ bestie, this tries to turn PIC calls that would normally get dispatched through register$25into direct calls instead. It can only happen if the linker can figure out the destination at link time and that destination is within range for a direct call. No cap.
-mrelax-pic-calls is the default if GCC was configured to use an assembler and a linker that support the .reloc assembly directive and -mexplicit-relocs is in effect. But with -mno-explicit-relocs, this optimization can be done by the assembler and the linker all on their own, no compiler help needed. Teamwork fr. ๐ซถ
-mmcount-ra-address/-mno-mcount-ra-addressโ emit (or don't emit) code that lets_mcountmodify the calling function's return address. When you turn it on, this option extends the usual_mcountinterface with a new ra-address parameter, which has typeintptr_t *and gets 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 (or disable) frame header optimization in the o32 ABI. When you're using the o32 ABI, calling functions allocate 16 bytes on the stack so the called function can write out register arguments. When this is enabled, the optimization will suppress that frame header allocation if it can tell it's unused. Iconic, honestly.
Heads up: this optimization is off by default at all optimization levels. ๐ญ
-mlxc1-sxc1/-mno-lxc1-sxc1โ when applicable, enable (or disable) generatinglwxc1,swxc1,ldxc1,sdxc1instructions. Enabled by default. โจ-mmadd4/-mno-madd4โ when applicable, enable (or disable) generating 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. Periodt.-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 (inside the called function) are seen as registers$0and up, as opposed to the GNU ABI which uses global registers$231and up. Two whole vibes.-mzero-extend/-mno-zero-extendโ when reading data from memory in sizes shorter than 64 bits, use (or do not use) zero-extending load instructions by default, rather than sign-extending ones.-mknuthdiv/-mno-knuthdivโ make the result of a division yielding a remainder have the same sign as the divisor. With the default,-mno-knuthdiv, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, but the latter is almost exclusively used. iykyk.-mtoplevel-symbols/-mno-toplevel-symbolsโ prepend (or do not prepend) a:to all global symbols, so the assembly code can be used with thePREFIXassembly directive.-melfโ generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator.-mbranch-predict/-mno-branch-predictโ use (or do not use) the probable-branch instructions, when static branch prediction indicates a probable branch.-mbase-addresses/-mno-base-addressesโ generate (or do not generate) code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register. That register is used for one or more base address requests within the range 0 to 255 from the value held in the register. This generally leads to short and fast code, but the number of different data items that can be addressed is limited. Which means a program that uses lots of static data may require-mno-base-addresses. ๐-msingle-exit/-mno-single-exitโ force (or do not force) generated code to have a single exit point in each function.
๐ MN10300 Options ๐
These -m options are defined for Matsushita MN10300 architectures:
-mmult-bugโ 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โ tell the linker it should perform a relaxation optimization pass to shorten branches, calls and absolute memory addresses. This option only does anything when used on the command line for the final link step.
Fr fr, careful: 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 the SETLB and Lcc instructions 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 generate SETLB or Lcc instructions. 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โ generate mul.x and umul.x instructions. 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 to see it. ๐-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__. That symbol 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's known to only support the 430 ISA, then that's what gets selected โ otherwise the 430X ISA is selected. A generic MCU name of msp430 can also be used to select the 430 ISA. Similarly, the generic msp430x MCU name selects the 430X ISA.
On top of all that, an MCU-specific linker script gets added to the linker command line. The script's name is the name of the MCU with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and causes the linker to search for a script called xxx.ld.
The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However, an external devices.csv file can be used to extend device support beyond those that have been hard-coded. ๐
GCC searches for the devices.csv file 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-Ldevices.csvwill be searched for in each of the directories specified by include paths and linker library search paths. - Path specified by the environment variable
MSP430_GCC_INCLUDE_DIRDefine the value of the global environment variableMSP430_GCC_INCLUDE_DIRto the full path to the directory containingdevices.csv, and GCC will search this directory fordevices.csv. Ifdevices.csvis found, this directory will also be registered as an include path, and linker library path. Header files and linker scripts in this directory can therefore be used without manually specifying-Iand-Lon the command line. - The
msp430-elf{,bare}/include/devicesdirectory Finally, GCC will examinemsp430-elf{,bare}/include/devicesfrom the toolchain root directory. This directory does not exist in a default installation, but if the user has created it and copieddevices.csvthere, then the MCU data will be read. As above, this directory will also be registered as an include path, and linker library path.
If none of the above search methods find devices.csv, then the hard-coded MCU data is used.
-mwarn-mcu/-mno-warn-mcuโ this option enables or disables warnings about conflicts between the MCU name specified by the-mmcuoption and the ISA set by the-mcpuoption and/or the hardware multiply support set by the-mhwmultoption. It also toggles warnings about unrecognized MCU names. This option is on by default. โจ-mcpu=โ specifies the ISA to use. Accepted values aremsp430,msp430xandmsp430xv2.
Ngl, this option is deprecated. The -mmcu= option should be used to select the ISA.
-msimโ link to the simulator runtime libraries and linker script. Overrides any scripts that would be selected by the-mmcu=option.-mlargeโ use large-model addressing (20-bit pointers, 20-bitsize_t).-msmallโ small-model addressing era ๐ like, 16-bit pointers and a 16-bitsize_t. tiny bb energy.-mrelaxโ hands this off to the assembler and the linker, and it lets the linker do certain optimizations that literally cannot happen until the final link. last-minute glow-up, no cap.mhwmult=โ tells everyone what kind of hardware multiply your target actually supports. accepted values, bestie:noneโ no hardware multiply at all, we cope ๐ซถ16bitโ 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โ GCC deduces the hardware multiply support based upon the MCU name provided by the-mmcuoption. if no-mmcuoption is specified or if the MCU name is not recognized, then no hardware multiply support is assumed."auto"is the default setting, periodt.
so normally, hardware multiplies get performed by calling a library routine. this saves space in the generated code โ skinny legend. but when compiling at -O3 or higher, the hardware multiplier is invoked inline instead, which makes for bigger but faster code. trade-offs, we love a trade-off โจ
also! the hardware multiply routines disable interrupts whilst running and restore the previous interrupt state when they finish. so they're safe to use inside interrupt handlers as well as in normal code. considerate queens ๐
-minrtโ enable the use of a minimum runtime environment โ no static initializers, no constructors. intended for memory-constrained devices (the broke-but-thriving ones ๐). the compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required.-mtiny-printfโ turns on the reduced code sizeprintfandputslibrary functions. heads up tho: 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. raw, unfiltered, sending it straight ๐
this option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.
-mmax-inline-shift=โ takes an integer between 0 and 64 inclusive, and sets the maximum number of inline shift instructions which should be emitted to perform a shift operation by a constant amount. when this value needs to be exceeded, an mspabi helper 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 passed for this option is divided by 2 and the resulting value used instead. math is mathing โจ
-mcode-region=,-mdata-region=โ these options tell the compiler where to place functions and data that do not have one of the"lower","upper","either"or"section"attributes. possible values are"lower","upper","either"or"any". the first three behave like the corresponding attribute. the fourth possible value โ"any"โ is the default. it leaves placement entirely up to the linker script and how it assigns the standard sections (.text,.data, etc) to the memory regions. let the linker script have its main character moment ๐-msilicon-errata=โ this option passes on a request to assembler to enable the fixes for the named silicon errata. fixing the past, iconic.-msilicon-errata-warn=โ this option passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied. we love a heads-up ๐-mwarn-devices-csv,-mno-warn-devices-csvโ warn ifdevices.csvis not found or there are problem parsing it (default: on).
๐ฆ NDS32 Options ๐ฆ
these options are defined for NDS32 implementations:
-mbig-endianโ generate code in big-endian mode.-mlittle-endianโ generate code in little-endian mode.-mreduced-regsโ use reduced-set registers for register allocation.-mfull-regsโ use full-set registers for register allocation.-mcmovโ generate conditional move instructions.-mno-cmovโ do not generate conditional move instructions.-mext-perfโ generate performance extension instructions.-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 within 512KB addressing space. the text segment must be within 16MB addressing space.mediumโ the data segment must be within 512KB while the read-only data segment can be within 4GB addressing space. the text segment should be still within 16MB addressing space.largeโ all the text and data segments can be within 4GB addressing space. go big ๐ซถ
-mctor-dtorโ enable constructor/destructor feature.-mrelaxโ guide linker to relax instructions. manifesting chill for the linker โจ
๐ 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 to num bytes into the small data or BSS sections instead of the normal data or BSS sections. the default value of num is8.-mgpopt=option,-mgpopt,-mno-gpoptโ generate (do not 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 a"section"attribute.globalโ as forlocal, but also generate GP-relative accesses for small data objects that are external, weak, or common. if you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same-Gsetting. ๐dataโ generate GP-relative accesses for all data objects in the program. if you use this option, the entire data and BSS segments of your program must fit in 64K of 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 in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. all-in, no crumbs ๐
-mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none.
the default is -mgpopt except when -fpic or -fPIC is specified to generate position-independent code. note that the Nios II ABI does not permit GP-relative accesses from shared libraries.
you may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. in this case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section. ๐ญ
-mgprel-sec=regexpโ this option specifies additional section names that can be accessed via GP-relative addressing. it is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. the regexp is a POSIX Extended Regular Expression.
this option does not affect the behavior of the -G option, and the specified sections are in addition to the standard .sdata and .sbss small-data sections that are recognized by -mgpopt.
-mr0rel-sec=regexpโ this option specifies names of sections that can be accessed via a 16-bit offset from"r0"; that is, in the low 32K or high 32K of the 32-bit address space. it is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. the regexp is a POSIX Extended Regular Expression.
in contrast to the use of GP-relative addressing for small data, zero-based addressing is never generated by default and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory. quirky, but we respect it ๐ธ
-mel,-mebโ generate little-endian (default) or big-endian (experimental) code, respectively.-march=archโ this specifies the name of the target Nios II architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. permissible names are:r1,r2.
the preprocessor macro __nios2_arch__ is available to programs, with value 1 or 2, indicating the targeted ISA level.
-mbypass-cache,-mno-bypass-cacheโ force all load and store instructions to always bypass cache by using I/O variants of the instructions. the default is not to bypass the cache.-mno-cache-volatile,-mcache-volatileโ volatile memory access bypass the cache using the I/O variants of the load and store instructions. the default is not to bypass the cache.-mno-fast-sw-div,-mfast-sw-divโ do not use table-based fast divide for small numbers. the default is to use the fast divide at-O3and above.-mno-hw-mul,-mhw-mul,-mno-hw-mulx,-mhw-mulx,-mno-hw-div,-mhw-divโ enable or disable emittingmul,mulxanddivfamily of instructions by the compiler. the default is to emitmuland not emitdivandmulx.-mbmx,-mno-bmx,-mcdx,-mno-cdxโ turn generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions on or off. Heads up bestie: enabling these also needs-march=r2. And since these are optional extensions to the R2 architecture, the default is not to emit them. Periodt.-mcustom-insn=N,-mno-custom-insnโ each-mcustom-insn=Noption enables use of a custom instruction with encodingNwhen generating code that uses insn. Like, for example,-mcustom-fadds=253generates custom instruction253for single-precision floating-point add operations instead of the default behavior of using a library call. ๐
The following values of insn are supported. Except as otherwise noted, floating-point operations are expected to be implemented with normal IEEE 754 semantics and correspond directly to the C operators or the equivalent GCC built-in functions.
Single-precision floating point:
fadds,fsubs,fdivs,fmulsโ binary arithmetic operations. the classics ๐fnegsโ unary negation.fabssโ unary absolute value.fcmpeqs,fcmpges,fcmpgts,fcmples,fcmplts,fcmpnesโ comparison operations.fmins,fmaxsโ floating-point minimum and maximum. Only generated if-ffinite-math-onlyis specified.fsqrtsโ unary square root operation.fcoss,fsins,ftans,fatans,fexps,flogsโ floating-point trigonometric and exponential functions. 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. Only generated if-ffinite-math-onlyis specified.fsqrtdโ unary square root operation.fcosd,fsind,ftand,fatand,fexpd,flogdโ double-precision trigonometric and exponential functions. Only generated if-funsafe-math-optimizationsis also specified.
Conversions:
fextsdโ conversion from single precision to double precision.ftruncdsโ conversion from double precision to single precision.fixsi,fixsu,fixdi,fixduโ conversion from floating point to signed or unsigned integer types, with truncation towards zero.roundโ conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the"__builtin_lroundf"function when-fno-math-errnois used.floatis,floatus,floatid,floatudโ conversion from signed or unsigned integer types to floating-point types.
Also, all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or only operand of a unary operation) is given to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction that returns a double-precision result returns the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC automatically generates the necessary code sequences to write register X and/or read register Y when double-precision floating-point instructions are used. no cap ๐ซถ
fwrxโ writesrc1into the least significant half of X andsrc2into the most significant half of X.fwryโ writesrc1into Y.frdxhi,frdxloโ read the most or least (respectively) significant half of X and store it indest.frdyโ read the value of Y and store it intodest.
Lowkey a lil PSA: 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 option enables a predefined, named set of custom instruction encodings (peep-mcustom-insnabove for the lore). 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. ๐
Another lil PSA: 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."read"and"write". This option is typically used to link with a library provided by a HAL BSP.
๐ Nvidia PTX Options ๐
These options are defined for Nvidia PTX:
-m64โ ignored, but preserved for backward compatibility. Only 64-bit ABI is supported. it's giving legacy code energy, we keep it around for the vibes-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 target architecture issm_30.
This option sets the value of the preprocessor macro "__PTX_SM__"; for instance, for sm_35, it has the value 350.
-misa=architecture-stringโ alias of-march=.-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 specified PTX ISA target architecture via option-march=.
This option sets the values of the preprocessor macros "__PTX_ISA_VERSION_MAJOR__" and "__PTX_ISA_VERSION_MINOR__"; for instance, for 3.1 the macros have the values 3 and 1, respectively.
-mmainkernelโ link in code for a__mainkernel. This is for stand-alone instead of offloading execution.-moptimizeโ apply partitioned execution optimizations. This is the default when any level of optimization is selected.-msoft-stackโ generate code that does not use".local"memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or"alloca"), and when global memory is used for underlying storage, makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option-mgomp. ๐ฅ-muniform-simtโ switch to 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.-mgompโ generate code for use in OpenMP offloading: enables-msoft-stackand-muniform-simtoptions, and selects corresponding multilib variant.
๐ OpenRISC Options ๐
These options are defined for OpenRISC:
-mboard=nameโ sets up a board-specific runtime ๐ ๏ธ. This gets handed off to the linker so it can link the right newlib board library. Default is"or1ksim", bestie.-mnewlibโ this one does literally nothing ๐ it's only here for compatibility. Back in the day it picked the linker and preprocessor options for newlib, and now it just vibes.-msoft-div-mhard-divโ pick whether divide ops use software or hardware, i.e. thel.divandl.divuinstructions. Default is hardware divide ๐ .-msoft-mul-mhard-mulโ software or hardware multiply, sol.mulandl.muli. Default is hardware multiply.-msoft-float-mhard-floatโ software or hardware for floating point operations. Default is software, no cap.-mdouble-floatโ when-mhard-floatis on, this enables generating double-precision floating point instructions โจ. By default, functions from libgcc handle double-precision floating point instead.-munordered-floatโ when-mhard-floatis on, this enables generating unordered floating point compare and set flag (lf.sfun*) instructions. By default, libgcc functions do the unordered floating point compare and set flag work.-mcmovโ enables generating conditional move (l.cmov) instructions ๐ซ. By default the equivalent gets generated with set and branch instead.-mrorโ enables generating rotate right (l.ror) instructions. By default, libgcc functions handle rotate right.-mroriโ enables generating rotate right with immediate (l.rori) instructions. By default, libgcc functions handle rotate right with immediate.-msextโ enables generating sign extension (l.ext*) instructions. By default, memory loads do the sign extension.-msfimmโ enables generating compare and set flag with immediate (l.sf*i) instructions. By default, extra instructions get generated to store the immediate to a register first.-mshftimmโ enables generating shift with immediate (l.srai,l.srli,l.slli) instructions. By default, extra instructions get generated to store the immediate to a register first.-mcmodel=smallโ generates OpenRISC code for the small model: the GOT is limited to 64k. This is the default model ๐.-mcmodel=largeโ generates OpenRISC code for the large model: the GOT may grow up to 4G in size ๐ซ .
๐ PDP-11 Options ๐
These options are defined for the PDP-11, periodt:
-mfpuโ use hardware FPP floating point. This is the default โจ. (FIS floating point on the PDP-11/40 is not supported, sorry babe.) Implies-m45.-msoft-floatโ do not use hardware floating point.-mac0โ return floating-point results in ac0 (fr0in 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-bitint. This is the default.-mint32-mno-int16โ use 32-bitint.-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 oldreloadallocator is used.
๐ picoChip Options ๐
These -m options are defined for picoChip implementations:
-mae=ae_typeโ set the instruction set, register set, and instruction scheduling parameters for array element type ae_type. Supported values for ae_type areANY,MUL, andMAC.-mae=ANYselects a completely generic AE type. Code generated with this option runs on any of the other AE types. The code is not as efficient as it would be if compiled for a specific AE type, and some types of operation (e.g., multiplication) do not work properly on all types of AE ๐.-mae=MULselects a MUL AE type. This is the most useful AE type for compiled code, and is the default ๐.-mae=MACselects a DSP-style MAC AE. Code compiled with this option may suffer from poor performance of byte (char) manipulation, since the DSP AE does not provide hardware support for byte load/stores ๐ญ.
-msymbol-as-addressโ lets the compiler directly use a symbol name as an address in a load/store instruction, without first loading it into a register. Typically, using this option generates larger programs, which run faster than when the option isn't used. However, the results vary from program to program, so it's left as a user option rather than being permanently enabled ๐ซถ.-mno-inefficient-warningsโ disables warnings about the generation of inefficient code. These warnings can be generated, for example, when compiling code that performs byte-level memory operations on the MAC AE type. The MAC AE has no hardware support for byte-level memory operations, so all byte load/stores must be synthesized from word load/store operations. This is inefficient and a warning is generated to indicate that you should rewrite the code to avoid byte operations, or to target an AE type that has the necessary hardware support. This option disables these warnings ๐.
๐ PowerPC Options ๐
These are listed under
๐ฆ PRU Options ๐ฆ
These command-line options are defined for PRU target:
-minrtโ link with a minimum runtime environment, with no support for static initializers and constructors. Using this option can significantly reduce the size of the final ELF binary ๐ช. Beware 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.-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.
๐ธ RISC-V Options ๐ธ
These command-line options are defined for RISC-V targets:
-mbranch-cost=nโ set the cost of branches to roughly n instructions.-mplt-mno-pltโ when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC. The default is-mplt.-mabi=ABI-stringโ specify 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 definingintto 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, so bestie, if you want a specific calling convention you 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.
-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, no shouting allowed ๐ . Examples includerv64i,rv32g,rv32e, andrv32imaf.
When -march= is not specified, use the setting from -mcpu.
okay so if you literally don't hand over either -march or -mcpu=, bestie, the default for this argument is system dependent โ like, it's giving "ask your system, not me". So if you want specific architecture extensions, say it out loud and specify one yourself. No vibes-based guessing. ๐
-mcpu=processor-stringโ use the architecture of and optimize the output for whatever processor you name, by its particular CPU name. The permissible values here 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 guest list, no plus-ones. โจ-mtune=processor-stringโ optimize the output for the given processor, specified by microarchitecture or particular CPU name. Permissible values for this one are:rocket,sifive-3-series,sifive-5-series,sifive-7-series,size, and all valid options for-mcpu=. When-mtune=isn't specified, it uses the setting from-mcpu, and the default isrocketif both are not specified. Thesizechoice is not intended for end-users, okay? That one is used when-Osis 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. ๐ฆ-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. If-mpreferred-stack-boundaryisn't specified, the default 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. All of them. No mix-and-matching, that's the rule. ๐ญ
-msmall-data-limit=nโ put global and static data smaller than n bytes into a special section (on some targets).-msave-restore,-mno-save-restoreโ do or don't use smaller but slower prologue and epilogue code that uses library function calls. The default is to use fast inline prologues and epilogues. โก-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. So specific, so iconique. ๐-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. It's giving "it depends on the CPU, bestie". ๐-mcmodel=medlowโ generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This is the default code model. ๐-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. So like, position-independent, but don't get too comfy. ๐-mexplicit-relocs,-mno-exlicit-relocsโ use or do not use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit optimization. (And yes, that second spelling is exactly what it says โ copy it character for character, no autocorrect energy. ๐ )-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. ๐ฅ-memit-attribute,-mno-emit-attributeโ emit (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32. Version check first, bestie. ๐ง-malign-data=typeโ control how GCC aligns variables and constants of array, structure, or union types. Supported values for type arexlen, which uses x register width as the alignment value, andnatural, which uses natural alignment.xlenis the default. โจ-mbig-endianโ generate big-endian code. This is the default when GCC is configured for ariscv64be-*-*orriscv32be-*-*target.-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for ariscv64-*-*orriscv32-*-*but not ariscv64be-*-*orriscv32be-*-*target.-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ generate stack protection code using canary at guard. Supported locations areglobalfor a global canary ortlsfor per-thread canary in the TLS block. With the latter choice, the options-mstack-protector-guard-reg=regand-mstack-protector-guard-offset=offsetfurthermore 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. iykyk. ๐ง
๐ธ RL78 Options ๐ธ
-msimโ links in additional target libraries to support operation within a simulator. Simulation slay. ๐-mmul=none,-mmul=g10,-mmul=g13,-mmul=g14,-mmul=rl78โ specifies the type of hardware multiplication and division support to be used. The simplest isnone, which uses software for both multiplication and division. This is the default. Theg13value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. Theg14value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The valuerl78is an alias forg14and the valuemg10is an alias fornone. In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are:__RL78_MUL_NONE__,__RL78_MUL_G13__or__RL78_MUL_G14__. ๐ฆ-mcpu=g10,-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=noneoption on the command line. Thus specifying-mcpu=g13enables the use of the G13 hardware multiply peripheral and specifying-mcpu=g10disables the use of hardware multiplications altogether. Note: although the RL78/G14 core is the default target, specifying-mcpu=g14or-mcpu=rl78on 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. 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 registersr24..r31are reserved for use in interrupt handlers. With this option enabled these registers can be used in ordinary functions as well. All the registers, all the time. ๐-m64bit-doubles,-m32bit-doublesโ make thedoubledata 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, we love to see it. โจ
๐ฅ 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_typeoverrides the specification of these options. We recommend you use the-mcpu=cpu_typeoption rather than the options listed above. (Main character move: just use-mcpu=cpu_type. ๐)
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. ๐
okay bestie, back to the PowerPC/POWER buffet, no interruption, we just keep eating ๐
The -mmfcrf option lets GCC generate the move from condition register field instruction โ the one that lives on the POWER4 processor and every other chip that supports the PowerPC V2.01 architecture. Then -mpopcntb lets GCC generate the popcount and double-precision FP reciprocal estimate instructions, which are a POWER5 thing and show up on other PowerPC V2.02 architecture processors. Next, -mpopcntd lets GCC generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture. Then -mfprnd lets GCC generate the FP round to integer instructions implemented on the POWER5+ processor and other processors supporting the PowerPC V2.03 architecture. And -mcmpb lets GCC generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture. Finally, -mhard-dfp lets GCC generate the decimal floating-point instructions implemented on some POWER processors. Obsessed with how many of these exist ngl ๐ซถ
The -mpowerpc64 option lets GCC generate the extra 64-bit instructions you find in the full PowerPC64 architecture, and it treats GPRs as 64-bit, doubleword quantities. And guess what โ GCC defaults to -mno-powerpc64. So if you want the 64-bit sauce, you gotta ask for it. ๐ญ
โจ OPTIONS โจ <span>(still going, we're so back)</span>
-mcpu=cpu_typeโ sets the architecture type, register usage, <em>and</em> instruction scheduling parameters for the machine type cpu_type. Here's the full roster of supported values for cpu_type, no skips, no cuts, we list all of them like the queens they 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, andnative.
So like, -mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endian), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes. Simple, clean, iconic. โจ
If you say native as the cpu type, it 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. She can't detect what she doesn't know, bestie. ๐
Every other option there names a specific processor. Code generated under those options runs best on that processor, and may not run at all on others. So don't be out here being messy with your CPU choice. ๐ซฃ
The -mcpu options automatically enable or disable this whole squad of 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
And here's the tea: which particular options get set for any particular CPU <em>varies between compiler versions</em>, depending on what setting seems to produce optimal code for that CPU. It doesn't necessarily reflect the actual hardware's capabilities โ it's giving <em>vibes-based optimization</em>, not hardware documentation. So if you wanna set an individual option to a particular value yourself, just specify it <em>after</em> the -mcpu option, like:
-mcpu=970 -mno-altivec
On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option at present, because AIX doesn't have full support for these options. You can still enable or disable them individually if you're sure it'll work in your environment. Your call, your risk, your main character moment. ๐
-mtune=cpu_typeโ sets the <em>instruction scheduling parameters</em> for machine type cpu_type, but does not set the architecture type or register usage the way-mcpu=cpu_typedoes. Same values for cpu_type as-mcpuuses, so you're not learning a whole new list, you're welcome. ๐ If both are specified, the generated code uses the architecture and registers set by-mcpu, but the scheduling parameters set by-mtune. Best of both, no conflict, slay.-mcmodel=smallโ generates PowerPC64 code for the small model: the TOC is limited to64k.-mcmodel=mediumโ generates PowerPC64 code for the medium model: the TOC and other static data may be up to a total of4Gin size. This is the default for 64-bit Linux. ๐-mcmodel=largeโ generates PowerPC64 code for the large model: the TOC may be up to4Gin size. Other data and code is only limited by the 64-bit address space. Go big fr fr.-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 like vec_splat, vec_extract, and vec_insert matches array element order corresponding to the endianness of the target. Translation: element zero identifies the <em>leftmost</em> element in a vector register when targeting a big-endian platform, and identifies the <em>rightmost</em> element in a vector register when targeting a little-endian platform. The way that one little detail flips everything ๐ญ
-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. Security girlie behavior ๐ก๏ธ-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. Yeah that's the vibe โ powerful but a little dangerous, we're saying it plainly. ๐จ-misel,-mno-iselโ this switch enables or disables the generation of ISEL instructions. On/off, that's it, cute.-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 (disable) the use of the built-in functions that allow direct access to the cryptographic instructions added in version2.07of the PowerPC ISA. Crypto girlies rise ๐-mhtm,-mno-htmโ enable (disable) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions added in version2.07of the PowerPC ISA.-mpower8-fusion,-mno-power8-fusionโ generate code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors. (Yes, the original says "does not keeps" and I am <em>not</em> touching it, that's canon, character for character bestie ๐ญ)-mpower8-vector,-mno-power8-vectorโ generate code that uses (does not use) the vector and scalar instructions added in version2.07of 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. Note:-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. Note:-mquad-memory-atomicrequires 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.
Important: the VSX instruction set (-mvsx) <em>must</em> be enabled to use the IEEE 128-bit floating point support. And the IEEE 128-bit floating point is <em>only</em> 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 <em>also</em> 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. Slower but valid, periodt. ๐
-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 <em>any</em> 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โ these modify generation of the TOC (<em>Table Of Contents</em>), which gets created for every executable file.-mfull-tocis selected by default. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also places floating-point constants in the TOC. But heads up: only16,384entries 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 -mno-fp-in-toc and -mno-sum-in-toc. -mno-fp-in-toc prevents GCC from putting floating-point constants in the TOC, and -mno-sum-in-toc forces GCC to generate code to calculate 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 <em>very slightly</em> slower and larger code, at the expense of conserving TOC space. Trade-offs, bestie, it's giving balance. โ๏ธ
If you <em>still</em> run out of space in the TOC even when you specify both of these options, specify -mminimal-toc instead. This option causes GCC to make only one TOC entry for every file. When you specify this option, GCC produces code that is slower and larger, but which uses <em>extremely little</em> TOC space. You may wish to use this option only on files that contain less frequently-executed code. Desperate times, minimal TOC, iconic. ๐
-maix64,-maix32โ bestie we're flipping the 64-bit AIX ABI and calling convention switch ๐ซ Turn it on and you get 64-bit pointers, a 64-bitlongtype, and all the infrastructure that has to exist to hold those up. Heads up tho: saying-maix64drags-mpowerpc64in with it, while-maix32kills the 64-bit ABI and implies-mno-powerpc64. GCC's default?-maix32, always, no cap.-mxl-compat,-mno-xl-compatโ this one makes your code behave more like IBM XL compiler semantics when you're riding with the AIX-compatible ABI. It passes floating-point arguments to prototyped functions beyond the register save area (RSA) onto the stack, on top of the argument FPRs. It also refuses to assume that the most significant double inside a 128-bitlong doublevalue is properly rounded when you're comparing values and converting todouble. And it uses XL symbol names forlong doublesupport routines. Iconic behavior tbh.
Okay so storytime ๐ the AIX calling convention got extended but nobody documented it at first โ all to handle some obscure K&R C case where you call a function that takes the address of its arguments, with fewer arguments than were declared. IBM XL compilers reach for floating-point arguments that don't fit in the RSA from the stack whenever a subroutine is compiled without optimization. But since always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not on by default โ you only need it when you're calling subroutines that IBM XL compilers built without optimization. iykyk ๐ซถ
-mpeโ support for the IBM RS/6000 SP Parallel Environment (PE). It links an application written to use message passing with special startup code so the app can actually run. Your system needs PE installed in the standard location (/usr/lpp/ppe.poe/), or you gotta override the specs file with the-specs=option to point at the right directory. And listen โ the Parallel Environment does not support threads, so-mpeand-pthreadare incompatible. Periodt, pick a lane ๐-malign-natural,-malign-powerโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux,-malign-naturaloverrides the ABI-defined alignment of larger types (think floating-point doubles) and aligns them on their natural size-based boundary. Meanwhile-malign-powertells GCC to just follow the ABI-specified alignment rules like a good little compiler. GCC defaults to whatever the ABI defines โจ
Special case bestie: on 64-bit Darwin, natural alignment is the default, and -malign-power isn't supported at all. Not me having favorites ๐
-msoft-float,-mhard-floatโ generate code that does not use (uses) the floating-point register set. Software floating-point emulation is provided if you use-msoft-float, and you also gotta pass the option to GCC when linking. Don't forget the linking part fr fr ๐-mmultiple,-mno-multipleโ generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions. These get generated by default on POWER systems, and not generated on PowerPC systems. Do not use-mmultipleon little-endian PowerPC systems, because 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. Little rebels, obsessed.-mupdate,-mno-updateโ generate code that uses (does not use) the load or store instructions that update the base register to the address of the calculated memory location. These are generated by default. But if you use-mno-update, there's a small window between when the stack pointer gets updated and when the address of the previous frame is stored โ which means code that walks the stack frame across interrupts or signals may get corrupted data ๐ญ Be careful with that one.-mavoid-indexed-addresses,-mno-avoid-indexed-addressesโ generate code that tries to avoid (not avoid) the use of indexed load or store instructions. These instructions can incur a performance penalty on Power6 processors in certain situations, like when you're stepping through large arrays that cross a 16M boundary ๐ Enabled by default when targeting Power6, disabled otherwise.-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions. These get generated by default if hardware floating point is being used. Plot twist: the machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. The way that the machine-dependent flag got a glow-up โจ-mmulhw,-mno-mulhwโ generate code that uses (does not use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These get generated by default when you're targeting those processors ๐-mdlmzb,-mno-dlmzbโ generate code that uses (does not use) the string-searchdlmzbinstruction on the IBM 405, 440, 464 and 476 processors. This instruction is generated by default when targeting those processors. Slay ๐ฅ-mno-bit-align,-mbit-alignโ on System V.4 and embedded PowerPC systems, do not (do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.
Example time, because this one's so much clearer with one ๐ by default, a structure containing nothing but 8 unsigned bit-fields of length 1 is aligned to a 4-byte boundary and has a size of 4 bytes. But if you use -mno-bit-align, that same structure is aligned to a 1-byte boundary and is 1 byte in size. Tiny struct, big energy ๐
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems, do not (do) assume that unaligned memory references are handled by the system. Simple as that, bestie.-mrelocatable,-mno-relocatableโ generate code that allows (does not allow) a static executable to be relocated to a different address at run time. A simple embedded PowerPC system loader should relocate the entire contents of.got2and the 4-byte locations listed in the.fixupsection โ that's a table of 32-bit addresses generated by this option. For this to work, every object linked together must be compiled with-mrelocatableor-mrelocatable-lib. Also-mrelocatablecode aligns the stack to an 8-byte boundary ๐-mrelocatable-lib,-mno-relocatable-libโ like-mrelocatable,-mrelocatable-libgenerates a.fixupsection so static executables can be relocated at run time, but-mrelocatable-libdoes not use the smaller stack alignment of-mrelocatable. The nice part? Objects compiled with-mrelocatable-libmay be linked with objects compiled with any combination of the-mrelocatableoptions. Flexible queen ๐-mno-toc,-mtocโ on System V.4 and embedded PowerPC systems, do not (do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program.-mlittle,-mlittle-endianโ on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode. And btw-mlittle-endianis the same as-mlittle. Twins ๐-mbig,-mbig-endianโ on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode. And-mbig-endianis the same as-mbig. Also twins ๐ฆ-mdynamic-no-picโ on Darwin and Mac OS X systems, compile code so that it is not relocatable, but its external references are relocatable. The resulting code is suitable for applications, but not for shared libraries. Read that again before you ship it ๐-msingle-pic-baseโ treat the register used for PIC addressing as read-only, instead of loading it in the prologue for each function. The runtime system is responsible for initializing this register with an appropriate value before execution begins. So like, that part is on you/runtime, not GCC ๐ค-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, or2, to 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.
-mcall-sysvโ on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement. This is the default unless you configured GCC usingpowerpc-*-eabiaixโญ-mcall-sysv-eabi,-mcall-eabiโ specify both-mcall-sysvand-meabioptions. Two for one, we love a bundle ๐-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. Whole BSD family reunion up in 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 โ this one levels up your current ABI with a lil extension, or yeets one back out. The valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default. That's the whole menu, bestie.-mabi=ibmlongdoubleโ switches your current ABI to use IBM extended-precisionlong double. Lowkey it's probably not gonna work if your system defaults to IEEE extended-precisionlong double. And if you change thelong doubletype away from IEEE extended-precision, the compiler will throw a warning unless you pass-Wno-psabi. Also it requires-mlong-double-128to be enabled. ๐ญ-mabi=ieeelongdoubleโ switches your current ABI to use IEEE extended-precisionlong double. Same energy, flipped: not likely to work if your system defaults to IBM extended-precisionlong double. If you change thelong doubletype away from IBM extended-precision, the compiler warns unless you use-Wno-psabi. Requires-mlong-double-128to be enabled too. ๐-mabi=elfv1โ switches your current ABI to the ELFv1 ABI. This is the default ABI for big-endian PowerPC 64-bit Linux. Overriding the default ABI needs special system support and is likely to fail in spectacular ways. Not "oops" fail. Spectacular fail. ๐-mabi=elfv2โ switches your current ABI to the ELFv2 ABI. This is the default for little-endian PowerPC 64-bit Linux. Overriding the default ABI also requires special system support and is likewise likely to fail in spectacular ways. Same drama, different endianness. ๐ฆ-mgnu-attribute,-mno-gnu-attributeโ emit (or don't emit).gnu_attributeassembly directives that set tag/value pairs in a.gnu.attributessection, which specify ABI variations in function parameters or return values. Metadata girlies, rise.-mprototype,-mno-prototypeโ on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped. Otherwise, the compiler has to insert an instruction before every non-prototyped call to set or clear bit 6 of the condition code register (CR), to indicate whether floating-point values are passed in the floating-point registers in case the function takes variable arguments. With-mprototype, only calls to prototyped variable argument functions set or clear the bit. One bit. So much drama over one 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. Same vibe, different library names.-madsโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.a.-myellowknifeโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a. Yellowknife is literally such a name, iconic.-mvxworksโ on System V.4 and embedded PowerPC systems, specifies that you're compiling for a VxWorks system. ๐ซถ-membโ on embedded PowerPC systems, sets thePPC_EMBbit in the ELF flags header to indicate that eabi extended relocations are used. Little bit, big meaning.-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__eabiis called frommainto set up the EABI environment, and the-msdataoption can use bothr2andr13to 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 frommain, and the-msdataoption only usesr13to point to a single small data area. The-meabioption is on by default if you configured GCC using one of thepowerpc*-*-eabi*options.-msdata=eabiโ on System V.4 and embedded PowerPC systems, put small initializedconstglobal and static data in the.sdata2section, which is pointed to by registerr2. Put small initialized non-constglobal and static data in the.sdatasection, which is pointed to by registerr13. Put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. Heads up: the-msdata=eabioption is incompatible with the-mrelocatableoption. It also sets the-memboption. ๐-msdata=sysvโ on System V.4 and embedded PowerPC systems, put small global and static data in the.sdatasection, which is pointed to by registerr13. Put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. The-msdata=sysvoption is incompatible with the-mrelocatableoption. Yes, again. It's a thing.-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. Mystery box energy, but documented.-msdata=dataโ on System V.4 and embedded PowerPC systems, put small global data in the.sdatasection. Put small uninitialized global data in the.sbsssection. Do not use registerr13to address small data though. This is the default behavior unless other-msdataoptions are used.-msdata=none,-mno-sdataโ on embedded PowerPC systems, put all initialized global and static data in the.datasection, and all uninitialized data in the.bsssection. Back to basics, bestie.-mreadonly-in-sdataโ put read-only objects in the.sdatasection as well. This is the default. ๐-mblock-move-inline-limit=num โ inline all block moves (like calls tomemcpyor 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 โ generate non-looping inline code for all block compares (like calls tomemcmpor 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 โ generate an inline expansion using loop code for all block compares that are less than or equal to num bytes, but greater than the limit for non-loop inline block compare expansion. If the block length isn't constant, at most num bytes will be compared beforememcmpis called to compare the remainder of the block. The default value is target-specific. ๐ฆ-mstring-compare-inline-limit=num โ compare 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 tostrcmporstrncmptakes care of the rest of the comparison. The default is 64 bytes.-Gnum โ on embedded PowerPC systems, put 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-Gnum switch is also passed to the linker. Important: all modules should be compiled with the same-Gnum value. Consistency is the vibe. ๐-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, assume that all calls are far away, so a longer and more expensive calling sequence is required. This is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call is generated if the compiler knows the call cannot be that far away. This setting can be overridden by theshortcallfunction 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 generate slower code. As of this writing, the AIX linker can do this, as can the GNU linker for PowerPC/64. It is planned to add this feature to the GNU linker for 32-bit PowerPC systems as well. Planned. Not promised. We're being honest.
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 is 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 or discard it.
In the future, GCC may ignore all longcall specifications when the linker is known to generate glue. Future tea, take it with a grain of salt.
-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_addrwith a relocation specifying the function argument. The relocation lets the linker reliably associate a function call with argument setup instructions for TLS optimization, which in turn lets GCC better schedule the sequence. Coordination queen behavior. ๐ธ-mrecip,-mno-recipโ okay so this one turns on the reciprocal estimate and reciprocal square root estimate instructions, plus extra Newton-Raphson steps to bump the precision, instead of actually doing a divide or a square root + divide for floating-point args ๐ . You should pair it with-ffast-mathwhen you use-mrecip(or at minimum-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math). Heads up tho: 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 of 1.0 equals 0.99999994) for reciprocal square roots ๐ญ.-mrecip=optโ this is the one that controls which reciprocal estimate instructions get used.optis a comma-separated list of options, and any of them can have a!in front to invert it ๐:allโ enable all estimate instructions.defaultโ enable the default instructions, equivalent to-mrecip.noneโ disable all estimate instructions, equivalent to-mno-recip.divโ enable the reciprocal approximation instructions for both single and double precision.divfโ enable the single-precision reciprocal approximation instructions.divdโ enable the double-precision reciprocal approximation instructions.rsqrtโ enable the reciprocal square root approximation instructions for both single and double precision.rsqrtfโ enable the single-precision reciprocal square root approximation instructions.rsqrtdโ enable the double-precision reciprocal square root approximation instructions.
So for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions, except for the FRSQRTE, XSRSQRTEDP, and XVRSQRTEDP instructions which handle the double-precision reciprocal square root calculations. slay โจ
-mrecip-precision,-mno-recip-precisionโ assume (do not assume) that the reciprocal estimate instructions give higher-precision estimates than the PowerPC ABI says they have to ๐ซถ. 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, because 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 (do not 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 (do not 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. 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โ ๏ธ.-msave-toc-indirect,-mno-save-toc-indirectโ generate (do not generate) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. If the TOC value is not saved in the prologue, it is saved just before the call through the pointer.-mno-save-toc-indirectis the default ๐.-mcompat-align-parm,-mno-compat-align-parmโ generate (do not 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 is 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 atguard. Supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default with GNU libc version 2.4 or later) ๐.
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. 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 (do not generate) pc-relative addressing. The-mpcreloption requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled โจ.-mprefixed,-mno-prefixedโ generate (do not generate) addressing modes using prefixed load and store instructions. The-mprefixedoption requires that the option-mcpu=power10(or later) is enabled.-mmma,-mno-mmaโ generate (do not generate) the MMA instructions. The-mmaoption requires that the option-mcpu=power10(or later) is enabled.-mrop-protect,-mno-rop-protectโ generate (do not generate) ROP protection instructions when the target processor supports them. Currently this option disables the shrink-wrap optimization (-fshrink-wrap) ๐ .-mprivileged,-mno-privilegedโ generate (do not generate) code that will run in privileged state ๐.-mblock-ops-unaligned-vsx,-mno-block-ops-unaligned-vsxโ generate (do not generate) unaligned vsx loads and stores for inline expansion ofmemcpyandmemmove.
๐ธ RX Options ๐ธ
These command-line options are defined for RX targets, bestie:
-m64bit-doubles,-m32bit-doublesโ make thedoubledata type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles. Note 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 ๐ณ.
-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 is no longer available for use by the compiler. This could result in slower and/or larger code if variables are pushed onto the stack instead of being held in this register.
Note, common variables (variables that have not been initialized) and constants are not placed into the small data area as they are assigned to other sections in the output executable.
The default value is zero, which disables this feature. Note, this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register ๐. It is up to the programmer to experiment and discover whether this feature is of benefit to their program. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen.
-msim,-mno-simโ use the simulator runtime. The default is to use the libgloss board-specific runtime ๐.-mas100-syntax,-mno-as100-syntaxโ okay so when you're spitting out assembler, this makes it use a syntax that Renesas's AS100 assembler can vibe with ๐ . GAS can also handle this syntax but it's got some restrictions, so it's not what gets generated by default. No cap.-mmax-constant-size=Nโ sets the max size, in bytes, of a constant that can be used as an operand in an RX instruction. So here's the tea: the RX instruction set does let constants up to 4 bytes long chill inside instructions, but a longer value means a longer instruction, periodt. So sometimes it's lowkey beneficial to restrict how big the constants in your instructions get โ the too-big ones get yeeted into a constant pool and referenced via register indirection instead.
The value N can be anywhere between 0 and 4. A value of 0 (the default, bestie) or 4 means constants of any size are allowed. Slay.
-mrelaxโ enables linker relaxation ๐. That's the process where the linker tries to shrink your program by hunting down shorter versions of various instructions. Disabled by default, sad.-mint-register=Nโ tell GCC how many registers to reserve for fast interrupt handler functions โก. N can be between0and4. A value of1means register"r13"is reserved for the exclusive use of fast interrupt handlers. A value of2reserves"r13"and"r12". A3reserves"r13","r12"and"r11", and a4reserves"r13"through"r10". A value of0, the default, reserves absolutely nothing. Main character energy only.-msave-acc-in-interruptsโ says interrupt handler functions should preserve the accumulator register ๐ซถ. This is only necessary if normal code might use the accumulator register โ like if it's doing 64-bit multiplications. The default is to ignore the accumulator because that makes the interrupt handlers faster. Speed ๐จ.-mpid,-mno-pidโ turns on generation of position independent data โจ. When it's enabled, any access to constant data happens via an offset from a base address held in a register. This lets the location of constant data be figured out at run time without needing the executable to be relocated, which is a whole benefit for embedded applications with tight memory constraints. Data that can be modified? Not affected by this option, bestie.
Note that using this feature reserves a register, usually "r13", for the constant data base address. That can result in slower and/or larger code, especially in complicated functions ๐ญ.
The actual register chosen to hold the constant data base address depends on whether the -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register "r13" and proceeding downwards, registers get allocated first to satisfy the requirements of -mint-register, then -mpid and finally -msmall-data-limit. So it is literally possible for the small data area register to be "r8" if both -mint-register=4 and -mpid are specified on the command line. Iconic.
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โ stops GCC from throwing a warning message if it finds more than one fast interrupt handler while compiling a file ๐. The default is to issue a warning for each extra fast interrupt handler found, because the RX only supports one such interrupt. It's giving strict.-mallow-string-insns,-mno-allow-string-insnsโ enables or disables the use of the string manipulation instructions"SMOVF","SCMPU","SMOVB","SMOVU","SUNTIL""SWHILE"and also the"RMPA"instruction ๐ง. These instructions may prefetch data, which is not safe to do if you're accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more info.)
The default is to allow these instructions, but it's not possible for GCC to reliably detect all the circumstances where a string instruction might be used to access an I/O register, so their use can't be disabled automatically ๐ญ. Instead it's reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space. Your move, bestie.
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)"JSR"instructions to access functions ๐. This option can be used when code size exceeds the range of"BSR"instructions. Note that-mno-jsrdoes not mean "don't use"JSR"" โ it means any type of branch may be used. Read it twice, bestie.
Note: the generic GCC command-line option-ffixed-reghas special significance to the RX port when used with the"interrupt"function attribute. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registers"r10","r11","r12"and/or"r13"โ and only provided that the normal use of the corresponding registers has 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. Buckle up ๐.
-mhard-float,-msoft-floatโ use (or don't 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. That one's the default ๐.-mhard-dfp,-mno-hard-dfpโ use (or don't 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 of the"long double"type ๐ฆ. A size of 64 bits makes the"long double"type equivalent to the"double"type. This is the default.-mbackchain,-mno-backchainโ store (or don't 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 don't 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 (or don't use) the packed stack layout ๐. When-mno-packed-stackis specified, the compiler uses all fields of the 96/160 byte register save area only for their default purpose; unused fields still take up stack space, wasteful fr. When-mpacked-stackis specified, register save slots are densely packed at the top of the register save area; unused space gets reused for other purposes, allowing for more efficient use of the available stack space โจ. However, when-mbackchainis also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain.
As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes ๐ญ. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float.
The default is to not use the packed stack layout.
-msmall-exec,-mno-small-execโ generate (or don't generate) code using the"bras"instruction to do subroutine calls ๐ซ. This only works reliably if the total executable size does not exceed 64k. The default is to use the"basr"instruction instead, which does not have this limitation. Periodt.-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โ when-mvxis specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation ๐. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context a GAS.gnu_attributecommand will be added to mark the resulting binary with the ABI used.-mvxis enabled by default when using-march=z13.-mzvector,-mno-zvectorโ okay so-mzvectorturns on the vector language extensions and builtins that use the instructions from the vector extension facility that came in with the IBM z13 machine generation. It adds support forvectorto be used as a keyword when you're defining vector type variables and arguments. Heads up though:vectoris only available when GNU extensions are enabled, so it will not be expanded when you're asking for strict standard compliance, e.g. with-std=c99. On top of the GCC low-level builtins,-mzvectoralso enables a whole set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. To actually make use of those builtins you gotta include the header filevecintrin.h. And-mzvectoris disabled by default. ๐-mmvcle,-mno-mvcleโ generate (or do not generate) code using themvcleinstruction to perform block moves. When-mno-mvcleis specified, it uses amvcloop instead. This one is the default unless you're optimizing for size. โจ-mdebug,-mno-debugโ print (or do not print) additional debug information when compiling. The default is to not print debug information. ๐- *
-march=cpu-type* โ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. Possible values for cpu-type arez900/arch5,z990/arch6,z9-109,z9-ec/arch7,z10/arch8,z196/arch9,zEC12,z13/arch11,z14/arch12,z15/arch13,z16/arch14, andnative.
The default is -march=z900.
Specifying native as the cpu type can be used to select the best architecture option for the host processor. But bestie, listen: -march=native has no effect if GCC doesn't recognize the processor. ๐ญ
- *
-mtune=cpu-type* โ tune to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions. The list of cpu-type values is the same as for-march. The default is the value used for-march. ๐ฏ -mtpf-trace,-mno-tpf-traceโ generate code that adds (does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS. ๐-mtpf-trace-skip,-mno-tpf-trace-skipโ generate code that changes (does not change) the default branch targets enabled by-mtpf-traceto point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying-mtpf-trace. ๐-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used. ๐ฅ- *
-mwarn-framesize=framesize* โ emit a warning if the current function exceeds the given frame size. Because this is a compile-time check it doesn't need to be a real problem when the program runs. It's intended to identify functions that most probably cause a stack overflow. It's 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. This is generally a bad idea with a limited stack size. ๐- *
-mstack-guard=stack-guard*,-mstack-size=stack-size โ if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows downward). If the stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to be used to help debug stack overflow problems. The additionally emitted code causes only little overhead and hence can also be used in production-like systems without greater performance degradation. The given values have to be exact powers of 2 and stack-size has to be greater than stack-guard without exceeding 64k. In order to be efficient the extra code makes the assumption that the stack starts at an address aligned to the value given by stack-size. The stack-guard option can only be used in conjunction with stack-size. โญ - *
-mhotpatch=pre-halfwords*,post-halfwords โ if the hotpatch option is enabled, a "hot-patching" function prologue is generated for all functions in the compilation unit. The funtion label is prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label,2 * post-halfwordsbytes are appended, using the largest NOP like instructions the architecture allows (maximum 1000000).
If both arguments are zero, hotpatching is disabled.
This option can be overridden for individual functions with the hotpatch attribute. ๐
๐ธ Score Options ๐ธ
These options are defined for Score implementations:
-mebโ compile code for big-endian mode. This is the default. ๐ฆ-melโ compile code for little-endian mode. ๐-mnhwloopโ disable generation ofbcnzinstructions. ๐ซ-mulsโ enable generation of unaligned load and store instructions. โจ-mmacโ enable the use of multiply-accumulate instructions. Disabled by default. ๐-mscore5โ specify the SCORE5 as the target architecture. ๐ฏ-mscore5uโ specify the SCORE5U of the target architecture. ๐ฏ-mscore7โ specify the SCORE7 as the target architecture. This is the default. ๐-mscore7dโ specify the SCORE7D as the target architecture. ๐ฏ
๐ง SH Options ๐ง
These -m options are defined for the SH implementations:
-m1โ generate code for the SH1.-m2โ generate code for the SH2.-m2eโ generate code for the SH2e.-m2a-nofpuโ generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.-m2a-single-onlyโ generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.-m2a-singleโ generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.-m2aโ generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.-m3โ generate code for the SH3.-m3eโ generate code for the SH3e.-m4-nofpuโ generate code for the SH4 without a floating-point unit.-m4-single-onlyโ generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.-m4-singleโ generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.-m4โ generate code for the SH4.-m4-100โ generate code for SH4-100.-m4-100-nofpuโ generate code for SH4-100 in such a way that the floating-point unit is not used.-m4-100-singleโ generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.-m4-100-single-onlyโ generate code for SH4-100 in such a way that no double-precision floating-point operations are used.-m4-200โ generate code for SH4-200.-m4-200-nofpuโ generate code for SH4-200 without in such a way that the floating-point unit is not used.-m4-200-singleโ generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.-m4-200-single-onlyโ 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 without 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. Note that this changes the calling conventions, and thus some functions from the standard C library do not work unless you recompile it first with-mdalign. ๐-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โ bestie this one inlines code to invalidate instruction cache entries after you've set up nested function trampolines ๐. It has no effect if-musermodeis in effect and the selected code generation option (like-m4) doesn't allow the use of theicbiinstruction. Now if the selected code generation option doesn't allowicbi, and-musermodeis not in effect, the inlined code straight-up manipulates the instruction cache address array directly with an associative write ๐ . And that? That not only requires privileged mode at run time, it also fails if the cache line had been mapped via the TLB and has become unmapped. so, yk, careful.-misizeโ dumps instruction size and location right into the assembly code โจ. receipts!-mpadstructโ > this option is deprecated, no cap. It pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. so like, it's giving legacy energy, beware ๐.-matomic-model=modelโ sets the model of atomic operations and additional parameters as a comma separated list ๐ฅ. For details on the atomic built-in functions see__atomic Builtins. The following models and parameters are supported:noneโ disable compiler generated atomic sequences and emit library calls for atomic operations. This is the default if the target is notsh*-*-linux*.soft-gusaโ generate GNU/Linux compatible gUSA software atomic sequences for the atomic built-in functions ๐ธ. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for SH3* and SH4* single-core systems. This option is enabled by default when the target issh*-*-linux*and SH3* or SH4*. When the target is SH4A, this option also partially utilizes the hardware atomic instructionsmovli.landmovco.lto create more efficient code, unlessstrictis specified.soft-tcbโ generate software atomic sequences that use a variable in the thread control block ๐ฆ. This is a variation of the gUSA sequences which can also be used on SH1* and SH2* targets. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for single-core systems. When using this model, thegbr-offset=parameter has to be specified as well, periodt.soft-imaskโ generate software atomic sequences that temporarily disable interrupts by settingSR.IMASK = 1111๐ . This model works only when the program runs in privileged mode and is only suitable for single-core systems. Additional support from the interrupt/exception handling code of the system is not required. This model is enabled by default when the target issh*-*-linux*and SH1* or SH2*.hard-llcsโ generate hardware atomic sequences using themovli.landmovco.linstructions only ๐. This is only available on SH4A and is suitable for multi-core systems. Since the hardware instructions support only 32 bit atomic variables, access to 8 or 16 bit variables is emulated with 32 bit accesses. Code compiled with this option is also compatible with other software atomic model interrupt/exception handling systems if executed on an SH4A system. Additional support from the interrupt/exception handling code of the system is not required for this model.gbr-offset=โ this parameter specifies the offset in bytes of the variable in the thread control block structure that should be used by the generated atomic sequences when thesoft-tcbmodel has been selected ๐. For other models this parameter is ignored. The specified value must be an integer multiple of four and in the range0-1020.strictโ this parameter prevents mixed usage of multiple atomic models, even if they are compatible, and makes the compiler generate atomic sequences of the specified model only โจ.
-mtasโ generate thetas.bopcode for__atomic_test_and_set. > notice that depending on the particular hardware and software configuration this can degrade overall performance due to the operand cache line flushes that are implied by thetas.binstruction ๐. On multi-core SH4A processors thetas.binstruction must be used with caution since it can result in data corruption for certain cache configurations. not me telling you twice but fr fr, be careful.-mprefergotโ when generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table ๐.-musermode,-mno-usermodeโ don't allow (allow) the compiler generating privileged mode code ๐ฅ. Specifying-musermodealso implies-mno-inline-ic_invalidateif the inlined code would not work in user mode.-musermodeis the default when the target issh*-*-linux*. If the target is SH1* or SH2*,-musermodehas no effect, since there is no user mode ๐คท.-multcost=numberโ set the cost to assume for a multiply insn ๐.-mdiv=strategyโ set the division strategy to be used for integer division operations ๐. strategy can be one of:call-div1โ calls a library function that uses the single-step division instructiondiv1to perform the operation. Division by zero calculates an unspecified result and does not trap. This is the default except for SH4, SH2A and SHcompact.call-fpโ calls a library function that performs the operation in double precision floating point. Division by zero causes a floating-point exception ๐ญ. This is the default for SHcompact with FPU. Specifying this for targets that do not have a double precision FPU defaults tocall-div1.call-tableโ calls a library function that uses a lookup table for small divisors and thediv1instruction with case distinction for larger divisors ๐. Division by zero calculates an unspecified result and does not trap. This is the default for SH4. Specifying this for targets that do not have dynamic shift instructions defaults tocall-div1.
When a division strategy has not been specified, the default strategy is selected based on the current target. For SH2A the default strategy is to use the divs and divu instructions instead of library function calls โจ.
-maccumulate-outgoing-argsโ reserve space once for outgoing arguments in the function prologue rather than around each call ๐ . Generally beneficial for performance and size. Also needed for unwinding to avoid changing the stack frame around conditional code.-mdivsi3_libfunc=nameโ set the name of the library function used for 32-bit signed division to name ๐ฆ. This only affects the name used in the call division strategies, and the compiler still expects the same sets of input/output/clobbered registers as if this option were not present.-mfixed-range=register-rangeโ generate code treating the given register range as fixed registers ๐ธ. A fixed register is one that the register allocator cannot use. This is useful when compiling kernel code. A register range is specified as two registers separated by a dash. Multiple register ranges can be specified separated by a comma.-mbranch-cost=numโ assume num to be the cost for a branch instruction ๐. Higher numbers make the compiler try to generate more branch-free code if possible. If not specified the value is selected depending on the processor type that is being compiled for.-mzdcbranch,-mno-zdcbranchโ assume (do not assume) that zero displacement conditional branch instructionsbtandbfare fast โญ. If-mzdcbranchis specified, the compiler prefers zero displacement branch code sequences. This is enabled by default when generating code for SH4 and SH4A. It can be explicitly disabled by specifying-mno-zdcbranch.-mcbranch-force-delay-slotโ force the usage of delay slots for conditional branches, which stuffs the delay slot with anopif a suitable instruction cannot be found ๐. By default this option is disabled. It can be enabled to work around hardware bugs as found in the original SH7055.-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions ๐ฅ. These instructions are generated by default if hardware floating point is used. The machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off.-mfsca,-mno-fscaโ allow or disallow the compiler to emit thefscainstruction for sine and cosine approximations ๐. The option-mfscamust be used in combination with-funsafe-math-optimizations. It is enabled by default when generating code for SH4A. Using-mno-fscadisables sine and cosine approximations even if-funsafe-math-optimizationsis in effect.-mfsrra,-mno-fsrraโ allow or disallow the compiler to emit thefsrrainstruction for reciprocal square root approximations ๐. The option-mfsrramust be used in combination with-funsafe-math-optimizationsand-ffinite-math-only. It is enabled by default when generating code for SH4A. Using-mno-fsrradisables reciprocal square root approximations even if-funsafe-math-optimizationsand-ffinite-math-onlyare in effect.-mpretend-cmoveโ prefer zero-displacement conditional branches for conditional move instruction patterns ๐ . This can result in faster code on the SH4 processor.-mfdpicโ generate code using the FDPIC ABI โจ.
๐ Solaris 2 Options ๐
These -m options are supported on Solaris 2, bestie โ๏ธ:
-mclear-hwcapโ-mclear-hwcaptells the compiler to remove the hardware capabilities generated by the Solaris assembler ๐งน. This is only necessary when object files use ISA extensions not supported by the current machine, but check at runtime whether or not to use them.-mimpure-textโ-mimpure-text, used in addition to-shared, tells the compiler to not pass-z textto the linker when linking a shared object ๐. Using this option, you can link position-dependent code into a shared object.-mimpure-textโ this one suppresses the linker's whole "relocations remain against allocatable but non-writable sections" error message. But bestie, listen ๐ญ the relocations it needs trigger copy-on-write, so the shared object is not actually shared across processes. Instead of using-mimpure-text, you should compile all your source code with-fpicor-fPIC. It's giving "technically works, emotionally not worth it" ๐
On Solaris 2 these switches are supported on top of everything above:
-pthreadsโ this is literally just a synonym for-pthread. Same vibe, different name ๐
๐ธ SPARC Options ๐ธ
These -m options are supported on the SPARC:
โจ -mno-app-regs / -mapp-regs โจ
Say -mapp-regs and GCC generates output using global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications. Just like global register 1, each of global registers 2 through 4 then gets treated as an allocable register that's clobbered by function calls. This is the default โจ
If you want to be fully SVR4 ABI-compliant and are willing to eat a little performance loss, specify -mno-app-regs. You should compile libraries and system software with this option, fr fr ๐ซถ
โจ -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 get saved on the stack as needed.
With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode, the main character energy default ๐
โจ -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 though ๐ซถ
-msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a โ the library that comes with GCC โ with -msoft-float in order for this to work. All or nothing, bestie ๐ค
โจ -mhard-quad-float โจ
Generate output containing quad-word (long double) floating-point instructions. Fancy ๐ฅ
โจ -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 "the hardware said no, the trap handler said fine, I'll do it myself" ๐ญ
โจ -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. The vibe check did not pass on speed ๐
โจ -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. You're on your own, bestie ๐
โจ -mstd-struct-return / -mno-std-struct-return โจ
With -mstd-struct-return, the compiler generates checking code in functions returning structures or unions to detect size mismatches between the two sides of function calls, as per the 32-bit ABI.
The default is -mno-std-struct-return. This option has no effect in 64-bit mode.
โจ -mlra / -mno-lra โจ
Enable Local Register Allocation. This is the default for SPARC since GCC 7, so -mno-lra needs to be passed to get the old Reload. Nostalgia unlocked ๐
โจ -mcpu=cpu_type โจ
Set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type are v7, cypress, v8, supersparc, hypersparc, leon, leon3, leon3v7, leon5, sparclite, f930, f934, sparclite86x, sparclet, tsc701, v9, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8.
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's the 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. Upgrade arc โจ
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. The whole lineup, periodt ๐
โจ -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.
โจ -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 -mvis2 when targeting a cpu that supports such instructions, such as UltraSPARC-III and later. Setting -mvis2 also sets -mvis. Stacking upgrades, we love to see it ๐
โจ -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 -mvis3 when targeting a cpu that supports such instructions, such as niagara-3 and later. Setting -mvis3 also sets -mvis2 and -mvis. ๐
-mvis4,-mno-vis4โ turn on the good stuff from version 4.0 of the UltraSPARC Visual Instruction Set extensions. It's already the default when you're targeting a cpu that supports those instructions, likeniagara-7and later. And bestie, setting-mvis4is a package deal: it also sets-mvis3,-mvis2and-mvis. ๐-mvis4b,-mno-vis4bโ same energy but louder: version 4.0 of the UltraSPARC Visual Instruction Set extensions plus the extra VIS instructions that showed up in the Oracle SPARC Architecture 2017. Default is-mvis4bwhen the cpu supports it, likem8and later. Setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvis. cascade of slay โจ-mcbcond,-mno-cbcondโ unlocks the UltraSPARC Compare-and-Branch-on-Condition instructions. Default is-mcbcondwhen you're targeting a CPU that has them, likeNiagara-4and later. ๐-mfmaf,-mno-fmafโ enables the UltraSPARC Fused Multiply-Add Floating-point instructions. Default is-mfmafwhen the target CPU supports them, likeNiagara-3and later. ๐ฅ-mfsmuld,-mno-fsmuldโ enables the Floating-point Multiply Single to Double (FsMULd) instruction. Default is-mfsmuldwhen you're targeting a CPU that supports architecture versions V8 or V9 with an FPU โ the one exception being-mcpu=leon. ๐-mpopc,-mno-popcโ enables the UltraSPARC Population Count instruction. Default is-mpopcwhen the CPU supports it, likeNiagara-2and later. count them, queen ๐-msubxc,-mno-subxcโ enables the UltraSPARC Subtract-Extended-with-Carry instruction. Default is-msubxcwhen the CPU supports it, likeNiagara-7and later. ๐ง-mfix-at697fโ flips on the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). not me fixing hardware bugs at 3am ๐ญ-mfix-ut699โ flips on the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.-mfix-ut700โ flips on the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ flips on 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. glow up time ๐- *
-mcmodel=which* โ pick your code model, one of these four:medlowโ the Medium/Low code model: 64-bit addresses, and 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* โ sets the memory model in force on the processor, one of:defaultโ the default memory model for the processor and operating system.rmoโ Relaxed Memory Order.psoโ Partial Store Order.tsoโ Total Store Order.scโ Sequential Consistency.
These memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's PSTATE.MM field.
-mstack-bias,-mno-stack-biasโ with-mstack-bias, GCC assumes that the stack pointer (and frame pointer, if it's there) are offset by-2047, which has to be added back whenever you make stack frame references. This is the default in 64-bit mode. Otherwise, assume no such offset is present. ๐ซถ
๐พ Options for System V ๐พ
These extra options are available on System V Release 4, purely so GCC plays nice with the other compilers on those systems:
-Gโ create a shared object. Lowkey though, it's recommended that-symbolicor-sharedbe used instead. (iconic but deprecated behavior, bestie)-Qyโ identify the versions of each tool used by the compiler, in a.identassembler directive in the output.-Qnโ refrain from adding.identdirectives to the output file (this is the default).-YP,dirs โ search the directories dirs, and no others, for libraries specified with-l.-Ym,dir โ look in the directory dir to find the M4 preprocessor. The assembler uses this option.
๐งฉ TILE-Gx Options ๐งฉ
These -m options are supported on the TILE-Gx:
-mcmodel=smallโ generate code for the small model. The distance for direct calls is limited to 500M in either direction. PC-relative addresses are 32 bits. Absolute addresses support the full address range.-mcmodel=largeโ generate code for the large model. There is no limitation on call distance, pc-relative addresses, or absolute addresses. no cap, unlimited ๐ฆ- *
-mcpu=name* โ selects the type of CPU to be targeted. Currently the only supported type istilegx. -m32,-m64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,long, and pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits.-mbig-endian,-mlittle-endianโ generate code in big/little endian mode, respectively.
๐งฉ TILEPro Options ๐งฉ
These -m options are supported on the TILEPro:
- *
-mcpu=name* โ selects the type of CPU to be targeted. Currently the only supported type istilepro. -m32โ generate code for a 32-bit environment, which setsint,long, and pointer to 32 bits. This is the only supported behavior so the flag is essentially ignored.
๐ธ 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 the pointer into theepregister and use the shortersldandsstinstructions. The-mepoption is on by default if you optimize.-mno-prolog-function,-mprolog-functionโ do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. The external functions are slower, but use less code space if more than one function saves the same number of registers. The-mprolog-functionoption is on by default if you optimize.-mspaceโ try to make the code as small as possible. At present, this just turns on the-mepand-mprolog-functionoptions. tiny code tiny code ๐- *
-mtda=n* โ put static or global variables whose size is n bytes or less into the tiny data area that registereppoints to. The tiny data area can hold up to 256 bytes in total (128 bytes for byte references). - *
-msda=n* โ put static or global variables whose size is n bytes or less into the small data area that registergppoints to. The small data area can hold up to 64 kilobytes. - *
-mzda=n* โ put static or global variables whose size is n bytes or less into the first 32 kilobytes of memory. -mv850โ specify that the target processor is the V850.-mv850e3v5โ specify that the target processor is the V850E3V5. The preprocessor constant__v850e3v5__is defined if this option is used.-mv850e2v4โ specify that the target processor is the V850E3V5. This is an alias for the-mv850e3v5option. (yes bestie, the original really says V850E3V5 here, I'm not the one who wrote it ๐)-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. always. periodt. ๐
-mdisable-callt,-mno-disable-calltโ this option suppresses generation of theCALLTinstruction for thev850e,v850e1,v850e2,v850e2v3andv850e3v5flavors 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โ turn OFF (or back ON) generating hardware floating point instructions. Heads up: this one only matters when your target arch is V850E2V3 or higher. If hardware float instructions are getting generated, the C preprocessor symbol__FPU_OK__gets defined; otherwise you get__NO_FPU__instead. ๐-mloopโ turns on the e3v5LOOPinstruction. It's not on by default even when you pick the e3v5 architecture, because bestie... its use is still experimental. ๐-mrh850-abi,-mghsโ enables support for the RH850 version of the V850 ABI. This is the default. With this ABI version, here's the tea:- Integer sized structures and unions get 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 ABI version is enabled, the C preprocessor symbol __V850_RH850_ABI__ is defined. โจ
-mgcc-abiโ enables support for the old GCC version of the V850 ABI. With this version, the rules go like this:- 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 ABI version 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โ generates 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 causesr2andr5to be used in the code generated by the compiler. This setting is the default. ๐-mno-app-regsโ this option causesr2andr5to be treated as fixed registers.
๐ VAX Options ๐
These -m options are defined for the VAX, bestie:
-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 that 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 that 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.
Real talk:-msoft-floatchanges the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option. In particular, you need to compilelibgcc.a, the library that comes with GCC, with-msoft-floatin order for this to work. ๐ญ
- *
-mcpu=cpu_type* โ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type aremcm,gr5andgr6.
mcm is a synonym of gr5 present for backward compatibility.
By default (unless configured otherwise), GCC generates code for the GR5 variant of the Visium architecture.
With -mcpu=gr6, GCC generates code for the GR6 variant of the Visium architecture. The only difference from GR5 code is that the compiler will generate block move instructions.
-mtune=cpu_type โ set the instruction scheduling parameters for machine type cpu_type, but do *not set the instruction set or register set that the option-mcpu=cpu_type* would.-msv-modeโ generate code for the supervisor mode, where there are no restrictions on the access to general registers. This is the default. ๐-muser-modeโ generate code for the user mode, where the access to some general registers is forbidden: on the GR5, registersr24tor31cannot be accessed in this mode; on the GR6, only registersr29tor31are affected. ๐
๐ธ VMS Options ๐ธ
These -m options are defined for the VMS implementations:
-mvms-return-codesโ return VMS condition codes 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. iykyk, this is the big one bestie ๐
-march=cpu-type โ generate instructions for the machine type cpu-type. In contrast to-mtune=cpu-type, which merely tunes the generated code for the specified cpu-type,-march=cpu-type allows GCC to generate code that *may not run at all on processors other than the one indicated. Specifying-march=cpu-type* implies-mtune=cpu-type, except where noted otherwise. โ ๏ธ
The choices for cpu-type are:
nativeโ this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines). Using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set.x86-64โ a generic CPU with 64-bit extensions.x86-64-v2,x86-64-v3,x86-64-v4โ these choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. On ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.
Since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. Specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value.
i386โ Original Intel i386 CPU.i486โ Intel i486 CPU. (No scheduling is implemented for this chip.)i586,pentiumโ Intel Pentium CPU with no MMX support.lakemontโ Intel Lakemont MCU, based on Intel Pentium CPU.pentium-mmxโ Intel Pentium MMX CPU, based on Pentium core with MMX instruction set support.pentiumproโ Intel Pentium Pro CPU.i686โ 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,corei7โ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support.
westmereโ Intel Westmere CPU, 64-bit extensions girlie โจ, and she's bringing MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR and PCLMUL instruction set support to the function. periodt.sandybridge,corei7-avxโ Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE and PCLMUL instruction set support. lowkey a legend.ivybridge,core-avx-iโ Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND and F16C instruction set support. she ate.haswell,core-avx2โ Intel Haswell CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE and HLE instruction set support. the whole roster fr fr.broadwellโ Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX and PREFETCHW instruction set support. ๐skylakeโ Intel Skylake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES and SGX instruction set support. iconic behavior.skylake-avx512โ Intel Skylake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support. the AVX-512 era begins bestie ๐ฆcascadelakeโ Intel Cascade Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support. โจcannonlakeโ Intel Cannon Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA and SHA instruction set support. no cap.cooperlakeโ Intel Cooper Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support. ๐ฅicelake-clientโ Intel Ice Lake Client CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. she's stacked ๐ญicelake-serverโ Intel Ice Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD and CLWB instruction set support. ๐tigerlakeโ Intel Tiger Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, MOVDIRI, MOVDIR64B, CLWB, AVX512VP2INTERSECT and KEYLOCKER instruction set support. ๐rocketlakeโ Intel Rocket Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. ๐alderlakeโ Intel Alder Lake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL and AVX-VNNI instruction set support. ๐sapphirerapidsโ Intel Sapphire Rapids CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16 and AVX512BF16 instruction set support. main character energy, literally ๐bonnell,atomโ Intel Bonnell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. smol but mighty ๐ฃsilvermont,slmโ Intel Silvermont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW and RDRND instruction set support. โจgoldmontโ Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT and FSGSBASE instruction set support. ๐goldmont-plusโ Intel Goldmont Plus CPU 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 and SGX instruction 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, CLDEMOTE and WAITPKG instruction set support. ๐knlโ Intel Knights 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, AVX512CD and PREFETCHWT1 instruction 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, AVX512CD and PREFETCHWT1, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support. ๐ญ
k6โ AMD K6 CPU with MMX instruction set support. throwback fr.k6-2,k6-3โ Improved versions of AMD K6 CPU with MMX and 3DNow! 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. ๐ฆ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.) 64-bit girlies rise up ๐ฅ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.) the AMD section said "hold my 3DNow!" ๐bdver2โ AMD Family 15h core based CPUs, x86-64 instruction set support. (Bestie this one supersetsBMI,TBM,F16C,FMA,FMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand the 64-bit instruction set extensions.) ๐bdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (SupersetsBMI,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.) โจbdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This one ate and left no crumbs: supersetsBMI,BMI2,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,AVX2,XOP,LWP,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.) ๐ฅznver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (SupersetsBMI,BMI2,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT, and 64-bit instruction set extensions.) ๐znver2โ AMD Family 17h core based CPUs with x86-64 instruction set support. (SupersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD, and 64-bit instruction set extensions.) ๐ธznver3โ AMD Family 19h core based CPUs with x86-64 instruction set support. (SupersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES, and 64-bit instruction set extensions.) ๐ฆznver4โ AMD Family 19h core based CPUs with x86-64 instruction set support. (SupersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNIand 64-bit instruction set extensions.) like that's a whole alphabet of slay ๐ญ๐znver5โ AMD Family 1ah core based CPUs with x86-64 instruction set support. (SupersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNI,AVXVNNI,MOVDIRI,MOVDIR64B,AVX512VP2INTERSECT,PREFETCHIand 64-bit instruction set extensions.) this list is giving โจwar and peaceโจ but we respect it ๐btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (SupersetsMMX,SSE,SSE2,SSE3,SSSE3,SSE4A,CX16,ABMand 64-bit instruction set extensions.) ๐btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includesMOVBE,F16C,BMI,AVX,PCLMUL,AES,SSE4.2,SSE4.1,CX16,ABM,SSE4A,SSSE3,SSE3,SSE2,SSE,MMXand 64-bit instruction set extensions. ๐ซwinchip-c6โ IDT WinChip C6 CPU, dealt in same way asi486with additionalMMXinstruction set support. ๐winchip2โ IDT WinChip 2 CPU, dealt in same way asi486with additionalMMXand3DNow!instruction set support. ๐c3โ VIA C3 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.) ๐ซถc3-2โ VIA C3-2 (Nehemiah/C5XL) CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.) ๐ซถc7โ VIA C7 (Esther) CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐ซถsamuel-2โ VIA Eden Samuel 2 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.) ๐nehemiahโ VIA Eden Nehemiah CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.) ๐estherโ VIA Eden Esther CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐eden-x2โ VIA Eden X2 CPU with x86-64,MMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.) ๐eden-x4โ VIA Eden X4 CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,AVXandAVX2instruction set support. (No scheduling is implemented for this chip.) ๐nanoโ Generic VIA Nano CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) โญnano-1000โ VIA Nano 1xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) โญnano-2000โ VIA Nano 2xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.) โญnano-3000โ VIA Nano 3xxx CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) โญnano-x2โ VIA Nano Dual Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) ๐nano-x4โ VIA Nano Quad Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.) ๐geodeโ AMD Geode embedded processor withMMXand3DNow!instruction set support. ๐
the -mtune=cpu-type moment ๐
</p>
-mtune=cpu-typeโ okay so this one tunes to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions. Lowkey the whole vibe: 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. โจ
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. bestie that distinction is important, write it down ๐
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. ๐
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. same energy, different chip brand, we stay consistent ๐
-mcpu=cpu-typeโ a deprecated synonym for-mtune. yeah it's giving "old money but make it legacy", don't start using it now ๐
-mfpmath=unit โจ
-mfpmath=unitโ Generate floating-point arithmetic for selected unit unit. The choices for unit are:387โ Use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See-ffloat-storefor more detailed description.
This is the default choice for non-Darwin x86-32 targets. ๐
sseโ Use scalar floating-point instructions present in the SSE instruction set. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too. ๐ฆ
okay so</p> for the x86-32 compiler you must use -march=cpu-type, -msse or -msse2 switches to turn SSE extensions on and actually make this option do anything. For the x86-64 compiler, bestie, these extensions are already on 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,387sse+387bothโ attempt to utilize both instruction sets at once. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE the execution resources too. Use this option with care, as it is still experimental, because the GCC register allocator does not model separate functional units well, resulting in unstable performance. ๐
๐ธ x86 Options, cont. ๐ธ
-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 arecompatuses increased alignment value compatible uses GCC 4.8 and earlier,abiuses alignment value as specified by the psABI, andcachelineuses 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 to65535.-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 for float and double arguments 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. ๐ฅ
Setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. Note that some mathematical libraries assume that extended-precision (80-bit) floating-point operations are enabled by default; routines in such libraries could suffer significant loss of accuracy, typically through so-called "catastrophic cancellation", when this option is used to set the precision to less than extended precision. ๐ญ
-mdaz-ftzโ the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register are used to control floating-point calculations. SSE and AVX instructions including scalar and vector instructions could benefit from enabling the FTZ and DAZ flags when-mdaz-ftzis specified. Don't set FTZ/DAZ flags when-mno-daz-ftzis specified. ๐-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, and bestie I need you to actually read this one, no skimming: when you're generating code for the x86-64 architecture with SSE extensions disabled, -mpreferred-stack-boundary=3 can be used to keep the stack boundary aligned to an 8 byte boundary. But since the x86-64 ABI requires 16 byte stack alignment, this is ABI incompatible and is only meant for a controlled environment where stack space is an important limitation. ๐
This option literally leads to wrong code when functions compiled with 16 byte stack alignment (like, say, functions from a standard library, iykyk) get called with a misaligned stack. And in that case? SSE instructions may lead to misaligned memory access traps. Not cute. On top of that, variable arguments are handled incorrectly for 16 byte aligned objects (including x87 long double and __int128), which gives you wrong results.
You must build all modules with -mpreferred-stack-boundary=3, including any libraries. Yes, that includes the system libraries and startup modules. All of them. No exceptions. ๐ซถ
-mincoming-stack-boundary=num
Okay so this one assumes the incoming stack is aligned to a 2 raised to num byte boundary. And if -mincoming-stack-boundary isn't specified, the one specified by -mpreferred-stack-boundary is used. Slay, inherited defaults.
On Pentium and Pentium Pro, "double" and "long double" values should be aligned to an 8-byte boundary (see -malign-double) or you suffer significant run time performance penalties. And on Pentium III, the Streaming SIMD Extension (SSE) data type "__m128" may not work properly if it isn't 16-byte aligned. ๐
To ensure proper alignment of 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. So the way that 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... yeah. It's recommended that libraries that use callbacks always use the default setting. Just do that. โจ
This extra alignment does consume extra stack space, and generally increases code size. So code that is sensitive to stack space usage โ think embedded systems and operating system kernels โ may want to reduce the preferred alignment to -mpreferred-stack-boundary=2.
The extended-instruction-set switch wall ๐งฑ
-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
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 or CLDEMOTE extended instruction sets. And every single one has a corresponding -mno- option to disable use of these instructions. Balanced, as all things should be. โ๏ธ
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. The way it just swaps them out? Iconic behaviour honestly.
These options enable GCC to use these extended instructions in generated code, even without -mfpmath=sse. Applications that perform run-time CPU detection must compile separate files for each supported architecture, using the appropriate flags. In particular, the file containing the CPU detection code should be compiled without these options. ๐
-mdump-tune-features
This option instructs GCC to dump the names of the x86 performance tuning features and default settings. Those names can then be used in -mtune-ctrl=feature-list. It's giving "here's the menu, now order". ๐
-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. So like... bestie, don't. Unless you are a GCC developer, in which case slay, go off.
-mno-default
This option instructs GCC to turn off all tunable features. See also -mtune-ctrl=feature-list and -mdump-tune-features. Everything off. Lights out. ๐
-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. Rude of them, honestly. ๐
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-cld configure option. Generation of "cld" instructions can be suppressed with the -mno-cld compiler 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. Peak efficiency. ๐ฅ
-mprefer-avx128
This option instructs GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. Sometimes smaller is the vibe. ๐ฆ
-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 are 128, 256 and 512.
-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 are 128, 256 and 512.
And for the vector-width vibe check, the accepted values are:
noneโ no extra limitations applied to GCC other than defined by the selected platform. Free-spirited, no notes. ๐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 __sync Builtins. However, for __atomic Builtins operating on 128-bit integers, a library call is always used. Noted! ๐
-msahf
This option enables generation of "SAHF" instructions in 64-bit code. Early Intel Pentium 4 CPUs with Intel 64 support, prior to the introduction of Pentium 4 G1 step in December 2005, lacked the "LAHF" and "SAHF" instructions which are supported by AMD64. These are load and store instructions, respectively, for certain status flags. In 64-bit mode, the "SAHF" instruction is used to optimize "fmod", "drem", and "remainder" built-in functions; see Other Builtins for details. History lesson AND a compiler flag, we love a multitasker. ๐
-mmovbe
This option enables use of the "movbe" instruction to implement "__builtin_bswap32" and "__builtin_bswap64".
-mshstk
The -mshstk option enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). ๐ก๏ธ
-mcrc32
This option enables built-in functions "__builtin_ia32_crc32qi", "__builtin_ia32_crc32hi", "__builtin_ia32_crc32si" and "__builtin_ia32_crc32di" to generate the "crc32" machine instruction.
-mmwait
This option enables built-in functions "__builtin_ia32_monitor", and "__builtin_ia32_mwait" to generate the "monitor" and "mwait" machine instructions. ๐
-mrecip
This option enables use of "RCPSS" and "RSQRTSS" instructions (and their vectorized variants "RCPPS" and "RSQRTPS") with an additional Newton-Raphson step to increase precision instead of "DIVSS" and "SQRTSS" (and their vectorized variants) for single-precision floating-point arguments. These instructions are generated only when -funsafe-math-optimizations is enabled together with -ffinite-math-only and -fno-trapping-math.
๐ซฃ Note that while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994). So like, fast but slightly lying. Pick your fighter.
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. Already handled, bestie, it's got you. ๐
Also note that GCC emits the above sequence with additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the above option combination), and doesn't need -mrecip. ๐
โจ -mrecip=opt โจ
This one is the menu for which reciprocal estimate instructions are allowed to show up. opt is a comma-separated list of options, and bestie, any one of them can get a ! slapped in front to flip it upside down (i.e. invert it):
allโ Enable all estimate instructions. everything everywhere all at once โจ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. the way that one little ! just cancels sqrt, iconic ๐
โจ -mveclibabi=type โจ
This specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values for type are svml for the Intel short vector math library and acml for the AMD math core library. to unlock this one, both -ftree-vectorize and -funsafe-math-optimizations have to be enabled, and an SVML or ACML ABI-compatible library must be specified at link time. no cap ๐ฅ
GCC currently emits calls to these for corresponding function type when -mveclibabi=svml is used:
"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"
And these for the corresponding function type when -mveclibabi=acml is used:
"__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"
โจ -mabi=name โจ
Generate code for the specified calling convention. Permissible values are sysv for the ABI used on GNU/Linux and other systems, and ms for the Microsoft ABI. The default is to use the Microsoft ABI when targeting Microsoft Windows and the SysV ABI on all other systems. You can control this behavior for specific functions by using the function attributes ms_abi and sysv_abi. pick your 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. indirect era, we love to see it ๐
โจ -mmanual-endbr โจ
Insert ENDBR instruction at function entry only via the cf_check function attribute. This is useful when used with the option -fcf-protection=branch to control ENDBR insertion at the function entry. ๐
โจ -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-xlogues emits 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, tiny bit more instructions, the classic trade โญ
โจ -mtls-dialect=type โจ
Generate code to access thread-local storage using the gnu or gnu2 conventions. gnu is the conservative default; gnu2 is more efficient, but it may add compile- and run-time requirements that cannot be satisfied on all systems. glow up with a catch, iykyk ๐
โจ -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. ๐ฅ
โจ -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. the catch: your code gets noticeably bigger. This switch implies -mno-push-args. ๐ญ
โจ -mthreads โจ
Support thread-safe exception handling on MinGW. Programs that rely on thread-safe exception handling must compile and link all code with the -mthreads option. When compiling, -mthreads defines -D_MT; when linking, it links in a special thread helper library -lmingwthrd which cleans up per-thread exception-handling data. compile AND link, don't half-do it bestie ๐ง
โจ -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. the vibes of structs are not universal, apparently ๐
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. one little : 0 doubling the size, the audacity ๐ญ
- 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;
For t2, bar is placed at offset 2, rather than offset 1. Accordingly, the size of t2 is 4. For t3, the zero-length bit-field does not affect the alignment of bar or, as a result, the size of the structure.
Taking this into account, it is important to note the following:
- If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field may affect the alignment of the structure as whole. For example,
t2has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short. - Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
{
char foo : 6;
long : 0;
} t4;
Here, t4 takes up 4 bytes.
- Zero-length bit-fields following non-bit-field members are ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
Here, t5 takes up 2 bytes. ignored, as it should be ๐
โจ -mno-align-stringops โจ
Do not align the destination of inlined string operations. This switch reduces code size and improves performance in case the destination is already aligned, but GCC doesn't know about it. GCC not knowing your alignment is so real ๐
โจ -minline-all-stringops โจ
By default GCC inlines string operations only when the destination is known to be aligned to least a 4-byte boundary. This enables more inlining and increases code size, but may improve performance of code that depends on fast memcpy and memset for short lengths. The option enables inline expansion of strlen for all pointer alignments. ๐ฆ
โจ -minline-stringops-dynamically โจ
For string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks. small blocks stay inline, big blocks call for backup โจ
โจ -mstringop-strategy=alg โจ
Override the internal decision heuristic for the particular algorithm to use for inlining string operations. The allowed values for alg are:
rep_byte,rep_4byte,rep_8byteโ expand using the i386repprefix of whatever size you picked. okay werk ๐byte_loop,loop,unrolled_loopโ expand into an inline loop. cute, compact, slay.libcallโ always use a library call. no inlining, no games, just call the lib like a civilized compiler bestie.
-mmemcpy-strategy=strategy โ this one overrides the internal decision heuristic that decides whether__builtin_memcpyshould get inlined at all, and which inline algorithm to use when the expected size of the copy is known. so strategy is a comma-separated list ofalg:max_size:dest_aligntriplets ๐- alg is specified in
-mstringop-strategy - max_size says the max byte size with which inline algorithm alg is allowed
- for the last triplet, the max_size must be
-1โ no cap on that one, it's the main character ๐
- alg is specified in
The max_size of the triplets in the list must be specified in increasing order. and the minimal byte size for alg is 0 for the first triplet, and max_size + 1 of the preceding range after that. fr fr, that's the math.
-mmemset-strategy=strategy โ literally the same vibe as-mmemcpy-strategy=except it's here to control__builtin_memsetexpansion instead. same triplet rules, different builtin ๐-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. this avoids the instructions that save, set up and restore frame pointers, and frees up an extra register in leaf functions. lowkey a little win. but heads up: the option-fomit-leaf-frame-pointerremoves the frame pointer for leaf functions, and that might make debugging harder ๐ญ-mtls-direct-seg-refs,-mno-tls-direct-seg-refsโ controls whether TLS variables may be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer must be added. whether that's valid or not depends on the operating system, and whether it maps the segment to cover the entire TLS area. iykyk.
for systems that use the GNU C Library, the default is on.
-msse2avx,-mno-sse2avxโ says the assembler should encode SSE instructions with the VEX prefix. and btw-mavxturns this on by default โจ-mfentry,-mno-fentryโ if profiling is active (-pg), put the profiling counter call before the prologue. note: on x86 architectures the attributems_hook_prologueisn't possible at the moment for-mfentryand-pg. ๐-mrecord-mcount,-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection that contains pointers to each profiling call. useful for automatically patching and out calls. periodt.-mnop-mcount,-mno-nop-mcountโ if profiling is active (-pg), generate the calls to the profiling functions as NOPs. useful when they should be patched in later dynamically. and ngl this is likely only useful together with-mrecord-mcount.-minstrument-return=type โ instrument function exit in-pg-mfentryinstrumented functions with a call to the specified function. this only instruments true returns ending withret, not sibling calls ending withjump. valid *type*s are:noneโ don't instrument at allcallโ generate a call to__return__nop5โ generate a 5 byte nop
-mrecord-return,-mno-record-returnโ generate a__return_locsection pointing to all return instrumentation code. cute lil breadcrumb trail ๐ฆ-mfentry-name=name โ set the name of the__fentry__symbol that gets called at function entry for-pg-mfentryfunctions.-mfentry-section=name โ set the name of the section used to record-mrecord-mcountcalls (default__mcount_loc).-mskip-rax-setup,-mno-skip-rax-setupโ when generating code for the x86-64 architecture with SSE extensions disabled,-mskip-rax-setupcan be used to skip setting up the RAX register when there are no variable arguments passed in vector registers.
Warning: since the RAX register is used to avoid unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave or jump to a random location ๐. GCC 4.4 or newer don't have those issues, regardless of the RAX register value.
-m8bit-idiv,-mno-8bit-idivโ on some processors, like Intel Atom, an 8-bit unsigned integer divide is much faster than a 32-bit/64-bit integer divide. this option generates a run-time check, and if both the dividend and the divisor are within the range0to255, the 8-bit unsigned integer divide is used instead of the 32-bit/64-bit integer divide. slay, adaptive ๐-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 a canary at guard. supported locations are:globalโ for a global canarytlsโ for a per-thread canary in the TLS block (this is the default)
this option only has effect when -fstack-protector or -fstack-protector-all is specified, so don't expect magic without them.
with the latter choice (tls), the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which segment register (%fs or %gs) to use as the base register for reading the canary, and from what offset from that base register. the default for those is as specified in the relevant ABI. no cap.
-mgeneral-regs-onlyโ generate code that uses only the general-purpose registers. this stops the compiler from using floating-point, vector, mask and bound registers. strict queen behavior ๐-mrelax-cmpxchg-loopโ relax the cmpxchg loop by emitting an early load and compare before the cmpxchg, and executepauseif the load value is not expected. this reduces excessive cachline bouncing when, and it works for all atomic logic fetch builtins that generate a compare and swap loop. iconic optimization fr fr ๐ฅ-mindirect-branch=choice โ convert indirect call and jump with choice. the default iskeep, which keeps indirect call and jump unmodified.thunkโ converts indirect call and jump to call and return thunkthunk-inlineโ converts indirect call and jump to inlined call and return thunkthunk-externโ converts indirect call and jump to external call and return thunk provided in a separate object file
you can control this behavior for a specific function by using the function attribute indirect_branch.
note that-mcmodel=largeis incompatible with-mindirect-branch=thunkand-mindirect-branch=thunk-extern, since the thunk function may not be reachable in the large code model. ๐
note that-mindirect-branch=thunk-externis compatible with-fcf-protection=branch, since the external thunk can be made to enable control-flow check.
-mfunction-return=choice โ convert function return with choice. the default iskeep, which keeps function return unmodified.thunkโ converts function return to call and return thunkthunk-inlineโ converts function return to inlined call and return thunkthunk-externโ converts function return to external call and return thunk provided in a separate object file
you can control this behavior for a specific function by using the function attribute function_return.
note that-mindirect-return=thunk-externis compatible with-fcf-protection=branch, since the external thunk can be made to enable control-flow check.
note that-mcmodel=largeis incompatible with-mfunction-return=thunkand-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. no detours, we goin' straight through the register bestie โจ-mharden-sls=choice โ generate code to mitigate against straight line speculation (SLS) with choice. the default isnone, which disables all SLS hardening.returnโ enables SLS hardening for function returnsindirect-jmpโ enables SLS hardening for indirect jumpsallโ enables all SLS hardening
-mindirect-branch-cs-prefixโ add a CS prefix tocallandjmpto the indirect thunk with branch target in ther8-r15registers, so that the call and jmp instruction length is 6 bytes. that lets them be replaced withlfence; call *%r8-r15orlfence; jmp *%r8-r15at run-time. sneaky and iconic ๐
These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments. okay now we're in the 64-bit zone, main character energy only ๐
-m32,-m64,-mx32,-m16,-miamcuโ generate code for a 16-bit, 32-bit or 64-bit environment.-m32โ setsint,long, and pointer types to 32 bits, and generates code that runs in 32-bit mode.-m64โ setsintto 32 bits andlongand pointer types to 64 bits, and generates code for the x86-64 architecture. for Darwin only, the-m64option also turns off the-fno-picand-mdynamic-no-picoptions.-mx32โ setsint,long, and pointer types to 32 bits, and generates code for the x86-64 architecture.-m16โ same as-m32, except for the fact that it outputs the.code16gccassembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode.-miamcuโ generates code which conforms to Intel MCU psABI. it requires the-m32option 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. she said no red zone today ๐ซ๐-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. non-negotiable fr fr.-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. unbothered, free, thriving ๐-maddress-mode=longโ generate code for long address mode. this is only supported for 64-bit and x32 environments. it's the default address mode for 64-bit environments. โจ-maddress-mode=shortโ generates code for short address mode. Only a thing for 32-bit and x32 environments, and ngl it's the default address mode for 32-bit and x32 environments, so it's giving main character energy by default ๐-mneeded,-mno-neededโ emits theGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for Linux targets, which tells everyone the micro-architecture ISA level you need to actually run the binary. iykyk โจ-mno-direct-extern-accessโ okay so: without-fpicnor-fPIC, this always uses the GOT pointer to access external symbols. With-fpicor-fPIC, it treats access to protected symbols as local symbols. The default is-mdirect-extern-access.
โ ๏ธ Warning, bestie, listen up: shared libraries compiled with-mno-direct-extern-accessand executables compiled with-mdirect-extern-accessmay not be binary compatible if protected symbols are used in shared libraries and executable. That's a real one, no cap ๐ญ
๐ช x86 Windows Options ๐ช
These additional options are available for Microsoft Windows targets:
-mconsoleโ says "make a console application," by instructing the linker to set the PE header subsystem type required for console applications. Available for Cygwin and MinGW targets, and it's enabled by default on those targets. periodt ๐-mdllโ available for Cygwin and MinGW targets. It says a DLL---a dynamic link library---is to be generated, which enables the selection of the required runtime startup object and entry point. slay ๐-mnop-fun-dllimportโ available for Cygwin and MinGW targets. It says the"dllimport"attribute should be ignored, period.-mthreadsโ available for MinGW targets. It says MinGW-specific thread support is to be used.-municodeโ available for MinGW-w64 targets. It makes the"UNICODE"preprocessor macro get predefined, and it chooses Unicode-capable runtime startup code. iconic ๐ฆ-mwin32โ available for Cygwin and MinGW targets. It says the typical Microsoft Windows predefined macros are to be set in the pre-processor, but it does not influence the choice of runtime library/startup code.-mwindowsโ available for Cygwin and MinGW targets. It says a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately โจ-fno-set-stack-executableโ available for MinGW targets. It says 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, because there the User32 API (which is what's used to set executable privileges) isn't available.-fwritable-relocated-rdataโ available for MinGW and Cygwin targets. It says relocated-data in a read-only section gets put into the".data"section. Necessary for older runtimes that don't support modification of".rdata"sections for pseudo-relocation.-mpe-aligned-commonsโ available for Cygwin and MinGW targets. It says the GNU extension to the PE file format that permits the correct alignment of COMMON variables should be used when generating code. It's enabled by default if GCC detects that the target assembler found during configuration supports the feature ๐
See also under x86 Options for standard options.
๐ฉ๏ธ Xstormy16 Options ๐ฉ๏ธ
These options are defined for Xstormy16:
-msimโ choose startup files and linker script suitable for the simulator. that's the whole thing, she's simple and she's valid ๐
๐ง Xtensa Options ๐ง
These options are supported for Xtensa targets:
-mconst16,-mno-const16โ enable or disable use of"CONST16"instructions for loading constant values. The"CONST16"instruction is currently not a standard option from Tensilica. When enabled,"CONST16"instructions are always used in place of the standard"L32R"instructions. The use of"CONST16"is enabled by default only if the"L32R"instruction is not available. it's giving "only when we have to" ๐-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. so real, the vibes must be reproducible ๐ธ-mserialize-volatile,-mno-serialize-volatileโ when this option is enabled, GCC inserts"MEMW"instructions before"volatile"memory references to guarantee sequential consistency. The default is-mserialize-volatile. Use-mno-serialize-volatileto omit the"MEMW"instructions.-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. kernel girlies, this one's for you ๐ฅ-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".literal"directives and loads literals into registers with"MOVI"instructions instead of"L32R"to let the assembler do relaxation and place literals as necessary. This option allows the assembler to create several literal pools per function and assemble very big functions, which may not be possible with-mtext-section-literals. big function rights ๐ซถ-mtarget-align,-mno-target-alignโ when this option is enabled, GCC instructs the assembler to automatically align instructions to reduce branch penalties at the expense of some code density. The assembler attempts to widen density instructions to align branch targets and the instructions following call instructions. If there are not enough preceding safe density instructions to align a target, no widening is performed. The default is-mtarget-align. These options do not affect the treatment of auto-aligned instructions like"LOOP", which the assembler always aligns, either by widening density instructions or by inserting NOP instructions."LOOP"does what it wants, always has ๐-mlongcalls,-mno-longcallsโ when this option is enabled, GCC instructs the assembler to translate direct calls to indirect calls unless it can determine that the target of a direct call is in the range allowed by the call instruction. This translation typically occurs for calls to functions in other source files. Specifically, the assembler translates a direct"CALL"instruction into an"L32R"followed by a"CALLX"instruction. The default is-mno-longcalls. This option should be used in programs where the call target can potentially be out of range. This option is implemented in the assembler, not the compiler, so the assembly code generated by GCC still shows direct call instructions---look at the disassembled object code to see the actual instructions. Note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range. so if you're confused about why your asm looks normal, that's why bestie ๐-mabi=nameโ generate code for the specified ABI. Permissible values are:call0,windowed. Default ABI is chosen by the Xtensa core configuration.-mabi=call0โ when this option is enabled, function parameters are passed in registers"a2"through"a7", registers"a12"through"a15"are caller-saved, and register"a15"may be used as a frame pointer. When this version of the ABI is enabled the C preprocessor symbol"__XTENSA_CALL0_ABI__"is defined. โจ-mabi=windowedโ when this option is enabled, function parameters are passed in registers"a10"through"a15", and the called function rotates the register window by 8 registers on entry so that its arguments are found in registers"a2"through"a7". Register"a7"may be used as a frame pointer. Register window is rotated 8 registers back upon return. When this version of the ABI is enabled the C preprocessor symbol"__XTENSA_WINDOWED_ABI__"is defined. rotating windows, we love a structural moment ๐ซ
๐ zSeries Options ๐
These are listed under
โจ ENVIRONMENT โจ
Okay bestie, this section is all about the environment variables that change how GCC does its thing. Some of them are like, โhey, look in these directories or use these prefixes when youโre hunting for files,โ and some are just vibes about the compilation environment. ๐
Also real quick: you can tell GCC where to look with options like -B, -I, and -L. Those options beat environment variables, and environment variables beat whatever GCC was configured with. Order of operations, periodt. ๐
LANG, LC_CTYPE, LC_MESSAGES, LC_ALL โ the localization girlies ๐
These environment variables control how GCC uses localization info so it can work with different national conventions. GCC peeks at the locale categories LC_CTYPE and LC_MESSAGES if itโs been configured to do so. Those locale categories can be set 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 figure out character boundaries in a string. Thatโs needed for some multibyte encodings that contain quote and escape characters which would otherwise be interpreted as a string end or escape. ๐ญ
The LC_MESSAGES environment variable specifies the language to use in diagnostic messages. So your compiler errors can speak your language, slay. ๐ฌ
If LC_ALL is set, it overrides the value of LC_CTYPE and LC_MESSAGES. Otherwise, LC_CTYPE and LC_MESSAGES default to the value of the LANG environment variable. If none of these variables are set, GCC defaults to traditional C English behavior. ๐บ๐ธ๐
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 going 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. ๐
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. ๐คฏ
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. ๐งญ
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). ๐
LANG (round two, bestie ๐)
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. ๐ซ
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. โ ๏ธ
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. ๐ง โจ
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. ๐ซถ
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. ๐ค
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. โ๏ธ
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. ๐ฐ๏ธโจ
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. ๐
๐ BUGS ๐
For instructions on reporting bugs, see <file:///usr/share/doc/gcc-12/README.Bugs>. ๐
๐ 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. ๐
๐ SEE ALSO ๐
gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1), dbx(1) and the Info entries for gcc, cpp, as, ld, binutils and gdb. ๐
โ๏ธ AUTHOR โ๏ธ
See the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC. ๐
ยฉ๏ธ COPYRIGHT ยฉ๏ธ
Copyright (c) 1988-2022 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page.
(a) The FSFโs Front-Cover Text is: A GNU Manual
(b) The FSFโs Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.
And thatโs a wrap on the GCC(1) man page, bestie! This version is from gcc-12 and itโs dated 2025-07-11. You ate this whole thing, no cap. ๐โจ๐ฆ๐
๐ฆ where this page comes from
- ubuntu questing: g++-12-arc-linux-gnu 12.5.0-6ubuntu1cross1
- ubuntu resolute: g++-12-arc-linux-gnu 12.5.0-9ubuntu1cross1
- ubuntu stonking: g++-12-arc-linux-gnu 12.5.0-9ubuntu1cross1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms