GCC(1)
GCC(1) โ GNU project C and C++ compiler ๐ โจ
๐ธ NAME ๐ธ
gcc - GNU project C and C++ compiler
Itโs giving โthe compiler icon,โ bestie. ๐
๐ฆ 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 ๐
Okay so 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. No cap.
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. Itโs the cheat sheet era. ๐
โจ Overall Options โจ
-c -S -E -o file -dumpbase dumpbase -dumpbase-ext auxdropsuf
-dumpdir dumppfx -x language -v -### --help[=class[,...]]
--target-help --version -pass-exit-codes -pipe -specs=file
-wrapper @file -ffile-prefix-map=old=new -fcanon-prefix-map
-fplugin=file -fplugin-arg-name=arg -fdump-ada-spec[-slim]
-fada-spec-parent=unit -fdump-go-spec=file
๐ธ C Language Options ๐ธ
-ansi -std=standard -aux-info filename -fno-asm -fno-builtin
-fno-builtin-function -fcond-mismatch -ffreestanding -fgimple
-fgnu-tm -fgnu89-inline -fhosted -flax-vector-conversions
-fms-extensions -foffload=arg -foffload-options=arg -fopenacc
-fopenacc-dim=geom -fopenmp -fopenmp-simd
-fopenmp-target-simd-clone[=device-type]
-fpermitted-flt-eval-methods=standard -fplan9-extensions
-fsigned-bitfields -funsigned-bitfields -fsigned-char
-funsigned-char -fstrict-flex-arrays[=n] -fsso-struct=endianness
๐ C++ Language Options ๐
-fabi-version=n -fno-access-control -faligned-new=n
-fargs-in-order=n -fchar8_t -fcheck-new -fconstexpr-depth=n
-fconstexpr-cache-depth=n -fconstexpr-loop-limit=n
-fconstexpr-ops-limit=n -fno-elide-constructors
-fno-enforce-eh-specs -fno-gnu-keywords -fno-implicit-templates
-fno-implicit-inline-templates -fno-implement-inlines
-fmodule-header[=kind] -fmodule-only -fmodules-ts
-fmodule-implicit-inline -fno-module-lazy
-fmodule-mapper=specification -fmodule-version-ignore
-fms-extensions -fnew-inheriting-ctors -fnew-ttp-matching
-fno-nonansi-builtins -fnothrow-opt -fno-operator-names
-fno-optional-diags -fpermissive -fno-pretty-templates -fno-rtti
-fsized-deallocation -ftemplate-backtrace-limit=n -ftemplate-depth=n
-fno-threadsafe-statics -fuse-cxa-atexit -fno-weak -nostdinc++
-fvisibility-inlines-hidden -fvisibility-ms-compat
-fext-numeric-literals -flang-info-include-translate[=header]
-flang-info-include-translate-not -flang-info-module-cmi[=module]
-stdlib=libstdc++,libc++ -Wabi-tag -Wcatch-value -Wcatch-value=n
-Wno-class-conversion -Wclass-memaccess -Wcomma-subscript
-Wconditionally-supported -Wno-conversion-null
-Wctad-maybe-unsupported -Wctor-dtor-privacy -Wdangling-reference
-Wno-delete-incomplete -Wdelete-non-virtual-dtor
-Wno-deprecated-array-compare -Wdeprecated-copy
-Wdeprecated-copy-dtor -Wno-deprecated-enum-enum-conversion
-Wno-deprecated-enum-float-conversion -Weffc++ -Wno-exceptions
-Wextra-semi -Wno-inaccessible-base -Wno-inherited-variadic-ctor
-Wno-init-list-lifetime -Winvalid-constexpr
-Winvalid-imported-macros -Wno-invalid-offsetof -Wno-literal-suffix
-Wmismatched-new-delete -Wmismatched-tags -Wmultiple-inheritance
-Wnamespaces -Wnarrowing -Wnoexcept -Wnoexcept-type
-Wnon-virtual-dtor -Wpessimizing-move -Wno-placement-new
-Wplacement-new=n -Wrange-loop-construct -Wredundant-move
-Wredundant-tags -Wreorder -Wregister -Wstrict-null-sentinel
-Wno-subobject-linkage -Wtemplates -Wno-non-template-friend
-Wold-style-cast -Woverloaded-virtual -Wno-pmf-conversions
-Wself-move -Wsign-promo -Wsized-deallocation
-Wsuggest-final-methods -Wsuggest-final-types -Wsuggest-override
-Wno-terminate -Wuseless-cast -Wno-vexing-parse
-Wvirtual-inheritance -Wno-virtual-move-assign -Wvolatile
-Wzero-as-null-pointer-constant
๐ฆ Objective-C and Objective-C++ Language Options ๐ฆ
-fconstant-string-class=class-name -fgnu-runtime -fnext-runtime
-fno-nil-receivers -fobjc-abi-version=n -fobjc-call-cxx-cdtors
-fobjc-direct-dispatch -fobjc-exceptions -fobjc-gc -fobjc-nilcheck
-fobjc-std=objc1 -fno-local-ivars
-fivar-visibility=[public|protected|private|package]
-freplace-objc-classes -fzero-link -gen-decls -Wassign-intercept
-Wno-property-assign-default -Wno-protocol -Wobjc-root-class
-Wselector -Wstrict-selector-match -Wundeclared-selector
๐ฉท Diagnostic Message Formatting Options ๐ฉท
-fmessage-length=n -fdiagnostics-plain-output
-fdiagnostics-show-location=[once|every-line]
-fdiagnostics-color=[auto|never|always]
-fdiagnostics-urls=[auto|never|always]
-fdiagnostics-format=[text|sarif-stderr|sarif-file|json|json-stderr|json-file]
-fno-diagnostics-show-option -fno-diagnostics-show-caret
-fno-diagnostics-show-labels -fno-diagnostics-show-line-numbers
-fno-diagnostics-show-cwe -fno-diagnostics-show-rule
-fdiagnostics-minimum-margin-width=width
-fdiagnostics-parseable-fixits -fdiagnostics-generate-patch
-fdiagnostics-show-template-tree -fno-elide-type
-fdiagnostics-path-format=[none|separate-events|inline-events]
-fdiagnostics-show-path-depths -fno-show-column
-fdiagnostics-column-unit=[display|byte]
-fdiagnostics-column-origin=origin
-fdiagnostics-escape-format=[unicode|bytes]
โ ๏ธ Warning Options โ ๏ธ
Okay bestie, breathe. This is the big one. This is the entire warning catalogue, and yes, it is giving "my mom's grocery list but make it compilers." These are all the little flags that make GCC tell you stuff. Some yell. Some whisper. Some just vibe. Every single one is here, in order, no cap. ๐ซถ
-fsyntax-onlyโ checks the syntax and then dips โจ-fmax-errors=nโ cap the error count at n, we're not doing infinity today-Wpedanticโ the hall monitor of warnings ๐-pedantic-errorsโ hall monitor, but now it's serious-wโ the "la la la I can't hear you" flag ๐-Wextraโ extra warnings, extra love-Wallโ the one everyone types first, iconic behavior ๐-Wabi=nโ ABI tea โ-Waddressโ address her directly-Wno-address-of-packed-memberโ the no version, respectfully ๐-Waggregate-returnโ aggregates, returning them, drama-Walloc-size-larger-than=byte-sizeโ watch that byte-size number bestie-Walloc-zeroโ zero allocations, zero chill-Wallocaโ alloca is main character energy ๐-Walloca-larger-than=byte-sizeโ again with the byte-size-Wno-aggressive-loop-optimizationsโ not me being aggressive-Warith-conversionโ arithmetic conversion arc-Warray-boundsโ stay in your lane, array-Warray-bounds=nโ same but with a n because levels โจ-Warray-compareโ comparing arrays, bold of you-Wno-attributesโ attributes? not today-Wattribute-alias=nโ alias with a n on top-Wno-attribute-aliasโ nope to that too-Wno-attribute-warningโ the quiet one ๐-Wbidi-chars=[none|unpaired|any|ucn]โ pick your mode: none, unpaired, any, or ucn-Wbool-compareโ bool comparisons, very true/false of you-Wbool-operationโ bool operations slay-Wno-builtin-declaration-mismatchโ no mismatch parties today-Wno-builtin-macro-redefinedโ macro said what it said-Wc90-c99-compatโ C90 to C99 compatibility era ๐ฐ๏ธ-Wc99-c11-compatโ C99 to C11, the sequel-Wc11-c2x-compatโ C11 to C2x, the threequel-Wc++-compatโ C++ compatibility, we contain multitudes-Wc++11-compatโ C++11 era-Wc++14-compatโ C++14 era-Wc++17-compatโ C++17 era-Wc++20-compatโ C++20 era-Wno-c++11-extensionsโ no extensions, C++11 division-Wno-c++14-extensionsโ C++14 division, also no-Wno-c++17-extensionsโ you get the idea-Wno-c++20-extensionsโ yes, also this one-Wno-c++23-extensionsโ and this one, she's new ๐-Wcast-alignโ casts, aligned-Wcast-align=strictโ strict mode, behave-Wcast-function-typeโ cast that function, I dare you-Wcast-qualโ qualifiers keep their meaning, tyvm-Wchar-subscriptsโ chars as subscripts, chaotic-Wclobberedโ the word itself is a threat ๐-Wcommentโ comment section moderation-Wno-complain-wrong-langโ not complaining about the wrong language, growth ๐ฑ-Wconversionโ conversions get called out-Wno-coverage-mismatchโ no coverage mismatch discourse-Wno-cppโ not the preprocessor's problem-Wdangling-elseโ dangling else, dangling earrings, same energy ๐-Wdangling-pointerโ pointer just hanging around-Wdangling-pointer=nโ same, but with a n-Wdate-timeโ date and time check โฐ-Wno-deprecatedโ deprecated? never heard of her-Wno-deprecated-declarationsโ the declarations version of never heard of her-Wno-designated-initโ designated init and no commentary-Wdisabled-optimizationโ optimization said "not today"-Wno-discarded-array-qualifiersโ qualifiers, discarded, array flavored-Wno-discarded-qualifiersโ the plain version-Wno-div-by-zeroโ division by zero, we simply don't discuss it ๐-Wdouble-promotionโ double promotion, she's climbing the ranks ๐-Wduplicated-branchesโ twins but branches-Wduplicated-condโ twins but conditions-Wempty-bodyโ empty body, no thoughts head empty-Wno-endif-labelsโ endif said no labels-Wenum-compareโ enums comparing each other, petty-Wenum-conversionโ enums converting, glow up-Wenum-int-mismatchโ mismatch, enum vs int ๐-Werrorโ every warning is now an ERROR. good luck bestie ๐ฅ-Werror=*โ the wildcard version, truly unhinged-Wexpansion-to-definedโ expansion to defined, she's a journey-Wfatal-errorsโ one error and we're DONE ๐ญ-Wfloat-conversionโ floats converting-Wfloat-equalโ floats being equal, suspicious-Wformatโ format strings get the spotlight-Wformat=2โ format level two, because levels-Wno-format-contains-nulโ nul in format, no comment-Wno-format-extra-argsโ extra args, extra baggage-Wformat-nonliteralโ nonliteral format, mysterious โจ-Wformat-overflow=nโ overflow, with a n-Wformat-securityโ security check, very demure, very mindful-Wformat-signednessโ signedness discourse-Wformat-truncation=nโ truncation plus n-Wformat-y2kโ y2k called, she wants her warning back ๐-Wframe-addressโ frame address, framed-Wframe-larger-than=byte-sizeโ that byte-size again-Wno-free-nonheap-objectโ no freeing non-heap today-Wno-if-not-alignedโ not aligned, not addressed-Wno-ignored-attributesโ ignored attributes, ignored accordingly-Wignored-qualifiersโ qualifiers getting ignored, rude-Wno-incompatible-pointer-typesโ incompatible pointers? in this economy?-Wimplicitโ implicit things being loud-Wimplicit-fallthroughโ fallthrough, careful ๐-Wimplicit-fallthrough=nโ fallthrough with a n-Wno-implicit-function-declarationโ no implicit function declarations, growth-Wno-implicit-intโ no implicit int-Winfinite-recursionโ infinite recursion, we LOVE a loop ๐-Winit-selfโ init self, self care-Winlineโ inline, in line, in love-Wno-int-conversionโ leave int conversion alone-Wint-in-bool-contextโ int in a bool context, choose a lane-Wno-int-to-pointer-castโ no intโpointer casts-Wno-invalid-memory-modelโ memory model said valid actually-Winvalid-pchโ PCH said invalid-Winvalid-utf8โ utf8 no longer valid, embarrassing-Wno-unicodeโ unicode, unbothered-Wjump-misses-initโ jump missed init, relatable-Wlarger-than=byte-sizeโ byte-size, again, love her-Wlogical-not-parenthesesโ logical not + parentheses = chaos combo-Wlogical-opโ logical operators doing logic-Wlong-longโ long long, extra long ๐-Wno-lto-type-mismatchโ LTO said no mismatch today-Wmainโ main character, literally โญ-Wmaybe-uninitializedโ maybe ๐ญ-Wmemset-elt-sizeโ memset element size check-Wmemset-transposed-argsโ transposed args, we've all been there-Wmisleading-indentationโ misleading indentation, evil actually ๐-Wmissing-attributesโ attributes missing, come back-Wmissing-bracesโ braces missing, put them back ๐-Wmissing-field-initializersโ field initializers went MIA-Wmissing-format-attributeโ format attribute absent-Wmissing-include-dirsโ include dirs, where'd they go-Wmissing-noreturnโ noreturn missing, ironic-Wno-missing-profileโ profile missing and nobody's talking-Wno-multicharโ multichar, mind your business-Wmultistatement-macrosโ macros with multiple statements, bold-Wnonnullโ non-null check-Wnonnull-compareโ comparing against nonnull, why-Wnormalized=[none|id|nfc|nfkc]โ modes: none, id, nfc, nfkc-Wnull-dereferenceโ null dereference, the classic ๐ญ-Wno-odrโ ODR, but she said no-Wopenacc-parallelismโ OpenACC parallelism era-Wopenmp-simdโ OpenMP SIMD, we parallel here-Wno-overflowโ overflow, not today-Woverlength-stringsโ strings too long, she's extra-Wno-override-init-side-effectsโ side effects, declined-Wpackedโ packed, compact, cute-Wno-packed-bitfield-compatโ bitfield compat, no thanks-Wpacked-not-alignedโ packed but not aligned, pick one-Wpaddedโ padded, cozy-Wparenthesesโ the parentheses committee has notes ๐-Wno-pedantic-ms-formatโ the MS format pedantry has been excused-Wpointer-arithโ pointer arithmetic doing math-Wno-pointer-compareโ pointers compared? not on my watch-Wno-pointer-to-int-castโ no pointerโint casts-Wno-pragmasโ pragmas, unbothered-Wno-prio-ctor-dtorโ ctor/dtor priority, we simply moved on-Wredundant-declsโ redundant declarations, say it once bestie-Wrestrictโ restrict, respectfully-Wno-return-local-addrโ local address returned? not discussed ๐-Wreturn-typeโ return type check, do it right-Wno-scalar-storage-orderโ storage order, no comment-Wsequence-pointโ sequence points, stay in sequence-Wshadowโ spooky variable names ๐ป-Wshadow=globalโ global spooky-Wshadow=localโ local spooky-Wshadow=compatible-localโ compatible local spooky-Wno-shadow-ivarโ ivar shadowing, blocked-Wno-shift-count-negativeโ negative shift count, not today-Wno-shift-count-overflowโ shift count overflow, also not today-Wshift-negative-valueโ negative value shifted, hmm-Wno-shift-overflowโ shift overflow, declined-Wshift-overflow=nโ shift overflow with a n-Wsign-compareโ sign comparison discourse-Wsign-conversionโ sign conversion era-Wno-sizeof-array-argumentโ sizeof on array argument, let it go-Wsizeof-array-divโ sizeof divided, math girlie-Wsizeof-pointer-divโ sizeof on pointer, divided, chaotic-Wsizeof-pointer-memaccessโ sizeof with pointer memaccess-Wstack-protectorโ stack protector, she protects ๐ธ-Wstack-usage=byte-sizeโ byte-size strikes again-Wstrict-aliasingโ strict aliasing, no shortcuts-Wstrict-aliasing=nโ strict aliasing with a n-Wstrict-overflowโ strict overflow, strict vibes-Wstrict-overflow=nโ strict overflow with a n-Wstring-compareโ strings compared-Wno-stringop-overflowโ stringop overflow, off the table-Wno-stringop-overreadโ no overreading-Wno-stringop-truncationโ no truncation commentary-Wstrict-flex-arraysโ flexible arrays but strict ๐-Wsuggest-attribute=[pure|const|noreturn|format|malloc]โ pick one: pure, const, noreturn, format, malloc-Wswitchโ switch statements get a look ๐-Wno-switch-boolโ switch on bool, no thoughts-Wswitch-defaultโ default case check-Wswitch-enumโ enum switches, she's thorough-Wno-switch-outside-rangeโ outside range, outside jurisdiction-Wno-switch-unreachableโ unreachable, unreachable-Wsync-nandโ sync nand, iconic name actually-Wsystem-headersโ system headers count now, beware ๐-Wtautological-compareโ comparing a thing to itself, we've all done it-Wtrampolinesโ trampolines, jumping ๐ฆ-Wtrigraphsโ trigraphs, vintage-Wtrivial-auto-var-initโ trivial auto var init-Wtsanโ TSan said hello-Wtype-limitsโ type limits, boundaries-Wundefโ undef, undefined, unbothered-Wuninitializedโ uninitialized, the classic ๐ญ-Wunknown-pragmasโ unknown pragmas, mysterious-Wunsuffixed-float-constantsโ float constants without a suffix, rude-Wunusedโ the whole "you're not using that" section ๐-Wunused-but-set-parameterโ set but not used, a parameter tragedy-Wunused-but-set-variableโ same but a variable-Wunused-const-variableโ const variable, unused, sad-Wunused-const-variable=nโ with a n, obviously-Wunused-functionโ function just sitting there-Wunused-labelโ label with nothing to do-Wunused-local-typedefsโ local typedefs gathering dust-Wunused-macrosโ macro unused, ghosted-Wunused-parameterโ parameter unused, relatable-Wno-unused-resultโ unused result, no comment-Wunused-valueโ value unused, wasteful-Wunused-variableโ variable unused, we been knew-Wno-varargsโ varargs, not today-Wvariadic-macrosโ variadic macros, so many args-Wvector-operation-performanceโ vector ops, performance era โก-Wvlaโ VLA, variable length, variable vibes-Wvla-larger-than=byte-sizeโ VLA + byte-size, iconic combo-Wno-vla-larger-thanโ the no version of that-Wvolatile-register-varโ volatile register var, rare sighting-Wwrite-stringsโ write strings, careful-Wxor-used-as-powโ xor pretending to be pow, we see you ๐-Wzero-length-boundsโ zero length, zero bounds, zero problems
๐ฎ Static Analyzer Options ๐ฎ
This next batch is the analyzer squad. She reads your code, builds a whole little world in her head, and then tells you what she thinks. Very main character, very "I did my own research." ๐
-fanalyzerโ the analyzer herself, the moment ๐-fanalyzer-call-summariesโ call summaries, she takes notes-fanalyzer-checker=nameโ pick a checker by name-fno-analyzer-feasibilityโ feasibility checks off-fanalyzer-fine-grainedโ fine grained, she's detailed-fno-analyzer-state-mergeโ no state merging-fno-analyzer-state-purgeโ no state purging-fno-analyzer-suppress-followupsโ no suppressing follow-ups-fanalyzer-transitivityโ transitivity, very math of her-fno-analyzer-undo-inliningโ inlining stays undone-fanalyzer-verbose-edgesโ verbose edges, edges with lore-fanalyzer-verbose-state-changesโ state changes but verbose-fanalyzer-verbosity=levelโ set the level, queen of settings-fdump-analyzerโ dump it, bestie ๐พ-fdump-analyzer-callgraphโ dump the callgraph-fdump-analyzer-exploded-graphโ exploded graph, dramatic much-fdump-analyzer-exploded-nodesโ exploded nodes-fdump-analyzer-exploded-nodes-2โ the sequel-fdump-analyzer-exploded-nodes-3โ the threequel-fdump-analyzer-exploded-pathsโ exploded paths-fdump-analyzer-feasibilityโ feasibility dump-fdump-analyzer-jsonโ json flavored dump โจ-fdump-analyzer-state-purgeโ state purge dump-fdump-analyzer-stderrโ dump to stderr-fdump-analyzer-supergraphโ supergraph, super dump-fdump-analyzer-untrackedโ the untracked ones get dumped too-Wno-analyzer-double-fcloseโ double fclose, muted-Wno-analyzer-double-freeโ double free, muted-Wno-analyzer-exposure-through-output-fileโ exposure via output file, shh-Wno-analyzer-exposure-through-uninit-copyโ exposure via uninit copy, also shh-Wno-analyzer-fd-access-mode-mismatchโ fd access mode mismatch, no comment-Wno-analyzer-fd-double-closeโ fd double close, we closed that chapter-Wno-analyzer-fd-leakโ fd leak, plugged-Wno-analyzer-fd-phase-mismatchโ fd phase mismatch, off the table-Wno-analyzer-fd-type-mismatchโ fd type mismatch, nope-Wno-analyzer-fd-use-after-closeโ use after close, not discussed-Wno-analyzer-fd-use-without-checkโ use without check, declined-Wno-analyzer-file-leakโ file leak, contained-Wno-analyzer-free-of-non-heapโ freeing non-heap, let it be-Wno-analyzer-imprecise-fp-arithmeticโ imprecise fp arithmetic, whatever-Wno-analyzer-infinite-recursionโ infinite recursion, we've made peace ๐๏ธ-Wno-analyzer-jump-through-nullโ jumping through null, blocked-Wno-analyzer-malloc-leakโ malloc leak, muzzled-Wno-analyzer-mismatching-deallocationโ mismatching deallocation, quiet-Wno-analyzer-null-argumentโ null argument, hushed-Wno-analyzer-null-dereferenceโ null dereference, silenced-Wno-analyzer-out-of-boundsโ out of bounds, out of mind-Wno-analyzer-possible-null-argumentโ possible null argument, also quiet-Wno-analyzer-possible-null-dereferenceโ possible null deref, quiet-Wno-analyzer-putenv-of-auto-varโ putenv of auto var, moving on-Wno-analyzer-shift-count-negativeโ negative shift count, no comment-Wno-analyzer-shift-count-overflowโ shift count overflow, no comment-Wno-analyzer-stale-setjmp-bufferโ stale setjmp buffer, stale discourse-Wno-analyzer-tainted-allocation-sizeโ tainted allocation size, declined-Wno-analyzer-tainted-assertionโ tainted assertion, also declined-Wno-analyzer-tainted-array-indexโ tainted array index, no-Wno-analyzer-tainted-divisorโ tainted divisor, no-Wno-analyzer-tainted-offsetโ tainted offset, no-Wno-analyzer-tainted-sizeโ tainted size, no-Wanalyzer-too-complexโ the analyzer telling you you're too complex ๐-Wno-analyzer-unsafe-call-within-signal-handlerโ unsafe call in a signal handler, muted-Wno-analyzer-use-after-freeโ use after free, we don't talk about it-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ stale stack frame pointer, quiet-Wno-analyzer-use-of-uninitialized-valueโ uninitialized value use, silenced-Wno-analyzer-va-arg-type-mismatchโ va_arg type mismatch, hushed-Wno-analyzer-va-list-exhaustedโ va_list exhausted, she's tired-Wno-analyzer-va-list-leakโ va_list leak, contained-Wno-analyzer-va-list-use-after-va-endโ va_list use after va_end, no comment-Wno-analyzer-write-to-constโ writing to const, blocked-Wno-analyzer-write-to-string-literalโ writing to a string literal, absolutely not ๐
๐ C and Objective-C-only Warning Options ๐
C girlies and Objective-C girlies, this section is for you specifically. Everyone else can scroll. ๐
-Wbad-function-castโ bad function cast, we've all had one-Wmissing-declarationsโ declarations went missing-Wmissing-parameter-typeโ parameter type absent-Wmissing-prototypesโ prototypes MIA-Wnested-externsโ nested externs, nesting doll energy ๐ช-Wold-style-declarationโ old style declaration, vintage-Wold-style-definitionโ old style definition, also vintage-Wstrict-prototypesโ strict prototypes, she has standards-Wtraditionalโ traditional, classic, timeless ๐ธ-Wtraditional-conversionโ traditional conversion, old money-Wdeclaration-after-statementโ declaration after statement, the audacity-Wpointer-signโ pointer sign, sign of the times
๐ฆ Debugging Options ๐ฆ
Okay so debugging is literally where you become the detective. These flags are your magnifying glass, your little notebook, your "wait what happened here" toolkit. -g girlies rise. ๐
-gโ the debugging flag, the blueprint, the icon ๐-glevelโ set a level, because levels-gdwarfโ DWARF flavored debug info-gdwarf-versionโ DWARF but pick a version-gbtfโ BTF debug info, so specific, love her-gctfโ CTF debug info-gctflevelโ CTF plus a level-ggdbโ GDB-specific debug info, bestie behavior ๐ซถ-grecord-gcc-switchesโ record those GCC switches, receipts kept-gno-record-gcc-switchesโ no receipts, no problem-gstrict-dwarfโ strict DWARF-gno-strict-dwarfโ not strict DWARF, she's chill-gas-loc-supportโ as loc support, on-gno-as-loc-supportโ as loc support, off-gas-locview-supportโ as locview support, on-gno-as-locview-supportโ as locview support, off-gcolumn-infoโ column info, column queen-gno-column-infoโ no column info-gdwarf32โ DWARF 32, compact-gdwarf64โ DWARF 64, extra-gstatement-frontiersโ statement frontiers, very frontiers-gno-statement-frontiersโ frontiers, declined-gvariable-location-viewsโ variable location views-gno-variable-location-viewsโ no views today-ginternal-reset-location-viewsโ internal reset locations views-gno-internal-reset-location-viewsโ the no version-ginline-pointsโ inline points, points made-gno-inline-pointsโ points retracted-gvmsโ VMS debug info, retro-gz[=type]โ compressed debug info, optional type ๐-gsplit-dwarfโ split DWARF, she's divided but thriving-gdescribe-diesโ describe the DIEs, tell us everything-gno-describe-diesโ DIEs undescribed-fdebug-prefix-map=old=newโ map old to new, remap era-fdebug-types-sectionโ types section, sectioned-fno-eliminate-unused-debug-typesโ keep those unused debug types, don't eliminate-femit-struct-debug-baseonlyโ emit struct debug, base only-femit-struct-debug-reducedโ emit struct debug, reduced-femit-struct-debug-detailed[=spec-list]โ detailed, optionally with a spec-list โจ-fno-eliminate-unused-debug-symbolsโ unused debug symbols stay-femit-class-debug-alwaysโ class debug, always-fno-merge-debug-stringsโ no merging those debug strings-fno-dwarf2-cfi-asmโ no DWARF2 CFI asm-fvar-trackingโ var tracking, she's watching ๐-fvar-tracking-assignmentsโ var tracking but assignments
โก Optimization Options โก
Okay bestie, breathe. This is the roster โ every optimization switch GCC has, dumped in one glorious pile. No skips, no "you don't need those", nothing. Copy-paste to your heart's content. ๐ซถ
-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]]]] -fmin-function-alignment=[n]
-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
A couple of faves to call out so you don't get lost in there ๐
--param name=valueโ the "set a knob by name" escape hatch, sitting right before the-Ocrew.-O,-O0,-O1,-O2,-O3,-Os,-Ofast,-Og,-Ozโ yes, all nine of them, chilling at the very bottom of the list. The main characters, honestly. ๐
๐ฉบ Program Instrumentation Options ๐ฉบ
Now we're in the "watch what my program is actually doing" zone: profiling, coverage, sanitizers, stack protection, function instrumentation. It's giving ๐ต๏ธโโ๏ธ investigator era.
-p -pg -fprofile-arcs --coverage -ftest-coverage
-fprofile-abs-path -fprofile-dir=path -fprofile-generate
-fprofile-generate=path -fprofile-info-section
-fprofile-info-section=name -fprofile-note=path
-fprofile-prefix-path=path -fprofile-update=method
-fprofile-filter-files=regex -fprofile-exclude-files=regex
-fprofile-reproducible=[multithreaded|parallel-runs|serial]
-fsanitize=style -fsanitize-recover -fsanitize-recover=style
-fsanitize-trap -fsanitize-trap=style -fasan-shadow-offset=number
-fsanitize-sections=s1,s2,... -fsanitize-undefined-trap-on-error
-fbounds-check -fcf-protection=[full|branch|return|none|check]
-fharden-compares -fharden-conditional-branches -fstack-protector
-fstack-protector-all -fstack-protector-strong
-fstack-protector-explicit -fstack-check -fstack-limit-register=reg
-fstack-limit-symbol=sym -fno-stack-limit -fsplit-stack
-fvtable-verify=[std|preinit|none] -fvtv-counts -fvtv-debug
-finstrument-functions -finstrument-functions-once
-finstrument-functions-exclude-function-list=sym,sym,...
-finstrument-functions-exclude-file-list=file,file,...
-fprofile-prefix-map=old=new
Do notice the -fsanitize=style family and -fsanitize-recover=style / -fsanitize-trap=style โ those take a style argument, they're not just vibes. Same for -fcf-protection=[full|branch|return|none|check] and -fvtable-verify=[std|preinit|none], all spelled out with their exact options above. ๐
๐ Preprocessor Options ๐
The preprocessor is the part of the pipeline that shows up before anyone else and starts rewriting stuff โ very "let me just fix your text rq" energy. ๐ญ
-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
Note the two weirdos at the bottom: -Wp,option and -Xpreprocessor option โ your little smuggling routes for handing something straight to the preprocessor. And -Aquestion=answer / -A-question[=answer] are the assertion ones, in case you were like "wait, -A?" yeah. ๐
๐ Assembler Options ๐
Two, count 'em, two. Both are "pass this along to the assembler" moves.
-Wa,optionโ handsoptionover to the assembler.-Xassembler optionโ same idea, different spelling, oneoptionper flag.
๐ Linker Options ๐
This is the section where you and the linker have a little chat about how your program gets put together. ๐ซถ
object-file-name -fuse-ld=linker -llibrary -nostartfiles
-nodefaultlibs -nolibc -nostdlib -nostdlib++ -e entry
--entry=entry -pie -pthread -r -rdynamic -s -static -static-pie
-static-libgcc -static-libstdc++ -static-libasan -static-libtsan
-static-liblsan -static-libubsan -shared -shared-libgcc -symbolic
-T script -Wl,option -Xlinker option -u symbol -z keyword
Little tour: object-file-name is literally a file name, -llibrary is your -l flag, and at the end you've got -Wl,option and -Xlinker option for forwarding stuff to the linker itself. There's also -T script, -u symbol, -z keyword, -e entry, --entry=entry โ all right there. No cap. ๐ฅ
๐ Directory Options ๐
The "where do I find your stuff" section. Search paths, sysroots, include dirs โ all of it. ๐ฆ
-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
Careful with -I- โ that one's got a trailing dash and it is absolutely not a typo, so don't be out here "cleaning it up". ๐
๐งฌ Code Generation Options ๐งฌ
The nitty-gritty of what the compiler is actually allowed to emit: registers, exceptions, PIC, struct returns, enums, visibility, all that good stuff. It's giving low-level main character. ๐
-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
Yes -fpic, -fPIC, -fpie and -fPIE are all four separate things โ case matters, bestie, always. Also -fvisibility=[default|internal|hidden|protected] takes exactly those four values, spelled with a lowercase i in internal. ๐
๐งช Developer Options ๐งช
The dev-only zone. Dumps, logs, debug counters, statistics, timing reports โ this is what you turn on when you're like "why is my compiler doing that??" ๐ญ
-dletters -dumpspecs -dumpmachine -dumpversion -dumpfullversion
-fcallgraph-info[=su,da] -fchecking -fchecking=n -fdbg-cnt-list
-fdbg-cnt=counter-value-list -fdisable-ipa-pass_name
-fdisable-rtl-pass_name -fdisable-rtl-pass-name=range-list
-fdisable-tree-pass_name -fdisable-tree-pass-name=range-list
-fdump-debug -fdump-earlydebug -fdump-noaddr -fdump-unnumbered
-fdump-unnumbered-links -fdump-final-insns[=file] -fdump-ipa-all
-fdump-ipa-cgraph -fdump-ipa-inline -fdump-lang-all
-fdump-lang-switch -fdump-lang-switch-options
-fdump-lang-switch-options=filename -fdump-passes -fdump-rtl-pass
-fdump-rtl-pass=filename -fdump-statistics -fdump-tree-all
-fdump-tree-switch -fdump-tree-switch-options
-fdump-tree-switch-options=filename -fcompare-debug[=opts]
-fcompare-debug-second -fenable-kind-pass
-fenable-kind-pass=range-list -fira-verbose=n -flto-report
-flto-report-wpa -fmem-report-wpa -fmem-report
-fpre-ipa-mem-report -fpost-ipa-mem-report -fopt-info
-fopt-info-options[=file] -fmultiflags -fprofile-report
-frandom-seed=string -fsched-verbose=n -fsel-sched-verbose
-fsel-sched-dump-cfg -fsel-sched-pipelining-verbose -fstats
-fstack-usage -ftime-report -ftime-report-details
-fvar-tracking-assignments-toggle -gtoggle -print-file-name=library
-print-libgcc-file-name -print-multi-directory -print-multi-lib
-print-multi-os-directory -print-prog-name=program
-print-search-dirs -Q -print-sysroot -print-sysroot-headers-suffix
-save-temps -save-temps=cwd -save-temps=obj -time[=file]
Tiny heads-up because I know you're gonna squint at these: -fdisable-ipa-pass_name and -fdisable-tree-pass_name use the bare pass_name spelling, while -fdisable-rtl-pass-name=range-list, -fdisable-tree-pass-name=range-list and -fenable-kind-pass=range-list use the =range-list shape. They're different forms, both listed, both real. ๐
Also: -fchecking and -fchecking=n are two separate entries, -fdump-final-insns[=file] has that optional =file, and -frandom-seed=string wants a string, not a number. And at the very end, -save-temps, -save-temps=cwd, -save-temps=obj and -time[=file] close it out. ๐ธ
And that's the developer pile done โ but bestie, we are so not done. There's more page, more options, more everything. Keep scrolling. ๐ฆ
๐ ๏ธ Machine-Dependent Options ๐ ๏ธ
Ok bestie, brace yourself โ this is the big one. Every architecture GCC has ever had opinions about, and every flag that comes with it. It's a lot. Like, a LOT lot. ๐ซ But no skimming, because this is literally the whole menu, spelled exactly right, so you can ctrl-F your heart out and find your fave. ๐
๐ AArch64 Options ๐
The 64-bit ARM squad. Absolute main characters.
-mabi=name-mbig-endian-mlittle-endian-mgeneral-regs-only-mcmodel=tiny-mcmodel=small-mcmodel=large-mstrict-align-mno-strict-align-momit-leaf-frame-pointer-mtls-dialect=desc-mtls-dialect=traditional-mtls-size=size-mfix-cortex-a53-835769-mfix-cortex-a53-843419-mlow-precision-recip-sqrt-mlow-precision-sqrt-mlow-precision-div-mpc-relative-literal-loads-msign-return-address=scope-mbranch-protection=none|standard|pac-ret[+leaf +b-key]|bti-mharden-sls=opts-march=name-mcpu=name-mtune=name-moverride=string-mverbose-cost-dump-mstack-protector-guard=guard-mstack-protector-guard-reg=sysreg-mstack-protector-guard-offset=offset-mtrack-speculation-moutline-atomics
โจ Adapteva Epiphany Options โจ
Niche? Yes. Iconic? Also yes.
-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 ๐ธ
A whole three flags. Short king energy, we respect it. ๐
-march=gpu-mtune=gpu-mstack-size=bytes
๐ฆ ARC Options ๐ฆ
This list is long, bestie. Deep breaths.
-mbarrel-shifter-mjli-always-mcpu=cpu-mA6-mARC600-mA7-mARC700-mdpfp-mdpfp-compact-mdpfp-fast-mno-dpfp-lrsr-mea-mno-mpy-mmul32x16-mmul64-matomic-mnorm-mspfp-mspfp-compact-mspfp-fast-msimd-msoft-float-mswap-mcrc-mdsp-packa-mdvbf-mlock-mmac-d16-mmac-24-mrtsc-mswape-mtelephony-mxy-misize-mannotate-align-marclinux-marclinux_prof-mlong-calls-mmedium-calls-msdata-mirq-ctrl-saved-mrgf-banked-regs-mlpc-width=width-G num-mvolatile-cache-mtp-regno=regno-malign-call-mauto-modify-reg-mbbit-peephole-mno-brcc-mcase-vector-pcrel-mcompact-casesi-mno-cond-exec-mearly-cbranchsi-mexpand-adddi-mindexed-loads-mlra-mlra-priority-none-mlra-priority-compact-mlra-priority-noncompact-mmillicode-mmixed-code-mq-class-mRcq-mRcw-msize-level=level-mtune=cpu-mmultcost=num-mcode-density-frame-munalign-prob-threshold=probability-mmpy-option=multo-mdiv-rem-mcode-density-mll64-mfpu=fpu-mrf16-mbranch-index
๐ ARM Options ๐
The classic. The blueprint. Watch how many times -mcpu, -march and -mtune show up in this one โ it's giving recurring guest star. โญ
-mapcs-frame-mno-apcs-frame-mabi=name-mapcs-stack-check-mno-apcs-stack-check-mapcs-reentrant-mno-apcs-reentrant-mgeneral-regs-only-msched-prolog-mno-sched-prolog-mlittle-endian-mbig-endian-mbe8-mbe32-mfloat-abi=name-mfp16-format=name-mthumb-interwork-mno-thumb-interwork-mcpu=name-march=name-mfpu=name-mtune=name-mprint-tune-info-mstructure-size-boundary=n-mabort-on-noreturn-mlong-calls-mno-long-calls-msingle-pic-base-mno-single-pic-base-mpic-register=reg-mnop-fun-dllimport-mpoke-function-name-mthumb-marm-mflip-thumb-mtpcs-frame-mtpcs-leaf-frame-mcaller-super-interworking-mcallee-super-interworking-mtp=name-mtls-dialect=dialect-mword-relocations-mfix-cortex-m3-ldrd-mfix-cortex-a57-aes-1742098-mfix-cortex-a72-aes-1655431-munaligned-access-mneon-for-64bits-mslow-flash-data-masm-syntax-unified-mrestrict-it-mverbose-cost-dump-mpure-code-mcmse-mfix-cmse-cve-2021-35465-mstack-protector-guard=guard-mstack-protector-guard-offset=offset-mfdpic-mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]]
๐ AVR Options ๐
Microcontroller girlies rise up. Note that the last two are -W warnings, not -m flags โ don't come for me, that's just how the original rolls. ๐
-mmcu=mcu-mabsdata-maccumulate-args-mbranch-cost=cost-mcall-prologues-mgas-isr-prologues-mint8-mdouble=bits-mlong-double=bits-mn_flash=size-mno-interrupts-mmain-is-OS_task-mrelax-mrmw-mstrict-X-mtiny-stack-mfract-convert-truncate-mshort-calls-mskip-bug-nodevicelib-nodevicespecs-Waddr-space-convert-Wmisspelled-isr
๐ Blackfin Options ๐
The -mno- twins are out in full force here. Every vibe has its opposite. ๐ซ
-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 ๐ง
Five flags. Five. Honestly? Efficient. We love a minimal aesthetic. โจ
-mbig-endian-mlittle-endian-march=cpu-msim-msdata=sdata-type
๐ CRIS Options ๐
Careful here โ -sim and -sim2 are not wearing the m. Copy them exactly, bestie, no autocorrect. ๐ซถ
-mcpu=cpu-march=cpu-mtune=cpu-mmax-stack-frame=n-metrax4-metrax100-mpdebug-mcc-init-mno-side-effects-mstack-align-mdata-align-mconst-align-m32-bit-m16-bit-m8-bit-mno-prologue-epilogue-melf-maout-sim-sim2-mmul-bug-workaround-mno-mul-bug-workaround
๐ C-SKY Options ๐
Look at this lineup. -EB and -EL are the short lil nicknames of -mbig-endian and -mlittle-endian here โ they're both listed, so both go in the notes. ๐
-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 ๐
Ok this one is unhinged and I mean that lovingly. It's a whole different dialect โ mostly no m prefix at all, plus -F, -gused and -gfull thrown in at the end. And yes, some entries literally repeat in the original (-sectobjectsymbols, -segs_read_only_addr, -segs_read_write_addr each show up twice) โ I'm keeping them both times because that's what the page says. Don't @ me. ๐ญ
-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 ๐
-mieee has lore and I refuse to elaborate. Anyway, here's the whole crew:
-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 ๐ฅ
Modern, sleek, kernel-adjacent. Obsessed. ๐
-mbig-endian-mlittle-endian-mkernel=version-mframe-limit=bytes-mxbpf-mco-re-mno-co-re-mjmpext-mjmp32-malu32-mcpu=version
๐ FR30 Options ๐
Two flags. That's it. That's the whole personality. ๐
-msmall-model-mno-lsim
๐ฆ FT32 Options ๐ฆ
Six little guys, just vibing.
-msim-mlra-mnodiv-mft32b-mcompress-mnopm
๐ธ FRV Options ๐ธ
A truly disrespectful number of flags. Respectfully. Look at all those -mno- pairs again โ the duality of man. ๐ซ
-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
Note -mTLS and -mtls are both there and they are not the same thing โ casing matters, bestie, always. ๐
๐ GNU/Linux Options ๐
The C-library-and-Android chapter. Also -tno-android-cc and -tno-android-ld are two more of the no-m weirdos. ๐ซถ
-mglibc-muclibc-mmusl-mbionic-mandroid-tno-android-cc-tno-android-ld
โจ H8/300 Options โจ
Tiny names, big energy. -mh, -ms, -mn โ one letter each and they mean business.
-mrelax-mh-ms-mn-mexr-mno-exr-mint32-malign-300
๐ HPPA Options ๐
The -mno- counterparts are back and they brought friends. Also -nolibdld, -static and -threads are chillin' at the end without the usual prefix. ๐
-march=architecture-type-matomic-libcalls-mbig-switch-mcaller-copies-mdisable-fpregs-mdisable-indexing-mordered-mfast-indirect-calls-mgas-mgnu-ld-mhp-ld-mfixed-range=register-range-mcoherent-ldcw-mjump-in-delay-mlinker-opt-mlong-calls-mlong-load-store-mno-atomic-libcalls-mno-disable-fpregs-mno-disable-indexing-mno-fast-indirect-calls-mno-gas-mno-jump-in-delay-mno-long-load-store-mno-portable-runtime-mno-soft-float-mno-space-regs-msoft-float-mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0-mportable-runtime-mschedule=cpu-type-mspace-regs-msoft-mult-msio-mwsio-munix=unix-std-nolibdld-static-threads
๐ง IA-64 Options ๐ง
This is the "min-latency vs max-throughput" and "sched" section and it goes hard. Buckle up. ๐ช๏ธ
-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 ๐
Every single one of these ends in -enabled. Consistency queen. ๐
-mbarrel-shift-enabled-mdivide-enabled-mmultiply-enabled-msign-extend-enabled-muser-enabled
๐ LoongArch Options ๐
Another gorgeous long one, and the -mno- twins came to play too. ๐
-march=cpu-type-mtune=cpu-type-mabi=base-abi-type-mfpu=fpu-type-msoft-float-msingle-float-mdouble-float-mbranch-cost=n-mcheck-zero-division-mno-check-zero-division-mcond-move-int-mno-cond-move-int-mcond-move-float-mno-cond-move-float-memcpy-mno-memcpy-mstrict-align-mno-strict-align-mmax-inline-memcpy-size=n-mexplicit-relocs-mno-explicit-relocs-mdirect-extern-access-mno-direct-extern-access-mcmodel=code-model-mrelax-mpass-mrelax-to-as
๐ธ M32R/D Options ๐ธ
Ends on a -G num with a space in it, so type it exactly like that. ๐ซถ
-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 ๐ฆ
And we're closing this part out with the cutest tiny list of all. Three flags. Slay. ๐
-mcpu=cpu-msim-memregs=number
โฆand yeah we're STILL in the machine-specific options ๐ like the OPTIONS section never ends and honestly? iconic. Buckle up bestie, the rest of this is basically a tour of every CPU family ever. No cap.
๐ M680x0 Options ๐
Motorola 68000 family hours โจ here's the whole roster, don't make me repeat myself:
-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
Heads up:-mno-bitfieldand-mnobitfieldare both real and they are not the same string. Yes I'm serious. Type carefully ๐ซถ
๐ MCore Options ๐
-mhardlit-mno-hardlit-mdiv-mno-div-mrelax-immediates-mno-relax-immediates-mwide-bitfields-mno-wide-bitfields-m4byte-functions-mno-4byte-functions-mcallgraph-data-mno-callgraph-data-mslow-bytes-mno-slow-bytes-mno-lsim-mlittle-endian-mbig-endian-m210-m340-mstack-increment
๐ฆ MicroBlaze Options ๐ฆ
-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 ๐ธ
Okay so this one is enter-the-group-chat-and-scroll-for-an-hour long ๐ญ but every single one is real and you need them, so here we go, no skipping:
-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
Real talk:-mno-goptand-mmno-mcuare spelled exactly like that in the list, bestie, and-Gnumis capital-G-no-space. I'm not fixing them, I'm copying them, that's the whole job. ๐
โญ MMIX Options โญ
-mlibfuncs-mno-libfuncs-mepsilon-mno-epsilon-mabi=gnu-mabi=mmixware-mzero-extend-mknuthdiv-mtoplevel-symbols-melf-mbranch-predict-mno-branch-predict-mbase-addresses-mno-base-addresses-msingle-exit-mno-single-exit
๐ MN10300 Options ๐
-mmult-bug-mno-mult-bug-mno-am33-mam33-mam33-2-mam34-mtune=cpu-type-mreturn-pointer-on-d0-mno-crt0-mrelax-mliw-msetlb
๐ง Moxie Options ๐ง
Short and sweet, we love a low-maintenance icon:
-meb-mel-mmul.x-mno-crt0
-mmul.x has a literal dot in it. Not a typo on my end, that's the actual string. ๐
๐ MSP430 Options ๐
-msim-masm-hex-mmcu=-mcpu=-mlarge-msmall-mrelax-mwarn-mcu-mcode-region=-mdata-region=-msilicon-errata=-msilicon-errata-warn=-mhwmult=-minrt-mtiny-printf-mmax-inline-shift=
Notice the ones ending in a bare =. That's a value slot waiting for you, bestie, don't leave it empty and then act surprised. ๐ญ
๐ 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
See that-G numwith an actual space? MIPS had-Gnumglued together. Two different worlds, both valid, do not come for me. โญ
๐ฅ Nvidia PTX Options ๐ฅ
-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 ๐
-mfpu-msoft-float-mac0-mno-ac0-m40-m45-m10-mint32-mno-int16-mint16-mno-int32-msplit-munix-asm-mdec-asm-mgnu-asm-mlra
๐ PowerPC Options ๐
See RS/6000 and PowerPC Options.
That's it. That's the whole entry. She's a cross-reference and she said "go look over there" ๐ (and yes, "over there" is literally the next-but-a-few section, keep scrolling babe)
๐ PRU Options ๐
-mmcu=mcu-minrt-mno-relax-mloop-mabi=variant
๐ฆ RISC-V Options ๐ฆ
Okay queen energy, this group is STACKED:
-mbranch-cost=N-instruction-mplt-mno-plt-mabi=ABI-string-mfdiv-mno-fdiv-mdiv-mno-div-misa-spec=ISA-spec-string-march=ISA-string-mtune=processor-string-mpreferred-stack-boundary=num-msmall-data-limit=N-bytes-msave-restore-mno-save-restore-mshorten-memrefs-mno-shorten-memrefs-mstrict-align-mno-strict-align-mcmodel=medlow-mcmodel=medany-mexplicit-relocs-mno-explicit-relocs-mrelax-mno-relax-mriscv-attribute-mno-riscv-attribute-malign-data=type-mbig-endian-mlittle-endian-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mcsr-check-mno-csr-check-minline-atomics-mno-inline-atomics
The three-mstack-protector-guard*ones are a little family โ=guard,-reg=reg,-offset=offset. They travel together, iykyk ๐ซถ
๐ 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. Deep breath. This is the big one, the main character of the architecture list, and I'm giving you every single flag because that's the assignment ๐
-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-msplit-patch-nops-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
Two things I refuse to smooth over: it's-mno-mpower8-fusionbut-mno-power8-vector(different, I checked, they really are like that) ๐ and-G numhere also has the space, same as Nios II, unlike MIPS's-Gnum. Typing is a skill bestie.
๐ 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
PSA:-fpuand-nofpuhave NO leadingm. Everyone else in this whole page has anm. RX woke up and chose chaos and honestly? Respect. ๐
๐ S/390 and zSeries Options ๐
-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
Last one's got a comma in the value โ -mhotpatch=halfwords,halfwords, two whole slots. Nobody said this was gonna be easy, bestie ๐ซถ
๐ธ SH Options ๐ธ
okay bestie, these are all the SH-flavored -m knobs. they're literally just the names, no blurbs attached โ treat it like a aesthetics moodboard for your SH target ๐
-m1 -m2 -m2e -m2a-nofpu -m2a-single-only -m2a-single
-m2a -m3 -m3e -m4-nofpu -m4-single-only -m4-single -m4
-m4a-nofpu -m4a-single-only -m4a-single -m4a -m4al -mb -ml
-mdalign -mrelax -mbigtable -mfmovd -mrenesas -mno-renesas
-mnomacsave -mieee -mno-ieee -mbitops -misize
-minline-ic_invalidate -mpadstruct -mprefergot -musermode
-multcost=number -mdiv=strategy -mdivsi3_libfunc=name
-mfixed-range=register-range -maccumulate-outgoing-args
-matomic-model=atomic-model -mbranch-cost=num -mzdcbranch
-mno-zdcbranch -mcbranch-force-delay-slot -mfused-madd
-mno-fused-madd -mfsca -mno-fsca -mfsrra -mno-fsrra
-mpretend-cmove -mtas
โ๏ธ Solaris 2 Options โ๏ธ
solaris squad, your flags are here ๐ซถ
-mclear-hwcap -mno-clear-hwcap -mimpure-text
-mno-impure-text -pthreads
๐ซ SPARC Options ๐ซ
the whole SPARC situation, no cap โจ
-mcpu=cpu-type -mtune=cpu-type -mcmodel=code-model
-mmemory-model=mem-model -m32 -m64 -mapp-regs -mno-app-regs
-mfaster-structs -mno-faster-structs -mflat -mno-flat -mfpu
-mno-fpu -mhard-float -msoft-float -mhard-quad-float
-msoft-quad-float -mstack-bias -mno-stack-bias -mstd-struct-return
-mno-std-struct-return -munaligned-doubles -mno-unaligned-doubles
-muser-mode -mno-user-mode -mv8plus -mno-v8plus -mvis -mno-vis
-mvis2 -mno-vis2 -mvis3 -mno-vis3 -mvis4 -mno-vis4 -mvis4b
-mno-vis4b -mcbcond -mno-cbcond -mfmaf -mno-fmaf -mfsmuld
-mno-fsmuld -mpopc -mno-popc -msubxc -mno-subxc -mfix-at697f
-mfix-ut699 -mfix-ut700 -mfix-gr712rc -mlra -mno-lra
๐ System V Options ๐
-Qy -Qn -YP,paths -Ym,dir
๐ฆ V850 Options ๐ฆ
-mlong-calls -mno-long-calls -mep -mno-ep
-mprolog-function -mno-prolog-function -mspace -mtda=n -msda=n
-mzda=n -mapp-regs -mno-app-regs -mdisable-callt
-mno-disable-callt -mv850e2v3 -mv850e2 -mv850e1 -mv850es -mv850e
-mv850 -mv850e3v5 -mloop -mrelax -mlong-jumps -msoft-float
-mhard-float -mgcc-abi -mrh850-abi -mbig-switch
๐ง VAX Options ๐ง
-mg -mgnu -munix -mlra
โญ Visium Options โญ
-mdebug -msim -mfpu -mno-fpu -mhard-float
-msoft-float -mcpu=cpu-type -mtune=cpu-type -msv-mode -muser-mode
๐ VMS Options ๐
-mvms-return-codes -mdebug-main=prefix -mmalloc64
-mpointer-size=size
๐ VxWorks Options ๐
-mrtp -non-static -Bstatic -Bdynamic -Xbind-lazy
-Xbind-now
๐ฅ x86 Options ๐ฅ
the x86 list is so long, bestie, it's giving encyclopedia ๐ญ but every single one is here, untouched:
-mtune=cpu-type -march=cpu-type
-mtune-ctrl=feature-list -mdump-tune-features -mno-default
-mfpmath=unit -masm=dialect -mno-fancy-math-387 -mno-fp-ret-in-387
-m80387 -mhard-float -msoft-float -mno-wide-multiply -mrtd
-malign-double -mpreferred-stack-boundary=num
-mincoming-stack-boundary=num -mcld -mcx16 -msahf -mmovbe
-mcrc32 -mmwait -mrecip -mrecip=opt -mvzeroupper -mprefer-avx128
-mprefer-vector-width=opt -mmove-max=bits -mstore-max=bits -mmmx
-msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -msse4 -mavx
-mavx2 -mavx512f -mavx512pf -mavx512er -mavx512cd -mavx512vl
-mavx512bw -mavx512dq -mavx512ifma -mavx512vbmi -msha -maes
-mpclmul -mfsgsbase -mrdrnd -mf16c -mfma -mpconfig -mwbnoinvd
-mptwrite -mprefetchwt1 -mclflushopt -mclwb -mxsavec -mxsaves
-msse4a -m3dnow -m3dnowa -mpopcnt -mabm -mbmi -mtbm -mfma4
-mxop -madx -mlzcnt -mbmi2 -mfxsr -mxsave -mxsaveopt -mrtm
-mhle -mlwp -mmwaitx -mclzero -mpku -mthreads -mgfni -mvaes
-mwaitpkg -mshstk -mmanual-endbr -mcet-switch -mforce-indirect-call
-mavx512vbmi2 -mavx512bf16 -menqcmd -mvpclmulqdq -mavx512bitalg
-mmovdiri -mmovdir64b -mavx512vpopcntdq -mavx5124fmaps
-mavx512vnni -mavx5124vnniw -mprfchw -mrdpid -mrdseed -msgx
-mavx512vp2intersect -mserialize -mtsxldtrk -mamx-tile -mamx-int8
-mamx-bf16 -muintr -mhreset -mavxvnni -mavx512fp16 -mavxifma
-mavxvnniint8 -mavxneconvert -mcmpccxadd -mamx-fp16 -mprefetchi
-mraoint -mamx-complex -mcldemote -mms-bitfields
-mno-align-stringops -minline-all-stringops
-minline-stringops-dynamically -mstringop-strategy=alg -mkl
-mwidekl -mmemcpy-strategy=strategy -mmemset-strategy=strategy
-mpush-args -maccumulate-outgoing-args -m128bit-long-double
-m96bit-long-double -mlong-double-64 -mlong-double-80
-mlong-double-128 -mregparm=num -msseregparm -mveclibabi=type
-mvect8-ret-in-mem -mpc32 -mpc64 -mpc80 -mdaz-ftz -mstackrealign
-momit-leaf-frame-pointer -mno-red-zone -mno-tls-direct-seg-refs
-mcmodel=code-model -mabi=name -maddress-mode=mode -m32 -m64
-mx32 -m16 -miamcu -mlarge-data-threshold=num -msse2avx -mfentry
-mrecord-mcount -mnop-mcount -m8bit-idiv -minstrument-return=type
-mfentry-name=name -mfentry-section=name
-mavx256-split-unaligned-load -mavx256-split-unaligned-store
-malign-data=type -mstack-protector-guard=guard
-mstack-protector-guard-reg=reg
-mstack-protector-guard-offset=offset
-mstack-protector-guard-symbol=symbol -mgeneral-regs-only
-mcall-ms2sysv-xlogues -mrelax-cmpxchg-loop -mindirect-branch=choice
-mfunction-return=choice -mindirect-branch-register
-mharden-sls=choice -mindirect-branch-cs-prefix -mneeded
-mno-direct-extern-access -munroll-only-small-loops -mlam=choice
๐ช x86 Windows Options ๐ช
-mconsole -mcygwin -mno-cygwin -mdll
-mnop-fun-dllimport -mthread -municode -mwin32 -mwindows
-fno-set-stack-executable
๐ Xstormy16 Options ๐
-msim
๐ Xtensa Options ๐
-mconst16 -mno-const16 -mfused-madd -mno-fused-madd
-mforce-no-pic -mserialize-volatile -mno-serialize-volatile
-mtext-section-literals -mno-text-section-literals -mauto-litpools
-mno-auto-litpools -mtarget-align -mno-target-align -mlongcalls
-mno-longcalls -mabi=abi-type -mextra-l32r-costs=cycles
๐ zSeries Options ๐
head over to S/390 and zSeries Options, bestie โ that's where this party's at ๐ซถ
โจ Options Controlling the Kind of Output โจ
okay so compiling? it's a whole journey, not a single step. there are up to four stages, and they always go in this exact order:
- preprocessing
- compilation proper
- assembly
- linking
GCC can preprocess and compile several files either into several assembler input files or into one assembler input file. then each assembler input file produces an object file, and linking combines all the object files โ the ones it just newly compiled and the ones you passed in as input โ into an executable file. periodt ๐
the suffix lore ๐ฆ
for any given input file, the file name suffix is what decides which kind of compilation happens. here's the whole vibe check:
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: you must link with thelibobjclibrary to make an Objective-C program actually 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. also note that.Mrefers to a literal capitalM.file.miiโ Objective-C++ source code that should not be preprocessed.file.hโ C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (that's the default), or 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 capitalC.file.mm,file.Mโ Objective-C++ source code that must be preprocessed.file.miiโ Objective-C++ source code that should not be preprocessed. (yes bestie, it's literally listed again โ that's what the page says ๐ญ)file.hh,file.H,file.hp,file.hxx,file.hpp,file.HPP,file.h++,file.tccโ C++ header file to be turned into a precompiled header or Ada spec.file.f,file.for,file.ftnโ Fixed form Fortran source code that should not be preprocessed.file.F,file.FOR,file.fpp,file.FPP,file.FTNโ Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).file.f90,file.f95,file.f03,file.f08โ Free form Fortran source code that should not be preprocessed.file.F90,file.F95,file.F03,file.F08โ Free form Fortran source code that must be preprocessed (with the traditional preprocessor).file.goโ Go source code.file.dโ D source code.file.diโ D interface file.file.ddโ D documentation code (Ddoc).file.adsโ Ada source code file that contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). these files also get called specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). these files also get 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 gets treated this way.
picking your language on purpose ๐
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 objc-cpp-output
objective-c++ objective-c++-header objective-c++-cpp-output
objc++-cpp-output
assembler assembler-with-cpp
ada adascil adawhy
d
f77 f77-cpp-input f95 f95-cpp-input
go
modula-2 modula-2-cpp-output
rust
lto
-x noneโ Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (exactly like they are if-xhas not been used at all).
so if you only want some of the stages โ mood, honestly โ you can use-x(or filename suffixes) to tellgccwhere to start, and one of the options-c,-S, or-Eto say wheregccis to stop. and ngl, watch out: some combinations (for example,-x cpp-output -E) instructgccto do nothing at all ๐
-cโ okay so this one is the classic โcompile/assemble but do not linkโ girlie ๐ . 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. Lowkey iconic behavior.
-Sโ stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified โจ.
By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.
Input files that don't require compilation are ignored.
-Eโ stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output ๐ธ.
Input files that don't require preprocessing are ignored.
-o fileโ place the primary output in filefile. This applies to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.
If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output.
Though -o names only the primary output, it also affects the naming of auxiliary and dump outputs. See the examples below. Unless overridden, both auxiliary outputs and dump outputs are placed in the same directory as the primary output. In auxiliary outputs, the suffix of the input file is replaced with that of the auxiliary output file type; in dump outputs, the suffix of the dump file is appended to the input file suffix. In compilation commands, the base name of both auxiliary and dump outputs is that of the primary output; in compile and link commands, the primary output name, minus the executable suffix, is combined with the input file name. If both share the same base name, disregarding the suffix, the result of the combination is that base name, otherwise, they are concatenated, separated by a dash.
gcc -c foo.c ...
will use foo.o as the primary output, and place aux outputs and dumps next to it, e.g., aux file foo.dwo for -gsplit-dwarf, and dump file foo.c.???r.final for -fdump-rtl-final.
If a non-linker output file is explicitly specified, aux and dump files by default take the same base name:
gcc -c foo.c -o dir/foobar.o ...
will name aux outputs dir/foobar.* and dump outputs dir/foobar.c.*.
A linker output will instead prefix aux and dump outputs:
gcc foo.c bar.c -o dir/foobar ...
will generally name aux outputs dir/foobar-foo.* and dir/foobar-bar.*, and dump outputs dir/foobar-foo.c.* and dir/foobar-bar.c.*.
The one exception to the above is when the executable shares the base name with the single input:
gcc foo.c -o dir/foo ...
in which case aux outputs are named dir/foo.* and dump outputs named dir/foo.c.*.
The location and the names of auxiliary and dump outputs can be adjusted by the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj.
-dumpbase dumpbaseโ this option sets the base name for auxiliary and dump output files. It does not affect the name of the primary output file. Intermediate outputs, when preserved, are not regarded as primary outputs, but as auxiliary outputs:
gcc -save-temps -S foo.c
saves the (no longer) temporary preprocessed file in foo.i, and then compiles to the (implied) output file foo.s, whereas:
gcc -save-temps -dumpbase save-foo -c foo.c
preprocesses to in save-foo.i, compiles to save-foo.s (now an intermediate, thus auxiliary output), and then assembles to the (implied) output file foo.o.
Absent this option, dump and aux files take their names from the input file, or from the (non-linker) output file, if one is explicitly specified: dump output files (e.g. those requested by -fdump-* options) with the input name suffix, and aux output files (those requested by other non-dump options, e.g. -save-temps, -gsplit-dwarf, -fcallgraph-info) without it.
Similar suffix differentiation of dump and aux outputs can be attained for explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf.
If dumpbase is explicitly specified with any directory component, any dumppfx specification (e.g. -dumpdir or -save-temps=*) is ignored, and instead of appending to it, dumpbase fully overrides it:
gcc foo.c -c -o dir/foo.o -dumpbase alt/foo \
-dumpdir pfx- -save-temps=cwd ...
creates auxiliary and dump outputs named alt/foo.*, disregarding dir/ in -o, the ./ prefix implied by -save-temps=cwd, and pfx- in -dumpdir.
When -dumpbase is specified in a command that compiles multiple inputs, or that compiles and then links, it may be combined with dumppfx, as specified under -dumpdir. Then, each input file is compiled using the combined dumppfx, and default values for dumpbase and auxdropsuf are computed for each input file:
gcc foo.c bar.c -c -dumpbase main ...
creates foo.o and bar.o as primary outputs, and avoids overwriting the auxiliary and dump outputs by using the dumpbase as a prefix, creating auxiliary and dump outputs named main-foo.* and main-bar.*.
An empty string specified as dumpbase avoids the influence of the output basename in the naming of auxiliary and dump outputs during compilation, computing default values:
gcc -c foo.c -o dir/foobar.o -dumpbase " ...
will name aux outputs dir/foo.* and dump outputs dir/foo.c.*. Note how their basenames are taken from the input name, but the directory still defaults to that of the output.
The empty-string dumpbase does not prevent the use of the output basename for outputs during linking:
gcc foo.c bar.c -o dir/foobar -dumpbase " -flto ...
The compilation of the source files will name auxiliary outputs dir/foo.* and dir/bar.*, and dump outputs dir/foo.c.* and dir/bar.c.*. LTO recompilation during linking will use dir/foobar. as the prefix for dumps and auxiliary files.
-dumpbase-ext auxdropsufโ when forming the name of an auxiliary (but not a dump) output file, drop trailingauxdropsuffromdumpbasebefore appending any suffixes. If not specified, this option defaults to the suffix of a defaultdumpbase, i.e., the suffix of the input file when-dumpbaseis not present in the command line, ordumpbaseis combined withdumppfx.
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, usedumppfxas a prefix:
gcc -dumpdir pfx- -c foo.c ...
creates foo.o as the primary output, and auxiliary outputs named pfx-foo.*, combining the given dumppfx with the default dumpbase derived from the default primary output, derived in turn from the input name. Dump outputs also take the input name suffix: pfx-foo.c.*.
If dumppfx is to be used as a directory name, it must end with a directory separator:
gcc -dumpdir dir/ -c foo.c -o obj/bar.o ...
creates obj/bar.o as the primary output, and auxiliary outputs named dir/bar.*, combining the given dumppfx with the default dumpbase derived from the primary output name. Dump outputs also take the input name suffix: dir/bar.c.*.
It defaults to the location of the output file, unless the output file is a special file like "/dev/null". Options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option. In case multiple such options are given, the last one prevails:
gcc -dumpdir pfx- -c foo.c -save-temps=obj ...
outputs foo.o, with auxiliary outputs named foo.* because -save-temps=* overrides the dumppfx given by the earlier -dumpdir option. It does not matter that =obj is the default for -save-temps, nor that the output directory is implicitly the current directory. Dump outputs are named foo.c.*.
When compiling from multiple input files, if -dumpbase is specified, dumpbase, minus a auxdropsuf suffix, and a dash are appended to (or override, if containing any directory components) an explicit or defaulted dumppfx, so that each of the multiple compilations gets differently-named aux and dump outputs.
gcc foo.c bar.c -c -dumpdir dir/pfx- -dumpbase main ...
outputs auxiliary dumps to dir/pfx-main-foo.* and dir/pfx-main-bar.*, appending dumpbase- to dumppfx. Dump outputs retain the input file suffix: dir/pfx-main-foo.c.* and dir/pfx-main-bar.c.*, respectively. Contrast with the single-input compilation:
gcc foo.c -c -dumpdir dir/pfx- -dumpbase main ...
that, applying -dumpbase to a single source, does not compute and append a separate dumpbase per input file. Its auxiliary and dump outputs go in dir/pfx-main.*.
Okay so continuing the dump-prefix saga, because we're still not done, bestie ๐
When you compile and then link from multiple input files, a dumppfx โ whether it's the default one or one you explicitly specified โ also goes through that dumpbase- transformation we talked about above (think the compilation of foo.c and bar.c from earlier, but without -c). If neither -dumpdir nor -dumpbase are given, then the linker output base name (minus auxdropsuf if you specified one, or the executable suffix otherwise) plus a dash gets appended to the default dumppfx instead. But heads up โ unlike the earlier linking cases:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...
does not append the output name main to dumppfx, because -dumpdir was explicitly specified. The whole goal here is that your explicitly-specified dumppfx may contain the specified output name as part of the prefix if you want it to; only an explicitly-specified -dumpbase gets combined with it, so that a meaningful option doesn't just get straight-up discarded ๐ซถ
When you compile and then link from a single input file, the linker output base name only gets appended to the default dumppfx as described above if it doesn't share the base name with that single input file name. This was already covered in the single-input linking cases above, but not with an explicit -dumpdir that blocks the combination โ even if it gets overridden by -save-temps=*:
gcc foo.c -dumpdir alt/pfx- -o dir/main.exe -save-temps=cwd ...
Auxiliary outputs get named foo.*, and dump outputs get named foo.c.*, in the current working directory exactly as -save-temps=cwd ultimately requested โจ
So summing it all up into an intuitive-but-slightly-imprecise data flow, because that's how we roll: the primary output name gets broken into a directory part and a basename part; dumppfx is set to the directory part unless it's overridden by -dumpdir or -save-temps=*; and dumpbase is set to the basename part unless it's overridden by -dumpbase. If there are multiple inputs or you're linking, this dumpbase may be combined with dumppfx and taken from each input file. Auxiliary output names for each input are formed by combining dumppfx, dumpbase minus the suffix, and the auxiliary output suffix; dump output names are only different in that the suffix from dumpbase is retained. Iconic, honestly ๐
Now, when it comes to auxiliary and dump outputs created during LTO recompilation: a combination of dumppfx and dumpbase โ as given, or as derived from the linker output name but not from inputs, even in cases where this combination wouldn't otherwise be used as such โ 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 just ignores them.
When it runs sub-compilers, lto-wrapper appends LTO stage names to the dumppfx it received, makes sure it contains a directory component so that it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. Slay ๐ฆ
-vโ Prints (on standard error output) the commands executed to run the stages of compilation. It also prints the version number of the compiler driver program, plus the version numbers of the preprocessor and the compiler proper. Very "show me your receipts" energy ๐ฅ-###โ Like-v, except the commands are not executed and the arguments get quoted unless they contain only alphanumeric characters or./-_. This one's useful for shell scripts that want to capture the driver-generated command lines. Perfect for the little script girlies ๐--helpโ Prints (on standard output) a description of the command-line options thatgccunderstands. If-vis also specified, then--helpalso gets passed on to the various processes invoked bygcc, so they can display the command-line options they accept. And if-Wextrahas also been specified (prior to the--helpoption), then command-line options that have no documentation associated with them are also displayed. No option left behind ๐ซถ--target-helpโ Prints (on standard output) a description of target-specific command-line options for each tool. For some targets, extra target-specific information may also be printed โจ--help={class|[^]qualifier}[,...]โ Prints (on standard output) a description of the command-line options understood by the compiler that fit into all the specified classes and qualifiers. These are the supported classes:optimizersโ Display all of the optimization options supported by the compiler.warningsโ Display all of the options controlling warning messages produced by the compiler.targetโ Display target-specific options. Unlike the--target-helpoption, though, target-specific options of the linker and assembler are not displayed. This is 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 supported by the compiler, use:
--help=target,undocumented
The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e. ones that are either on or off and that do not take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
The argument to --help= should not consist solely of inverted qualifiers. Don't do it, bestie ๐ญ
Combining several classes is possible, although this usually restricts the output so much that there's nothing 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 those 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 appears on the command line before the --help= option, then the descriptive text displayed by --help= changes. Instead of describing the displayed options, you get an indication of whether the option is enabled, disabled, or set to a specific value (assuming the compiler knows this at the point where the --help= option is used).
Here's a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi= 2
-mabort-on-noreturn [disabled]
-mapcs [disabled]
The output is sensitive to the effects of previous command-line options, so for example it's possible to find out which optimizations are enabled at -O2 by using:
-Q -O2 --help=optimizers
Alternatively you can discover which binary optimizations are enabled by -O3 by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
Literally the diff-your-way-to-truth pipeline, we love to see it ๐ธ
--versionโ Displays 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, then thegccprogram instead returns with the numerically highest error produced by any phase that returns an error indication. The C, C++, and Fortran front ends return4if an internal compiler error is encountered.-pipeโ Uses pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe โ but the GNU assembler has no trouble at all ๐ซถ-specs=fileโ Processes file after the compiler reads in the standard specs file, in order to override the defaults that thegccdriver program uses when determining what switches to pass tocc1,cc1plus,as,ld, etc. More than one-specs=filecan be specified on the command line, and they're processed in order, from left to right โจ-wrapperโ Invokes all subcommands under a wrapper program. The name of the wrapper program and its parameters are passed as a comma-separated list.
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 is gdb --args cc1 .... Very "debug-ception" of it ๐
-ffile-prefix-map=old=newโ When compiling files residing in directoryold, records any references to them in the result of the compilation as if the files resided in directorynewinstead. Specifying this option is equivalent to specifying all the individual-f*-prefix-mapoptions. This can be used to make reproducible builds that are location independent. Directories referenced by directives are not affected by these options. See also-fmacro-prefix-map,-fdebug-prefix-map,-fprofile-prefix-mapand-fcanon-prefix-map. Queen of not snitching on your home directory ๐-fcanon-prefix-mapโ For the-f*-prefix-mapoptions, normally the comparison ofoldprefix against the filename that would normally be referenced in the result of the compilation is done using textual comparison of the prefixes โ or ignoring character case for case-insensitive filesystems, and considering slashes and backslashes as equal on DOS-based filesystems. The-fcanon-prefix-mapoption causes such comparisons to be done on canonicalized paths ofoldand the referenced filename. Canonicalize first, ask questions never ๐
-fplugin=name.soโ loads the plugin code in filename.so, which is assumed to be a shared object that the compiler willdlopenโจ. The base name of the shared object file is what identifies the plugin when it comes to parsing arguments (peep-fplugin-arg-name-key=valuebelow ๐). Every plugin is supposed to define the callback functions listed in the Plugins API, no cap.-fplugin-arg-name-key=valueโ defines an argument called key with a value of value, for the plugin called name. That's it, that's the whole vibe ๐.-fdump-ada-spec[-slim]โ for C and C++ source and include files, generates the corresponding Ada specs ๐ .-fada-spec-parent=unitโ works together with-fdump-ada-spec[-slim](above) to generate Ada specs as child units of parent unit. Teamwork makes the dream work ๐ซถ.-fdump-go-spec=fileโ for input files in any language, generates the corresponding Go declarations in file. It spits out Go"const","type","var", and"func"declarations, which lowkey can be a really useful way to start writing a Go interface to code that's written in some other language ๐ฆ.@fileโ reads command-line options from file. The options it reads get inserted in place of the original@fileoption. And if file doesn't exist, or can't be read? Then the option is treated literally and not removed โ it just stays there, living its truth ๐.
Options inside file are separated by whitespace. You can sneak a whitespace character into an option by wrapping the entire option in either single or double quotes ๐. Any character at all (backslash included!) can be included by prefixing it with a backslash. And plot twist: the file can itself contain additional @file options โ any of those get processed recursively ๐.
๐ธ Compiling C++ Programs ๐ธ
C++ source files conventionally use one of these suffixes: .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx ๐. C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc, and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the exact same way you would for compiling C programs (usually with the name gcc). Same energy, different language, iykyk ๐ซ.
But bestie, listen โ using gcc does not add the C++ library. That's the plot twist nobody warns you about ๐ญ.
g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files, unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed under the name c++ ๐.
When you compile C++ programs, you may specify many of the same command-line options you'd use for compiling programs in any language; or command-line options that are meaningful for C and related languages; or options that are meaningful only for C++ programs. Pick your fighter ๐ .
๐ฆ Options Controlling C Dialect ๐ฆ
The following options control the dialect of C (or languages derived from C, like C++, Objective-C and Objective-C++) that the compiler accepts. Vibe check for your compiler, basically โญ:
-ansiโ in C mode, this is equivalent to-std=c90. In C++ mode, it's equivalent to-std=c++98๐ซ.
This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code) โ things like the "asm" and "typeof" keywords, and predefined macros such as "unix" and "vax" that identify the type of system you're using. It also enables the undesirable and rarely used ISO trigraph feature ๐. For the C compiler, it disables recognition of C++ style // comments as well as the "inline" keyword. Not them getting cancelled fr.
The alternate keywords "__asm__", "__extension__", "__inline__" and "__typeof__" continue to work despite -ansi ๐. You would not want to use them in an ISO C program, of course, but it's useful to put them in header files that might get included in compilations done with -ansi. Alternate predefined macros such as "__unix__" and "__vax__" are also available, with or without -ansi.
The -ansi option does not cause non-ISO programs to be rejected gratuitously โ for that you need -Wpedantic in addition to -ansi. It's giving "I'm not gonna snitch unless you ask me to" ๐
.
The macro "__STRICT_ANSI__" is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things. Respectful queen behavior ๐.
Functions that are normally built in but don't have semantics defined by ISO C (such as "alloca" and "ffs") are not built-in functions when -ansi is used. Sorry bestie ๐ญ.
-std=โ determines the language standard โจ. This option is currently only supported when compiling C or C++.
The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that 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 have no meaning in ISO C90, like omitting the middle term of a "?:" expression. On the other hand, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard ๐. As a result, some strict-conforming programs may be rejected. The particular standard is what -Wpedantic uses to identify which features count as GNU extensions for that version of the standard. For example, -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not. The receipts matter ๐
.
A value for this option must be provided; possible values are:
c90,c89,iso9899:1990โ support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as-ansifor C code ๐.iso9899:199409โ ISO C90 as modified in amendment 1.c99,c9x,iso9899:1999,iso9899:199xโ ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). Seehttps://gcc.gnu.org/c99status.htmlfor more info ๐ฆ. The namesc9xandiso9899:199xare deprecated.c11,c1x,iso9899:2011โ ISO C11, the 2011 revision of the ISO C standard. This standard is substantially completely supported, modulo bugs, floating-point issues (mainly but not entirely relating to optional C11 features from Annexes F and G) and the optional Annexes K (Bounds-checking interfaces) and L (Analyzability). The namec1xis deprecated ๐ซถ.c17,c18,iso9899:2017,iso9899:2018โ ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is the same as C11 except for corrections of defects (all of which are also applied with-std=c11) and a new value of"__STDC_VERSION__", and so is supported to the same extent as C11 โจ.c2xโ the next version of the ISO C standard, still under development. Support for this version is experimental and incomplete ๐.gnu90,gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99,gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11,gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17,gnu18โ GNU dialect of ISO C17. This is the default for C code ๐๐ฅ.gnu2xโ the next version of the ISO C standard, still under development, plus GNU extensions. Support for this version is experimental and incomplete.c++98,c++03โ the 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code ๐ซ.gnu++98,gnu++03โ GNU dialect of-std=c++98.c++11,c++0xโ the 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11,gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14,c++1yโ the 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14,gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17,c++1zโ the 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17,gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code ๐. The namegnu++1zis deprecated.c++20,c++2aโ the 2020 ISO C++ standard plus amendments. Support is experimental, and could change in incompatible ways in future releases ๐ญ. The namec++2ais deprecated.gnu++20,gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2b,c++23โ the next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases ๐.gnu++2b,gnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases ๐.
-aux-info filenameโ outputs 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 (rude, but okay ๐).
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. It's giving annotated receipts, and honestly? We stan ๐ซถ.
-fno-asmโ okay so this one is literally telling GCC "bestie, please stop treatingasm,inlineandtypeoflike sacred keywords" ๐ that way your code gets to use those words as plain old identifiers. If you still need the real deal, the blessed spellings__asm__,__inline__and__typeof__are always there for you ๐ซถ In C,-ansiimplies-fno-asm, so heads up.
In C++, inline is a standard keyword and this switch does not touch it โ if that's what you're after, you probably want -fno-gnu-keywords instead, which kills typeof but leaves asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only affects asm and typeof, because inline is a standard keyword in ISO C99 โจ And in C2X mode (-std=c2x or -std=gnu2x), it only affects asm, since typeof is a standard keyword in ISO C2X. the way the keyword list keeps growing, honestly ๐ญ
-fno-builtin,-fno-builtin-functionโ don't recognize built-in functions that don't begin with__builtin_as a prefix. Simple as that.
Ngl, 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. highkey a real tradeoff, bestie ๐
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. so it's giving "helpful friend who reads your code over your shoulder" ๐
With the -fno-builtin-function option only the built-in function function is disabled โ and 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))
DIY built-ins, we love to see it ๐
-fcond-mismatchโ allow 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++. like, C++ said "no โค๏ธ" politely.-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 ๐งช very "we're in the lab" energy, ngl โ experimental, so treat it like a new hyperfixation, not a stable relationship.-fgnu-tmโ when this one is specified, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes โ ๏ธ Please note that not all architectures are supported for this feature.
For more information on GCC's support for transactional memory,
bestie the manpage just trails off there, I'm not making that up ๐ anyway โ note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). incompatible, no cap.
-fgnu89-inlineโ tells GCC to use the traditional GNU semantics forinlinefunctions when in C99 mode. Using this option is roughly equivalent to adding thegnu_inlinefunction attribute to all inline functions โจ
The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behavior). This option is not supported in -std=c90 or -std=gnu90 mode. the preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions โ vibe check your inline, basically ๐ฆ
-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 ๐ฉ red flag, bestie, it's giving "legacy code only, do not perceive".-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 type declarations, like:
typedef int UOW;
struct ABC {
UOW UOW;
};
Some cases of unnamed fields in structures and unions are only accepted with this option. Note that this option is off for all targets except for x86 targets using ms-abi. sad for everyone else, but ok ๐
-foffload=disable,-foffload=default,-foffload=target-listโ specify for which OpenMP and OpenACC offload targets code should be generated ๐ The default behavior, equivalent to-foffload=default, is to generate code for all supported offload targets. The-foffload=disableform generates code only for the host fallback, while-foffload=target-listgenerates code only for the specified comma-separated list of offload targets.
Offload targets are specified in GCC's internal target-triplet format. You can run the compiler with -v to show the list of configured offload targets under OFFLOAD_TARGET_NAMES. iykyk ๐
-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
look at those target-specific vibes go ๐ โจ
-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. no pthread, no party ๐-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 ordergang,workerandvector. A size can be omitted, to use a target-specific default value. skipping a size is highkey valid ๐ฆ-fopenmpโ enable handling of OpenMP directives#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran. When-fopenmpis specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5 <https://www.openmp.org> ๐ This option implies-pthread, and thus is only supported on targets that have support for-pthread.-fopenmpimplies-fopenmp-simd, periodt.-fopenmp-simdโ enable handling of OpenMP'ssimd,declare simd,declare reduction,assume,ordered,scan,loopdirectives and combined or composite directives withsimdas constituent with#pragma ompin C/C++,[[omp::directive(...)]]and[[omp::sequence(...)]]in C++ and!$ompin Fortran. Other OpenMP directives are ignored ๐ picky but in a cute way.-fopenmp-target-simd-clone,-fopenmp-target-simd-clone=device-typeโ in addition to generating SIMD clones for functions marked with thedeclare simddirective, GCC also generates clones for functions marked with the OpenMPdeclare targetdirective that are suitable for vectorization when this option is in effect โจ The device-type may be one ofnone,host,nohost, andany, which correspond to keywords for thedevice_typeclause of thedeclare targetdirective; clones are generated for the intersection of devices specified.-fopenmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=anyand-fno-openmp-target-simd-cloneis equivalent to-fopenmp-target-simd-clone=none.
At -O2 and higher (but not -Os or -Og) this optimization defaults to -fopenmp-target-simd-clone=nohost; otherwise it is disabled by default. so check your optimization level before you come for it ๐
-fpermitted-flt-eval-methods=styleโ ISO/IEC TS 18661-3 defines new permissible values forFLT_EVAL_METHODthat indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type ๐ง These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values ofFLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values ๐ณ plot twist for legacy code.
-fpermitted-flt-eval-methods specifies whether the compiler should allow only the values of FLT_EVAL_METHOD specified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3. style is either c11 or ts-18661-3 as appropriate.
The default when in a standards compliant mode (-std=c11 or similar) is -fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11 or similar) is -fpermitted-flt-eval-methods=ts-18661-3. GNU stays extra, as always ๐
-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++. C++ girlies, this one's not for you ๐ญ-fsigned-bitfields,-funsigned-bitfields,-fno-signed-bitfields,-fno-unsigned-bitfieldsโ okay so these four besties decide whether a bit-field is signed or unsigned when the declaration is being lazy and doesn't saysignedorunsignedout loud. And the default? Signed, periodt. Why? Because it's consistent โ the basic integer types likeintare signed types, so it just matches the vibe. โจ-fsigned-charโ makes the typecharsigned, exactly likesigned char. ๐ซถ
Lowkey important note: this is equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. And likewise? The option -fno-signed-char is equivalent to -funsigned-char. It's giving mirror universe, iykyk. ๐
-funsigned-charโ makes the typecharunsigned, likeunsigned char. ๐ธ
Every kind of machine has its own default for what char should be โ it's either like unsigned char by default or like signed char by default. No universal answer, unfortunately. ๐ญ
Ideally, a portable program should always use signed char or unsigned char when it depends on the signedness of an object. But ngl, so many programs out there were written to use plain char and just expect it to be signed, or expect it to be unsigned, depending on the machines they were originally written for. This option, and its inverse, let you make such a program work with the opposite default. Slay, compatibility. ๐ฅ
And the type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two. Main character energy: distinct, but acting identical. ๐
-fstrict-flex-arraysโ controls when to treat the trailing array of a structure as a flexible array member for the purpose of accessing the elements of such an array. The positive form is equivalent to-fstrict-flex-arrays=3, which is the strictest. A trailing array is only treated as a flexible array member when it's actually declared as a flexible array member per C99 standard onwards. The negative form is equivalent to-fstrict-flex-arrays=0, which is the least strict โ all trailing arrays of structures get treated as flexible array members. ๐ฆ- *
-fstrict-flex-arrays=level* โ same whole deal (when to treat the trailing array of a structure as a flexible array member for the purpose of accessing the elements), except the value of level controls the level of strictness. ๐
The possible values of level are the same as for the strict_flex_array attribute.
And if you want to control this behavior for one specific trailing array field of a structure? Just use the variable attribute strict_flex_array attribute. Iconic, targeted, no collateral. ๐
- *
-fsso-struct=endianness* โ sets the default scalar storage order of structures and unions to the specified endianness. The accepted values arebig-endian,little-endianandnativefor the native endianness of the target (that's the default). This option is not supported for C++. ๐
โ ๏ธ Warning: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it, if the specified endianness is not the native endianness of the target. Like, for real, check yourself before you wreck yourself. ๐
โจ Options Controlling C++ Dialect โจ
This section is all about the command-line options that are only meaningful for C++ programs. But bestie, 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. ๐
Also FYI, some options for compiling C programs, such as -std, are also relevant for C++ programs.
Here is the 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 get fixed. (Yes, it moves. It's alive. It's growing. ๐ญ)
Version 1 is the version of the C++ ABI that first appeared in G++ 3.2. โญ
Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.
Version 3 corrects an error in mangling a constant address as a template argument.
Version 4, which first appeared in G++ 4.5, implements a standard mangling for vector types.
Version 5, which first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.
Version 6, which first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.
Version 7, which first appeared in G++ 4.8, treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.
Version 8, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
Version 9, which first appeared in G++ 5.2, corrects the alignment of nullptr_t.
Version 10, which first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).
Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors.
Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Oops? ๐
Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. Redemption arc. โจ
Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression.
Version 15, which first appeared in G++ 10.3, corrects G++ 10 ABI tag regression.
Version 16, which first appeared in G++ 11, changes the mangling of __alignof__ to be distinct from that of alignof, and dependent operator names.
Version 17, which first appeared in G++ 12, fixes layout of classes that inherit from aggregate classes with default member initializers in C++14 and up.
Version 18, which first appeared in G++ 13, fixes manglings of lambdas that have additional context.
See also -Wabi. ๐
- *
-fabi-compat-version=n* โ on targets that support strong aliases, G++ works around mangling changes by creating an alias with the correct mangled name when defining a symbol with an incorrect mangled name. This switch specifies which ABI version to use for the alias. ๐
With -fabi-version=0 (the default), this defaults to 13 (GCC 8.2 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option is not provided but -Wabi=n is, that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning. The version-trading here is real. ๐
-fno-access-controlโ turns off all access checking. This switch is mainly useful for working around bugs in the access control code. Like, it's a "the compiler is wrong, not me" button. ๐-faligned-newโ enables support for C++17newof types that require more alignment thanvoid* ::operator new(std::size_t)provides. A numeric argument such as-faligned-new=32can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default ofalignof(std::max_align_t). ๐ธ
This flag is enabled by default for -std=c++17. Slay.
-fchar8_t,-fno-char8_tโ enable support forchar8_tas adopted for C++20. This includes the addition of a newchar8_tfundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new__cpp_char8_tand__cpp_lib_char8_tfeature test macros. ๐ฆ
This option enables functions to be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
and introduces new signatures for user-defined literals:
int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;
The change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. For example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified. ๐ญ
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
-fcheck-newโ check that the pointer returned byoperator newis non-null before attempting to modify the storage allocated. ๐ฅ
This check is normally unnecessary, because the C++ standard specifies that operator new only returns 0 if it is declared throw(), in which case the compiler always checks the return value even without this option. In all other cases, when operator new has a non-empty exception specification, memory exhaustion is signalled by throwing std::bad_alloc.
See also new (nothrow). ๐ซถ
-fconcepts,-fconcepts-tsโ okay so this one turns on support for the C++ Concepts feature for constraining template arguments ๐ . With-std=c++20and above, Concepts are literally part of the language standard, so-fconceptsdefaults to on. Slay.
Some constructs that were allowed by the earlier C++ Extensions for Concepts Technical Specification, ISO 19217 (2015), but didn't make it into the standard, can additionally be enabled by -fconcepts-ts โจ.
-fconstexpr-depth=nโ sets the maximum nested evaluation depth for C++11constexprfunctions to n. A limit is needed to detect endless recursion during constant expression evaluation ๐. The minimum specified by the standard is512.-fconstexpr-cache-depth=nโ sets the maximum level of nested evaluation depth for C++11constexprfunctions that will be cached to n. This is a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows very large from highly recursive evaluations) ๐ซถ. The default is8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you ngl.-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. Iconic behavior fr.
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 is262144(1<<18).-fconstexpr-ops-limit=nโ sets the maximum number of operations during a single constexpr evaluation. Even when number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long ๐. The default is33554432(1<<25).-fcontractsโ enables experimental support for the C++ Contracts feature, as briefly added to and then removed from the C++20 working paper (N4820) ๐. The implementation also includes proposed enhancements from papers P1290, P1332, and P1429. This functionality is intended mostly for those interested in experimentation towards refining the feature to get it into shape for a future C++ standard.
On violation of a checked contract, the violation handler is called. Users can replace the violation handler by defining
void
handle_contract_violation (const std::experimental::contract_violation&);
There are different sets of additional flags that can be used together to specify which contracts will be checked and how, for N4820 contracts, P1332 contracts, or P1429 contracts; these sets cannot be used together โ ๏ธ.
-fcontract-mode=[on|off]โ control whether any contracts have any semantics at all. Defaults toon.-fcontract-assumption-mode=[on|off]โ [N4820] control whether contracts with level axiom should have the assume semantic. Defaults toon.-fcontract-build-level=[off|default|audit]โ [N4820] specify which level of contracts to generate checks for. Defaults todefault.-fcontract-continuation-mode=[on|off]โ [N4820] control whether to allow the program to continue executing after a contract violation. That is, do checked contracts have the maybe semantic described below rather than the never semantic. Defaults tooff.-fcontract-role=<name>:<default>,<audit>,<axiom>โ [P1332] specify the concrete semantics for each contract level of a particular contract role.-fcontract-semantic=[default|audit|axiom]:<semantic>โ [P1429] specify the concrete semantic for a particular contract level.-fcontract-strict-declarations=[on|off]โ control whether to reject adding contracts to a function after its first declaration. Defaults tooff.
The possible concrete semantics that can be specified with -fcontract-role or -fcontract-semantic are:
"ignore"โ this contract has no effect."assume"โ this contract is treated like C++23"[[assume]]"."check_never_continue","never","abort"โ this contract is checked. If it fails, the violation handler is called. If the handler returns,"std::terminate"is called ๐."check_maybe_continue","maybe"โ this contract is checked. If it fails, the violation handler is called. If the handler returns, execution continues normally โจ.
-fcoroutinesโ enable support for the C++ coroutines extension (experimental) ๐.-fno-elide-constructorsโ the C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases ๐ค. This option also causes G++ to call trivial member functions which otherwise would be expanded inline.
In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.
-fno-enforce-eh-specsโ don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard, but may be useful for reducing code size in production builds, much like defining"NDEBUG"๐ญ. This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. You've been warned bestie โ ๏ธ.-fextern-tls-init,-fno-extern-tls-initโ the C++11 and OpenMP standards allow"thread_local"and"threadprivate"variables to have dynamic (runtime) initialization. To support this, any use of such a variable goes through a wrapper function that performs any necessary initialization. When the use and definition of the variable are in the same translation unit, this overhead can be optimized away, but when the use is in a different translation unit there is significant overhead even if the variable doesn't actually need dynamic initialization ๐ฎโ๐จ. If the programmer can be sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because the variable is statically initialized, or a use of the variable in the defining TU will be executed before any uses in another TU), they can avoid this overhead with the-fno-extern-tls-initoption.
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init ๐
.
-ffold-simple-inlines,-fno-fold-simple-inlinesโ permit the C++ frontend to fold calls to"std::move","std::forward","std::addressof"and"std::as_const". In contrast to inlining, this means no debug information will be generated for such calls ๐. Since these functions are rarely interesting to debug, this flag is enabled by default unless-fno-inlineis active.-fno-gnu-keywordsโ do not recognize"typeof"as a keyword, so that code can use this word as an identifier. You can use the keyword"__typeof__"instead ๐. This option is implied by the strict ISO C++ dialects:-ansi,-std=c++98,-std=c++11, etc.-fimplicit-constexprโ make inline functions implicitlyconstexpr, if they satisfy the requirements for a constexpr function. This option can be used in C++14 mode or later โจ. This can result in initialization changing from dynamic to static and other optimizations. Efficient queen behavior.-fno-implicit-templatesโ never emit code for non-inline templates that are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. If you use this option, you must take care to structure your code to include all the necessary explicit instantiations to avoid getting undefined symbols at link time ๐ญ. Like, seriously, be careful.-fno-implicit-inline-templatesโ don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization need the same set of explicit instantiations ๐ซถ.-fno-implement-inlinesโ to save space, do not emit out-of-line copies of inline functions controlled by"#pragma implementation". This causes linker errors if these functions are not inlined everywhere they are called ๐. Not a vibe.-fmodules-ts,-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, as that is the default ๐ฆ. Even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. Sneaky.-fmodule-header,-fmodule-header=user,-fmodule-header=systemโ compile a header file to create an importable header unit ๐ฆ.-fmodule-implicit-inlineโ member functions defined in their class definitions are not implicitly inline for modular code. This is different to traditional C++ behavior, for good reasons. However, it may result in a difficulty during code porting ๐ฌ. This option makes such function definitions implicitly inline. It does however generate an ABI incompatibility, so you must use it everywhere or nowhere โ ๏ธ. (Such definitions outside of a named module remain implicitly inline, regardless.)-fno-module-lazyโ disable lazy module importing and module mapper creation ๐ด.-fmodule-mapper=[hostname]:port[?ident],-fmodule-mapper=|program[?ident] args...,-fmodule-mapper==socket[?ident],-fmodule-mapper=<>[inout][?ident],-fmodule-mapper=<in>out[?ident],-fmodule-mapper=file[?ident]โ an oracle to query for module name to filename mappings ๐ฎ. If unspecified theCXX_MODULE_MAPPERenvironment variable is used, and if that is unset, an in-process default is provided.-fmodule-onlyโ only spits out the Compiled Module Interface and that's it, no object file at all. Like, it does the one thing and dips. ๐-fms-extensionsโ turns off theWpedanticwarnings about stuff used in MFC โ think implicitint, and getting a pointer to member function via non-standard syntax. Basically "we know it's not standard, we're doing it anyway, don't @ us."-fnew-inheriting-ctorsโ enables the P0136 adjustment to the semantics of C++11 constructor inheritance. It's part of C++17 but also counts as a Defect Report against C++11 and C++14. Enabled by default unless you specify-fabi-version=10or lower. (so if you're on the old ABI, sorry bestie, no adjustment for you ๐ญ)-fnew-ttp-matchingโ turns on 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โ no built-in declarations of functions that aren't mandated by ANSI/ISO C. The ones getting axed includeffs,alloca,_exit,index,bzero,conjf, and other related functions. bye besties ๐-fnothrow-optโ treats athrow()exception specification like it was anoexceptspec, so it can reduce or eliminate the text size overhead compared to a function with no exception spec at all. And here's the fun bit: 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. โญ Semantic effect: an exception thrown out of a function with such a spec results in a call toterminaterather thanunexpected.-fno-operator-namesโ nope, don't treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms for keywords.-fno-optional-diagsโ kills diagnostics that the standard says the compiler doesn't even need to issue. Currently the only such diagnostic G++ issues is the one for a name having multiple meanings within a class. so like, one singular diagnostic. iconic honestly ๐-fpermissiveโ downgrades some diagnostics about nonconformant code from errors to warnings. So yes, with-fpermissivesome nonconforming code will actually compile. (chaotic, but valid ๐)-fno-pretty-templatesโ okay so normally, when an error message refers to a specialization of a function template, the compiler prints the template's signature followed by the template arguments and any typedefs or typenames in the signature โ likevoid f(T) [with T = int]rather thanvoid f(int)โ so it's super clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of these behaviors makes the error message harder to understand instead of easier, use-fno-pretty-templatesto disable them. (the name is a lie, it's the un-pretty one ๐ )-fno-rttiโ disables generation of the info about every class with virtual functions that the C++ run-time type identification features (dynamic_castandtypeid) need. If you don't use those parts of the language, you can save some space with this flag. Heads up: exception handling uses the same information, but G++ generates it as needed. Thedynamic_castoperator still works 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. (do not do this to yourself ๐ญ)
-fsized-deallocationโ enables the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
as introduced in C++14. This is useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. And -Wsized-deallocation warns about places that might want to add a definition. ๐ฅ
-fstrict-enumsโ lets the compiler optimize on the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that can be represented in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. โ ๏ธ so like, if you're out here casting randoms into enums, this flag will absolutely betray you.-fstrong-eval-orderโ evaluates member access, array subscripting, and shift expressions left-to-right, and evaluates assignment right-to-left, as adopted for C++17. Enabled by default with-std=c++17.-fstrong-eval-order=someenables just the ordering of member access and shift expressions, and is the default without-std=c++17.- *
-ftemplate-backtrace-limit=n* โ sets the max number of template instantiation notes for a single warning or error to n. The default value is10. (after that, the backtrace just gives up, relatable ๐ซถ) - *
-ftemplate-depth=n* โ sets the max instantiation depth for template classes to n. A limit on template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than17(changed to1024in C++11). The default value is900, because the compiler can run out of stack space before hitting1024in some situations. ๐ญ -fno-threadsafe-staticsโ do NOT emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shave a little code size in code that doesn't need to be thread-safe. (only if you're sure bestie, only if you're sure ๐)-fuse-cxa-atexitโ registers destructors for objects with static storage duration with the__cxa_atexitfunction instead of theatexitfunction. This option is required for fully standards-compliant handling of static destructors, but it only works if your C library supports__cxa_atexit.-fno-use-cxa-get-exception-ptrโ don't use the__cxa_get_exception_ptrruntime routine. This makesstd::uncaught_exceptionincorrect, but it's necessary if the runtime routine isn't available. ๐-fvisibility-inlines-hiddenโ this switch declares that the user isn't trying to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.
The effect: GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))) so they don't appear in the export table of a DSO and don't require a PLT indirection when used within the DSO. Enabling this can have a dramatic effect on load and link times of a DSO, because it massively reduces the size of the dynamic export table when the library makes heavy use of templates. โจ
Heads up though: this switch is not quite the same as marking the methods hidden directly, because it doesn't affect static variables local to the function, and it doesn't cause the compiler to deduce that the function is defined in only one shared object.
You may mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do want to compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility has no effect.
Explicitly instantiated inline methods are unaffected by this option, since their linkage might otherwise cross a shared library boundary.
-fvisibility-ms-compatโ this flag attempts to use visibility settings to make GCC's C++ linkage model compatible with Microsoft Visual Studio's. ๐ช
The flag makes these changes to GCC's linkage model:
- It sets the default visibility to
hidden, like-fvisibility=hidden. - Types, but not their members, are not hidden by default.
- The One Definition Rule is relaxed for types without explicit visibility specifications that are defined in more than one shared object: those declarations are permitted if they are permitted when this option is not used.
In new code it's better to use -fvisibility=hidden and export those classes that are intended to be externally visible. Unfortunately it's possible for code to rely, perhaps accidentally, on the Visual Studio behavior. ๐
Among the consequences of these changes: static data members of the same type with the same name but defined in different shared objects are different, so changing one doesn't change the other; and pointers to function members defined in different shared objects may not compare equal. When this flag is given, it's a violation of the ODR to define types with the same name differently. โ ๏ธ
-fno-weakโ don't use weak symbol support, even if the linker provides it. By default G++ uses weak symbols if they're available. This option exists only for testing, and should not be used by end-users; it results in inferior code and has no benefits. It may be removed in a future release of G++. (so like, genuinely don't ๐ซ)-fext-numeric-literals(C++ and Objective-C++ only) โ accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off, those suffixes are treated as C++11 user-defined literal numeric suffixes. 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. 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.)-flang-info-include-translate,-flang-info-include-translate-not, *-flang-info-include-translate=header* โ inform of include translation events. The first one notes accepted include translations, the second notes declined include translations. The header form informs of include translations relating to that specific header. If header is of the formuseror<system>, it gets resolved to a specific user or system header using the include path. ๐ง-flang-info-module-cmi,-flang-info-module-cmi=_module_ โ bestie, this one is your little spy into Compiled Module Interface pathnames ๐. The plain form notes all read CMI pathnames. The=moduleform won't note reading a specific module's CMI. And module can be a named module or a header-unit (that second one is indicated by either being a pathname containing directory separators, or being enclosed in"<>"or""). Slay.-stdlib=libstdc++,libc++โ okay so when G++ is configured to support this option, it lets you specify alternate C++ runtime libraries โจ. Two options are available: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. Both vibes are valid, iykyk ๐ .
In addition, these warning options have meanings only for C++ programs:
-Wabi-tag(C++ and Objective-C++ only) โ warns when a type with an ABI tag is used in a context that does not have that ABI tag. See C++ Attributes for more info about ABI tags ๐ท๏ธ.-Wcomma-subscript(C++ and Objective-C++ only) โ warns about uses of a comma expression within a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23 ๐ญ. BUT โ 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 is valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that is not valid in C++23 but used to be valid but deprecated in C++20 with a pedantic warning that can be disabled with -Wno-comma-subscript.
Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated. Periodt ๐.
-Wctad-maybe-unsupported(C++ and Objective-C++ only) โ warns when you're performing class template argument deduction (CTAD) on a type with no explicitly written deduction guides ๐. This warning points out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended. Certain style guides allow CTAD only on types that specifically "opt-in"; i.e., on types that are designed to support CTAD. You can suppress this warning with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
S(T) { }
};
// Guide with incomplete parameter type will never be considered.
S(allow_ctad_t) -> S<void>;
-Wctor-dtor-privacy(C++ and Objective-C++ only) โ warns when a class seems unusable because all the constructors or destructors in that class are private, and it has neither friends nor public static member functions ๐. Also warns if there are no non-private methods, and there's at least one private member function that isn't a constructor or destructor.-Wdangling-reference(C++ and Objective-C++ only) โ warns when a reference is bound to a temporary whose lifetime has ended ๐. For example:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling
In the example above, two temporaries are created, one for each argument, and a reference to one of the temporaries is returned. However, both temporaries are destroyed at the end of the full expression, so the reference "r" is dangling. This warning also detects dangling references in member initializer lists:
const int& f(const int& i) { return i; }
struct S {
const int &r; // r is dangling
S() : r(f(10)) { }
};
Member functions are checked as well, but only their object argument:
struct S {
const S& self () { return *this; }
};
const S& s = S().self(); // s is dangling
Certain functions are safe in this respect, for example "std::use_facet": they take and return a reference, but they don't return one of its arguments, which can fool the warning ๐ซ . Such functions can be excluded from the warning by wrapping them in a "#pragma":
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-reference"
const T& foo (const T&) { ... }
#pragma GCC diagnostic pop
-Wdangling-reference also warns about code like
auto p = std::minmax(1, 2);
where "std::minmax" returns "std::pair<const int&, const int&>", and both references dangle after the end of the full expression that contains the call to "std::minmax" ๐ญ.
This warning is enabled by -Wextra.
-Wdelete-non-virtual-dtor(C++ and Objective-C++ only) โ warns whendeleteis used to destroy an instance of a class that has virtual functions and a non-virtual destructor. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class does not have a virtual destructor โ ๏ธ. This warning is enabled by-Wall.-Wdeprecated-copy(C++ and Objective-C++ only) โ warns that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up. 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) โ disables the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;
-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion โจ.
-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only) โ disables the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a floating-point type. This conversion was deprecated in C++20. 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 of"std::initializer_list"that are likely to result in dangling pointers. Since the underlying array for an"initializer_list"is handled like a normal C++ temporary object, it is 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 local"initializer_list"variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer. - If a new-expression creates an
"initializer_list", the array only lives until the end of the enclosing full-expression, so the"initializer_list"in the heap has a dangling pointer. - When an
"initializer_list"variable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement the"initializer_list"variable has a dangling pointer. Like so:
- If a function returns a temporary
// li's initial underlying array lives as long as li
std::initializer_list<int> li = { 1,2,3 };
// assignment changes li to point to a temporary array
li = { 4, 5 };
// now the temporary is gone and li has a dangling pointer
int i = li.begin()[0] // undefined behavior
- When a list constructor stores the
"begin"pointer from the"initializer_list"argument, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporary"initializer_list", the pointer is left dangling by the end of the variable declaration statement ๐.
-Winvalid-constexprโ warns when a function never produces a constant expression ๐ง. In C++20 and earlier, for every"constexpr"function and function template, there must be at least one set of function arguments in at least one instantiation such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression. C++23 removed this restriction, so it's possible to have a function or a function template marked"constexpr"for which no invocation satisfies the requirements of a core constant expression.
This warning is enabled as a pedantic warning by default in C++20 and earlier. In C++23, -Winvalid-constexpr can be turned on, in which case it will be an ordinary warning. For example:
void f (int& i);
constexpr void
g (int& i)
{
// Warns by default in C++20, in C++23 only with -Winvalid-constexpr.
f(i);
}
-Winvalid-imported-macrosโ verifies all imported macro definitions are valid at the end of compilation โ . This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros ๐.-Wno-literal-suffix(C++ and Objective-C++ only) โ do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility with code that uses formatting macros from"<inttypes.h>"๐. For example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
so this next bit picks up right where the last option left off โ here's the little snippet that was being talked about:
int main() {
int64_t i64 = 123;
printf("My int64: %" PRId64"\n", i64);
}
And in this case, PRId64 is treated as a separate preprocessing token, bestie. That's the whole point.
This same option also controls the warnings you get when a user-defined literal operator is declared with a literal suffix identifier that doesn't start with an underscore. And why do we care? Because literal suffix identifiers that don't begin with an underscore are reserved for future standardization ๐ โ so touching them is asking for trouble.
These warnings are enabled by default. Lucky you ๐
-Wno-narrowing(C++ and Objective-C++ only) โ okay so for C++11 and later standards, narrowing conversions get diagnosed by default, as the standard literally requires. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning โ but-Wno-narrowingsuppresses that diagnostic entirely. Important tho: this does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed in SFINAE contexts. Don't get it twisted ๐
With -Wnarrowing in C++98, it warns when a narrowing conversion prohibited by C++11 happens inside { }, like this:
int i = { 2.2 }; // error: narrowing from double to int
This flag is included in -Wall and -Wc++11-compat.
-Wnoexcept(C++ and Objective-C++ only) โ warns when anoexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e.throw()or"noexcept") but is known by the compiler to never throw an exception. The compiler knows things, and it's gonna tell you ๐ง-Wnoexcept-type(C++ and Objective-C++ only) โ warns if the C++17 feature making"noexcept"part of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat. As an example:
template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }
In C++14, "f" calls "f<void(*)()>", but in C++17 it calls "f<void(*)()noexcept>". Tiny difference, huge consequences, iykyk ๐ญ
-Wclass-memaccess(C++ and Objective-C++ only) โ warns when the destination of a call to a raw memory function like"memset"or"memcpy"is an object of class type, and when writing into such an object might bypass the class's non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects can violate invariants maintained by member functions of the class. For example, the"memset"call below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available.
std::string str = "abc";
memset (&str, 0, sizeof str);
The -Wclass-memaccess option is enabled by -Wall. And hey โ 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. Slay โจ
-Wnon-virtual-dtor(C++ and Objective-C++ only) โ warns when a class has virtual functions and an accessible non-virtual destructor, either in itself or in an accessible polymorphic base class โ in which 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. The-Wdelete-non-virtual-dtoroption (enabled by-Wall) should be preferred, because it warns about the unsafe cases without false positives. Prefer the better one, bestie ๐ซถ-Wregister(C++ and Objective-C++ only) โ warns on uses of the"register"storage class specifier, except when it's part of the GNU Explicit Register Variables extension. The use of the"register"keyword as a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with-std=c++17. It's giving "we don't do that anymore" ๐-Wreorder(C++ and Objective-C++ only) โ warns when the order of member initializers given in the code doesn't match the order in which they must actually be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for "i" and "j" to match the declaration order of the members, and emits a warning to that effect. This warning is enabled by -Wall. The compiler said "not the order you wrote, bestie" ๐
-Wno-pessimizing-move(C++ and Objective-C++ only) โ this warning yells at you when a call to"std::move"prevents copy elision. A typical scenario where 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. Big oof. This warning is enabled by -Wall.
-Wno-redundant-move(C++ and Objective-C++ only) โ this warning is about redundant calls to"std::move"โ that is, when a move operation would have been performed even without the"std::move"call. This happens because the compiler is forced to treat the object as if it were an rvalue in certain situations, such as returning a local variable, where copy elision isn't applicable. Consider:
struct T {
...
};
T fn(T t)
{
...
return std::move (t);
}
Here, the "std::move" call is redundant. And because G++ implements Core Issue 1579, another example is:
struct T { // convertible to U
...
};
struct U {
...
};
U fn()
{
T t;
...
return std::move (t);
}
In this example, copy elision isn't applicable because the type of the expression being returned and the function return type differ โ yet G++ treats the return value as if it were designated by an rvalue. This warning is enabled by -Wextra.
-Wrange-loop-construct(C++ and Objective-C++ only) โ 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. (Sixty-four! A very specific number. Respect it ๐)
This warning also warns when a loop variable in a range-based for-loop is initialized with a value of a different type, resulting in a copy. For example:
void fn() {
int arr[10];
for (const double &x : arr) { ... }
}
In the example above, in every iteration of the loop a temporary value of type "double" is created and destroyed, to which the reference const double & is bound. Every. Single. Iteration. ๐ญ This warning is enabled by -Wall.
-Wredundant-tags(C++ and Objective-C++ only) โ warns about redundant class-key and enum-key in references to class types and enumerated types, in contexts where the key can be eliminated without causing an ambiguity. For example:
struct foo;
struct foo *p; // warn that keyword struct can be eliminated
On the other hand, in this example there is no warning:
struct foo;
void foo (); // "hides" struct foo
void bar (struct foo&); // no warning, keyword struct is necessary
Context is everything, periodt ๐
-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. Here's the why: 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. And the compiler doesn't give this warning for types defined in the main.Cfile, since those are unlikely to have multiple definitions.-Wsubobject-linkageis enabled by default. Okay so we love a well-explained caveat ๐-Weffc++(C++ and Objective-C++ only) โ warns about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:- Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
- Prefer initialization to assignment in constructors.
- Have
"operator="return a reference to*this. - Don't try to return a reference when you must return an object.
- Distinguish between prefix and postfix forms of increment and decrement operators.
- Never overload
"&&","||", or",".
This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of a virtual destructor in accessible non-polymorphic base classes too.
When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings. Not kidding, you'll need it ๐ง
-Wno-exceptions(C++ and Objective-C++ only) โ disables the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. Sometimes you just want the compiler to hush ๐คซ-Wstrict-null-sentinel(C++ and Objective-C++ only) โ warns about the use of an uncasted"NULL"as a 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's guaranteed to be of the same size as a pointer. But this use is not portable across different compilers โ so like, it works until it doesn't ๐-Wno-non-template-friend(C++ and Objective-C++ only) โ turns off the warning you get when non-template friend functions get declared inside a template. Here's the lore: in very old versions of GCC (like, pre-ISO-standard ancient), a declaration likefriend int foo(int), where the friend's name is an unqualified-id, could get read as a specific specialization of a template function ๐ญ. The warning exists purely to diagnose compatibility drama โ and it's on by default, bestie.-Wold-style-cast(C++ and Objective-C++ only) โ yells at you if you use an old-style (C-style) cast to a non-void type inside a C++ program ๐ . The new-style casts (dynamic_cast,static_cast,reinterpret_cast, andconst_cast) are way less vulnerable to unintended effects and so much easier to search for. It's giving glow-up, honestly.-Woverloaded-virtual/-Woverloaded-virtual=n(C++ and Objective-C++ only) โ warns when a function declaration hides virtual functions from a base class. Classic example, look:
struct A {
virtual void f();
};
struct B: public A {
void f(int); // does not override
};
so the A class version of f is hidden in B, and code like:
B* b;
b->f();
fails to compile ๐. When the different signatures aren't an accident, the simplest fix is adding a using-declaration to the derived class to un-hide the base function โ e.g. add using A::f; to B ๐ซถ.
The optional level suffix controls behavior when all the declarations in the derived class override virtual functions in the base class, even if not all of the base functions are overridden:
struct C {
virtual void f();
virtual void f(int);
};
struct D: public C {
void f(int); // does override
}
This pattern is less likely to be a mistake; if D is only used virtually, the user might have decided that the base class semantics for some of the overloads are fine.
At level 1, this case does not warn; at level 2, it does. -Woverloaded-virtual by itself selects level 2. And level 1 is included in -Wall โจ.
-Wno-pmf-conversions(C++ and Objective-C++ only) โ disables the diagnostic for converting a bound pointer to member function into a plain pointer. That's it, that's the vibe ๐.-Wsign-promo(C++ and Objective-C++ only) โ warns when overload resolution picks a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size ๐. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. Standards said what they said ๐ .-Wtemplates(C++ and Objective-C++ only) โ warns when a primary template declaration is encountered. Some coding rules disallow templates, and this may be used to enforce that rule ๐จ. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also instantiate or specialize templates โ those are fine, no cap.-Wmismatched-new-delete(C++ and Objective-C++ only) โ warns for mismatches between calls tooperator neworoperator deleteand the corresponding call to the allocation or deallocation function ๐ญ. This includes invocations of C++operator deletewith pointers returned from either mismatched forms ofoperator new, or from other functions that allocate objects for which theoperator deleteisn't a suitable deallocator โ plus calls to other deallocation functions with pointers returned fromoperator newfor which the deallocation function isn't suitable.
For example, the delete expression in the function below is diagnosed because it doesn't match the array form of the new expression the pointer argument was returned from. Similarly, the call to free is also diagnosed:
void f ()
{
int *a = new int[n];
delete a; // warning: mismatch in array forms of expressions
char *p = new char[n];
free (p); // warning: mismatch between new and free
}
The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete.
-Wmismatched-new-delete is included in -Wall ๐ฅ.
-Wmismatched-tags(C++ and Objective-C++ only) โ warns for declarations of structs, classes, and class templates and their specializations with a class-key that does not match either the definition or the first declaration (if no definition is provided) ๐.
For example, the declaration 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 โ -Wmismatched-tags is just here to help achieve a consistent style of class declarations โจ. In code 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.
-Wmultiple-inheritance(C++ and Objective-C++ only) โ warns when a class is defined with multiple direct base classes ๐. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use multiple inheritance โ loophole found, bestie ๐ฆ.-Wvirtual-inheritanceโ warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule ๐จ. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use virtual inheritance.-Wno-virtual-move-assignโ suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous ๐ญ because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled. Like, only turn this off if you actually know what you're doing, fr fr.-Wnamespacesโ warns when a namespace definition is opened ๐. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also useusingdirectives and qualified names โ those aren't definitions, so they slay through unaffected โจ.-Wno-terminate(C++ and Objective-C++ only) โ disables the warning about a throw-expression that will immediately result in a call toterminate๐. (RIP to that throw, it never stood a chance.)-Wno-vexing-parse(C++ and Objective-C++ only) โ warns about the most vexing parse syntactic ambiguity ๐ญ. This warns about 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.
-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 it's lowkey pointless, but also harmless.-Wvolatile(C++ and Objective-C++ only) โ warns about deprecated uses of thevolatilequalifier ๐จ. This includes postfix and prefix++and--expressions ofvolatile-qualified types, using simple assignments where the left operand is avolatile-qualified non-class type for their value, compound assignments where the left operand is avolatile-qualified non-class type,volatile-qualified function return type,volatile-qualified parameter type, and structured bindings of avolatile-qualified type. This usage was deprecated in C++20 ๐.
Enabled by default with -std=c++20.
-Wzero-as-null-pointer-constant(C++ and Objective-C++ only) โ warns when a literal0is used as a null pointer constant ๐. This can be useful to facilitate the conversion tonullptrin C++11. Like,0is not the moment anymore,nullptris the main character โจ.-Waligned-newโ warns about a new-expression of a type that requires greater alignment thanalignof(std::max_align_t)but uses an allocation function without an explicit alignment parameter ๐ฅ. This option is enabled by-Wall.
Normally this only warns about global allocation functions, but -Waligned-new=all also warns about class member allocation functions ๐
-Wno-placement-new/-Wplacement-new=nโ warns about placementnewexpressions with undefined behavior, such as constructing an object in a buffer that is smaller than the type of the object ๐ญ. For example, the placementnewexpression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large:
char buf [64];
new (buf) int[64];
This warning is enabled by default.
-Wplacement-new=1โ this is the default warning level of-Wplacement-newโจ. At this level the warning is not issued for some strictly undefined constructs that GCC allows as extensions for compatibility with legacy code. For example, the followingnewexpression is not diagnosed at this level even though it has undefined behavior according to the C++ standard because it writes past the end of the one-element array.
struct S { int n, a[1]; };
S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
new (s->a)int [32]();
-Wplacement-new=2โ okay level 2 is where it gets extra. Same diagnostics as level 1, plus it also yells at you for placementnewexpressions that construct an object in the last member of a structure โ when that member's type is an array of a single element and its size is less than the size of the object you're constructing. So yeah, the example above would totally get flagged. But the version below uses the flexible member array extension to dodge the warning at level 2. Sneaky. Love that for them. ๐
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
-Wcatch-value,-Wcatch-value=n(C++ and Objective-C++ only) โ this one's aboutcatchhandlers that refuse to catch via reference. Rude of them, honestly. With-Wcatch-value=1(or just-Wcatch-valuefor short) it warns about polymorphic class types that get caught by value. With-Wcatch-value=2it warns about all class types caught by value. With-Wcatch-value=3it warns about every type that isn't caught by reference. And heads up:-Wcatch-valueis enabled by-Wall.-Wconditionally-supported(C++ and Objective-C++ only) โ warns you about conditionally-supported constructs (C++11 [intro.defs]). That's it, that's the whole vibe. โจ-Wno-delete-incomplete(C++ and Objective-C++ only) โ turns OFF the warning you get when you delete a pointer to an incomplete type โ which, btw, may cause undefined behavior at runtime. So like, you're allowed to silence it, but the compiler is judging you. This warning is enabled by default.-Wextra-semi(C++, Objective-C++ only) โ warns about redundant semicolons after in-class function definitions. Extra semis, bestie. We see them. ๐ซถ-Wno-inaccessible-base(C++, Objective-C++ only) โ this one controls warnings for when a base class is inaccessible in a class derived from it due to ambiguity. Enabled by default. Quick note tho: the warning for ambiguous virtual bases is enabled by the-Wextraoption instead, not this one.
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ suppresses warnings about using C++11 inheriting constructors when the base class you inherited from has a C variadic constructor. The warning is on by default, because the ellipsis is not inherited. That's the whole reason. ๐ญ-Wno-invalid-offsetof(C++ and Objective-C++ only) โ suppresses warnings from applying the"offsetof"macro to a non-POD type. Per the 2014 ISO C++ standard, applying"offsetof"to a non-standard-layout type is undefined. That said, in existing C++ implementations"offsetof"typically gives you meaningful results anyway. So this flag is for the users who know they're writing nonportable code and deliberately chose to ignore the warning about it. Main character energy, honestly. ๐
Also, the restrictions on "offsetof" may be relaxed in a future version of the C++ standard. So like, watch this space.
-Wsized-deallocation(C++ and Objective-C++ only) โ warns you when you define an unsized deallocation function:
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
โฆwithout also defining the corresponding sized deallocation function:
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
โฆor the other way around (sized without unsized). Either direction, it clocks it. Enabled by -Wextra along with -fsized-deallocation.
-Wsuggest-final-typesโ warns about types with virtual methods where your code quality would literally improve if the type were declared with the C++11"final"specifier โ or, if possible, declared in an anonymous namespace. Why do we care? Because it lets GCC more aggressively devirtualize the polymorphic calls. ๐ And this warning is more effective with link-time optimization, where the info about the class hierarchy graph is more complete.-Wsuggest-final-methodsโ same energy but for virtual methods: warns when code quality would improve if the method were declared with the C++11"final"specifier, or if possible its type were declared in an anonymous namespace or with the"final"specifier. Again, more effective with link-time optimization for the same class-hierarchy-graph reasons. Pro tip from the manual itself: it's recommended you first consider the suggestions of-Wsuggest-final-typesand then rebuild with new annotations. Order matters, bestie. ๐-Wsuggest-overrideโ warns about overriding virtual functions that aren't marked with the"override"keyword. Just say override. It's not that hard. ๐-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. Enabled at all optimization levels, but ngl it may yield different results with optimization than without. ๐ฅ-Wuse-after-free=1โ at level 1 the warning only tries to diagnose unconditional uses of pointers made indeterminate by a deallocation call or a successful call to"realloc"โ regardless of whether the call actually resulted in a reallocation of memory. This includes double-"free"calls, plus uses in arithmetic and relational expressions. Even though it's undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.-Wuse-after-free=2โ at level 2, on top of unconditional uses, it also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call to"free"in this function gets diagnosed at this level:
struct A { int refcount; void *data; };
void release (struct A *p)
{
int refcount = --p->refcount;
free (p);
if (refcount == 0)
free (p->data); // warning: p may be used after free
}
-Wuse-after-free=3โ level 3 goes there: it also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined, but equality tests sometimes show up after calls to"realloc"as an attempt to figure out whether the call relocated the object to a different address. They get diagnosed at a separate level to help legacy code gradually transition to safe alternatives. Example โ the equality test in this function 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);
}
Want to dodge the warning at this level? Store offsets into the allocated memory instead of pointers. That approach obviates needing to adjust the stored pointers after reallocation. Clean. โจ
-Wuse-after-free=2is included in-Wall. So you're getting it whether you asked or not, bestie.
-Wuseless-cast(C++ and Objective-C++ only) โ warns when an expression is cast to its own type. Kinda pointless, hence the name, get it? This warning does not fire when a class object is converted to a non-reference type, because that's actually a way to create a temporary:
struct S { };
void g (S&&);
void f (S&& arg)
{
g (S(arg)); // make arg prvalue so that it can bind to S&&
}
-Wno-conversion-null(C++ and Objective-C++ only) โ don't warn for conversions between"NULL"and non-pointer types. For the record,-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 flags, diva.)
This section is all about the command-line options that are only meaningful for Objective-C and Objective-C++ programs. Good news tho: you can also use most of the language-independent GNU compiler options. Like, 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 GCC supports. ๐ฆ
Also, 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). They contain multitudes. ๐
Here's the list of options that are only for compiling Objective-C and Objective-C++ programs:
-fconstant-string-class=_class-name_ โ use class-name as the name of the class to instantiate for each literal string specified with the syntax"@"..."".The default class name is"NXConstantString"if the GNU runtime is being used, and"NSConstantString"if the NeXT runtime is being used (see below, bestie, it's coming). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption, if also present, overrides the-fconstant-string-classsetting, and causes"@"...""literals to be laid out as constant CoreFoundation strings. Note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. ๐ธ-fgnu-runtimeโ generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. The classic. ๐ซถ-fnext-runtimeโ generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. And the macro"__NEXT_RUNTIME__"is predefined if (and only if) this option is used. If and only if, no cap. โญ-fno-nil-receiversโ assume that all Objective-C message dispatches ("[receiver message:arg]") in this translation unit ensure that the receiver is not"nil". Why would you do that? Because it allows 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. Just so you know.-fobjc-abi-version=nโ picks version n of the Objective-C ABI for whichever runtime you've got going on. Heads up: this is currently only a NeXT-runtime thing. So like, on NeXT: Version 0 is the traditional (32-bit) ABI, no support for properties or the other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and the rest of the Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. Don't specify anything and the default is Version 0 on 32-bit target machines, and Version 2 on 64-bit target machines. ๐-fobjc-call-cxx-cdtorsโ okay so for each Objective-C class, this checks if any of its instance variables is a C++ object with a non-trivial default constructor. If it finds one, it synthesizes a special- (id) .cxx_constructinstance method that runs those non-trivial default constructors on all such instance variables, in order, and then returnsself. Same deal for destructors: it checks whether any instance variable is a C++ object with a non-trivial destructor, and if so synthesizes a special- (void) .cxx_destructmethod that runs all such default destructors, in reverse order. โจ
Important: the - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class โ not the ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods across an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime immediately after a new object instance is allocated; the - (void) .cxx_destruct methods get invoked immediately before the runtime deallocates an object instance.
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the - (id) .cxx_construct and - (void) .cxx_destruct methods. ๐ซถ
-fobjc-direct-dispatchโ allows fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. โก-fobjc-exceptionsโ turns on syntactic support for structured exception handling in Objective-C, kinda like what C++ offers. This one is required if you want to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. Available with both the GNU runtime and the NeXT runtime (but not available in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier). ๐ญ-fobjc-gcโ enables garbage collection (GC) in Objective-C and Objective-C++ programs. Only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that does not require special compiler flags. ๐๏ธโจ-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, this checks for a nil receiver in method invocations before doing the actual method call. This is the default, and you can disable it using-fno-objc-nilcheck. Class methods and super calls are never checked for nil this way, no matter what this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used.-fobjc-std=objc1โ conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that isn't 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. ๐-freplace-objc-classesโ emits a special marker instructingld(1)not to statically link in the resulting object file, and letsdyld(1)load it in at run time instead. This is used 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 needing to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later. ๐-fzero-linkโ when compiling for the NeXT runtime, the compiler ordinarily replaces calls toobjc_getClass("...")(when the 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. ๐ง-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. ๐-fivar-visibility=[public|protected|private|package]โ sets the default instance variable visibility to the specified option, so instance variables declared outside the scope of any access modifier directives default to that visibility.-gen-declsโ dumps interface declarations for all classes seen in the source file to a file named sourcename.decl. ๐-Wassign-intercept(Objective-C and Objective-C++ only) โ warns whenever an Objective-C assignment is being intercepted by the garbage collector.-Wno-property-assign-default(Objective-C and Objective-C++ only) โ don't warn if a property for an Objective-C object has no assign semantics specified.-Wno-protocol(Objective-C and Objective-C++ only) โ if a class is declared to implement a protocol, a warning is issued for every method in the protocol that isn't implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the-Wno-protocoloption, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.-Wobjc-root-class(Objective-C and Objective-C++ only) โ warns if a class interface lacks a superclass. Most classes will inherit from"NSObject"(or"Object") for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with__attribute__((objc_root_class)). ๐ฑ-Wselector(Objective-C and Objective-C++ only) โ warns if multiple methods of different types for the same selector are found during compilation. The check is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a@selector(...)expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation isn't reached โ for example because an error is found during compilation, or because the-fsyntax-onlyoption is being used.-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warns if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of typeidorClass. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.-Wundeclared-selector(Objective-C and Objective-C++ only) โ warns if a@selector(...)expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the@selector(...)expression, either explicitly in an@interfaceor@protocoldeclaration, or implicitly in an@implementationsection. This option always performs its checks as soon as a@selector(...)expression is found, while-Wselectoronly performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. ๐ต๏ธโโ๏ธ-print-objc-runtime-infoโ generates a C header describing the largest structure that is passed by value, if any.
๐ฉบ Options to Control Diagnostic Messages Formatting
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. Just know that some language front ends may not honor these options. ๐
-fmessage-length=nโ tries to format error messages so they fit on lines of about n characters. If n is zero, then no line-wrapping is done; each error message appears on a single line. This is the default for all front ends. ๐
Note โ this option also affects the display of the #error and #warning pre-processor directives, and the deprecated function/type/variable attribute. It does not, however, affect the pragma GCC warning and pragma GCC error pragmas.
-fdiagnostics-plain-outputโ this option requests that diagnostic output look as plain as possible, which may be useful when runningdejagnuor other utilities that need to parse diagnostics output and prefer that it remain more stable over time.-fdiagnostics-plain-outputis currently equivalent to the following options:
-fno-diagnostics-show-caret -fno-diagnostics-show-line-numbers
-fdiagnostics-color=never -fdiagnostics-urls=never
-fdiagnostics-path-format=separate-events
In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list. ๐ฎ
-fdiagnostics-show-location=onceโ okay so this one only does anything in line-wrapping mode (iykyk). 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 won't keep getting re-emitted as a prefix over and over on every continuation line. Which is literally the default behavior, bestie. ๐-fdiagnostics-show-location=every-lineโ again, only meaningful in line-wrapping mode. This one says: yes, actually, emit that same source location info (as a prefix) on every physical line that comes out of breaking up a message that's too long for a single line. Consistent, if a lil repetitive. ๐-fdiagnostics-color[=WHEN],-fno-diagnostics-colorโ use color in diagnostics, periodt. WHEN isnever,always, orauto. The default depends on how the compiler was configured โ it can be any of those WHEN options, or alsoneverif theGCC_COLORSenvironment variable isn't present in the environment, andautootherwise.automakes GCC use color only when standard error is a terminal, and when it's not executing in an emacs shell. And the forms-fdiagnostics-colorand-fno-diagnostics-colorare aliases for-fdiagnostics-color=alwaysand-fdiagnostics-color=never, respectively. โจ
The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator โ check the docs for your text terminal for the permitted values and what they mean as character attributes. Those substring values are integers in decimal representation and you can concatenate them with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. ๐
The default GCC_COLORS is
error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\
quote=01:path=01;36:fixit-insert=32:fixit-delete=31:\
diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
type-diff=01;32:fnname=01;32:targs=35
where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. Supported capabilities are as follows, bestie:
"error="โ SGR substring forerror:markers."warning="โ SGR substring forwarning:markers."note="โ SGR substring fornote:markers."path="โ SGR substring for colorizing paths of control-flow events as printed via-fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns."range1="โ SGR substring for first additional range."range2="โ SGR substring for second additional range."locus="โ SGR substring for location information,file:lineorfile:line:columnetc."quote="โ SGR substring for information printed within quotes."fnname="โ SGR substring for names of C++ functions."targs="โ SGR substring for C++ function template parameter bindings."fixit-insert="โ SGR substring for fix-it hints suggesting text to be inserted or replaced."fixit-delete="โ SGR substring for fix-it hints suggesting text to be deleted."diff-filename="โ SGR substring for filename headers within generated patches."diff-hunk="โ SGR substring for the starts of hunks within generated patches."diff-delete="โ SGR substring for deleted lines within generated patches."diff-insert="โ SGR substring for inserted lines within generated patches."type-diff="โ SGR substring for highlighting mismatching types within template arguments in the C++ frontend.
-fdiagnostics-urls[=WHEN]โ use escape sequences to embed URLs in diagnostics, iconic behavior honestly. For example, when-fdiagnostics-show-optionemits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option. ๐
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when standard error is a terminal, and when it's not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature โ see below, bestie. ๐
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, that is). Specifying the-fno-diagnostics-show-optionflag suppresses that behavior. Poof, gone. ๐-fno-diagnostics-show-caretโ by default, each diagnostic emitted includes the original source line and a caret^indicating the column. This option suppresses that info. The source line is truncated to n characters if the-fmessage-length=noption is given. When the output is done to the terminal, the width is limited to the width given by theCOLUMNSenvironment variable or, if not set, to the terminal width. ๐-fno-diagnostics-show-labelsโ by default, when printing source code (via-fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions:
printf ("foo %s bar", long_i + long_j);
~^ ~~~~~~~~~~~~~~~
| |
char * long int
This option suppresses the printing of these labels (in the example above, the vertical bars and the "char *" and "long int" text). โจ
-fno-diagnostics-show-cweโ diagnostic messages can optionally have an associated CWE ("https://cwe.mitre.org/index.html") identifier. GCC itself only provides such metadata for some of the-fanalyzerdiagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata. ๐ต๏ธ-fno-diagnostics-show-rulesโ diagnostic messages can optionally have rules associated with them, such as from a coding standard, or a specification. GCC itself does not do this for any of its diagnostics, but plugins may do so. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata. ๐-fno-diagnostics-show-line-numbersโ by default, when printing source code (via-fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin. No numbers, no margin, no problem. ๐ซถ-fdiagnostics-minimum-margin-width=widthโ this option controls the minimum width of the left margin printed by-fdiagnostics-show-line-numbers. It defaults to6. Bestie, that's the whole flag. ๐-fdiagnostics-parseable-fixitsโ emit fix-it hints in a machine-parseable format, suitable for consumption by IDEs. For each fix-it, a line will be printed after the relevant diagnostic, starting with the string"fix-it:". For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013"). ๐ฅ
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position.
-fdiagnostics-generate-patchโ print fix-it hints to stderr in unified diff format, after any diagnostics are printed. For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
void show_cb(GtkDialog *dlg)
{
- gtk_widget_showall(dlg);
+ gtk_widget_show_all(dlg);
}
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color). ๐
-fdiagnostics-show-template-treeโ okay so picture this: the C++ frontend is printing diagnostics showing mismatching template types, and it hits you with something like:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
This flag is the little glow-up that enables printing a tree-like structure showing the common and differing parts of the types, like:
map<
[...],
vector<
[double != float]>>
The parts that differ are highlighted with color (double and float in this case). Itโs giving โmap of the chaosโ and honestly? Obsessed. ๐
โจ
-fno-elide-typeโ by default, when the C++ frontend prints diagnostics showing mismatching template types, common parts of the types are printed as[...]to simplify the error message. For example:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
Specifying the -fno-elide-type flag suppresses that behavior. This flag also affects the output of the -fdiagnostics-show-template-tree flag. No more mystery [...], bestie โ weโre seeing it all. ๐ซถ
-fdiagnostics-path-format=KINDโ this one says how to print paths of control-flow events for diagnostics that have such a path associated with them.KINDisnone,separate-events, orinline-eventsโ andinline-eventsis the default.
none means to not print diagnostic paths. Simple. Iconic. Minimal.
separate-events means 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-events means 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. The drama of it all! ๐
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=inline-events. If provided with -fdiagnostics-path-format=separate-events, then the stack depth and function declaration will be appended when printing each event.
This is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. Very โdevs only, but make it forensic.โ ๐๐
-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. Sometimes the tooling just isnโt ready for the column lore. ๐ญ-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. Unicode said โI contain multitudes,โ and GCC said โbestie, same.โ ๐ธ
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.
-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. Zero-indexed girlies, this oneโs for you. ๐-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.FORMATistext,sarif-stderr,sarif-file,json,json-stderr, orjson-file.
The default is text.
The sarif-stderr and sarif-file formats both emit diagnostics in SARIF Version 2.1.0 format, either to stderr, or to a file named source.sarif, respectively.
The json format is a synonym for json-stderr. The json-stderr and json-file formats are identical, apart from where the JSON is emitted to โ with the former, the JSON is emitted to stderr, whereas with json-file it is written to source.gcc.json.
The emitted JSON consists of a top-level JSON array containing JSON objects representing the diagnostics. The JSON is emitted as one line, without formatting; the examples below have been formatted for clarity.
Diagnostics can have child diagnostics. For example, this error and note:
misleading-indentation.c:15:3: warning: this 'if' clause does not
guard... [-Wmisleading-indentation]
15 | if (flag)
| ^~
misleading-indentation.c:17:5: note: ...this statement, but the latter
is misleadingly indented as if it were guarded by the 'if'
17 | y = 2;
| ^
might be printed in JSON form (after formatting) like this:
...where that "note" is literally a child of the "warning", bestie, like it's holding its hand ๐ซถ
A diagnostic has a "kind". If that kind is "warning", then there's an "option" key describing the command-line option that controls the warning. Iykyk.
A diagnostic can have zero or more locations โ yes, zero, it's giving minimalist ๐
. Each location has an optional "label" string plus 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 telling you the column position:
"display-column"โ counts display columns, and it does account for tabs and multibyte characters โจ"byte-column"โ counts raw bytes, no vibes, just bytes"column"โ equal to one of the previous two, whichever the-fdiagnostics-column-unitoption dictates ๐
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 gets 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 keep it cute and short ๐ธ).
So like, check out 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}
It has three locations, no cap. Its primary location is at the + token at column 23, and it has two secondary locations describing the left and right-hand sides of the expression, which have labels. It might be printed in JSON form as:
{
"children": [],
"kind": "error",
"locations": [
{
"caret": {
"column": 23, "file": "bad-binary-ops.c", "line": 64
}
},
{
"caret": {
"column": 10, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 21, "file": "bad-binary-ops.c", "line": 64
},
"label": "S {aka struct s}"
},
{
"caret": {
"column": 25, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 36, "file": "bad-binary-ops.c", "line": 64
},
"label": "T {aka struct t}"
}
],
"escape-source": false,
"message": "invalid operands to binary + ..."
}
If a diagnostic contains fix-it hints, it has a "fixits" array, consisting of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits ๐. For example, this diagnostic with a replacement fix-it hint:
demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
mean 'color'?
8 | return ptr->colour;
| ^~~~~~
| color
might be printed in JSON form as:
{
"children": [],
"fixits": [
{
"next": {
"column": 21,
"file": "demo.c",
"line": 8
},
"start": {
"column": 15,
"file": "demo.c",
"line": 8
},
"string": "color"
}
],
"kind": "error",
"locations": [
{
"caret": {
"column": 15,
"file": "demo.c",
"line": 8
},
"finish": {
"column": 20,
"file": "demo.c",
"line": 8
}
}
],
"escape-source": false,
"message": "\u2018struct s\u2019 has no member named ..."
}
...where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value. Deletions are expressed via an empty value for "string", insertions by having "start" equal "next". Tiny detail, huge slay ๐
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. Stacked like your iced coffee order, honestly ๐ง
For example, the intraprocedural example shown for -fdiagnostics-path-format= might have this JSON for its path:
"path": [
{
"depth": 0,
"description": "when 'PyList_New' fails, returning NULL",
"function": "test",
"location": {
"column": 10,
"file": "test.c",
"line": 25
}
},
{
"depth": 0,
"description": "when 'i < count'",
"function": "test",
"location": {
"column": 3,
"file": "test.c",
"line": 27
}
},
{
"depth": 0,
"description": "when calling 'PyList_Append', passing NULL from (1) as argument 1",
"function": "test",
"location": {
"column": 5,
"file": "test.c",
"line": 29
}
}
]
Diagnostics have a boolean attribute "escape-source", hinting whether non-ASCII bytes should be escaped when printing the pertinent lines of source code ("true" for diagnostics involving source encoding issues). It's literally just a little heads-up ๐
โจ Options to Request or Suppress Warnings โจ
Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error ๐. Like, the code runs, but it's giving "this is fine" meme energy.
The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC. Main character options only ๐
-fsyntax-onlyโ Check the code for syntax errors, but don't do anything beyond that. Just a lil vibe check on your syntax, then it dips โ๏ธ-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 โ go off, infinite chaos ๐ญ. If-Wfatal-errorsis also specified, then-Wfatal-errorstakes precedence over this option. Periodt.-wโ Inhibit all warning messages. Not me silencing the haters ๐โจ-Werrorโ Make all warnings into errors. Glow-up gone wrong: every warning now has main-character stakes ๐๐ฅ
ok so next we have the glow-up where warnings get promoted to errors ๐
-Werror=โ makes the warning you name into a full-on error. You just tack the specifier onto the end, like-Werror=switchturns all those-Wswitchwarnings into errors. And bestie, it's got a negative form too, for when you want to un-error one specific warning:-Wno-error=switchmakes-Wswitchwarnings not be errors, even when-Werroris out here being all dramatic and in effect.
Every controllable warning's message shows you which option controls it โ that's the whole point โ so you can take that option straight back to -Werror= or -Wno-error= like we just talked about. (You can hide the option from the message with the -fno-diagnostics-show-option flag if you're feeling shy. ๐)
Heads up though: -Werror=foo automatically implies -Wfoo. But -Wno-error=foo implies literally nothing. Not a single thing. It's giving "no thoughts, head empty." ๐
-Wfatal-errorsโ the compiler just โจgives upโจ on the first error instead of trying to keep going and printing a whole pile more error messages. No cap, this one's for when you can't handle the secondhand embarrassment of a hundred errors at once.
so there's a whole genre of options that start with -W, and you can request a ton of specific warnings that way โ -Wimplicit, for instance, asks for warnings on implicit declarations. Every one of these specific warning options has a negative twin that starts with -Wno-, which turns it off (-Wno-implicit, iconic behaviour). This manual only lists one of the two forms โ whichever one isn't the default โ so don't come for me when you only see half the set. ๐ซถ
For language-specific stuff, go check out C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And more warnings can be produced by enabling the static analyzer;
ok and this next bit is important, so pay attention bestie ๐ โ some options, like -Wall and -Wextra, turn on other options, like -Wunused, which then turn on further options, like -Wunused-value. It's a whole chain of enabling, very main character energy. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, regardless of where they sit on the command line. For options of the same specificity, the last one takes effect (last one wins, as per usual). And options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. ๐ฆ
Now, when you request an unrecognized warning option (say -Wunknown-warning), GCC hits you with a diagnostic saying the option is not recognized. But the -Wno- form is quirky: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced anyway. Why? So you can use shiny new -Wno- options with old compilers. And if something goes wrong, the compiler will warn you that an unrecognized option is present. Balance. โญ
Also real talk: some warnings only hit different when optimizations are on too. -Wsuggest-final-types is way more effective with link-time optimization, and some other warnings may not be issued at all unless optimization is enabled. Optimizing generally improves the efficacy of control- and data-flow-sensitive warnings, but in some cases it may also cause false positives. ๐ It's giving "trade-offs."
๐ the pedantic zone ๐
-Wpedantic,-pedanticโ issues all the warnings demanded by strict ISO C and ISO C++, rejects all programs that use forbidden extensions, and rejects some other programs that don't follow ISO C and ISO C++. For ISO C, it follows whichever version of the ISO C standard your-stdoption specified.
Valid ISO C and ISO C++ programs should compile properly with or without this option (a rare few do need -ansi or a -std option specifying the required version of ISO C). But without this option, certain GNU extensions and traditional C and C++ features are supported too. With this option, they get rejected. ๐ซ
-Wpedantic does not throw warnings for the alternate keywords whose names begin and end with __. That alternate format also works to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". But โ and I cannot stress this enough โ 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 does not do quite what they want: it finds some non-ISO practices, but not all โ only those for which ISO C requires a diagnostic, plus 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'd 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. Sorry 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 the base standard requires them. (It wouldn't make sense to give them only for features not in the specified GNU C dialect, because by definition the GNU dialects of C include all features the compiler supports with the given option, and there'd be nothing to warn about. ๐ง)
-pedantic-errorsโ throws 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. And no, it is not equivalent to-Werror=pedanticโ there are errors enabled by this option and not by that one, and vice versa. They're different girlies. ๐
๐ฅ -Wall ๐ฅ
This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify so the warning stops), even when you're working 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++)
-Wenum-int-mismatch (C and Objective-C only) -Wformat
-Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and
Objective-C only) -Wimplicit-function-declaration (C and Objective-C
only) -Winit-self (only for C++) -Wlogical-not-parentheses -Wmain
(only for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wself-move (only for C++)
-Wsequence-point -Wsign-compare (only in C++) -Wsizeof-array-div
-Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstrict-aliasing
-Wstrict-overflow=1 -Wswitch -Wtautological-compare -Wtrigraphs
-Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label
-Wunused-value -Wunused-variable -Wuse-after-free=2 -Wvla-parameter
(C and Objective-C only) -Wvolatile-register-var
-Wzero-length-bounds
Note that some warning flags are not implied by -Wall. Some of them warn about constructions users generally don't consider questionable, but which occasionally you might want to check for anyway; 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 get enabled by -Wextra, but many of them have to be enabled individually. Sorry, no bundle deal on those. ๐
๐ -Wextra ๐
This enables some extra warning flags that -Wall didn't already scoop up. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive โ a glow-up, if you will. โจ)
-Wclobbered -Wcast-function-type -Wdangling-reference (C++ only)
-Wdeprecated-copy (C++ only) -Wempty-body -Wenum-conversion (C only)
-Wignored-qualifiers -Wimplicit-fallthrough=3
-Wmissing-field-initializers -Wmissing-parameter-type (C only)
-Wold-style-declaration (C only) -Woverride-init -Wsign-compare (C
only) -Wstring-compare -Wredundant-move (only for C++) -Wtype-limits
-Wuninitialized -Wshift-negative-value (in C++11 to C++17 and in C99
and newer) -Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for the following cases:
- A pointer is compared against integer zero with
"<","<=",">", or">=". - (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
- (C++ only) Ambiguous virtual bases.
- (C++ only) Subscripting an array that has been declared
"register". - (C++ only) Taking the address of a variable that has been declared
"register". - (C++ only) A base class is not initialized in the copy constructor of a derived class.
๐ฆ -Wabi (C, Objective-C, C++ and Objective-C++ only) ๐ฆ
Warns about code affected by ABI changes. That 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 only warns 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. See, it's all connected. ๐ธ๏ธ
Although an effort has been made to warn you about all of these cases, bestie, there are probably still some sneaky ones that aren't warned about even though G++ is literally out here generating incompatible code ๐ญ. And yeah โ there are also cases where warnings get emitted even though the generated code is actually compatible. Life's messy like that.
If the whole "code generated by G++ might not be binary compatible with code generated by other compilers" thing is keeping you up at night, you should rewrite your code to dodge these warnings. Full stop.
Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9) include:
- A template with a non-type template parameter of reference type was mangled incorrectly:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}
This was fixed in -fabi-version=3.
- SIMD vector types declared using
"__attribute ((vector_size))"were mangled in a non-standard way that does not allow for overloading of functions taking vectors of different sizes.
The mangling was changed in -fabi-version=4.
"__attribute ((const))"and"noreturn"were mangled as type qualifiers, and"decltype"of a plain declaration was folded away.
These mangling issues were fixed in -fabi-version=5.
- Scoped enumerators passed as arguments to a variadic function are promoted like unscoped enumerators, causing
"va_arg"to complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller than"int".
Also, the ABI changed the mangling of template argument packs, "const_cast", "static_cast", prefix increment/decrement, and a class scope function used as a template argument.
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 a"nullptr_t"parameter, as parameters have a minimum alignment.
This was fixed in -fabi-version=9, the default for GCC 5.2.
- Target-specific attributes that affect the identity of a type, such as ia32 calling conventions on a function type (stdcall, regparm, etc.), did not affect the mangled name, leading to name collisions when function pointers were used as template arguments.
This was fixed in -fabi-version=10, the default for GCC 6.1.
This option also enables warnings about psABI-related changes. The known psABI changes at this point include:
- For SysV/x86-64, unions with
"long double"members are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. For example:
union U {
long double ld;
int i;
};
"union U" is now always passed in memory.
-Wno-changes-meaning (C++ and Objective-C++ only)
Okay so C++ is very particular about names ๐ : it requires that unqualified uses of a name within a class have the same meaning in the complete scope of the class. Which means declaring the name after using it is ill-formed:
struct A;
struct B1 { A a; typedef A A; }; // warning, 'A' changes meaning
struct B2 { A a; struct A { }; }; // error, 'A' changes meaning
By default, the B1 case is only a warning because the two declarations have the same type, while the B2 case is an error. Both diagnostics can be disabled with -Wno-changes-meaning. Alternately, the error case can be reduced to a warning with -Wno-error=changes-meaning or -fpermissive.
Both diagnostics are also suppressed by -fms-extensions.
-Wchar-subscripts
Warns you if an array subscript has type "char". This is a super common cause of error because programmers constantly forget that this type is signed on some machines ๐. This warning is enabled by -Wall.
-Wno-coverage-mismatch
Warns you if feedback profiles do not match when you're using the -fprofile-use option. If a source file gets changed between compiling with -fprofile-generate and with -fprofile-use, the files with the profile feedback can fail to match the source file and GCC literally cannot use the profile feedback information.
By default, this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable the warning, or -Wno-error=coverage-mismatch can be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended.
-Wno-coverage-invalid-line-number
Warns you in case a function ends earlier than it begins, because of an invalid linenum macros. The warning is emitted only with --coverage enabled.
By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning, or -Wno-error=coverage-invalid-line-number can be used to disable the error.
-Wno-cpp (C, Objective-C, C++, Objective-C++ and Fortran only)
Suppresses warning messages emitted by "#warning" directives. That's it, that's the whole thing ๐.
-Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
Gives you a warning when a value of type "float" is implicitly promoted to "double". Why do we care? Because CPUs with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate "double" in software ๐ญ. On such a machine, doing computations using "double" values is much more expensive because of the overhead required for software emulation.
It is genuinely easy to accidentally do computations with "double" because floating-point literals are implicitly of type "double". For example, in:
float area(float radius)
{
return 3.14159 * radius * radius;
}
the compiler performs the entire computation with "double" because the floating-point literal is a "double". Sneaky, right? ๐
-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 appropriate to the format string you specified, and that the conversions specified in the format string actually make sense. This includes standard functions, and others specified by format attributes, in the "printf", "scanf", "strftime" and "strfmon" (an X/Open extension, not in the C standard) families (or other target-specific families).
Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for "strfmon" formats, since those are not in any version of the C standard).
-Wformat=1
-Wformat
Option -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 the options: -Wno-format-contains-nul, -Wno-format-extra-args, and -Wno-format-zero-length. -Wformat is enabled by -Wall.
-Wformat=2
Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
-Wno-format-contains-nul
If -Wformat is specified, do not warn about format strings that contain NUL bytes.
-Wno-format-extra-args
If -Wformat is specified, do not warn about excess arguments to a "printf" or "scanf" format function. The C standard specifies that such arguments are ignored. Cool of it, honestly ๐ฆ.
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to "va_arg" to skip the unused arguments. However, in the case of "scanf" formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.
-Wformat-overflow
-Wformat-overflow=level
Warns you about calls to formatted input/output functions such as "sprintf" and "vsprintf" that might overflow the destination buffer ๐ฌ. When the exact number of bytes written by a format directive 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. Ngl, that's just how it goes ๐.
-Wformat-overflow,-Wformat-overflow=1โ level 1 of-Wformat-overflow, which is what you get when-Wformatis on, is the cautious bestie of the family: it only yells 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 that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive's precision or by a finite set of string literals, are assumed to take on the value within the range that results in the most bytes on output. Like, for example, the call tosprintfbelow gets diagnosed because even with bothaandbequal to zero, the terminating NUL character ('\0') appended by the function to the destination buffer will be written past its end. Bumping the buffer size up by a single byte is enough to dodge the warning, though it may not be enough to dodge the overflow itself. ๐ซถ
void f (int a, int b)
{
char buf [13];
sprintf (buf, "a = %i, b = %i\n", a, b);
}
-Wformat-overflow=2โ level 2 is level 1 but with trust issues (affectionate). It also warns about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2, unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string arguments whose length 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 literally 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. slay ๐
void f (int a, int b)
{
char buf [23];
sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
-Wno-format-zero-lengthโ if-Wformatis specified, do not warn about zero-length formats. The C standard says zero-length formats are allowed, so like, let them live. โจ-Wformat-nonliteralโ if-Wformatis 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 ava_list.-Wformat-securityโ if-Wformatis specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls toprintfandscanffunctions where the format string is not a string literal and there are no format arguments, as inprintf (foo);. This may be a security hole if the format string came from untrusted input and contains%n. ๐จ (This is currently a subset of what-Wformat-nonliteralwarns about, but in future warnings may be added to-Wformat-securitythat are not included in-Wformat-nonliteralโ so don't go assuming they're the same thing, bestie.)-Wformat-signednessโ if-Wformatis specified, also warn if the format string requires an unsigned argument and the argument is signed, and vice versa. signed vs unsigned drama, caught in 4K ๐-Wformat-truncation,-Wformat-truncation=levelโ warn about calls to formatted input/output functions such assnprintfandvsnprintfthat might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time, it is estimated based on heuristics that depend on thelevelargument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives โ no cap, it's a tradeoff. Except as noted otherwise, the option uses the same logic as-Wformat-overflow.-Wformat-truncation,-Wformat-truncation=1โ level 1 of-Wformat-truncation, enabled by-Wformat, employs 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-Wformatis specified, also warn aboutstrftimeformats that may yield only a two-digit year. it's giving Y2K panic and honestly? valid ๐-Wnonnullโ warn about passing a null pointer for arguments marked as requiring a non-null value by thenonnullfunction attribute.-Wnonnullis included in-Walland-Wformat. It can be disabled with the-Wno-nonnulloption.-Wnonnull-compareโ warn when comparing an argument marked with thenonnullfunction attribute against null inside the function.-Wnonnull-compareis included in-Wall. It can be disabled with the-Wno-nonnull-compareoption.-Wnull-dereferenceโ warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. This option is only active when-fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used. ๐-Winfinite-recursionโ warn about infinitely recursive calls. The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions.-Winfinite-recursionis included in-Wall.
Compare with -Wanalyzer-infinite-recursion, which provides a similar diagnostic but is implemented in a different way (as part of -fanalyzer). same vibe, different machinery ๐
-Winit-self(C, C++, Objective-C and Objective-C++ only) โ warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the-Wuninitializedoption.
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++. (i = i is not the self-care we were talking about, bestie ๐ญ)
-Wno-implicit-int(C and Objective-C only) โ this option controls warnings when a declaration does not specify a type. This warning is enabled by default in C99 and later dialects of C, and also by-Wall.-Wno-implicit-function-declaration(C and Objective-C only) โ this option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by-Wall. The warning is made into an error by-pedantic-errors. โ ๏ธ-Wimplicit(C and Objective-C only) โ same as-Wimplicit-intand-Wimplicit-function-declaration. This warning is enabled by-Wall.-Wimplicit-fallthroughโ-Wimplicit-fallthroughis the same as-Wimplicit-fallthrough=3and-Wno-implicit-fallthroughis the same as-Wimplicit-fallthrough=0. matchy matchy ๐-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 a function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.:
switch (cond)
{
case 1:
if (i > 3) {
bar (5);
break;
} else if (i < 1) {
bar (0);
} else
return;
default:
...
}
Since there are occasions where a switch case fall through is 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=2โ case-insensitively matches this regex, bestie:".*falls?[ \t-]*thr(ough|u).*".-Wimplicit-fallthrough=3โ case-sensitively matches one of these regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
-Wimplicit-fallthrough=4โ case-sensitively matches one of these regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5โ doesn't recognize any comments as fallthrough comments, periodt. Only attributes disable the warning.
Okay so the comment needs to be followedโafter optional whitespace and other commentsโby case or default keywords, or by a user label that precedes some case or default label. Like this:
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.
-Wno-if-not-aligned(C, C++, Objective-C and Objective-C++ only) โ controls whether warnings triggered by thewarn_if_not_alignedattribute should be issued. These warnings are enabled by default.-Wignored-qualifiers(C and C++ only) โ warns if the return type of a function has a type qualifier such asconst. For ISO C, that kind of qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types orvoid. ISO C prohibits qualifiedvoidreturn types on function definitions, so those return types always get a warning even without this option. This warning is also enabled by-Wextra.-Wno-ignored-attributes(C and C++ only) โ controls warnings when an attribute is ignored. This is different from-Wattributes: it warns whenever the compiler decides to drop an attribute, not that the attribute is unknown, used in the wrong place, etc. This warning is enabled by default.-Wmainโ warns if the type ofmainis suspicious.mainshould be a function with external linkage, returningint, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either-Wallor-Wpedantic.-Wmisleading-indentation(C and C++ only) โ warns when the indentation of the code does not reflect the block structure. Specifically, a warning is issued forif,else,while, andforclauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation. In this example, the call tobaris misleadingly indented as if it were guarded by theifconditional:
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8). The warning is not issued for code involving multiline preprocessor logic such as this example:
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
The warning is not issued after a #line directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references. This warning is enabled by -Wall in C and C++.
-Wmissing-attributesโ warns when a declaration of a function is missing one or more attributes that a related function is declared with, and whose absence may adversely affect the correctness or efficiency of generated code. For example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the-Wattribute-alias=2option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. Attributes considered includealloc_align,alloc_size,cold,const,hot,leaf,malloc,nonnull,noreturn,nothrow,pure,returns_nonnull, andreturns_twice.
In C++, the warning is issued when an explicit specialization of a primary template declared with attribute alloc_align, alloc_size, assume_aligned, format, format_arg, malloc, or nonnull is declared without it. Attributes deprecated, error, and warning suppress the warning..
You can use the copy attribute to apply the same set of attributes to a declaration as that on another declaration without explicitly enumerating the attributes. This attribute can be applied to declarations of functions, variables, or types. -Wmissing-attributes is enabled by -Wall.
For example, since the declaration of the primary function template below makes use of both attribute malloc and alloc_size, the declaration of the explicit specialization of the template is diagnosed because it is missing one of the attributes:
template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);
template <>
void* __attribute__ ((malloc)) // missing alloc_size
allocate<void> (size_t);
-Wmissing-bracesโ warns if an aggregate or union initializer is not fully bracketed. In the following example, the initializer forais not fully bracketed, but the one forbis fully bracketed:
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall.
-Wmissing-include-dirs(C, C++, Objective-C, Objective-C++ and Fortran only) โ warns if a user-supplied include directory does not exist. This option is disabled by default for C, C++, Objective-C and Objective-C++. For Fortran, it is partially enabled by default by warning for-Iand-J, only.-Wno-missing-profileโ controls warnings if feedback profiles are missing when using the-fprofile-useoption. This option diagnoses those cases where a new function or a new file is added between compiling with-fprofile-generateand with-fprofile-use, without regenerating the profiles. In these cases, the profile feedback data files do not contain any profile feedback information for the newly added function or file respectively. Also, in the case when profile count data (.gcda) files are removed, GCC cannot use any profile feedback information. In all these cases, warnings are issued to inform you that a profile generation step is due. Ignoring the warning can result in poorly optimized code.-Wno-missing-profilecan be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified.-Wmismatched-deallocโ warns for calls to deallocation functions with pointer arguments returned from from allocations functions for which the former isn't a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of attributemalloc. Unless disabled by the-fno-builtinoption, the standard functionscalloc,malloc,realloc, andfree, as well as the corresponding forms of C++operator newandoperator 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 appear to be guarded by a clause such asif,else,for,switch, orwhile, in which only the first statement is actually guarded after the macro is expanded. For example:
#define DOIT x++; y++
if (c)
DOIT;
will increment y unconditionally, not just when c holds. 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, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.
Also warns if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.
Also warns for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.
For C++ this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:
-Wno-self-move(C++ and Objective-C++ only) โ this one clocks when a value gets moved to itself withstd::move. and like... that move does literally nothing, bestie. it's giving "I did something" but nothing happened ๐ญ
struct T {
...
};
void fn()
{
T t;
...
t = std::move (t);
}
enabled by -Wall ๐ซถ
-Wsequence-pointโ warns about code that might have undefined semantics because it breaks the sequence point rules in the C and C++ standards. ok so this is the messy one, let me explain ๐
The C and C++ standards define the order expressions get evaluated in terms of sequence points โ which are basically a partial ordering between parts of your program: the stuff that runs before the sequence point, and the stuff that runs after it. These happen after a full expression gets evaluated (a full expression = one that isn't part of a bigger expression), after the first operand of &&, ||, ? : or , (the comma operator) gets evaluated, before a function is called (but after its arguments and the expression naming the called function get evaluated), and in certain other places. Other than what the sequence point rules say, the order of evaluation of subexpressions is not specified. and all these rules only describe a partial order, not a total order โ like, if two functions get called in one expression with no sequence point between them, nobody's specifying which one goes first. however!! the standards committee ruled that function calls don't overlap. no cap ๐ฅ
It's also not specified when, between sequence points, modifications to object values actually take effect. programs that depend on that have undefined behavior. the C and C++ standards say: "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored." and if your program breaks those rules? the results on any particular implementation are entirely unpredictable ๐
examples of code with undefined behavior: a = a++;, a[n] = b[n++] and a[i++] = i;. some more complicated cases don't get diagnosed by this option, and it might give you the occasional false positive, but overall it's been found pretty effective at catching this sort of problem โจ
the C++17 standard defines the order of evaluation in more cases: specifically it requires the right-hand side of an assignment to be evaluated before the left-hand side, so the examples above stop being undefined. but this option still warns about them, to help people avoid writing code that's undefined in C and earlier revisions of C++. so it's a "for your own good" situation ๐
the standard is worded confusingly, so there's some debate over what the sequence point rules precisely mean in subtle cases. links to discussions of the problem (including proposed formal definitions) live 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โ don't warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (which is, like, a little scary but ok, your call bestie ๐)-Wreturn-typeโ warn whenever a function is defined with a return type that defaults toint. also warns about anyreturnstatement with no return value in a function whose return type is notvoid(falling off the end of the function body counts as 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, that latter case is accepted without a warning unless -Wpedantic is used. attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function? undefined ๐ญ
Unlike in C, in C++ flowing off the end of a non-void function other than main results in undefined behavior even when the value of the function isn't used. rude but true.
This warning is enabled by default in C++ and by -Wall otherwise.
-Wno-shift-count-negativeโ controls warnings if a shift count is negative. 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. enabled by default.-Wshift-negative-valueโ warn if you're left shifting a negative value. enabled by-Wextrain C99 (and newer) and C++11 to C++17 modes ๐ธ-Wno-shift-overflow,-Wshift-overflow=nโ these two control warnings about left shift overflows. levels below, bestie โฌ๏ธ-Wshift-overflow=1โ this is the warning level of-Wshift-overflowand it's enabled by default in C99 and C++11 modes (and newer). this 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), because signed left shifts always wrap. slay ๐-Wshift-overflow=2โ this 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 is missing 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's adefaultlabel. enabled by-Wallโญ-Wswitch-defaultโ warn whenever aswitchstatement doesn't have adefaultcase. simple as that ๐-Wswitch-enumโ warn whenever aswitchstatement has an index of enumerated type and is missing acasefor one or more of the named codes of that enumeration.caselabels outside the enumeration range also provoke warnings here too. the only difference between-Wswitchand this option: this one warns about an omitted enumeration code even if there's adefaultlabel. so it's the strict one ๐-Wno-switch-boolโ don't warn when aswitchstatement has an index of boolean type and the case values are outside the range of a boolean type. you can suppress this warning by casting the controlling expression to a type other thanbool. like so:
switch ((int) (a == 4))
{
...
}
this warning is enabled by default for C and C++ programs โจ
-Wno-switch-outside-rangeโ controls warnings when aswitchcase has a value outside of its respective type range. enabled by default for C and C++ programs.-Wno-switch-unreachableโ don't warn when aswitchstatement contains statements between the controlling expression and the first case label, which will never be executed. example time:
switch (cond)
{
i = 15;
...
case 5:
...
}
-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:
switch (cond)
{
int i;
...
case 5:
i = 5;
...
}
this warning is enabled by default for C and C++ programs ๐ฆ
-Wsync-nand(C and C++ only) โ warn when the__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions get used. these functions changed semantics in GCC 4.4, so like... watch out ๐-Wtrivial-auto-var-initโ warn when-ftrivial-auto-var-initcan't initialize the automatic variable. a common situation is an automatic variable 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 theunusedattribute. this warning is also enabled by-Wunusedtogether with-Wextra๐-Wunused-but-set-variableโ warn whenever a local variable is assigned to but otherwise unused (aside from its declaration). enabled by-Wall. to suppress it, use theunusedattribute. this warning is also enabled by-Wunused, which is enabled by-Wall. (yes, double-enabled, it's that serious ๐ค)-Wunused-functionโ warn whenever a static function is declared but not defined, or a non-inline static function is unused. enabled by-Wall๐-Wunused-labelโ warn whenever a label is declared but not used. enabled by-Wall. to suppress this warning, use theunusedattribute.-Wunused-local-typedefs(C, Objective-C, C++ and Objective-C++ only) โ warn when a typedef locally defined in a function isn't used. enabled by-Wall๐-Wunused-parameterโ warn whenever a function parameter is unused aside from its declaration. to suppress this warning, use theunusedattribute.-Wno-unused-resultโ don't warn if a caller of a function marked with thewarn_unused_resultattribute doesn't use its return value. the default is-Wunused-result.-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++. enabled by-Wall. to suppress this warning, use theunusedattribute ๐ซถ-Wunused-const-variable,-Wunused-const-variable=nโ bestie, this one yells at you whenever a constant static variable is just sitting there unused aside from its declaration ๐ like it's literally just vibing and contributing nothing. So-Wunused-const-variable=1gets switched on 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.
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.-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. โจ
-Wunused-valueโ warns whenever a statement computes a result that is explicitly not used ๐ like, why did you even compute it then. 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. iykyk ๐
This warning is enabled by -Wall.
-Wunusedโ all the above-Wunusedoptions combined. the whole squad, together ๐ซถ
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. no cap.
-Wuninitializedโ warns 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.
In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const-qualified argument of a built-in function known to read the object is also diagnosed by this warning. (-Wmaybe-uninitialized is issued for ordinary functions.)
If you want to warn about code that uses the uninitialized value of the variable in its own initializer, use the -Winit-self option.
These warnings occur for individual uninitialized elements of structure, union or array variables as well as for variables that are uninitialized as a whole. They do not occur for variables or elements declared volatile. Because these warnings depend on optimization, the exact variables or elements for which there are warnings depend on the precise optimization options and version of GCC used. โญ
Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed. the compiler literally deletes the evidence first ๐
In C++, this warning also warns about using uninitialized objects in member-initializer-lists. For example, GCC warns about b being uninitialized in the following snippet:
struct A {
int a;
int b;
A() : a(b) { }
};
-Wno-invalid-memory-modelโ this option controls warnings for invocations of__atomicBuiltins,__syncBuiltins, and the C11 atomic generic functions with a memory consistency argument that 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, the following code is diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default. ๐
-Wmaybe-uninitializedโ 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 exist some other paths for which the object is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time. "maybe" is doing so much heavy lifting here ๐ญ
In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const-qualified function argument is also diagnosed by this warning. (-Wuninitialized is issued for built-in functions known to read the object.) Annotating the function with attribute access (none) indicates that the argument isn't used to access the object and avoids the warning. cute little escape hatch ๐
These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables.
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 is one example of how this 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 this. To suppress the warning, you need to provide a default case with assert(0) or similar code. GCC is not a mind reader bestie, it needs receipts ๐ง
This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler sees only the calls to setjmp. It cannot know where longjmp will be called; in fact, a signal handler could call it at any point in the code. As a result, you may get a warning even when there is in fact no problem because longjmp cannot in fact be called at the place that would cause a problem. ๐ structural paranoia, honestly
Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn.
This warning is enabled by -Wall or -Wextra.
-Wunknown-pragmasโ warns when a#pragmadirective is encountered that is not understood by GCC ๐ฆ If this command-line option is used, warnings are even issued for unknown pragmas in system header files. This is not the case if the warnings are only enabled by the-Wallcommand-line option. so-Wallis chill about system headers, but this flag is like "no, all of them" ๐-Wno-pragmasโ do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also-Wunknown-pragmas. the "mind your own business" setting ๐-Wno-prio-ctor-dtorโ do not warn if a priority from 0 to 100 is used for constructor or destructor ๐ The use of constructor and destructor attributes allow you to 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 as the compiler reserves priority values between 0--100 for the implementation. so 0โ100 is the compiler's VIP section, stay out of it โจ
-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 does not catch all cases, but does attempt to catch the more common pitfalls. It is included in-Wall. It is equivalent to-Wstrict-aliasing=3.-Wstrict-aliasing=nโ this option is only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way-Oworks.-Wstrict-aliasingis equivalent to-Wstrict-aliasing=3.- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but
-fstrict-aliasingstill breaks the code, as 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. it's giving "snitch about everything and let god sort it out" ๐ - 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. the balanced icon, the main character ๐
- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but
-Wstrict-overflow,-Wstrict-overflow=nโ this option is only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur ๐ Note that it does not warn about all cases where the code might overflow: it only warns about cases where the compiler implements some optimization. Thus this warning depends on the optimization level.
An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is 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โ bestie this one's extra: it also clocks other cases where a comparison gets folded into a constant. Likeabs (x) >= 0โ iconic simplification, but only legit when signed integer overflow is undefined, becauseabs (INT_MIN)overflows right back toINT_MIN, which is literally less than zero ๐ญ. And btw,-Wstrict-overflowwith no level at all is the same as-Wstrict-overflow=2.-Wstrict-overflow=3โ now we're warning about other comparisons getting simplified too, fr fr. Example:x + 1 > 1becomesx > 0. Cute, but we're watching you ๐.-Wstrict-overflow=4โ and now also any simplifications not covered by the cases above. Example:(x * 10) / 5gets simplified tox * 2. Math girlies stay winning ๐ .-Wstrict-overflow=5โ the most dramatic level ๐ฅ. Warns when the compiler shrinks the magnitude of a constant involved in a comparison. Example:x + 2 > ybecomesx + 1 >= y. Heads up though โ this is only reported at the highest warning level because this simplification applies to so many comparisons, so this level gives you a very large number of false positives. Not me getting spammed ๐.-Wstring-compareโ warns on calls tostrcmpandstrncmpwhose result is already determined to be either zero or non-zero in equality tests, because one argument's length is bigger than the size of the array the other one lives in (or bigger than the bound, instrncmp's case). Basically these calls could be mistakes ๐ฉ. Look at this poorstrcmpdown here โ it gets diagnosed because its result is necessarily non-zero no matter what's actually in the arraya:
extern char a[4];
void f (char *d)
{
strcpy (d, "string");
...
if (0 == strcmp (a, d)) // cannot be true
puts ("a and d are the same");
}
Also, -Wstring-compare is enabled by -Wextra โจ.
-Wno-stringop-overflow-Wstringop-overflow-Wstringop-overflow=*type*โ this trio warns for calls to string manipulation functions likememcpyandstrcpythat are determined to overflow the destination buffer ๐ซ๐. The optional argument is one greater than the type of Object Size Checking used to figure out the destination's size. That argument is only meaningful for functions that operate on character arrays โ not for raw memory functions likememcpy, which always use Object Size type-0. This option also warns for calls that specify a size bigger than the largest possible object, or at mostSIZE_MAX / 2bytes. It gives its best results with optimization on, but it can still catch a small subset of simple buffer overflows even without optimization in calls to GCC built-in functions like__builtin_memcpythat correspond to the standard functions. Either way, the option only warns about a subset of the buffer overflows that the corresponding overflow-checking built-ins detect. For example, it flags thestrcpycall below because it copies at least 5 characters (the string"blue", terminating 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โ the-Wstringop-overflow=1option uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting it does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination could be one of several objects, it assumes it's the largest of them. On Linux systems, with optimization enabled at this setting, it warns for the same code as when the_FORTIFY_SOURCEmacro is defined to a non-zero value ๐ธ.-Wstringop-overflow=2โ the-Wstringop-overflow=2option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflows when writing to members of the largest complete objects whose exact size is known. But it does not warn for excessive writes to those same members of unknown objects referenced by pointers, since those pointers may point to arrays with an unknown number of elements ๐คท. This is the default setting of the option.-Wstringop-overflow=3โ the-Wstringop-overflow=3option uses type-two Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option that may result in warnings for safe code โ so like, it will call out your innocent code sometimes ๐ญ.-Wstringop-overflow=4โ the-Wstringop-overflow=4option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to warn. Same energy as-Wstringop-overflow=3: this setting may also result in warnings for benign code ๐.
-Wno-stringop-overreadโ warns for calls to string manipulation functions likememchr, orstrcpy, that are determined to read past the end of the source sequence ๐๐. Also: option-Wstringop-overreadis 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 call to strncat specifies a bound that's less than the length of the source string. So the copy of the source gets truncated, and the call is diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound:
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
Another example: this strncpy call copies into d just the characters before the terminating NUL, without appending the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call gets diagnosed. If you're not expecting a NUL-terminated result, call memcpy instead to avoid the warning:
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
And in this one, the strncpy call uses the size of the destination buffer as the bound. If the source string's length is equal to or greater than that size, the copy won't be NUL-terminated. So yeah, also diagnosed ๐. To avoid it, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL:
void copy (const char *s)
{
char buf[80];
strncpy (buf, s, sizeof buf);
...
}
Now, when a character array is genuinely meant to store a sequence of bytes with no terminating NUL, you can annotate that array with the attribute nonstring to avoid this warning. But heads up bestie: those arrays are not suitable arguments to functions that expect NUL-terminated strings ๐ซ. To help catch accidental misuse of such arrays, GCC issues warnings unless it can prove the use is safe ๐ก๏ธ.
-Wstrict-flex-arraysโ warns about improper usages of flexible array members, according to the level of thestrict_flex_array (level)attribute attached to a structure's trailing array field if that attribute's available โ otherwise according to the level of the option-fstrict-flex-arrays=level.
This option is only effective when level is bigger than 0. Otherwise it gets ignored, with a warning ๐.
- when level=1, warnings get issued for a trailing array reference of a structure that has 2 or more elements, if the trailing array is referenced as a flexible array member.
- when level=2, in addition to level=1, extra warnings get issued for a trailing one-element array reference of a structure, if the array is referenced as a flexible array member.
- when level=3, in addition to level=2, extra warnings get issued for a trailing zero-length array reference of a structure, if the array is referenced as a flexible array member.
-Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc]โ warns for cases where adding an attribute might be a glow-up โจ. The attributes currently supported are listed below.-Wsuggest-attribute=pure-Wsuggest-attribute=const-Wsuggest-attribute=noreturn-Wmissing-noreturn-Wsuggest-attribute=mallocโ these warn about functions that might be candidates for thepure,const,noreturnormallocattributes. The compiler only warns for functions visible in other compilation units, or (in thepureandconstcase) if it can't prove the function returns normally. A function counts as returning normally if it doesn't contain an infinite loop and doesn't 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 improve the accuracy of the analysis ๐.
-Wsuggest-attribute=format,-Wmissing-format-attributeโ bestie, this one points at function pointers that might be candidates forformatattributes. Keyword: might. These are only possible candidates, not absolute ones, okay? ๐ GCC's lil guess is that function pointers withformatattributes that get used in assignment, initialization, parameter passing or return statements should have a correspondingformatattribute in the resulting type. Translating to human: the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have aformatattribute โ otherwise, warning. โจ
GCC also warns about function definitions that might be candidates for format attributes. Again, only possible candidates, not a verdict. GCC guesses that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but that might not always be the case, and some functions for which format attributes are appropriate may not be detected. So it's giving vibes-based matching, not certainty. ๐ฆ
-Wsuggest-attribute=coldโ warns about functions that might be candidates for thecoldattribute. This is based on static detection and generally only warns about functions which always leads to a call to anothercoldfunction โ think wrappers of C++throwor fatal error reporting functions leading toabort. ๐-Walloc-zeroโ warns about calls to allocation functions decorated with attributealloc_sizethat specify zero bytes, including those to the built-in forms of the functionsaligned_alloc,alloca,calloc,malloc, andrealloc. Why do we care? Because the behavior of these functions when called with a zero size differs among implementations (and in the case ofreallochas been deprecated), so relying on it may result in subtle portability bugs and should be avoided. ๐ no cap, don't do it.-Walloc-size-larger-than=<byte-size>โ warns about calls to functions decorated with attributealloc_sizethat attempt 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 the option can be disabled either by specifying byte-size ofSIZE_MAXor more or by-Wno-alloc-size-larger-than. ๐-Wno-alloc-size-larger-thanโ disables the-Walloc-size-larger-than=warnings. The option is equivalent to-Walloc-size-larger-than=SIZE_MAXor larger. ๐-Wallocaโ this option warns on all uses ofallocain the source. all of them. every single one. ๐-Walloca-larger-than=<byte-size>โ warns on calls toallocawith an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits 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 appear to be constrained to the expected range. ๐ญ
For example, a bounded case of alloca could be:
void func (size_t n)
{
void *p;
if (n <= 1000)
p = alloca (n);
else
p = malloc (n);
f (p);
}
In the above example, passing -Walloca-larger-than=1000 would not issue a warning because the call to alloca is known to be at most 1000 bytes. However, if -Walloca-larger-than=500 were passed, the compiler would emit a warning. see, context matters bestie ๐
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. For example:
void func ()
{
void *p = alloca (n);
f (p);
}
If -Walloca-larger-than=500 were passed, the above would trigger a warning, but this time because of the lack of bounds checking. ๐ซถ
Note, that even seemingly correct code involving signed integers could cause a warning:
void func (signed int n)
{
if (n < 500)
{
p = alloca (n);
f (p);
}
}
In the above example, n could be negative, causing a larger than expected argument to be implicitly cast into the alloca call. ๐
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โ disables the-Walloca-larger-than=warnings. The option is equivalent to-Walloca-larger-than=SIZE_MAXor larger. ๐-Warith-conversionโ do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from-Wconversion,-Wfloat-conversion, and-Wsign-conversion. ๐ง
void f (char c, int i)
{
c = c + i; // warns with B<-Wconversion>
c = c + 1; // only warns with B<-Warith-conversion>
}
-Warray-bounds,-Warray-bounds=<n>โ warns about out of bounds subscripts or offsets into arrays. This warning is enabled by-Wall. It is more effective when-ftree-vrpis active (the default for-O2and above) but a subset of instances are issued even without optimization. โญ
By default, the trailing array of a structure will be treated as a flexible array member by -Warray-bounds or -Warray-bounds=<n> if it is declared as either a flexible array member per C99 standard onwards ([]), a GCC zero-length array extension ([0]), or an one-element array ([1]). As a result, out of bounds subscripts or offsets into zero-length arrays or one-element arrays are not warned by default. ๐
You can add the option -fstrict-flex-arrays or -fstrict-flex-arrays=<level> to control how this option treat trailing array of a structure as a flexible array member:
- when level
<=1, no change to the default behavior. - when level
=2, additional warnings will be issued for out of bounds subscripts or offsets into one-element arrays; - when level
=3, in addition to level=2, additional warnings will be issued for out of bounds subscripts or offsets into zero-length arrays. ๐ฆ -Warray-bounds=1โ this is the default warning level of-Warray-boundsand is enabled by-Wall; higher levels are not, and must be explicitly requested.-Warray-bounds=2โ this warning level also warns about the intermediate results of pointer arithmetic that may yield out of bounds values. This warning level may give a larger number of false positives and is deactivated by default. ๐ญ
-Warray-compareโ warns about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;
-Warray-compare is enabled by -Wall. ๐
-Warray-parameter,-Warray-parameter=<n>โ warns about redeclarations of functions involving arguments of array or pointer types of inconsistent kinds or forms, and enables the detection of out-of-bounds accesses to such parameters by warnings such as-Warray-bounds. ๐
If the first function declaration uses the array form the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed by warnings such as -Warray-bounds. At level 1 the warning diagnoses inconsistencies involving array parameters declared using the T[static N] form.
For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one with the keyword static specifies that the array argument must have at least four elements.
void f (int[static 4]);
void f (int[]); // warning (inconsistent array form)
void g (void)
{
int *p = (int *)malloc (4);
f (p); // warning (array too small)
...
}
At level 2 the warning also triggers for redeclarations involving any other inconsistency in array or pointer argument forms denoting array sizes. Pointers and arrays of unspecified bound are considered equivalent and do not trigger a warning. ๐
void g (int*);
void g (int[]); // no warning
void g (int[8]); // warning (inconsistent array bound)
-Warray-parameter=2 is included in -Wall. The -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments. ๐ธ
-Wattribute-alias=<n>,-Wno-attribute-aliasโ warns about declarations using thealiasand similar attributes whose target is incompatible with the type of the alias. ๐ซถ-Wattribute-alias=1โ the default warning level of the-Wattribute-aliasoption diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs.-Wattribute-alias=2โ at this level-Wattribute-aliasalso diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the-Wmissing-attributesoption, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive. ๐
โฆand the attributes it's clocking are alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice. Bestie that's the whole guest list ๐
-Wattribute-alias is literally just -Wattribute-alias=1, and that's the default, no cap. Wanna mute it? Either -Wno-attribute-alias or -Wattribute-alias=0, pick your fighter โจ
-Wbidi-chars=[none|unpaired|any|ucn]โ okay this one is kinda spooky ๐ป it warns you about possibly-misleading UTF-8 bidirectional control characters chilling in comments, string literals, character constants, and identifiers. These little gremlins can flip left-to-right writing direction into right-to-left (and vice versa), which causes chaos between the logical order and the visual order. It can be actually dangerous โ like, it might look like a chunk of code isn't commented out when it fr fr is. ๐ญ
GCC supports three levels of this warning. The default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the whole thing off. -Wbidi-chars=any warns about any use of bidirectional control characters. ๐ฉ
By default this warning does not warn about UCNs. But you can turn that checking on with -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. And heads up: -Wbidi-chars=ucn is valid, and it's equivalent to -Wbidi-chars=unpaired,ucn โ but only if you didn't already specify a previous -Wbidi-chars=any. iykyk ๐ง
-Wbool-compareโ warns when a boolean expression gets compared with an integer value that isn'ttrue/false. So like, this comparison is always false, bestie, always:
int n = 5;
...
if ((n > 1) == 2) { ... }
Enabled by -Wall. โ
-Wbool-operationโ warns about suspicious operations on boolean-typed expressions. Bitwise negation of a boolean? Very likely a bug in your program, ngl ๐. For C, this one 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.) ๐ซ
Enabled by -Wall.
-Wduplicated-branchesโ warns when an if-else has identical branches. It catches cases like:
if (p != NULL)
return 0;
else
return 0;
It does not warn when both branches contain just a null statement. It also warns for conditional operators:
int i = x ? *p : *p;
like girl why ๐ญ both sides are the same thing.
-Wduplicated-condโ warns about duplicated conditions in an if-else-if chain. For instance, it'll warn on this:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
ma'am you already checked that ๐
-Wframe-addressโ warns when__builtin_frame_addressor__builtin_return_addressis called with an argument greater than 0. Those calls may return indeterminate values or straight-up crash the program ๐ฌ. Included in-Wall.-Wno-discarded-qualifiers(C and Objective-C only) โ don't warn if type qualifiers on pointers are being discarded. Typically the compiler yells when aconst char *variable gets passed to a function that takes achar *parameter. This option suppresses that warning. ๐ซถ-Wno-discarded-array-qualifiers(C and Objective-C only) โ don't warn if type qualifiers on arrays that are pointer targets are being discarded. Typically the compiler warns when aconst int (*)[]variable gets passed to a function taking anint (*)[]parameter. Use this to suppress it.-Wno-incompatible-pointer-types(C and Objective-C only) โ don't warn when there's a conversion between pointers with incompatible types. This one's for cases that-Wno-pointer-signdoesn't cover โ that one handles pointer argument passing or assignment with different signedness.-Wno-int-conversion(C and Objective-C only) โ don't warn about incompatible integer-to-pointer and pointer-to-integer conversions. Note this is about implicit conversions; for explicit ones you'd reach for-Wno-int-to-pointer-castand-Wno-pointer-to-int-cast. ๐-Wzero-length-boundsโ warns about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined. ๐จ
For example, the first two stores in function bad are diagnosed because the array elements overlap the subsequent members b and c. The third store is diagnosed by -Warray-bounds because it's beyond the bounds of the enclosing object:
struct X { int a[0]; int b, c; };
struct X x;
void bad (void)
{
x.a[0] = 0; // -Wzero-length-bounds
x.a[1] = 1; // -Wzero-length-bounds
x.a[2] = 2; // -Warray-bounds
}
Option -Wzero-length-bounds is enabled by -Warray-bounds. โจ
-Wno-div-by-zeroโ don't warn about compile-time integer division by zero. Floating-point division by zero is not warned about, since it can be a totally legitimate way of obtaining infinities and NaNs. ๐-Wsystem-headersโ print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, based on the assumption that they usually don't indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. However โ note that using-Walltogether with this option does not warn about unknown pragmas in system headers. For that,-Wunknown-pragmasmust also be used. gotcha ๐ซก-Wtautological-compareโ warns if a self-comparison always evaluates to true or false. It catches all kinds 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. ๐
Enabled by -Wall.
-Wtrampolinesโ warns about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code created at run time on the stack when the address of a nested function is taken, and it's used to call the nested function indirectly. For some targets it's made up of data only and thus needs no special treatment. But for most targets it's made up of code, and thus requires the stack to be made executable for the program to work properly. ๐ณ no cap, that's a whole security vibe.-Wfloat-equalโ warns if floating-point values are used in equality comparisons. ๐ฉ
The idea behind this: sometimes it's convenient (for the programmer) 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 the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a whole different problem). 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. periodt ๐
-Wtraditional(C and Objective-C only) โ warns about certain constructs that behave differently in traditional C vs ISO C. Also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. Buckle up bestie, it's a list ๐- Macro parameters that appear within string literals in the macro body. In traditional C, macro replacement takes place within string literals, but in ISO C it does not.
- In traditional C, some preprocessor directives didn't exist. Traditional preprocessors only considered a line to be a directive if the
#appeared in column 1 on the line. So-Wtraditionalwarns about directives that traditional C understands but ignores because the#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 that 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.
- Prototype conversions between fixed/floating-point values and vice versa โ okay so if a prototype makes a type conversion happen that wouldnโt happen without the prototype, thatโs a whole vibe check fail ๐ญ. 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 โ yes this warns about that, but it intentionally does not fire for prototype declarations or variadic functions, because these ISO C features show up in your code when you use 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.
- Use of ISO C style function definitions โ yes this warns about that, but it intentionally does not fire for prototype declarations or variadic functions, because these ISO C features show up in your code when you use libibertyโs traditional C compatibility macros,
-Wtraditional-conversion(C and Objective-C only) โ warns if a prototype causes a type conversion that is 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 the same as the default promotion.-Wdeclaration-after-statement(C and Objective-C only) โ 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. This means that-Wno-shadow=localand-Wno-shadow=compatible-localare ignored when-Wshadowis used. Same as-Wshadow=global.-Wno-shadow-ivar(Objective-C only) โ do not warn whenever a local variable shadows an instance variable in an Objective-C method ๐.-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 is 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 the option can be disabled either by specifying byte-size ofSIZE_MAXor more or by-Wno-larger-than.
Also warn for calls to bounded functions such as memchr or strnlen that specify a bound greater than the largest possible object, which is PTRDIFF_MAX bytes by default. These warnings can only be disabled by -Wno-larger-than.
-Wno-larger-thanโ disables-Wlarger-than=warnings ๐. The option is equivalent to-Wlarger-than=SIZE_MAXor larger.-Wframe-larger-than=byte-sizeโ warns if the size of a function frame exceeds byte-size ๐. The computation done to determine the stack frame size is approximate and not conservative. The actual requirements may be somewhat greater than byte-size even if you do not get a warning. In addition, any space allocated viaalloca, variable-length arrays, or related constructs is not included by the compiler when determining whether or not to issue a warning.
-Wframe-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-frame-larger-than.
-Wno-frame-larger-thanโ disables-Wframe-larger-than=warnings ๐. The option is equivalent to-Wframe-larger-than=SIZE_MAXor larger.-Wfree-nonheap-objectโ warns when attempting to deallocate an object that was either not allocated on the heap, or by using a pointer that was not returned from a prior call to the corresponding allocation function ๐ญ. For example, because the call tostpcpyreturns a pointer to the terminating nul character and not to the beginning of the object, the call tofreebelow is diagnosed:
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is included in -Wall ๐.
-Wstack-usage=byte-sizeโ warns if the stack usage of a function might exceed byte-size ๐ธ. The computation done to determine the stack usage is conservative. Any space allocated viaalloca, variable-length arrays, or related constructs is included by the compiler when determining whether or not to issue a warning.
The message is in keeping with the output of -fstack-usage โจ.
- If the stack usage is fully static but exceeds the specified amount, itโs:
warning: stack usage is 1120 bytes
- If the stack usage is (partly) dynamic but bounded, itโs:
warning: stack usage might be 1648 bytes
- If the stack usage is (partly) dynamic and not bounded, itโs:
warning: stack usage might be unbounded
-Wstack-usage=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-stack-usage.
-Wno-stack-usageโ disables-Wstack-usage=warnings ๐ . The option is equivalent to-Wstack-usage=SIZE_MAXor larger.-Wunsafe-loop-optimizationsโ warns if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices ๐. With-funsafe-loop-optimizationswarn if the compiler makes such assumptions.-Wno-pedantic-ms-format(MinGW targets only) โ when used in combination with-Wformatand-pedanticwithout GNU extensions, this option disables the warnings about non-ISOprintf/scanfformat width specifiersI32,I64, andIused on Windows targets, which depend on the MS runtime ๐.-Wpointer-arithโ warns about anything that depends on the โsize ofโ a function type or ofvoid๐ฅ. GNU C assigns these types a size of 1, for convenience in calculations withvoid *pointers and pointers to functions. In C++, warn also when an arithmetic operation involvesNULL. This warning is also enabled by-Wpedantic.-Wno-pointer-compareโ do not warn if a pointer is compared with a zero character constant ๐. This usually means that the pointer was meant to be dereferenced. For example:
const char *p = foo ();
if (p == '\0')
return 42;
Note that the code above is invalid in C++11 ๐.
This warning is enabled by default โจ.
-Wtsanโ warns about unsupported features in ThreadSanitizer ๐ฆ. ThreadSanitizer does not supportstd::atomic_thread_fenceand can report false positives.
This warning is enabled by default ๐.
-Wtype-limitsโ warns if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions ๐ . For example, warn if an unsigned variable is compared against zero with<or>=. This warning is also enabled by-Wextra.-Wabsolute-value(C and Objective-C only) โ warns for calls to standard functions that compute the absolute value of an argument when a more appropriate standard function is available ๐ธ. For example, callingabs(3.14)triggers the warning because the appropriate function to call to compute the absolute value of a double argument isfabs. The option also triggers warnings when the argument in a call to such a function has an unsigned type. This warning can be suppressed with an explicit type cast and it is also enabled by-Wextra.-Wcomment,-Wcommentsโ warns whenever a comment-start sequence/*appears in a/*comment, or whenever a backslash-newline appears in a//comment ๐ญ. This warning is enabled by-Wall.-Wtrigraphsโ warns if any trigraphs are encountered that might change the meaning of the program ๐ซถ. Trigraphs within comments are not warned about, except those that would form escaped newlines.
This option is implied by -Wall. If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs.
-Wundefโ warns if an undefined identifier is evaluated in an#ifdirective โจ. Such identifiers are replaced with zero.-Wexpansion-to-definedโ warns wheneverdefinedis encountered in the expansion of a macro (including the case where the macro is expanded by an#ifdirective) ๐. Such usage is not portable. This warning is also enabled by-Wpedanticand-Wextra.-Wunused-macrosโ warns about macros defined in the main file that are unused ๐. A macro is used if it is expanded or tested for existence at least once. The preprocessor also warns if the macro has not been used at the time it is redefined or undefined.
Built-in macros, macros defined on the command line, and macros defined in include files are not warned about. slay, they get a pass ๐
Heads up bestie: if a macro is actually used, but only used in 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, for example, 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"#else"or an"#endif"are followed by text. This sometimes happens in older programs with code of the form
#if FOO
...
#else FOO
...
#endif FOO
The second and third "FOO" should be in comments. This warning is on by default. iykyk
-Wbad-function-cast(C and Objective-C only) โ warn when a function call is cast to a non-matching type. For example, warn if a call to a function returning an integer type is cast to a pointer type. sir that is not the same thing ๐ญ-Wc90-c99-compat(C and Objective-C only) โ warn about features not present in ISO C90, but present in ISO C99. For instance, warn about use of variable length arrays,"long long"type,"bool"type, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows"__extension__". time-travel vibes, but backwards ๐ฐ๏ธ-Wc99-c11-compat(C and Objective-C only) โ warn about features not present in ISO C99, but present in ISO C11. For instance, warn about use of anonymous structures and unions,"_Atomic"type qualifier,"_Thread_local"storage-class specifier,"_Alignas"specifier,"Alignof"operator,"_Generic"keyword, 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) โ warn about features not present in ISO C11, but present in ISO C2X. For instance, warn 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__". the future is now and it's judging your old code โจ-Wc++-compat(C and Objective-C only) โ warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from"void *"to a pointer to non-"void"type. caught in 4K crossing the language border ๐ฆ-Wc++11-compat(C++ and Objective-C++ only) โ warn 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) โ warn 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) โ warn 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) โ warn about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. This warning is enabled by-Wall. the glow-up timeline continues ๐-Wno-c++11-extensions(C++ and Objective-C++ only) โ do not warn about C++11 constructs in code being compiled using an older C++ standard. Even without this option, some C++11 constructs will only be diagnosed if-Wpedanticis used.-Wno-c++14-extensions(C++ and Objective-C++ only) โ do not warn about C++14 constructs in code being compiled using an older C++ standard. Even without this option, some C++14 constructs will only be diagnosed if-Wpedanticis used.-Wno-c++17-extensions(C++ and Objective-C++ only) โ do not warn about C++17 constructs in code being compiled using an older C++ standard. Even without this option, some C++17 constructs will only be diagnosed if-Wpedanticis used.-Wno-c++20-extensions(C++ and Objective-C++ only) โ do not warn about C++20 constructs in code being compiled using an older C++ standard. Even without this option, some C++20 constructs will only be diagnosed if-Wpedanticis used.-Wno-c++23-extensions(C++ and Objective-C++ only) โ do not warn about C++23 constructs in code being compiled using an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if-Wpedanticis used. five of these in a row, she ate ๐-Wcast-qualโ warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a"const char *"is cast to an ordinary"char *". literally stripping a qualifier, rude ๐
Also warn when making a cast that introduces a type qualifier in an unsafe way. For example, casting "char **" to "const char **" is unsafe, as in this example:
/* p is char ** value. */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK. */
*q = "string";
/* Now char** pointer points to read-only memory. */
**p = 'b';
-Wcast-alignโ warn whenever a pointer is cast such that the required alignment of the target is increased. For 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 check, bestie ๐-Wcast-align=strictโ warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a"char *"is cast to an"int *"regardless of the target machine. no exceptions, we're not playing ๐-Wcast-function-typeโ warn when a function pointer is cast to an incompatible function pointer. In a cast involving function types with a variable argument list only the types of initial arguments that are provided are considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are ignored, like"int"vs."long"on ILP32 targets. Likewise type qualifiers are ignored. The function type"void (*) (void)"is special and matches everything, which can be used to suppress this warning. In a cast involving pointer to member types this warning warns whenever the type cast is changing the pointer to member type. This warning is enabled by-Wextra. "void (*) (void)" is the main character that gets along with everyone ๐ซถ-Wwrite-stringsโ when compiling C, give 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 have been very careful about using"const"in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make-Wallrequest these warnings. ngl, that last line is such a mood ๐ญ
When compiling C++, warn about the deprecated conversion from string literals to "char *". This warning is enabled by default for C++ programs.
-Wclobberedโ warn for variables that might be changed by"longjmp"or"vfork". This warning is also enabled by-Wextra. your variable got jump-scared ๐-Wno-complain-wrong-langโ by default, language front ends complain when a command-line option is valid, but not applicable to that front end. This may be disabled with-Wno-complain-wrong-lang, which is mostly useful when invoking a single compiler driver for multiple source files written in different languages, for example:
$ g++ -fno-rtti a.cc b.f90
The driver g++ invokes the C++ front end to compile a.cc and the Fortran front end to compile b.f90. The latter front end diagnoses
f951: Warning: command-line option '-fno-rtti' is valid for
C++/D/ObjC++ but not for Fortran
which may be disabled with -Wno-complain-wrong-lang. mixing C++ and Fortran in one command is giving chaotic group project energy ๐
-Wconversionโ warn 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)". Do not warn for explicit casts like"abs ((int) x)"and"ui = (unsigned) -1", or if the value is not changed by the conversion like in"abs (2.0)". Warnings about conversions between signed and unsigned integers can be disabled by using-Wno-sign-conversion.
For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to "void", the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.
Warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion. implicit conversions are lowkey sneaky, keep an eye on them ๐
-Wdangling-elseโ warn about constructions where there may be confusion to which"if"statement an"else"branch belongs. Here is an example of such a case:
{
if (a)
if (b)
foo ();
else
bar ();
}
In C/C++, every "else" branch belongs to the innermost possible "if" statement, which in this example is "if (b)". This is often not what the programmer expected, as illustrated in the above example by indentation the programmer chose. When there is the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost "if" statement so there is 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. the braces are the boundaries bestie, set them ๐
-Wdangling-pointer-Wdangling-pointer=nโ okay bestie, this one's a whole vibe check on pointers (or C++ references) to objects with automatic storage duration that you're out here using after their lifetime has ended ๐. That includes local variables declared in nested blocks, compound literals, and other unnamed temporary objects. It also warns you about stashing the address of such objects in escaped pointers. The warning is enabled at all optimization levels, but ngl it may yield different results with optimization than without.
-Wdangling-pointer=1
At level 1 the warning diagnoses only unconditional uses of dangling pointers. For example:
int f (int c1, int c2, x)
{
char *p = strchr ((char[]){ c1, c2 }, c3);
// warning: dangling pointer to a compound literal
return p ? *p : 'x';
}
In the following function the store of the address of the local variable x in the escaped pointer *p also triggers the warning.
void g (int **p)
{
int x = 7;
// warning: storing the address of a local variable in *p
*p = &x;
}
-Wdangling-pointer=2
At level 2, in addition to unconditional uses the warning also diagnoses conditional uses of dangling pointers.
For example, because the array a in the following function is out of scope when the pointer s that was set to point is used, the warning triggers at this level.
void f (char *s)
{
if (!s)
{
char a[12] = "tmpname";
s = a;
}
// warning: dangling pointer to a may be used
strcat (s, ".tmp");
...
}
-Wdangling-pointer=2 is included in -Wall. slay, free coverage ๐ซถ
-Wdate-timeโ warns when macros__TIME__,__DATE__or__TIMESTAMP__show up, because they might prevent bit-wise-identical reproducible compilations ๐ญ. Your builds can't be twins if the timestamps keep changing, yk?-Wempty-bodyโ warns if an empty body occurs in anif,elseordo whilestatement. This warning is also enabled by-Wextra.-Wno-endif-labelsโ do not warn about stray tokens after#elseand#endif. That's it, that's the whole thing โจ-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.-Wenum-int-mismatch(C and Objective-C only) โ warns about mismatches between an enumerated type and an integer type in declarations. For example:
enum E { l = -1, z = 0, g = 1 };
int foo(void);
enum E foo(void);
In C, an enumerated type is compatible with char, a signed integer type, or an unsigned integer type. However, since the choice of the underlying type of an enumerated type is implementation-defined, such mismatches may cause portability issues ๐. In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat.
-Wjump-misses-init(C, Objective-C only) โ warns if agotostatement or aswitchstatement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized ๐. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option.
-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 is also enabled by-Wextra.-Wsign-conversionโ warns for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning ๐. 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.-Wsizeof-array-divโ warns about divisions of twosizeofoperators when the first one is applied to an array and the divisor does not equal the size of the array element. In such a case, the computation will not yield the number of elements in the array, which is likely what the user intended ๐ญ. This warning warns e.g. about
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall.
-Wsizeof-pointer-divโ warns for suspicious divisions of twosizeofexpressions that divide the pointer size by the element size, which is the usual way to compute the array size but won't work out correctly with pointers. This warning warns e.g. aboutsizeof (ptr) / sizeof (ptr[0])ifptris not an array, but a pointer. This warning is enabled by-Wall. classic gotcha fr fr ๐-Wsizeof-pointer-memaccessโ warns for suspicious length parameters to certain string and memory built-in functions if the argument usessizeof. This warning triggers for example formemset (ptr, 0, sizeof (ptr));ifptris not an array, but a pointer, and suggests a possible fix, or aboutmemcpy (&foo, ptr, sizeof (&foo));.
-Wsizeof-pointer-memaccess also warns about calls to bounded string copy functions like strncat or strncpy that specify as the bound a sizeof expression of the source array. For example, in the following function the call to strncat specifies the size of the source string as the bound. That is almost certainly a mistake and so the call is diagnosed.
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
The -Wsizeof-pointer-memaccess option is enabled by -Wall.
-Wno-sizeof-array-argumentโ do not warn when thesizeofoperator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs.-Wmemset-elt-sizeโ warns for suspicious calls to thememsetbuilt-in function, if the first argument references an array, and the third argument is a number equal to the number of elements, but not equal to the size of the array in memory ๐คจ. This indicates that the user has omitted a multiplication by the element size. This warning is enabled by-Wall.-Wmemset-transposed-argsโ warns for suspicious calls to thememsetbuilt-in function where the second argument is not zero and the third argument is zero. For example, the callmemset (buf, sizeof buf, 0)is diagnosed becausememset (buf, 0, sizeof buf)was meant instead ๐. The diagnostic is only emitted if the third argument is a literal zero. Otherwise, if it is an expression that is folded to zero, or a cast of zero to some type, it is far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by-Wall.-Waddressโ warns about suspicious uses of address expressions. These include comparing the address of a function or a declared object to the null pointer constant such as in
void f (void);
void g (void)
{
if (!f) // warning: expression evaluates to false
abort ();
}
comparisons of a pointer to a string literal, such as in
void f (const char *x)
{
if (x == "abc") // warning: expression evaluates to false
puts ("equal");
}
and tests of the results of pointer addition or subtraction for equality to null, such as in
void f (const int *p, int i)
{
return p + i == NULL;
}
Such uses typically indicate a programmer error: the address of most functions and objects necessarily evaluates to true (the exception are weak symbols), so their use in a conditional might indicate missing parentheses in a function call or a missing dereference in an array expression ๐. The subset of the warning for object pointers can be suppressed by casting the pointer operand to an integer type such as intptr_t or uintptr_t. Comparisons against string literals result in unspecified behavior and are not portable, and suggest the intent was to call strcmp. The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress warning is enabled by -Wall.
-Wno-address-of-packed-memberโ do not warn when the address of packed member of struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default.-Wlogical-opโ warns about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected. Also warns when the operands of a logical operator are the same:
extern int a;
if (a < 0 && a < 0) { ... }
like bestieโฆ that's the same check twice ๐ญ
-Wlogical-not-parenthesesโ warns about logical not used on the left hand side operand of a comparison. This option does not warn if the right operand is considered to be a boolean expression. Its purpose is to detect suspicious code like the following:
int a;
...
if (!a > 1) { ... }
Okay so you can hush that warning by wrapping the LHS in parentheses, like this:
if ((!a) > 1) { ... }
This warning is enabled by -Wall.
-Waggregate-returnโ Warn 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.) like, noted, bestie ๐-Wno-aggressive-loop-optimizationsโ Warn if in a loop with constant number of iterations the compiler detects undefined behavior in some statement during one or more of the iterations. compiler said โI saw what you did thereโ ๐ญ-Wno-attributesโ Do not warn if an unexpected"__attribute__"is used, such as unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes. so it mutes the vibe check, not the actual errors, got it
Additionally, using -Wno-attributes=, it is possible to suppress warnings about unknown scoped attributes (in C++11 and C2X). For example, -Wno-attributes=vendor::attr disables warning about the following declaration:
[[vendor::attr]] void f();
It is also possible to disable warning about all attributes in a namespace using -Wno-attributes=vendor:: which prevents warning about both of these declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Note that -Wno-attributes= does not imply -Wno-attributes. not me thinking they were the same thing ๐
-Wno-builtin-declaration-mismatchโ Warn if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that does not include a prototype is called with arguments whose promoted types do not match those expected by the function. When-Wextrais specified, also warn when a built-in function that takes arguments is declared without a prototype. The-Wbuiltin-declaration-mismatchwarning is enabled by default. To avoid the warning include the appropriate header to bring the prototypes of built-in functions into scope.
For example, the call to memset below is diagnosed by the warning because the function expects a value of type size_t as its argument but the type of 32 is int. With -Wextra, the declaration of the function is diagnosed as well.
extern void* memset ();
void f (void *d)
{
memset (d, '\0', 32);
}
header files really said โinclude me or catch these warningsโ ๐ญ
-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__. macro glow-up, no questions asked โจ-Wstrict-prototypes(C and Objective-C only) โ Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration that specifies the argument types.) old-school vibes but make it typed-Wold-style-declaration(C and Objective-C only) โ Warn for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers likestaticare not the first things in a declaration. This warning is also enabled by-Wextra. the C Standard said โmove,staticgoes firstโ ๐-Wold-style-definition(C and Objective-C only) โ Warn if an old-style function definition is used. A warning is given even if there is a previous prototype. A definition using()is not considered an old-style definition in C2X mode, because it is equivalent to(void)in that case, but is considered an old-style definition for older standards. standards really be moving the goalposts, fr fr-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. K&R said โtrust meโ and the compiler said โabsolutely notโ ๐ซถ
-Wmissing-prototypes(C and Objective-C only) โ Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. This option is not valid for C++ because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. Use-Wmissing-declarationsto detect missing declarations in C++. prototype bestie check ๐-Wmissing-declarationsโ Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations; use-Wmissing-prototypesto detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces. the header file said โyou forgot to introduce meโ ๐ญ-Wmissing-field-initializersโ Warn if a structureโs initializer has some fields missing. For example, the following code causes such a warning, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so the following modification does not trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
In C this option does not warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
Likewise, in C++ this option does not warn about the empty { } initializer, for example:
struct s { int f, g, h; };
s x = { };
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers. selective hearing, but for warnings ๐
-Wno-missing-requiresโ By default, the compiler warns about a concept-id appearing as a C++20 simple-requirement:
bool satisfied = requires { C<T> };
Here satisfied will be true if C<T> is a valid expression, which it is for all T. Presumably the user meant to write
bool satisfied = requires { requires C<T> };
so satisfied is only true if concept C is satisfied for type T.
This warning can be disabled with -Wno-missing-requires. bestie really forgot the second requires and the compiler noticed ๐ญ
-Wno-missing-template-keywordโ The member access tokens.,->and::must be followed by the"template"keyword if the parent object is dependent and the member being named is a template.
template <class X>
void DoStuff (X x)
{
x.template DoSomeOtherStuff<X>(); // Good.
x.DoMoreStuff<X>(); // Warning, x is dependent.
}
In rare cases it is possible to get false positives. To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:
void NotATemplate (my_class t)
{
int N = 5;
bool test = t.m < N > (0); // Treated as a template.
test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}
This warning can be disabled with -Wno-missing-template-keyword. parentheses are the original โno thoughts just vibesโ fix ๐
-Wno-multicharโ Do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the userโs code, as they have implementation-defined values, and should not be used in portable code. implementation-defined values said โdonโt put me in portable codeโ ๐-Wnormalized=[none|id|nfc|nfkc]โ In ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. To avoid confusion, the ISO 10646 standard sets out some normalization rules which when applied ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized; this option controls that warning.
There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized.
Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, thereโs no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default.
You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. LITERALLY impossible to see. not me being dramatic, thatโs the manpage ๐ญ
Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly. confusable characters are the original catfish ๐
-Wno-attribute-warningโ Do not warn about usage of functions declared with"warning"attribute. By default, this warning is enabled.-Wno-attribute-warningcan be used to disable the warning or-Wno-error=attribute-warningcan be used to disable the error when compiled with-Werrorflag. warning about a warning? iconic behavior, honestly-Wno-deprecatedโ Do not warn about usage of deprecated features. let them live their deprecated little life ๐ฆ-Wno-deprecated-declarationsโ Do not warn about uses of functions, variables, and types marked as deprecated by using the"deprecated"attribute. deprecated but make it quiet ๐คซ-Wno-overflowโ Do not warn about compile-time overflow in constant expressions. math said โoverflowโ and you said โnot todayโ ๐-Wno-odrโ lowkey the compiler will call out One Definition Rule violations while it's doing link-time optimization. It's on by default, so like, it's already watching ๐-Wopenacc-parallelismโ warns you when your OpenACC parallelism choices are giving "could be better, bestie" energy. Potentially suboptimal = it's not mad, it's just disappointed ๐ซถ-Wopenmp-simdโ fires when the vectorizer cost model straight-up overrides the OpenMPsimddirective you set. Rude tbh. If you wanna loosen the cost model, the-fsimd-cost-model=unlimitedoption is right there โจ-Woverride-init(C and Objective-C only) โ warns you when a field that was initialized and has no side effects gets overridden by your designated initializers. Like, why did you even write the first one ๐
This one is folded into -Wextra. Want all the other -Wextra goodies but not this one? Just do -Wextra -Wno-override-init. Problem solved ๐
-Wno-override-init-side-effects(C and Objective-C only) โ the opposite vibe: don't warn when an initialized field with side effects gets overridden via designated initializers. This warning is enabled by default ๐ฅ-Wpackedโ warns when a struct gets thepackedattribute but the attribute literally changes nothing about the layout or size. Those structs can end up mis-aligned for basically zero benefit. Case in point: here,f.xinsidestruct baris misaligned even thoughstruct baritself doesn't 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โ story time ๐ง the GCC 4.1, 4.2 and 4.3 series ignore thepackedattribute on bit-fields of typechar. That got fixed in GCC 4.4, but the fix can shift your structure layout around. GCC tells you when the offset of such a field changed in GCC 4.4. For example, there's no longer 4 bits of padding between fieldaandbin this struct:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to turn it off.
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warns when a struct field with explicitly specified alignment, sitting inside a packed struct or union, ends up misaligned. So onstruct Sbelow you'd get something likewarning: alignment 1 of 'struct S' is less than 8:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
struct S8 s8;
};
This warning is enabled by -Wall.
-Wpaddedโ warns when padding sneaks into a struct, whether it's there to align an element or to align the whole struct. Sometimes you can rearrange the fields to shrink the padding and make the struct smaller โ so this is basically a free glow-up hint ๐-Wredundant-declsโ warns if literally anything gets declared more than once in the same scope, even in the cases where the double declaration is valid and changes absolutely nothing. Redundant = not the main character ๐ธ-Wrestrictโ warns when an object referenced by arestrict-qualified parameter (or, in C++, a__restrict-qualified parameter) gets aliased by another argument, or when copies between such objects overlap. Example: thisstrcpycall is trying to truncate the string by replacing its first characters with the last four โ but because the call writes the terminating NUL intoa[4], the copies overlap and the call gets diagnosed:
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
-Wrestrict catches some simple-overlap instances even with no optimization, but it's at its best at -O2 and above. It's included in -Wall.
-Wnested-externs(C and Objective-C only) โ warns if anexterndeclaration shows up inside a function. Nested externs, in this economy? ๐ญ-Winlineโ warns when a function declaredinlinedoesn't actually get inlined. Even with this option on, the compiler stays quiet about failures to inline functions declared in system headers.
The compiler runs a whole bunch of heuristics to decide whether to inline something โ it factors in the size of the function being inlined, and how much inlining has already happened in the current function. So like, seemingly tiny changes in your source can make -Winline warnings appear or vanish out of nowhere. It's giving chaos ๐ฆ
-Winterference-sizeโ warns about using C++17'sstd::hardware_destructive_interference_sizewithout specifying its value via--param destructive-interference-size. It also warns about questionable values for that option.
This variable is meant for controlling class layout, so you can dodge false sharing in concurrent code:
struct independent_fields {
alignas(std::hardware_destructive_interference_size)
std::atomic<int> one;
alignas(std::hardware_destructive_interference_size)
std::atomic<int> two;
};
Here one and two are meant to be far enough apart that storing to one won't force accesses to the other to reload the cache line ๐ฅ
By default, --param destructive-interference-size and --param constructive-interference-size get set based on whatever -mtune option is active โ typically the L1 cache line size for that particular target CPU, and sometimes a range if you're tuning for a generic target. So every translation unit that depends on ABI compatibility for these variables has to be compiled with the same -mtune (or -mcpu). No mixing, bestie.
If ABI stability matters to you โ say, the use is in a header for a library โ you should probably not use the hardware interference size variables at all. Alternatively, you can force a particular value with --param.
If you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can kill the warning with -Wno-interference-size โจ
-Wint-in-bool-contextโ warns about suspicious use of integer values where boolean values are expected. Think conditional expressions (?:) using non-boolean integer constants in boolean context, likeif (a <= b ? 2 : 3). Or left shifting signed integers in boolean context, likefor (a = 0; 1 << a; a++);. Same deal for all kinds of multiplications regardless of data type. Enabled by-Wall๐-Wno-int-to-pointer-castโ suppresses warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error.Wint-to-pointer-castis enabled by default.-Wno-pointer-to-int-cast(C and Objective-C only) โ suppresses warnings from casts from a pointer to an integer type of a different size.-Winvalid-pchโ warns if a precompiled header is chillin' in the search path but can't be used. It's there, it's just not serving ๐-Winvalid-utf8โ warns if an invalid UTF-8 character is found. This one's on by default for C++23 if-finput-charset=UTF-8is used, and it gets turned into an error with-pedantic-errorsโญ-Wno-unicodeโ don't diagnose invalid forms of delimited or named escape sequences that get treated as separate tokens.Wunicodeis enabled by default.-Wlong-longโ warns if thelong longtype is used. This gets enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. Wanna silence it?-Wno-long-long๐-Wvariadic-macrosโ warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. Enabled by either-Wpedanticor-Wtraditional. To inhibit the warning messages, use-Wno-variadic-macros.-Wno-varargsโ don't warn about questionable usage of the macros used to handle variable arguments, likeva_start. These warnings are enabled by default.-Wvector-operation-performanceโ warns when a vector operation isn't implemented through the SIMD capabilities of the architecture. Mainly your go-to for performance tuning. A vector operation can be implemented:- "piecewise" โ the scalar operation is performed on every vector element
- "in parallel" โ the vector operation uses scalars of 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. Teamwork ๐ซถ-Wvla-larger-than=byte-sizeโ with this on, the compiler warns about declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that lets the array size exceed byte-size bytes. Works similarly to how-Walloca-larger-than=byte-sizeworks, except, y'know, with variable-length arrays.
Heads up: GCC may optimize small variable-length arrays of a known value into plain arrays, so the warning might not fire for those ones.
-Wvla-larger-than=PTRDIFF_MAX is enabled by default, but it's typically only effective when -ftree-vrp is active (which is the 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.-Wvla-parameterโ warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and it enables detection of out-of-bounds accesses to such parameters via warnings like-Warray-bounds๐
If the first function declaration uses the VLA form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function, and the maximum number of elements accessed by it. Fail to provide arguments of sufficient size, or access more than the maximum number of elements, and you may get diagnosed ๐
So like, for example, the warning pops off for these redeclarations โ because the first one lets you pass an array of literally any size to f, and then the second one is like "no bestie, that array argument needs at least n elements." Plus, if you call f and the VLA bound parameter you hand it is bigger than the actual VLA bound? Yeah, that warns too. ๐
void f (int n, int[n]);
// warning: argument 2 previously declared as a VLA
void f (int, int[]);
void g (int n)
{
if (n > 4)
return;
int a[n];
// warning: access to a by f may be out of bounds
f (sizeof a, a);
...
}
-Wvla-parameter is included in -Wall. And the -Warray-parameter option triggers warnings for similar problems but with ordinary array arguments (iykyk). โจ
-Wvolatile-register-varโ warns you if a register variable is declaredvolatile. Lowkey important: thatvolatilemodifier does not stop all the optimizations that might eliminate reads and/or writes to register variables. So don't think it's a magic shield, bestie. ๐ This warning is enabled by-Wall.-Wxor-used-as-pow(C, C++, Objective-C and Objective-C++ only) โ warns about uses of^, the exclusive or operator, where it looks like the user meant exponentiation. Specifically, the warning fires when the left-hand side is the decimal constant2or10and the right-hand side is also a decimal constant.
Real talk: in C and C++, ^ means exclusive or, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. So 2^8 is giving... not 256, babe. ๐ญ
This warning is enabled by default. You can silence it by converting one of the operands to hexadecimal โ cute little escape hatch. ๐
-Wdisabled-optimizationโ warns if a requested optimization pass is disabled. Ngl, this generally does not mean there's anything wrong with your code; it just means GCC's optimizers couldn't handle your code effectively. Usually the problem is your code is too big or too complex โ GCC straight up refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time. It's not you, it's the compile 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, bestie. It's implied by-Walland by-Wpedantic, and you can turn it off with-Wno-pointer-sign.-Wstack-protectorโ this option is only active when-fstack-protectoris active. It warns about functions that are not protected against stack smashing. ๐ก๏ธ-Woverlength-stringsโ warns about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings. Portable queen behavior only. ๐
The limit applies after string constant concatenation, and it does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++. Not us forgetting, it's just not specified. ๐ซถ
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.
-Wunsuffixed-float-constants(C and Objective-C only) โ issues a warning for any floating constant that does not have a suffix. When used together with-Wsystem-headersit warns about such constants in system header files too. This can be useful when preparing code to use with theFLOAT_CONST_DECIMAL64pragma from the decimal floating-point extension to C99. Get those suffixes in order, bestie. ๐-Wno-lto-type-mismatchโ during the link-time optimization, do not warn about type mismatches in global declarations from different compilation units. Requires-fltoto be enabled. Enabled by default.-Wno-designated-init(C and Objective-C only) โ suppresses warnings when a positional initializer is used to initialize a structure that has been marked with thedesignated_initattribute.
๐ 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. It's the drama-detector of compiler flags. ๐
Heads up though: this analysis is much more expensive than other GCC warnings. Like, highkey expensive. ๐ญ
In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It is a bug-finding tool, rather than a tool for proving program correctness. So don't come for it when it's wrong sometimes โ that's literally the deal. ๐
The analyzer is only suitable for use on C code in this release. C only, bestie. Periodt.
Enabling this option effectively enables the following warnings:
-Wanalyzer-allocation-size -Wanalyzer-deref-before-check
-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file
-Wanalyzer-exposure-through-uninit-copy
-Wanalyzer-fd-access-mode-mismatch -Wanalyzer-fd-double-close
-Wanalyzer-fd-leak -Wanalyzer-fd-phase-mismatch
-Wanalyzer-fd-type-mismatch -Wanalyzer-fd-use-after-close
-Wanalyzer-fd-use-without-check -Wanalyzer-file-leak
-Wanalyzer-free-of-non-heap -Wanalyzer-imprecise-fp-arithmetic
-Wanalyzer-infinite-recursion -Wanalyzer-jump-through-null
-Wanalyzer-malloc-leak -Wanalyzer-mismatching-deallocation
-Wanalyzer-null-argument -Wanalyzer-null-dereference
-Wanalyzer-out-of-bounds -Wanalyzer-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-putenv-of-auto-var
-Wanalyzer-shift-count-negative -Wanalyzer-shift-count-overflow
-Wanalyzer-stale-setjmp-buffer
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-use-of-uninitialized-value
-Wanalyzer-va-arg-type-mismatch -Wanalyzer-va-list-exhausted
-Wanalyzer-va-list-leak -Wanalyzer-va-list-use-after-va-end
-Wanalyzer-write-to-const -Wanalyzer-write-to-string-literal
This option is only available if GCC was configured with analyzer support enabled. Check your build, bestie. ๐ง
-Wanalyzer-too-complexโ if-fanalyzeris enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. (Rude, honestly.)
By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it reaches an internal limit. The -Wanalyzer-too-complex option warns if this occurs. So you actually find out instead of it ghosting you. ๐ป
-Wno-analyzer-allocation-sizeโ this warning requires-fanalyzer, which enables it; to disable it, use-Wno-analyzer-allocation-size.
This diagnostic warns for paths through the code in which a pointer to a buffer is assigned to point at a buffer with a size that is not a multiple of sizeof (*pointer). Math not mathing, basically. ๐งฎ
See CWE-131: Incorrect Calculation of Buffer Size (https://cwe.mitre.org/data/definitions/131.html).
-Wno-analyzer-deref-before-checkโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-deref-before-checkto disable it.
This diagnostic warns for paths through the code in which a pointer is checked for NULL after it has already been dereferenced, suggesting that the pointer could have been NULL. Such cases suggest that the check for NULL is either redundant, or that it needs to be moved to before the pointer is dereferenced. Bestie. Check first. Then dereference. The order is the whole point. ๐ญ
This diagnostic also considers values passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value, and thus will complain if such values are checked for NULL after returning from such a function call.
This diagnostic is unlikely to be reported when any level of optimization is enabled, as GCC's optimization logic will typically consider such checks for NULL as being redundant, and optimize them away before the analyzer "sees" them. Hence optimization should be disabled when attempting to trigger this diagnostic. Ironic, I know. ๐
-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. One close per file, babe, that's the rule. ๐
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-double-freeโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-freeto disable it.
This diagnostic warns for paths through the code in which a pointer can have a deallocator called on it more than once, either free, or a deallocator referenced by attribute malloc. Double-free is giving main character energy in the worst way. ๐ฅ
See CWE-415: Double Free (https://cwe.mitre.org/data/definitions/415.html).
-Wno-analyzer-exposure-through-output-fileโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-exposure-through-output-fileto disable it.
This diagnostic warns for paths through the code in which a security-sensitive value is written to an output file (such as writing a password to a log file). Bestie. Not the password in the log file. ๐ญ Please.
See CWE-532: Information Exposure Through Log Files (https://cwe.mitre.org/data/definitions/532.html).
-Wanalyzer-exposure-through-uninit-copyโ this warning requires both-fanalyzerand the use of a plugin to specify a function that copies across a "trust boundary". Use-Wno-analyzer-exposure-through-uninit-copyto disable it.
This diagnostic warns for "infoleaks" โ paths through the code in which uninitialized values are copied across a security boundary (such as code within an OS kernel that copies a partially-initialized struct on the stack to user space). Uninit struct goes on a little field trip to user space. Not the vibe. ๐จ
See CWE-200: Exposure of Sensitive Information to an Unauthorized Actor (https://cwe.mitre.org/data/definitions/200.html).
-Wno-analyzer-fd-access-mode-mismatchโ this warning requires-fanalyzer, which enables it; use-Wno-analyzer-fd-access-mode-mismatchto disable it.
This diagnostic warns for paths through code in which a read on a write-only file descriptor is attempted, or vice versa. Read the file you opened for reading, bestie. It's literally in the name. ๐
โฆand it also drags you for code paths where a function with attribute fd_arg_read (N) gets called with a file descriptor that was opened O_WRONLY at referenced argument N, or a function with attribute fd_arg_write (N) gets called with an fd opened O_RDONLY at referenced argument N. Like babe, you opened it read-only and now you're trying to write to it?? the audacity ๐ญ
-Wno-analyzer-fd-double-closeโ this one needs-fanalyzerto be on (it's enabled by it), so use-Wno-analyzer-fd-double-closeto turn it back off ๐
It warns about paths through your code where a file descriptor can get closed more than once. double-dipping. not it.
See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).
-Wno-analyzer-fd-leakโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-leakto disable it ๐ซถ
Warns about paths through your code where an open file descriptor justโฆ gets leaked. gone. never closed. absolutely ghosted you ๐ป
See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).
-Wno-analyzer-fd-phase-mismatchโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-phase-mismatchto disable it โจ
Warns about paths through your code where you try to do an operation in the wrong phase of a file descriptor's lifetime. iconic example: trying to call accept on a stream socket that hasn't had listen successfully called on it yet. girl it's not even listening!! ๐
See CWE-666: Operation on Resource in Wrong Phase of Lifetime (https://cwe.mitre.org/data/definitions/666.html).
-Wno-analyzer-fd-type-mismatchโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-type-mismatchto disable it ๐ธ
Warns about paths through your code where you do an operation on the wrong type of file descriptor. Example: trying socket operations on a file descriptor you got from open, or trying to use a stream socket operation on a datagram socket. bestie those are two completely different vibes ๐ญ
-Wno-analyzer-fd-use-after-closeโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-use-after-closeto disable it ๐
Warns about paths through your code where a read or write is called on a closed file descriptor. she's closed, bestie, move on.
It also warns about paths where a function with attribute fd_arg (N), fd_arg_read (N) or fd_arg_write (N) gets called with a closed file descriptor at referenced argument N.
-Wno-analyzer-fd-use-without-checkโ requires-fanalyzer, which enables it; use-Wno-analyzer-fd-use-without-checkto disable it ๐ฅ
Warns about paths through your code where a file descriptor is used without being checked for validity. no vibe check at all. rude.
Also warns about paths where a function with attribute fd_arg (N), fd_arg_read (N) or fd_arg_write (N) gets called with a file descriptor at referenced argument N without being checked for validity.
-Wno-analyzer-file-leakโ requires-fanalyzer, which enables it; use-Wno-analyzer-file-leakto disable it ๐ฆ
Warns about paths through the code where a <stdio.h> FILE * stream object gets leaked.
See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).
-Wno-analyzer-free-of-non-heapโ requires-fanalyzer, which enables it; use-Wno-analyzer-free-of-non-heapto disable it ๐
Warns about paths through the code where free gets called on a non-heap pointer โ like an on-stack buffer, or a global. you cannot free the stack, bestie, that is not how any of this works ๐ญ
See CWE-590: Free of Memory not on the Heap (https://cwe.mitre.org/data/definitions/590.html).
-Wno-analyzer-imprecise-fp-arithmeticโ requires-fanalyzer, which enables it; use-Wno-analyzer-imprecise-fp-arithmeticto disable it ๐ง
Warns about paths through the code where floating-point arithmetic is used in places where you actually need precise computation. rn it only warns on floating-point operands used inside the calculation of an allocation size. just so you know ๐
-Wno-analyzer-infinite-recursionโ requires-fanalyzer, which enables it; use-Wno-analyzer-infinite-recursionto disable it โญ
Warns about paths through the code that look like they lead to infinite recursion. we're going in circles and nobody's leaving ๐
Specifically: when the analyzer "sees" a recursive call, it compares the state of memory at the entry to the new frame against the memory state at the entry to the previous frame of that function on the stack. The warning fires if nothing in memory appears to be changing. Any changes it observes to parameters or globals are assumed to lead to the recursion terminating, which suppresses the warning.
Heads up: this diagnostic is likely to miss cases of infinite recursion that the optimizer converts into iteration before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic. fr fr ๐
Compare with -Winfinite-recursion, which gives a similar diagnostic but is implemented in a totally different way.
-Wno-analyzer-jump-through-nullโ requires-fanalyzer, which enables it; use-Wno-analyzer-jump-through-nullto disable it ๐
Warns about paths through the code where a NULL function pointer gets called. there's nothing there. void. empty. nobody's home. ๐
-Wno-analyzer-malloc-leakโ requires-fanalyzer, which enables it; use-Wno-analyzer-malloc-leakto disable it ๐
Warns about paths through the code where a pointer allocated via an allocator gets leaked โ either malloc, or a function marked with attribute malloc. allocate then abandon. classic ๐
See CWE-401: Missing Release of Memory after Effective Lifetime (https://cwe.mitre.org/data/definitions/401.html).
-Wno-analyzer-mismatching-deallocationโ requires-fanalyzer, which enables it; use-Wno-analyzer-mismatching-deallocationto disable it ๐
Warns about paths through the code where the wrong deallocation function gets called on a pointer value, based on which function allocated it. It'll flag mismatches between free, scalar delete and vector delete[], plus anything marked as allocator/deallocator pairs using attribute malloc. you don't get to break up with someone using a different breakup method, that's not how it works ๐
See CWE-762: Mismatched Memory Management Routines (https://cwe.mitre.org/data/definitions/762.html).
-Wno-analyzer-out-of-boundsโ requires-fanalyzer, which enables it; use-Wno-analyzer-out-of-boundsto disable it ๐ฅ
Warns about paths through the code where a buffer is definitely read or written out-of-bounds. It applies to cases where the analyzer can work out a constant offset, and to accesses past the end of a buffer with a constant capacity too. It also does limited checking for accesses past the end when the offset and the capacity are symbolic.
See CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer (https://cwe.mitre.org/data/definitions/119.html).
-Wno-analyzer-possible-null-argumentโ requires-fanalyzer, which enables it; use-Wno-analyzer-possible-null-argumentto disable it ๐ซถ
Warns about 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. "possibly" is doing a lot of heavy lifting there bestie ๐ญ
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-possible-null-dereferenceโ requires-fanalyzer, which enables it; use-Wno-analyzer-possible-null-dereferenceto disable it โจ
Warns about paths through the code where a possibly-NULL value gets dereferenced.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-null-argumentโ requires-fanalyzer, which enables it; use-Wno-analyzer-null-argumentto disable it ๐ธ
Warns about paths through the code where a value known to be NULL gets passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. known. confirmed. no doubt. and you did it anyway ๐
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-null-dereferenceโ requires-fanalyzer, which enables it; use-Wno-analyzer-null-dereferenceto disable it ๐ฆ
Warns about paths through the code where a value known to be NULL gets dereferenced.
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).
-Wno-analyzer-putenv-of-auto-varโ requires-fanalyzer, which enables it; use-Wno-analyzer-putenv-of-auto-varto disable it ๐
Warns about paths through the code where a call to putenv gets passed a pointer to an automatic variable or an on-stack buffer. that memory is not sticking around, bestie, it's leaving the function ๐
See POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument (https://wiki.sei.cmu.edu/confluence/x/6NYxBQ).
-Wno-analyzer-shift-count-negativeโ requires-fanalyzer, which enables it; use-Wno-analyzer-shift-count-negativeto disable it ๐
Warns about paths through the code where a shift is attempted with a negative count. shifting by negative amounts?? into the past?? ๐ญ It's basically the same idea as the -Wshift-count-negative diagnostic that lives in the C/C++ front ends, except this one is built on analyzing interprocedural paths instead of just parsing the syntax tree. Tiny caveat though: the analyzer doesn't prioritize finding these paths, so false negatives are more likely here than with other warnings. ngl she's not really looking for this one ๐
-Wno-analyzer-shift-count-overflowโ requires-fanalyzer, which enables it; use-Wno-analyzer-shift-count-overflowto disable it โญ
This one's about shifts, bestie โ specifically the cursed kind ๐ It flags paths through your code where a shift happens with a count that's greater than or equal to the precision of the operand's type. It's basically the same energy as the -Wshift-count-overflow diagnostic the C/C++ front ends have, except this one is built on analyzing interprocedural paths instead of just parsing the syntax tree โ way more detective work ๐. Lowkey important caveat though: the analyzer does not prioritize hunting these down, so false negatives are more likely here than with other warnings. Not it being a little lazy ๐
-Wno-analyzer-stale-setjmp-bufferโ ok so this one needs-fanalyzerto be enabled at all (that's what turns it on); use-Wno-analyzer-stale-setjmp-bufferto turn it off. It warns about paths through the code wherelongjmpgets called to rewind to ajmp_bufthat relates to asetjmpcall in a function that has already returned ๐ญ
Here's the lore: when setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. That stack frame becomes invalid the moment the function containing the setjmp call returns. So trying to rewind to it via longjmp would reference a stack frame that no longer exists โ and that likely leads to a crash (or worse). ๐ซ
-Wno-analyzer-tainted-allocation-sizeโ this warning requires both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-allocation-sizeto disable it. It warns for paths where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized ๐ฑ meaning an attacker could inject an excessively large allocation and potentially cause a denial of service attack.
See CWE-789: Memory Allocation with Excessive Size Value (https://cwe.mitre.org/data/definitions/789.html).
-Wno-analyzer-tainted-assertionโ requires both-fanalyzerand-fanalyzer-checker=taint; use-Wno-analyzer-tainted-assertionto disable. It warns for paths where a value that could be attacker-controlled is used as part of a condition without being sanitized first โ and that condition guards a call to a function marked with attributenoreturn(like the function__builtin_unreachable). Those functions typically signal abnormal termination of the program, e.g. assertion failure handlers. For example:
assert (some_tainted_value < SOME_LIMIT);
In such cases:
- when assertion-checking is enabled: an attacker could trigger a denial of service by injecting an assertion failure ๐
- when assertion-checking is disabled, like by defining
NDEBUG: an attacker could inject data that subverts the process, since it presumably violates a precondition the code is assuming ๐ฌ
Heads up bestie: when assertion-checking is disabled, the assertions are typically removed by the preprocessor before the analyzer even has a chance to "see" them โ so this diagnostic can only generate warnings on builds where assertion-checking is enabled. iykyk.
For the purpose of this warning, any function marked with attribute noreturn counts as a possible assertion failure handler, including __builtin_unreachable. And ngl, these functions are sometimes removed by the optimizer before the analyzer "sees" them โ so optimization should be disabled when you're trying to trigger this diagnostic. ๐ง
See CWE-617: Reachable Assertion (https://cwe.mitre.org/data/definitions/617.html).
It can also report problematic constructions like
switch (some_tainted_value) {
case 0:
/* [...etc; various valid cases omitted...] */
break;
default:
__builtin_unreachable (); /* BUG: attacker can trigger this */
}
even though, strictly speaking, the above isn't an assertion failure. Periodt ๐
-Wno-analyzer-tainted-array-indexโ requires both-fanalyzerand-fanalyzer-checker=taint; use-Wno-analyzer-tainted-array-indexto disable. It warns for paths where a value that could be attacker-controlled gets used as the index of an array access without being sanitized, so an attacker could inject an out-of-bounds access ๐ฅ
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).
-Wno-analyzer-tainted-divisorโ requires both-fanalyzerand-fanalyzer-checker=taint; use-Wno-analyzer-tainted-divisorto disable. It warns for paths where a value that could be attacker-controlled gets used as the divisor in a division or modulus operation without being sanitized โ so an attacker could inject a division-by-zero ๐
See CWE-369: Divide By Zero (https://cwe.mitre.org/data/definitions/369.html).
-Wno-analyzer-tainted-offsetโ requires both-fanalyzerand-fanalyzer-checker=taint; use-Wno-analyzer-tainted-offsetto disable. It warns for paths where a value that could be attacker-controlled gets used as a pointer offset without being sanitized, so an attacker could inject an out-of-bounds access ๐ญ
See CWE-823: Use of Out-of-range Pointer Offset (https://cwe.mitre.org/data/definitions/823.html).
-Wno-analyzer-tainted-sizeโ requires both-fanalyzerand-fanalyzer-checker=taint; use-Wno-analyzer-tainted-sizeto disable. It warns for paths where a value that could be attacker-controlled gets used as the size of an operation likememsetwithout being sanitized, so an attacker could inject an out-of-bounds access ๐
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).
-Wno-analyzer-unsafe-call-within-signal-handlerโ needs-fanalyzer(which enables it); use-Wno-analyzer-unsafe-call-within-signal-handlerto disable. It warns for paths where a function known to be async-signal-unsafe (likefprintf) is called from a signal handler โ ๏ธ
See CWE-479: Signal Handler Use of a Non-reentrant Function (https://cwe.mitre.org/data/definitions/479.html).
-Wno-analyzer-use-after-freeโ needs-fanalyzer(which enables it); use-Wno-analyzer-use-after-freeto disable. It warns for paths where a pointer is used after a deallocator is called on it โ eitherfree, or a deallocator referenced by attributemalloc๐ต
See CWE-416: Use After Free (https://cwe.mitre.org/data/definitions/416.html).
-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ needs-fanalyzer(which enables it); use-Wno-analyzer-use-of-pointer-in-stale-stack-frameto disable. It warns for paths where a pointer is dereferenced that points to a variable in a stale stack frame ๐ซ-Wno-analyzer-va-arg-type-mismatchโ needs-fanalyzer(which enables it); use-Wno-analyzer-va-arg-type-mismatchto disable. It warns for interprocedural paths through the code where the analyzer detects an attempt to useva_argto extract a value passed to a variadic call, but using a type that does not match the type of the expression passed to the call ๐ฏ
See CWE-686: Function Call With Incorrect Argument Type (https://cwe.mitre.org/data/definitions/686.html).
-Wno-analyzer-va-list-exhaustedโ needs-fanalyzer(which enables it); use-Wno-analyzer-va-list-exhaustedto disable. It warns for interprocedural paths where the analyzer detects an attempt to useva_argto access the next value passed to a variadic call โ except all of the values in theva_listhave already been consumed ๐ญ empty. gone. nothing left.
See CWE-685: Function Call With Incorrect Number of Arguments (https://cwe.mitre.org/data/definitions/685.html).
-Wno-analyzer-va-list-leakโ needs-fanalyzer(which enables it); use-Wno-analyzer-va-list-leakto disable. It warns for interprocedural paths where the analyzer detects thatva_startorva_copyhas been called on ava_listwithout a corresponding call tova_end๐ง-Wno-analyzer-va-list-use-after-va-endโ needs-fanalyzer(which enables it); use-Wno-analyzer-va-list-use-after-va-endto disable. It warns for interprocedural paths where the analyzer detects an attempt to use ava_listafterva_endhas been called on it.va_list.-Wno-analyzer-write-to-constโ needs-fanalyzer(which enables it); use-Wno-analyzer-write-to-constto disable. It warns for paths where the analyzer detects an attempt to write through a pointer to aconstobject ๐ซ But โ same caveat as before โ the analyzer doesn't prioritize detection of these paths, so false negatives are more likely relative to other warnings. ๐-Wno-analyzer-write-to-string-literalโ needs-fanalyzer(which enables it); use-Wno-analyzer-write-to-string-literalto disable. It warns for paths where the analyzer detects an attempt to write through a pointer to a string literal ๐ฑ (yes, the thing that lives in read-only memory, bestie, please don't). And again: the analyzer doesn't prioritize detection of such paths, so false negatives are more likely relative to other warnings.-Wno-analyzer-use-of-uninitialized-valueโ needs-fanalyzer(which enables it); use-Wno-analyzer-use-of-uninitialized-valueto disable. It warns for paths through the code in which an uninitialized value is used ๐ป
See CWE-457: Use of Uninitialized Variable (https://cwe.mitre.org/data/definitions/457.html).
The analyzer has hardcoded knowledge about the behavior of the following memory-management functions: ๐
alloca- the built-in functions
__builtin_alloc,__builtin_alloc_with_align,__builtin_calloc,__builtin_free,__builtin_malloc,__builtin_memcpy,__builtin_memcpy_chk,__builtin_memset,__builtin_memset_chk,__builtin_realloc,__builtin_stack_restore, and__builtin_stack_save callocfreemallocmemsetoperator deleteoperator delete []operator newoperator new []reallocstrdupstrndup
and like, these ones for doing stuff with file descriptors:
openclosecreatdup,dup2anddup3isattypipe, andpipe2readwritesocket,bind,listen,accept, andconnect
and the <stdio.h> stream girlies:
- the built-in functions
__builtin_fprintf,__builtin_fprintf_unlocked,__builtin_fputc,__builtin_fputc_unlocked,__builtin_fputs,__builtin_fputs_unlocked,__builtin_fwrite,__builtin_fwrite_unlocked,__builtin_printf,__builtin_printf_unlocked,__builtin_putc,__builtin_putchar,__builtin_putchar_unlocked,__builtin_putc_unlocked,__builtin_puts,__builtin_puts_unlocked,__builtin_vfprintf, and__builtin_vprintf fopenfcloseferrorfgetsfgets_unlockedfilenofreadgetcgetcharfprintfprintffwrite
aaaaand these besties too:
- the built-in functions
__builtin_expect,__builtin_expect_with_probability,__builtin_strchr,__builtin_strcpy,__builtin_strcpy_chk,__builtin_strlen,__builtin_va_copy, and__builtin_va_start - the GNU extensions
erroranderror_at_line getpasslongjmpputenvsetjmpsiglongjmpsignalsigsetjmpstrchrstrlen
Plus โ plot twist โ there's a whole bunch of functions with an __analyzer_ prefix that mean something special to the analyzer. Those are documented in the GCC Internals manual, iykyk ๐ง
Now for the lil knobs that control how far the exploration goes, we got these pertinent parameters:
--param analyzer-bb-explosion-factor=value--param analyzer-max-enodes-per-program-point=value--param analyzer-max-recursion-depth=value--param analyzer-min-snodes-for-call-summary=value
The following options control the analyzer. Buckle up ๐
-fanalyzer-call-summariesโ simplifies interprocedural analysis by computing the effect of certain calls instead of exploring, like, every single path through the function from callsite to each possible return. If it's enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per--param analyzer-min-snodes-for-call-summary=value). Lowkey efficient.-fanalyzer-checker=nameโ restricts the analyzer to run just the named checker, and enables it. Some checkers are disabled by default (even with-fanalyzer), like thetaintchecker that implements-Wanalyzer-tainted-array-index, and you need this option to turn them on.
Note: currently,-fanalyzer-checker=taintdisables the following warnings from-fanalyzer: --Wanalyzer-deref-before-check--Wanalyzer-double-fclose--Wanalyzer-double-free--Wanalyzer-exposure-through-output-file--Wanalyzer-fd-access-mode-mismatch--Wanalyzer-fd-double-close--Wanalyzer-fd-leak--Wanalyzer-fd-use-after-close--Wanalyzer-fd-use-without-check--Wanalyzer-file-leak--Wanalyzer-free-of-non-heap--Wanalyzer-malloc-leak--Wanalyzer-mismatching-deallocation--Wanalyzer-null-argument--Wanalyzer-null-dereference--Wanalyzer-possible-null-argument--Wanalyzer-possible-null-dereference--Wanalyzer-unsafe-call-within-signal-handler--Wanalyzer-use-after-free--Wanalyzer-va-list-leak--Wanalyzer-va-list-use-after-va-end
-fno-analyzer-feasibilityโ this one's for the analyzer developers, periodt. By default the analyzer verifies that there's a feasible control flow path for each diagnostic it emits: that the conditions that hold aren't mutually exclusive. Diagnostics with no feasible path get rejected. You can suppress that filtering with-fno-analyzer-feasibility, for debugging issues in this code. ๐-fanalyzer-fine-grainedโ also for analyzer developers. Internally the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. By default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. With-fanalyzer-fine-grained, each statement gets its own edge. So granular, we love to see it โจ-fanalyzer-show-duplicate-countโ analyzer-dev coded: if multiple diagnostics have been detected as being duplicates of each other, it emits a note when reporting the best diagnostic, giving the number of additional diagnostics that were suppressed by the deduplication logic. Iconic, honestly.-fno-analyzer-state-mergeโ analyzer developers only, bestie. 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-mergethis merging can be suppressed, for debugging state-handling issues.-fno-analyzer-state-purgeโ another dev-only one. 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-purgethis purging of state can be suppressed, for debugging state-handling issues.-fno-analyzer-suppress-followupsโ dev option again. By default the analyzer stops exploring an execution path after encountering certain diagnostics, to avoid potentially issuing a cascade of follow-up diagnostics. The diagnostics that terminate analysis along a path are:-Wanalyzer-null-argument-Wanalyzer-null-dereference-Wanalyzer-use-after-free-Wanalyzer-use-of-pointer-in-stale-stack-frame-Wanalyzer-use-of-uninitialized-value
With -fno-analyzer-suppress-followups the analyzer will keep exploring such paths even after those diagnostics, which may be helpful for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior. Chaotic but valid.
-fanalyzer-transitivityโ enables transitivity of constraints within the analyzer. Math girl summer ๐-fno-analyzer-undo-inliningโ analyzer developers, this way please.-fanalyzerruns relatively late compared to other code analysis tools, and some optimizations have already been applied to the code. In particular function inlining may have occurred, leading to the interprocedural execution paths emitted by the analyzer containing function frames that don't correspond to those in the original source code. By default the analyzer tries to reconstruct the original function frames, and to emit events showing the inlined calls. With-fno-analyzer-undo-inliningthis attempt to reconstruct the original frame information can be disabled, which may help when debugging issues in the analyzer.-fanalyzer-verbose-edgesโ analyzer developers only. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. Spicy detail.-fanalyzer-verbose-state-changesโ also dev-coded. Enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.-fanalyzer-verbosity=levelโ this controls the complexity of the control flow paths that get emitted for analyzer diagnostics. The level can be one of:0โ at this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-freediagnostic, both calls tofreewill be shown.1โ as per the previous level, but also show events for the entry to each function.2โ as per the previous level, but also show events relating to control flow that are significant to triggering the issue (e.g. "true path taken" at a conditional). This level is the default. ๐3โ as per the previous level, but show all control flow events, not just significant ones.4โ this level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
-fdump-analyzerโ dumps internal details about what the analyzer is doing tofile.analyzer.txt. Note that-fdump-analyzer-stderroverrides this option.-fdump-analyzer-stderrโ dumps internal details about what the analyzer is doing tostderr. This option overrides-fdump-analyzer. Your terminal is gonna be chatty.-fdump-analyzer-callgraphโ dumps a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot. Aesthetic AND functional ๐ธ-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. Fr it's giving art.-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. This is typically a large number of dump files. Like, a LOT of files. You've been warned ๐-fdump-analyzer-exploded-pathsโ dumps a textual representation of the "exploded path" for each diagnostic tofile.idx.kind.epath.txt.-fdump-analyzer-feasibilityโ dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the formfile.*.fg.dot,file.*.tg.dot, andfile.*.fpath.txt. ๐ฆ-fdump-analyzer-jsonโ dumps a compressed JSON representation of the analyzer's internals intofile.analyzer.json.gz. bestie i cannot stress this enough: the precise format is subject to change, so don't go building your whole personality around parsing it, mwah ๐-fdump-analyzer-state-purgeโ so, same energy as-fdump-analyzer-supergraph(dump a representation of the "supergraph" that's suitable for viewing with GraphViz), except it also annotates the graph with info on what state will be purged at each node โจ the graph gets written tofile.state-purge.dot.-fdump-analyzer-supergraphโ dumps representations of the "supergraph" suitable for viewing with GraphViz tofile.supergraph.dotand tofile.supergraph-eg.dot๐ฆ these show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" plus the diagnostics associated with them. it's giving โจwhole program visionโจ-fdump-analyzer-untrackedโ emits custom warnings with internal details, and those details are intended for analyzer developers ๐ซถ so like, iykyk. not really a you-and-me situation, it's a them situation.
๐ธ Options for Debugging Your Program ๐ธ
okay so the whole vibe here: to tell GCC to emit extra information for use by a debugger, in almost all cases you need only to add -g to your other options ๐ and some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options. slay, they can share the aux ๐
GCC allows you to use -g with -O. and the shortcuts taken by optimized code may occasionally be surprising, which is honestly so real of it ๐ญ like: 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 โ which is why it's 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 -Og may result in a better debugging experience. lowkey a glow-up, fr fr โจ
-gโ produces debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF) โญ GDB can work with this debugging information.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use ๐ซถ this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program ๐ so if you want to control for certain whether to generate the extra information, use -gvms (see below, it's right there).
-ggdbโ produces debugging information for use by GDB ๐ which means: 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. she's doing the most for you and honestly? icon behavior.-gdwarf,-gdwarf-versionโ produces debugging information in DWARF format (if that is supported) ๐ฆ the value of version may be either2,3,4or5; the default version for most targets is5(with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version2, and AIX, which defaults to version4).
note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables ๐
Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher. so like, check your GDB's vibe before you commit ๐
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. don't let the names gaslight you bestie, they're just old ๐
-gbtfโ requests BTF debug information โจ BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options. two formats, one queen, no drama ๐-gctf,-gctflevelโ requests CTF debug information and uses level to specify how much CTF debug information should be produced ๐ฆ if-gctfis specified without a value for level, the default level of CTF debug information is2.
CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options ๐ธ
- Level
0produces no CTF debug information at all. Thus,-gctf0negates-gctf. ghosted, gone, nothing. - Level
1produces CTF information for tracebacks only. This includes callsite information, but does not include type information. light info, just the receipts of who called whom ๐ซถ - Level
2produces type information for entities (functions, data objects etc.) at file-scope or global-scope only. the whole menu, but only at file/global scope, not going all nosy into locals.
-gvmsโ produces debugging information in Alpha/VMS debug format (if that is supported) โญ this is the format used by DEBUG on Alpha/VMS systems. vintage! iconic! niche!-glevel,-ggdblevel,-gvmslevelโ requests debugging information and also uses level to specify how much information ๐ the default level is2.- Level
0produces no debug information at all. Thus,-g0negates-g. yes bestie, the off switch ๐ - Level
1produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no information about local variables. it's giving โจjust the highlightsโจ - Level
3includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use-g3๐ฅ she's an over-sharer and we love her for it.
- Level
If you use multiple -g options, with or without level numbers, the last such option is the one that is effective. last one wins, no take-backs, periodt ๐
-gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. Instead use an additional -glevel option to change the debug level for DWARF ๐ซถ no sneaky smooshing the two together, keep them separate like a healthy situationship.
-fno-eliminate-unused-debug-symbolsโ by default, no debug information is produced for symbols that are not actually used. Use this option if you want debug information for all symbols ๐ all of them. every last one. main character energy for the unused symbols too ๐-femit-class-debug-alwaysโ instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class ๐ญ this option should be used only with debuggers that are unable to handle the way GCC normally emits debugging information for classes, because using this option increases the size of debugging information by as much as a factor of two โ ๏ธ so like, do it for compatibility, not for fun.-fno-merge-debug-stringsโ directs the linker to not merge together strings in the debugging information that are identical in different object files ๐ฆ merging is not supported by all assemblers or linkers. Merging decreases the size of the debug information in the output file at the cost of increasing link processing time. Merging is enabled by default. so this flag is the "actually, don't smush them" option ๐-fdebug-prefix-map=old=newโ when compiling files residing in directory old, record debugging information describing them as if the files resided in directory new instead โจ this can be used to replace a build-time path with an install-time path in the debug info. It can also be used to change an absolute path to a relative path by using.for new. This can give more reproducible builds, which are location independent, but may require an extra command to tell GDB where to find the source files ๐ซถ see also-ffile-prefix-mapand-fcanon-prefix-map. the "my paths are none of your business" tech, iykyk ๐-fvar-trackingโ runs the variable tracking pass ๐ธ it computes where variables are stored at each position in code. Better debugging information is then generated (if the debugging information format supports this information) โจ
It is enabled by default when compiling with optimization (-Os, -O, -O2, ...), debugging information (-g) and the debug info format supports it. so it's already doing its thing, no need to micromanage ๐
-fvar-tracking-assignmentsโ annotates assignments to user variables early in the compilation and attempts to carry the annotations over throughout the compilation all the way to the end, in an attempt to improve debug information while optimizing ๐ฆ use of-gdwarf-4is recommended along with it.
It can be enabled even if var-tracking is disabled, in which case annotations are created and maintained, but discarded at the end ๐ญ so like, all that effort and then she just lets it go. By default, this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled.
-gsplit-dwarfโ if DWARF debugging information is enabled, separate as much debugging information as possible into a separate output file with the extension.dwo๐ this option allows the build system to avoid linking files with debug information. To be useful, this option requires a debugger capable of reading.dwofiles. so like, package it up and ship it separately, but make sure your debugger can actually open the parcel ๐-gdwarf32,-gdwarf64โ if DWARF debugging information is enabled,-gdwarf32selects the 32-bit DWARF format and-gdwarf64selects the 64-bit DWARF format ๐ the default is target specific, on most targets it is-gdwarf32though. The 32-bit DWARF format is smaller, but can't support more than 2GiB of debug information in any of the DWARF debug information sections โ ๏ธ the 64-bit DWARF format allows larger debug information and might not be well supported by all consumers yet. so it's the classic trade: small and universally adored, or big and occasionally misunderstood ๐ญ-gdescribe-diesโ adds description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs โจ giving the nameless entities a little name tag, we love to see it ๐ซถ-gpubnamesโ generates DWARF.debug_pubnamesand.debug_pubtypessections ๐ the girlies love an index.-ggnu-pubnamesโ generates.debug_pubnamesand.debug_pubtypessections in a format suitable for conversion into a GDB index โญ this option is only useful with a linker that can produce GDB index version 7. so like, check your linker's credentials first, otherwise it's giving "bought the outfit, nowhere to wear it" ๐-fdebug-types-sectionโ when using DWARF Version 4 or higher, type DIEs can be put into their own.debug_typessection instead of making them part of the.debug_infosection ๐ฆ it is more efficient to put them in a separate comdat section since the linker can then remove duplicates ๐ฅ but not all DWARF consumers support.debug_typessections yet and on some objects.debug_typesproduces larger instead of smaller debugging information ๐ญ so like, it's giving efficiency and risk, your call bestie, no cap.-grecord-gcc-switchesโ okay so 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 information. 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.-gno-record-gcc-switchesโ the nope version: don't append those command-line options toDW_AT_producer.-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.-gno-strict-dwarfโ Allow using extensions of later DWARF standard version than selected with-gdwarf-version.-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.
-gno-as-loc-supportโ Force GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated.-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.
-gno-as-locview-supportโ Force GCC to assign view numbers internally, if-gvariable-location-viewsare explicitly requested.-gcolumn-infoโ Emit location column information into DWARF debugging information, rather than just file and line. This option is enabled by default.-gno-column-infoโ nah, don't emit location column info; just file and line.-gstatement-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 of"is_stmt"markers in the line number table. This is enabled by default when compiling with optimization (-Os,-O1,-O2, ...), and outputting DWARF 2 debug information at the normal level.-gno-statement-frontiersโ the off switch: skip those statement-frontier markers.-gvariable-location-viewsโ Augment variable location lists with progressive view numbers implied from the line number table. This enables debug information 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 information 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 information at the normal level, as long as there is assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is 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-views is not enabled, that will most certainly lead to silently mismatching location views.
-gvariable-location-views=incompat5โ 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.
heads up bestie: debug information consumers are not expected to support this extended format, and they would be rendered unable to decode location lists using it. ๐ญ
-gno-variable-location-viewsโ Turn off that variable-location-view augmentation completely.-ginternal-reset-location-viewsโ Attempt to determine location views that can be omitted from location view lists. This requires the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when using an assembler that 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.-gno-internal-reset-location-viewsโ Don't attempt that internal location-view omission thing.-ginline-pointsโ Generate extended debug information for inlined functions. Location view tracking markers are inserted at inlined entry points, so that address and view numbers can be computed and output in debug information. This can be enabled independently of location views, in which case the view numbers won't be output, but it can only be enabled along with statement frontiers, and it is only enabled by default if location views are enabled.-gno-inline-pointsโ Don't generate extended debug information for inlined functions.-gz[=type]โ Produce compressed debug sections in DWARF format, if that is supported. Iftypeis not given, the default type depends on the capabilities of the assembler and linker used.typemay be one ofnone(don't compress debug sections), orzlib(use zlib compression in ELF gABI format). If the linker doesn't support writing compressed debug sections, the option is rejected. Otherwise, if the assembler 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 intent 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.
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_framesection 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 is 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. like, the whole optimization menu, bestie.
Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. trade-offs, babes.
okay so real talk โ the compiler is out here doing actual detective work. It performs optimization based on the knowledge it has of the program, and honestly? It's kind of a genius move: 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. Bestie is connecting dots across the whole squad. ๐ต๏ธโโ๏ธโจ
But heads up โ not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section. So if you're like "where's the flag for X," it might just not have one, no cap.
Also super important, don't skip this: 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. Yeah. You can hand-write fifty -f flags and if there's no -O level in the mix, most of them are just gonna sit there doing nothing. ๐ญ Similarly, -Og suppresses many optimization passes โ it's just built different.
And 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. So like, don't come for me if your build differs. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level. That's your vibe check tool, periodt. ๐
๐ฅ the -O levels, ranked by chaos
-O,-O1โ Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.
With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O turns on the following optimization flags:
-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
-O2โ Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to-O, this option increases both compilation time and the performance of the generated code.
-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp -fipa-cp -fipa-icf -fipa-ra -fipa-sra -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition -freorder-functions
-frerun-cse-after-loop -fschedule-insns -fschedule-insns2
-fsched-interblock -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
โ ๏ธ Please note the warning under-fgcseabout invoking-O2on programs that use computed gotos. Like, actually go read it, bestie. It's giving important.
-O3โ Optimize yet more.-O3turns on all optimizations specified by-O2and also turns on the following optimization flags:
-fgcse-after-reload -fipa-cp-clone -floop-interchange
-floop-unroll-and-jam -fpeel-loops -fpredictive-commoning
-fsplit-loops -fsplit-paths -ftree-loop-distribution
-ftree-partial-pre -funswitch-loops -fvect-cost-model=dynamic
-fversion-loops-for-strides
-O0โ Reduce compilation time and make debugging produce the expected results. This is the default. No thoughts, just vibes, and the vibes are slow but predictable. ๐ข-Osโ Optimize for size.-Osenables all-O2optimizations except those that often increase code size:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size. Tiny is the moment. ๐
-Ofastโ Disregard strict standards compliance.-Ofastenables all-O3optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on-ffast-math,-fallow-store-data-racesand the Fortran-specific-fstack-arrays, unless-fmax-stack-var-sizeis specified, and-fno-protect-parens. It turns off-fsemantic-interposition.
๐จ This one is literally disregarding strict standards compliance. Read that again. If your program needs to be standards-compliant, this is not the vibe. Also the-fstack-arraysand-fmax-stack-var-sizebits are Fortran-specific, so don't get confused if you're a C girlie.
-Ogโ Optimize debugging experience.-Ogshould be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience. It is a better choice than-O0for producing debuggable code because some compiler passes that collect debug information are disabled at-O0.
Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect. Otherwise -Og enables all -O1 optimization flags except for those that may interfere with debugging:
-fbranch-count-reg -fdelayed-branch -fdse -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants -fmove-loop-stores -fssa-phiopt
-ftree-bit-ccp -ftree-dse -ftree-pta -ftree-sra
Honestly? The edit-compile-debug cycle needs her. ๐
-Ozโ Optimize aggressively for size rather than speed. This may increase the number of instructions executed if those instructions require fewer bytes to encode.-Ozbehaves similarly to-Osincluding enabling most-O2optimizations.
๐ซถ If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. Last one wins, always. Don't argue with the order.
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed โ the one you typically use. You can figure out the other form by either removing no- or adding it. It's giving DIY, iykyk. โจ
The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired. This is the artisan, small-batch, hand-selected part of the menu. ๐ง
-fno-defer-popโ For machines that must pop arguments after a function call, always pop the arguments as soon as each function returns. At levels-O1and higher,-fdefer-popis the default; this allows the compiler to let arguments accumulate on the stack for several function calls and pop them all at once. Efficiency queen. ๐-fforward-propagateโ Perform a forward propagation pass on RTL. The pass tries to combine two instructions and checks if the result can be simplified. If loop unrolling is active, two passes are performed and the second is scheduled after loop unrolling.
This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.
-ffp-contract=styleโ okay so the style here is the whole point:-ffp-contract=offdisables floating-point expression contraction.-ffp-contract=fastenables floating-point expression contraction such as forming of fused multiply-add operations if the target has native support for them.-ffp-contract=onenables floating-point expression contraction if allowed by the language standard. This is currently not implemented and treated equal to-ffp-contract=off.
The default is -ffp-contract=fast. ๐๏ธ
-fomit-frame-pointerโ Omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available.
On some targets this flag has no effect because the standard calling sequence always uses a frame pointer, so it cannot be omitted. Sad, but true.
โ ๏ธ 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. So like, don't count on it as a guarantee, bestie.
Enabled by default at -O1 and higher.
-foptimize-sibling-callsโ Optimize sibling and tail recursive calls.
Enabled at levels -O2, -O3, -Os.
-foptimize-strlenโ Optimize various standard C string functions (e.g.strlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives.
Enabled at levels -O2, -O3.
-fno-inlineโ Do not expand any functions inline apart from those marked with thealways_inlineattribute. This is the default when not optimizing.
Single functions can be exempted from inlining by marking them with the noinline attribute. "not me, not today" energy. ๐
-finline-small-functionsโ Integrate functions into their callers when their body is smaller than expected function call code (so overall size of program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating in this way. This inlining applies to all functions, even those not declared inline.
Enabled at levels -O2, -O3, -Os.
-findirect-inliningโ Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has any effect only when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
Enabled at levels -O2, -O3, -Os.
-finline-functionsโ Consider all functions for inlining, even if they are not declared inline. The compiler heuristically decides which functions are worth integrating in this way.
If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.
Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile. She's everywhere. ๐
-finline-functions-called-onceโ Consider allstaticfunctions called once for inlining into their caller even if they are not markedinline. If a call to a given function is integrated, then the function is not output as assembler code in its own right.
Enabled at levels -O1, -O2, -O3 and -Os, but not -Og. ๐
-fearly-inliningโ bestie, this one does the inlining early, before all the heavy stuff. It inlines functions markedalways_inlineplus any function whose body looks smaller than the overhead of just calling it, and it does this before the-fprofile-generateinstrumentation and before the real inlining pass kicks in. The result? Profiling gets significantly cheaper, and inlining is usually faster on programs that have big chains of nested wrapper functions. Wrapper city, honestly. โจ
Enabled by default. ๐ซถ
-fipa-sraโ this does interprocedural scalar replacement of aggregates, removes unused parameters, and swaps parameters passed by reference for parameters passed by value. It's giving "why carry the whole suitcase when you only need the passport". ๐
Enabled at levels -O2, -O3 and -Os.
-finline-limit=nโ okay so by default GCC limits the size of functions it'll inline, and this flag gives you coarse control over that limit.nis the size of functions that can be inlined, measured in number of pseudo instructions.
Inlining is actually controlled by a bunch of parameters, which you can set individually with --param name=value. This option sets some of them like so:
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 their defaults. ๐
Note: there may be no value to -finline-limit that results in default behavior. ๐ญ
Note: pseudo instruction here means an abstract measurement of a function's size. It absolutely does not represent a count of assembly instructions, and its exact meaning might change from one release to another. So don't come for me if it shifts. ๐
-fno-keep-inline-dllexportโ a more fine-grained version of-fkeep-inline-functions, which applies only to functions declared using thedllexportattribute or declspec. Little laser-focused icon. ๐ฏ-fkeep-inline-functionsโ in C, this emitsstaticfunctions declaredinlineinto the object file, even if the function has been inlined into all of its callers. Note that 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. Keeping them around, main character energy. ๐-fkeep-static-functionsโ emitsstaticfunctions into the object file even if the function is never used. Rude to leave them out, honestly. ๐ธ-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 optimization is on โ use the -fno-keep-static-consts option. ๐ฆ
-fmerge-constantsโ attempts to merge identical constants (string constants and floating-point constants) across compilation units. Dedupe slay. โจ
This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.
Enabled at levels -O1, -O2, -O3, -Os.
-fmerge-all-constantsโ attempts to merge identical constants and identical variables. ๐
This option implies -fmerge-constants. On top of that, it also considers things like even constant initialized arrays or initialized constant variables with integral or floating-point types. But bestie, listen: languages like C or C++ require each variable โ including multiple instances of the same variable in recursive calls โ to have distinct locations, so using this option results in non-conforming behavior. โ ๏ธ
Fr fr, that's a standards violation. Use with intention.
-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 whole glow-up. ๐ฅ-fmodulo-sched-allow-regmovesโ performs more aggressive SMS-based modulo scheduling with register moves allowed. Setting this flag deletes certain anti-dependences edges, which triggers generation of reg-moves based on the life-range analysis. This option is effective only with-fmodulo-schedenabled. Teamwork, iykyk. ๐-fno-branch-count-regโ disables the optimization pass that scans for chances to usedecrement and branchinstructions on a count register instead of instruction sequences that decrement a register, compare it against zero, and then branch based on the result. This option is only meaningful on architectures that support such instructions, which include x86, PowerPC, IA-64 and S/390. ๐
Note: -fno-branch-count-reg doesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes.
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 get confused by the optimizations performed when this option is not used. Strange hacks, we see you. ๐
The default is -ffunction-cse.
-fno-zero-initialized-in-bssโ if the target supports a BSS section, GCC by default puts variables initialized to zero into BSS. This can save space in the resulting code. Neat. โจ
This option turns that behavior off, because some programs explicitly rely on variables going to the data section โ e.g., so the resulting executable can find the beginning of that section and/or make assumptions based on that. Honestly, valid.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ performs optimizations that check whether 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. Jump hopscotch. ๐ฆ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-typesโ when you're using a type that occupies multiple registers, likelong longon a 32-bit system, this splits the registers apart and allocates them independently. Normally it generates better code for those types, but it may make debugging more difficult. Trade-offs, babes. ๐ญ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-types-earlyโ fully splits wide types early, instead of very late. This option has no effect unless-fsplit-wide-typesis turned on. Early bird gets the split. ๐ฃ
This is the default on some targets.
-fcse-follow-jumpsโ in common subexpression elimination (CSE), scan through jump instructions when the target of the jump isn't reached by any other path. For example, when CSE encounters anifstatement with anelseclause, CSE follows the jump when the condition tested is false. Following the plot. ๐
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ similar to-fcse-follow-jumps, but it makes CSE follow jumps that conditionally skip over blocks. When CSE encounters a simpleifstatement with no else clause,-fcse-skip-blocksmakes CSE follow the jump around the body of theif. Hop around it, periodt. ๐
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-runs common subexpression elimination after loop optimizations are performed. Round two, let's go. ๐
Enabled at levels -O2, -O3, -Os.
-fgcseโ performs a global common subexpression elimination pass. This pass also does global constant and copy propagation. ๐
Note: when compiling a program using computed gotos, a GCC extension, you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line.
Enabled at levels -O2, -O3, -Os.
-fgcse-lmโ when enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This lets a loop containing a load/store sequence get changed to a load outside the loop, and a copy/store inside the loop. Loop glow-up achieved. โญ
Enabled by default when -fgcse is enabled.
-fgcse-smโ when enabled, a store motion pass runs after global common subexpression elimination. This pass attempts to move stores out of loops. Used together with-fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. Iconic combo. ๐
Not enabled at any optimization level.
-fgcse-lasโ when enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies). Redundancy found crying in the club. ๐
Not enabled at any optimization level.
-fgcse-after-reloadโ when enabled, a redundant load elimination pass is performed after reload. The purpose of this pass is to clean up redundant spilling. Tidy vibes. ๐ง
Enabled by -O3, -fprofile-use and -fauto-profile.
-faggressive-loop-optimizationsโ this tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. It assumes the loop code does not invoke undefined behavior โ for example, by causing signed integer overflows or out-of-bound array accesses. Those derived bounds are used to guide loop unrolling and peeling and loop exit test optimizations. This option is enabled by default. Aggressive but in a confident way. ๐ฅ
Bestie, do not feed it UB. It will trust you and it will be wrong.
-funconstrained-commonsโ this 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. Don't assume the bounds, babe. ๐ธ-fcrossjumpingโ performs the cross-jumping transformation. This transformation unifies equivalent code and saves code size. Heads up: the resulting code may or may not perform better than without cross-jumping. Smaller, not necessarily faster. Ngl. ๐
Enabled at levels -O2, -O3, -Os.
-fauto-inc-decโ combines increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that don't have instructions to support it. Enabled by default at-O1and higher on architectures that support this. ๐-fdceโ performs dead code elimination (DCE) on RTL. Enabled by default at-O1and higher. Bye bye dead code, you're not invited to the group chat. ๐-fdseโ performs dead store elimination (DSE) on RTL. Enabled by default at-O1and higher. Same energy, but for stores. ๐๏ธ-fif-conversionโ okay so this one tries to turn conditional jumps into branch-less equivalents โจ and it's giving so many tricks: conditional moves,min,max, set flags,absinstructions, plus some cute stuff you can do with standard arithmetics. Whether it actually uses conditional execution on chips where that exists is controlled by-fif-conversion2, bestie. Enabled at levels-O1,-O2,-O3,-Os, but not with-Og.-fif-conversion2โ uses conditional execution (where available, iykyk) to transform conditional jumps into branch-less equivalents. Enabled at levels-O1,-O2,-O3,-Os, but not with-Og.-fdeclone-ctor-dtorโ the C++ ABI requires multiple entry points for constructors and destructors, and it's lowkey a lot: 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 you literally get two copies of the function ๐ญ. With this option, the base and complete variants get changed into thunks that call a common implementation. Enabled by-Os. Slay.-fdelete-null-pointer-checksโ assumes 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. On top of that, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; those assume a memory access to address zero always results in a trap, so if a pointer is checked after it's already been dereferenced, it cannot be null. Periodt.
โ ๏ธ 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 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 into 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 into speculative direct calls ๐ฅ. Based on the analysis of the type inheritance graph, it figures out for a given call the set of likely targets. If the set is small, preferably of size 1, it changes the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, such as inlining. When they seem useless after further optimization, they're converted back into their original form. Cute, right?-fdevirtualize-at-ltransโ streams extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode. This option enables more devirtualization but significantly increases the size of streamed data ๐. For this reason it is disabled by default.-fexpensive-optimizationsโ 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. Iconic.-fno-lifetime-dseโ in C++, the value of an object is only affected by changes within its lifetime: when the constructor begins, the object has an indeterminate value, and any changes during the 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. And-flifetime-dse=0is equivalent to-fno-lifetime-dse. iykyk ๐ซถ-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's the default because it generates better code ๐-fira-region=regionโ use the 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. 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 (>= 32registers), but it can slow the compiler down. Enabled at level-O3for some targets.-fno-ira-share-save-slotsโ disables sharing of stack slots used for saving call-used hard registers living through a call. Each hard register gets a separate stack slot, and as a result function stack frames are larger.-fno-ira-share-spill-slotsโ disables sharing of stack slots allocated for pseudo-registers. Each pseudo-register that does not get a hard register gets a separate stack slot, and as a result function stack frames are larger.-flra-rematโ enables CFG-sensitive rematerialization in LRA. Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it's profitable โจ. 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โ disables instruction scheduling across basic blocks, which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fno-sched-specโ disables speculative motion of non-load instructions, which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-pressureโ enables register pressure sensitive insn scheduling before register allocation. This only makes sense when scheduling before register allocation is enabled, i.e. with-fschedule-insnsor at-O2or higher. 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, and-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. And-fsched-stalled-insns-depwithout a value is equivalent to-fsched-stalled-insns-dep=1. ๐ฆ-fsched2-use-superblocksโ okay so when you're scheduling after register allocation, this one lets GCC use superblock scheduling ๐ which means instructions can move across basic block boundaries, and that gives you faster schedules. But bestie, listen: this option is experimental, because not every machine description GCC uses models the CPU closely enough to dodge unreliable results from this algorithm. So likeโฆ it might slay, it might be messy ๐ญ
This only makes sense when you're scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
-fsched-group-heuristicโ turns on the group heuristic in the scheduler โจ this one favors the instruction that belongs to a schedule group. It's on by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-critical-path-heuristicโ enables the critical-path heuristic in the scheduler ๐ฏ favors instructions on the critical path. On by default whenever scheduling is on, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-spec-insn-heuristicโ enables the speculative instruction heuristic in the scheduler ๐ฆ favors speculative instructions with greater dependency weakness. On by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-rank-heuristicโ enables the rank heuristic in the scheduler ๐ favors the instruction belonging to a basic block with greater size or frequency. On by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-last-insn-heuristicโ enables the last-instruction heuristic in the scheduler ๐ซ favors the instruction that's less dependent on the last instruction scheduled. On by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-dep-count-heuristicโ enables the dependent-count heuristic in the scheduler ๐ธ favors the instruction that has more instructions depending on it. On by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-freschedule-modulo-scheduled-loopsโ so modulo scheduling happens before traditional scheduling, right? And if a loop is modulo scheduled, later scheduling passes might change its schedule ๐ this option is how you control that behavior.-fselective-schedulingโ schedule instructions using the selective scheduling algorithm โญ selective scheduling runs instead of the first scheduler pass.-fselective-scheduling2โ same selective scheduling algorithm energy, but this one runs instead of the second scheduler pass ๐-fsel-sched-pipeliningโ enables software pipelining of innermost loops during selective scheduling ๐ heads up though: this option has no effect unless one of-fselective-schedulingor-fselective-scheduling2is turned on.-fsel-sched-pipelining-outer-loopsโ when you're pipelining loops during selective scheduling, this also pipelines outer loops ๐ but again, no effect unless-fsel-sched-pipeliningis turned on. iykyk.-fsemantic-interpositionโ some object formats, like ELF, allow interposing of symbols by the dynamic linker ๐ง which means: for symbols exported from the DSO, the compiler can't do interprocedural propagation, inlining and other optimizations, because it has to anticipate that the function or variable in question might change. Like, it's useful โ say, to rewrite memory allocation functions with a debugging implementation โ but it's 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). Same deal for variables: if interposition happens, the constructor of the variable will be the same. The flag has no effect for functions explicitly declared inline (where it's never allowed for interposition to change semantics) and for symbols explicitly declared weak.
-fshrink-wrapโ emit function prologues only before the parts of the function that actually need it, instead of dumping them at the top of the function like a normie ๐ฆ enabled by default at-Oand higher.-fshrink-wrap-separateโ shrink-wraps separate parts of the prologue and epilogue separately, so those parts only get executed when needed โจ on by default, but has no effect unless-fshrink-wrapis also turned on and the target supports this.-fcaller-savesโ enables allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls ๐พ such allocation only happens when it seems to result in better code.
This option is always enabled by default on certain machines โ usually the ones with no call-preserved registers to use instead.
Enabled at levels -O2, -O3, -Os.
-fcombine-stack-adjustmentsโ tracks stack adjustments (pushes and pops) and stack memory references, then tries to find ways to combine them ๐ฅ enabled by default at-O1and higher.-fipa-raโ use caller save registers for allocation if those registers aren't used by any called function ๐ฏ in that case you don't need to save and restore them around calls. Only possible if the called functions are part of the same compilation unit as the current function and they're compiled before it.
Enabled at levels -O2, -O3, -Os, however the option is disabled if generated code will be instrumented for profiling (-p, or -pg) or if the callee's register usage can't be known exactly (this happens on targets that don't expose prologues and epilogues in RTL).
-fconserve-stackโ attempt to minimize stack usage ๐ the compiler tries to use less stack space, even if that makes the program slower. This option implies setting thelarge-stack-frameparameter to100and thelarge-stack-frame-growthparameter to400.-ftree-reassocโ perform reassociation on trees ๐ 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. Especially useful as a code size optimization, but it often helps for code speed as well. Enabled by default at-O2and higher.-ftree-preโ perform partial redundancy elimination (PRE) on trees โจ enabled by default at-O2and-O3.-ftree-partial-preโ makes partial redundancy elimination (PRE) more aggressive ๐ enabled by default at-O3.-ftree-forwpropโ perform forward propagation on trees ๐ฆ 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. 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 ๐ enabled by default at-O2and higher.-ftree-copy-propโ perform copy propagation on trees ๐ซ this pass eliminates unnecessary copy operations. Enabled by default at-O1and higher.-fipa-pure-constโ discover which functions are pure or constant ๐ง enabled by default at-O1and higher.-fipa-referenceโ discover which static variables do not escape the compilation unit ๐ enabled by default at-O1and higher.-fipa-reference-addressableโ discover read-only, write-only and non-addressable static variables โญ enabled by default at-O1and higher.-fipa-stack-alignmentโ reduce stack alignment on call sites if possible ๐ฆ enabled by default.-fipa-ptaโ perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐ heads up: this option can cause excessive memory and compile-time usage on large compilation units ๐ it is not enabled by default at any optimization level.-fipa-profileโ perform interprocedural profile propagation. Functions called only from cold functions are marked as cold ๐ฅถ also, functions executed once (such as"cold","noreturn", static constructors or destructors) are identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at-O1and higher.-fipa-modrefโ perform interprocedural mod/ref analysis ๐ this optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. Enabled by default at-O1and higher.-fipa-cpโ perform interprocedural constant propagation โจ this optimization analyzes the program to figure out when values passed to functions are constants, then optimizes accordingly. Can substantially increase performance if the application has constants passed to functions ๐ฅ 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) ๐ enabled by default at-O3. It is also enabled by-fprofile-useand-fauto-profile.-fipa-bit-cpโ when enabled, perform interprocedural bitwise constant propagation ๐ enabled by default at-O2and by-fprofile-useand-fauto-profile. It requires that-fipa-cpis enabled.-fipa-vrpโ okay so this one does interprocedural propagation of value ranges when it's turned on. It's on by default at-O2, and heads up: it needs-fipa-cpto be enabled too, like it literally can't do its thing without it. ๐-fipa-icfโ this one does Identical Code Folding for functions and read-only variables. It shrinks your code size, but bestie, it may disturb unwind stacks because it replaces a function with an equivalent one that has a different name ๐ญ. Works way more effectively when link-time optimization is enabled.
So the behavior is similar to the Gold Linker's ICF optimization, but GCC ICF works on different levels, so the optimizations are not the same โ there are equivalences found only by GCC and equivalences found only by Gold. Both iconic, not identical, iykyk.
Enabled by default at -O2 and -Os โจ
-flive-patching=level โ this controls GCC's optimizations so the output is suitable for live-patching.
Real talk: if the compiler's optimization uses a function's body, or info extracted from its body, to optimize/change another function, that latter one is called an impacted function of the former. So if you patch a function, its impacted functions should be patched too. Periodt.
The impacted functions get 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. So to control how many impacted functions there are and to make computing that list easier, IPA optimizations can be partially enabled at two different levels.
The level argument should be one of these:
inline-cloneโ only enables inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. So when you patch a function, all its callers and its clones' callers are impacted, and therefore need patching too.
-flive-patching=inline-clone disables these optimization flags: -fwhole-program -fipa-pta -fipa-reference -fipa-ra -fipa-icf -fipa-icf-functions -fipa-icf-variables -fipa-bit-cp -fipa-vrp -fipa-pure-const -fipa-reference-addressable -fipa-stack-alignment -fipa-modref
inline-only-staticโ only enables inlining of static functions. So when you patch a static function, all its callers are impacted and need to be patched as well.
On top of all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static also disables: -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). No cap.
-fisolate-erroneous-paths-dereferenceโ detects paths that trigger erroneous or undefined behavior because of dereferencing a null pointer ๐. It isolates those paths from the main control flow and turns the statement with the erroneous or undefined behavior into a trap. Enabled by default at-O2and higher, and it depends on-fdelete-null-pointer-checksalso being enabled.-fisolate-erroneous-paths-attributeโ detects paths that trigger erroneous or undefined behavior because a null value is being used in a way that's forbidden by a"returns_nonnull"or"nonnull"attribute. It isolates those paths from the main control flow and turns the statement with the erroneous or undefined behavior into a trap. This is not currently enabled, but it may be enabled by-O2in the future ๐.-ftree-sinkโ performs forward store motion on trees. Enabled by default at-O1and higher โจ-ftree-bit-ccpโ performs sparse conditional bit constant propagation on trees and propagates pointer alignment information. This pass only operates on local scalar variables and is enabled by default at-O1and higher, except for-Og. It requires that-ftree-ccpis enabled ๐-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees. This pass only operates on local scalar variables and is enabled by default at-O1and higher.-fssa-backpropโ propagates information about uses of a value up the definition chain so the definitions can get simplified ๐. For example, this pass strips sign operations if the sign of a value never matters. Enabled by default at-O1and higher.-fssa-phioptโ performs pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at-O1and higher, except for-Og.-ftree-switch-conversionโ performs conversion of simple initializations in a switch to initializations from a scalar array. Enabled by default at-O2and higher โญ-ftree-tail-mergeโ looks for identical code sequences ๐. When it finds them, it replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. Enabled by default at-O2and higher. The compilation time in this pass can be limited using themax-tail-merge-comparisonsparameter and themax-tail-merge-iterationsparameter.-ftree-dceโ performs dead code elimination (DCE) on trees. Enabled by default at-O1and higher ๐-ftree-builtin-call-dceโ performs conditional dead code elimination (DCE) for calls to built-in functions that may set"errno"but are otherwise free of side effects. Enabled by default at-O2and higher if-Osisn't also specified.-ffinite-loopsโ assumes that a loop with an exit will eventually take that exit and not loop forever ๐ฅ. This lets the compiler remove loops that otherwise have no side-effects, since it doesn't consider eventual endless looping as one of those side-effects.
Enabled by default at -O2 for C++ with -std=c++11 or higher.
-ftree-dominator-optsโ performs a whole variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. It also does jump threading (to reduce jumps to jumps). Enabled by default at-O1and higher โจ-ftree-dseโ performs dead store elimination (DSE) on trees. So a dead store is a store into a memory location that gets overwritten later by another store without any intervening loads โ in that case the earlier store can be deleted ๐๏ธ. Enabled by default at-O1and higher.-ftree-chโ performs loop header copying on trees. This is beneficial because it increases the effectiveness of code motion optimizations, and it also saves one jump ๐ . Enabled by default at-O1and higher. It's not enabled for-Os, since it usually increases code size.-ftree-loop-optimizeโ performs loop optimizations on trees. Enabled by default at-O1and higher.-ftree-loop-linear,-floop-strip-mine,-floop-blockโ perform loop nest optimizations. Same as-floop-nest-optimize. To use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure ๐ฆ-fgraphite-identityโ enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using-fgraphite-identitywe can check the costs or benefits of the GIMPLE -> GRAPHITE -> GIMPLE transformation. Some minimal optimizations are also performed by the code generator isl, like index splitting and dead code elimination in loops ๐ธ-floop-nest-optimizeโ enables the isl based loop nest optimizer. It's a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental โ ๏ธ-floop-parallelize-allโ uses the Graphite data dependence analysis to identify loops that can be parallelized. It parallelizes all the loops that can be analyzed to not contain loop carried dependences, without checking that it's profitable to parallelize the loops ๐-ftree-coalesce-varsโ while transforming the program out of the SSA representation, it attempts to reduce copying by coalescing versions of different user-defined variables instead of just compiler temporaries. Warning bestie: this may severely limit the ability to debug an optimized program compiled with-fno-var-tracking-assignments๐ญ. In the negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise.-ftree-loop-if-convertโ attempts to transform conditional jumps in the innermost loops into branch-less equivalents. The intent is to remove control-flow from the innermost loops so the vectorization pass can handle these loops better ๐. Enabled by default if vectorization is enabled.-ftree-loop-distributionโ performs loop distribution. This can improve cache performance on big loop bodies and lets further loop optimizations โ like parallelization or vectorization โ take place. For example, the 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
This flag is 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, the loop
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
...it gets transformed into something like this:
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and bestie, that whole initialization loop becomes a straight-up call to memset zero. Chef's kiss. โจ This flag is on by default at -O3, and it's also switched on by -fprofile-use and -fauto-profile.
-floop-interchangeโ does loop interchange outside of graphite. It can level up your cache performance on loop nests and lets other loop optimizations (hi, vectorization ๐) actually happen. Like, 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];
becomes this:
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, and also enabled by -fprofile-use and -fauto-profile. ๐ซ
-floop-unroll-and-jamโ applies unroll-and-jam transformations to loops where that's actually feasible. In a loop nest it unrolls the outer loop by some factor and fuses the resulting multiple inner loops together. Enabled by default at-O3, and also enabled by-fprofile-useand-fauto-profile. ๐-ftree-loop-imโ performs loop invariant motion on trees. Real talk though, this pass only moves the invariants that are hard to handle at the RTL level (think function calls, and operations that expand into nontrivial sequences of insns). Paired with-funswitch-loops, it also lifts operands of conditions that are invariant out of the loop, so loop unswitching can get away with just trivial invariantness analysis. This pass also includes store motion. ๐ง-ftree-loop-ivcanonโ creates a canonical counter for the number of iterations in loops where figuring out that count takes complicated analysis. Later optimizations can then figure out the number easily. Super useful, especially when paired with unrolling. ๐ข-ftree-scev-cpropโ performs final value replacement. So if a variable gets modified inside a loop in a way where its value on exit can be worked out from just its initial value plus the number of loop iterations, then it replaces uses of that final value with the computation instead โ assuming that computation is cheap enough. This cuts down data dependencies and may unlock further simplifications. Enabled by default at-O1and higher. โจ-fivoptsโ performs induction variable optimizations on trees: strength reduction, induction variable merging, and induction variable elimination. The whole glow-up package. ๐-ftree-parallelize-loops=nโ parallelizes loops, i.e. splits their iteration space so they run acrossnthreads. Heads up: this only works for loops whose iterations are independent and can be reordered arbitrarily. And the optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive rather than constrained by, say, memory bandwidth. This option implies-pthread, which means it's only supported on targets that actually support-pthread. ๐งต-ftree-ptaโ performs function-local points-to analysis on trees. Enabled by default at-O1and higher, except for-Og. ๐ฏ-ftree-sraโ performs scalar replacement of aggregates. This pass swaps structure references out for scalars so it doesn't commit structures to memory too early. Enabled by default at-O1and higher, except for-Og. ๐๏ธ-fstore-mergingโ merges narrow stores that land on consecutive memory addresses. It takes contiguous stores of immediate values narrower than a word and merges them into fewer, wider stores to cut down the instruction count. Enabled by default at-O2and higher as well as-Os. ๐งฉ-ftree-terโ performs temporary expression replacement during the SSA->normal phase. Single use/single def temporaries get replaced at their use location with the expression that defines them. Yeah, this produces non-GIMPLE code, but it hands the expanders way more complex trees to work with, which results in better RTL generation. Enabled by default at-O1and higher. ๐-ftree-slsrโ performs straight-line strength reduction on trees. It spots related expressions involving multiplications and swaps them for cheaper calculations when it can. Enabled by default at-O1and higher. ๐ช-ftree-vectorizeโ performs vectorization on trees. This flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif you haven't explicitly specified them. ๐-ftree-loop-vectorizeโ performs loop vectorization on trees. Enabled by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile. ๐-ftree-slp-vectorizeโ performs basic block vectorization on trees. Enabled by default at-O2and by-ftree-vectorize,-fprofile-use, and-fauto-profile. ๐งฑ-ftrivial-auto-var-init=choiceโ initializes automatic variables with either a pattern or with zeroes, which boosts a program's security and predictability by preventing uninitialized memory disclosure and use. Okay but here's the catch, bestie โ GCC still treats an automatic variable that has no explicit initializer as uninitialized:-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still warn about those variables, and the compiler will optimize as if the variable were uninitialized. ๐ With this option, GCC also zeroes out any padding of automatic variables that have structure or union types. But โ and this is the annoying part โ the current implementation cannot initialize automatic variables that are declared between the controlling expression and the firstcaseof aswitchstatement. Use-Wtrivial-auto-var-initto report all those cases.
The three values of choice are:
uninitializedโ doesn't initialize any automatic variables. This is C and C++'s default.patternโ initializes automatic variables with values that will likely turn logic bugs into crashes down the line, are easily recognized in a crash dump, and aren't values programmers can lean on for useful program semantics. The current value is a byte-repeatable pattern with byte0xFE. Ngl, the values used for pattern initialization might change in the future.zeroโ initializes automatic variables with zeroes.
The default is uninitialized.
You can control this behavior for one specific variable using the variable attribute uninitialized. ๐
-fvect-cost-model=modelโ changes the cost model used for vectorization. The model argument should be one ofunlimited,dynamic,cheaporvery-cheap. With theunlimitedmodel, the vectorized code-path is assumed to be profitable. With thedynamicmodel, a runtime check guards the vectorized code-path so it only kicks in for iteration counts that will likely run faster than the original scalar loop. Thecheapmodel disables vectorization of loops where doing so would be cost prohibitive โ like when you'd need runtime checks for data dependence or alignment โ but otherwise it's equal to thedynamicmodel. Thevery-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code being vectorized. For 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 eitherdynamicorcheap. ๐ธ-fsimd-cost-model=modelโ changes the cost model used for vectorization of loops marked with the OpenMPsimddirective. The model argument should be one ofunlimited,dynamic,cheap. All the 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โ performs Value Range Propagation on trees. It's kinda like the constant propagation pass, except instead of values it propagates ranges of values. That lets the optimizers nuke unnecessary range checks like array bound checks and null pointer checks. Enabled by default at-O2and higher. Heads up: null pointer check elimination only happens if-fdelete-null-pointer-checksis enabled. ๐ง-fsplit-pathsโ splits paths that lead to loop backedges. This can improve dead code elimination and common subexpression elimination. Enabled by default at-O3and above. ๐-fsplit-ivs-in-unrollerโ lets values of induction variables in later iterations of the unrolled loop be expressed using the value from the first iteration. This breaks up long dependency chains, which makes the scheduling passes way more efficient. A combo of-fweband CSE is often enough to get the same effect โ but that's not reliable when the loop body is more complicated than a single basic block, and on some architectures it doesn't work at all because of restrictions in the CSE pass. This optimization is enabled by default. โ๏ธ๐ฅ-fvariable-expansion-in-unrollerโ with this, the compiler makes multiple copies of some local variables when unrolling a loop, which can result in superior code. Enabled by default for PowerPC targets, disabled by default everywhere else. ๐ฌ-fpartial-inliningโ inlines parts of functions. Just so you know, this option only does anything when inlining itself is turned on via the-finline-functionsor-finline-small-functionsoptions. Enabled at levels-O2,-O3,-Os. โ๏ธ-fpredictive-commoningโ performs predictive commoning optimization, i.e. reusing computations (especially memory loads and stores) that were performed in previous iterations of loops. Enabled at level-O3, and also enabled by-fprofile-useand-fauto-profile. ๐ฎ-fprefetch-loop-arraysโ if the target machine supports it, generates instructions to prefetch memory so loops that access large arrays run faster. Fair warning: this option may generate better or worse code โ the results are highly dependent on the structure of the loops within your source code. Disabled at level-Os. ๐ฌ๏ธ-fno-printf-return-valueโ bestie, this one is about not substituting constants for the known return value of formatted output functions likesprintf,snprintf,vsprintf, andvsnprintf(but heads up, notprintforfprintf๐ ). When the substitution is on, GCC can optimize โ or literally eliminate โ branches based on the known return value of those functions when they're called with arguments that are either constant, or whose values are known to be in a range that makes figuring out the exact return value possible. So 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 gives its best results with -O2 and above โจ. It works in tandem with the -Wformat-overflow and -Wformat-truncation options. And yes, -fprintf-return-value is enabled by default ๐.
-fno-peephole-fno-peephole2โ disables any machine-specific peephole optimizations ๐ซถ. The difference between-fno-peepholeand-fno-peephole2is literally just how they're implemented in the compiler โ some targets use one, some use the other, and a few use both, iykyk.
-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.
-fno-guess-branch-probabilityโ do not guess branch probabilities using heuristics, periodt.
GCC uses heuristics to guess branch probabilities if they aren't provided by profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by __builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can be complex, and in some cases it may be useful to disable the heuristics so that the effects of __builtin_expect are easier to understand ๐
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 so we reduce the number of taken branches and improve code locality ๐ธ. Enabled at levels-O1,-O2,-O3,-Os.-freorder-blocks-algorithm=algorithm โ use the specified algorithm for basic block reordering, bestie. The algorithm argument can besimple, which does not increase code size (except sometimes due to secondary effects like alignment), orstc, the "software trace cache" algorithm, which tries to put all often executed code together and minimize 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โ in addition to reordering basic blocks in the compiled function to reduce the number of taken branches, this one partitions hot and cold basic blocks into separate sections of the assembly and.ofiles, to improve paging and cache locality performance ๐ฅ.
This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or target specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that does not support named sections. When -fsplit-stack is used this option isn't enabled by default (to avoid linker errors), but it may be enabled explicitly (if you're using a working linker).
Enabled for x86 at levels -O2, -O3, -Os.
-freorder-functionsโ reorders functions in the object file to improve code locality โจ. This gets implemented by using special subsections.text.hotfor the most frequently executed functions and.text.unlikelyfor the unlikely-executed ones. Reordering is done by the linker, so the object file format must support named sections and the linker must place them in a reasonable way.
This option isn't effective unless you either provide profile feedback (see -fprofile-arcs for 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 applicable to the language being compiled ๐ . For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, anunsigned intcan alias anint, but not avoid*or adouble. A character type may alias any other type.
Pay special attention to code like this ๐:
union a_union {
int i;
double d;
};
int f() {
union a_union t;
t.d = 3.0;
return t.i;
}
The practice of reading from a different union member than the one most recently written to (called "type-punning") is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So the code above works as expected. However, this code might not:
int f() {
union a_union t;
int* ip;
t.d = 3.0;
ip = &t.i;
return *ip;
}
Similarly, access by taking the address, casting the resulting pointer, and dereferencing the result has undefined behavior โ even if the cast uses a union type, like:
int f() {
double d = 3.0;
return ((union a_union *) &d)->i;
}
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-fipa-strict-aliasingโ controls whether the rules of-fstrict-aliasingapply across function boundaries ๐. Note that if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary.
The -fipa-strict-aliasing option is enabled by default and is effective only in combination with -fstrict-aliasing.
-falign-functions-falign-functions=n-falign-functions=n:m-falign-functions=n:m:n2-falign-functions=n:m:n2:m2 โ align the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes ๐. This ensures that at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. It's an optimization of code performance, and alignment is ignored for functions considered cold. If alignment is required for all functions, use-fmin-function-alignment.
If m isn't specified, it defaults to n.
Examples, because we love a demo: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, and -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less โจ.
The second pair of n2:m2 values 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's rounded up ๐ซถ.
-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned.
If n isn't specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-flimit-function-alignmentโ if this is enabled, the compiler tries to avoid unnecessarily overaligning functions ๐. It attempts to instruct the assembler to align by the amount specified by-falign-functions, but not to skip more bytes than the size of the function.-falign-labels-falign-labels=n-falign-labels=n:m-falign-labels=n:m:n2-falign-labels=n:m:n2:m2 โ align all branch targets to a power-of-two boundary ๐.
The parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean labels aren't aligned.
If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.
If n isn't specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-falign-loops-falign-loops=n-falign-loops=n:m-falign-loops=n:m:n2-falign-loops=n:m:n2:m2 โ align loops to a power-of-two boundary ๐. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. It's an optimization of code performance, and alignment is ignored for loops considered cold.
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 aren't aligned. The maximum allowed n option value is 65536.
If n isn't 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 โ align 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. It's an optimization of code performance, and alignment is ignored for jumps considered cold.
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 that loops are not aligned.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
๐ฅ Enabled at levels -O2, -O3.
-fmin-function-alignmentโ Specify minimal alignment of functions to the next power-of-two greater than or equal ton. Unlike-falign-functionsthis alignment is applied also to all functions (even those considered cold). The alignment is also not affected by-flimit-function-alignment.-fno-allocation-dceโ Do not remove unused C++ allocations in dead code elimination. no ghost allocations getting swept, bestie ๐-fallow-store-data-racesโ Allow the compiler to perform optimizations that may introduce new data races on stores, without proving that the variable cannot be concurrently accessed by other threads. Does not affect optimization of local data. It is safe to use this option if it is known that global data will not be accessed by multiple threads.
Examples of optimizations enabled by -fallow-store-data-races include hoisting or if-conversions that may cause a value that was already in memory to be re-written with that same value. Such re-writing is safe in a single threaded context but may be unsafe in a multi-threaded context. Note that on some processors, if-conversions may be required in order to enable vectorization.
Enabled at level -Ofast. โจ
-funit-at-a-timeโ This option is left for compatibility reasons.-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, andasmstatements. Output them in the same order that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.
-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Additionally -fno-toplevel-reorder implies -fno-section-anchors.
-funreachable-trapsโ With this option, the compiler turns calls to__builtin_unreachableinto traps, instead of using them for optimization. This also affects any such calls implicitly generated by the compiler.
This option has the same effect as -fsanitize=unreachable -fsanitize-trap=unreachable, but does not affect the values of those options. If -fsanitize=unreachable is enabled, that option takes priority over this one.
This option is enabled by default at -O0 and -Og. ๐
-fwebโ Constructs webs as commonly used for register allocation purposes and assign each web individual pseudo register. This allows the register allocation pass to operate on pseudos directly, but also strengthens several other optimization passes, such as CSE, loop optimizer and trivial dead code remover. It can, however, make debugging impossible, since variables no longer stay in a "home register".
Enabled by default with -funroll-loops. ๐
-fwhole-programโ Assume that the current compilation unit represents the whole program being compiled. All public functions and variables with the exception ofmainand those merged by attributeexternally_visiblebecome static functions and in effect are optimized more aggressively by interprocedural optimizers.
With -flto this option has a limited use. In most cases the precise list of symbols used or exported from the binary is known the resolution info passed to the link-time optimizer by the linker plugin. It is still useful if no linker plugin is used or during incremental link step when final code is produced (with -flto -flinker-output=nolto-rel).
-flto[=n]โ 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.
To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example:
gcc -c -O2 -flto foo.c
gcc -c -O2 -flto bar.c
gcc -o myprog -flto -O2 foo.o bar.o
The first two invocations to GCC save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one. This means, for example, that the inliner is able to inline functions in bar.o into functions in foo.o and vice-versa.
Another (simpler) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
The above generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation and optimizes them as usual to produce myprog.
The important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command.
To make whole program optimization effective, it is necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of the link-time optimized unit. When supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to allow the compiler to make these assumptions, which leads to more aggressive optimization decisions.
When a file is compiled with -flto without -fuse-linker-plugin, the generated object file is larger than a regular object file because it contains GIMPLE bytecodes and the usual final code (see -ffat-lto-objects). This means that object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster but you cannot perform a regular, non-LTO link on them.
When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. Therefore, you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing.
Generally, options specified at link time override those specified at compile time, although in some cases GCC attempts to infer link-time options from the settings used to compile the input files.
If you do not specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files. Note that it is generally ineffective to specify an optimization level option only at link time and not at compile time, for two reasons. First, compiling without optimization suppresses compiler passes that gather information needed for effective optimization at link time. Second, some early optimization passes can be performed only at compile time and not at link time.
There are some code generation flags preserved by GCC when generating bytecodes, as they need to be used during the final link. Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags.
The following options -fPIC, -fpic, -fpie and -fPIE are combined based on the following scheme:
-fPIC + -fpic = -fpic
-fPIC + -fno-pic = -fno-pic
-fpic/-fPIC + (no option) = (no option)
-fPIC + -fPIE = -fPIE
-fpic + -fPIE = -fpie
-fPIC/-fpic + -fpie = -fpie
Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is ignored. This includes options such as -freg-struct-return and -fpcc-struct-return.
Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing are passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time.
Diagnostic options such as -Wstringop-overflow are passed through to the link stage and their setting matches that of the compile-step at function granularity. Note that this matters only for diagnostics emitted during optimization. Note that code transforms such as inlining can lead to warnings being enabled or disabled for regions if code not consistent with the setting at compile time.
When you need to pass options to the assembler via -Wa or -Xassembler make sure to either compile such translation units with -fno-lto or consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time. slay the link step, bestie ๐๐
okay bestie so to actually get debug info generated you gotta hand over -g at compile time, no way around it. if any of the input files at link time were built with debug info generation turned on, then the link turns debug info generation on too. but like โ any elaborate debug info settings, the fancy stuff like the dwarf level -gdwarf-5, have to be explicitly repeated at the linker command line, and mixing different settings across different translation units is discouraged fr fr. just don't.
and if LTO bumps into objects with C linkage declared with incompatible types in separate translation units being linked together โ which is undefined behavior per ISO C99 6.2.7, not me being dramatic, that's the spec โ a non-fatal diagnostic may be issued. the behavior is still undefined at run time. similar diagnostics may get raised for other languages too. so like, the compiler is being nice by warning you, but it's not saving you ๐
another very slay feature of LTO: you can apply interprocedural optimizations on files written in different languages. look at this:
gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran
notice the final link is done with g++ so you get the C++ runtime libraries, and -lgfortran is tacked on to get the Fortran runtime libraries. generally, when you're mixing languages in LTO mode, use the same link command options as you would when mixing languages in a regular (non-LTO) compilation. consistency is the vibe โจ
if object files containing GIMPLE bytecode are chilling in a library archive โ say libfoo.a โ you can extract and use them in an LTO link if you're using a linker with plugin support. to make static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; and to show the symbols of object files with GIMPLE bytecode, use gcc-nm. those commands require that ar, ranlib and nm have been compiled with plugin support. at link time, use the flag -fuse-linker-plugin to make sure the library actually participates in the LTO optimization process:
gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo
with the linker plugin enabled, the linker extracts the needed GIMPLE files from libfoo.a and passes them on to the running GCC so they become part of the aggregated GIMPLE image that's gonna get optimized. iconic behavior ๐ซถ
if you're not using a linker with plugin support and/or you don't enable the linker plugin, then the objects inside libfoo.a get extracted and linked as usual โ but they don't participate in the LTO optimization process. and if you want a static library that's suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects. both worlds, bestie ๐
link-time optimizations don't need the whole program present to operate, which is lowkey so nice. if the program doesn't require any symbols to be exported, you can combine -flto and -fwhole-program to let the interprocedural optimizers use more aggressive assumptions, which may lead to improved optimization opportunities. but heads up: use of -fwhole-program is not needed when the linker plugin is active (see -fuse-linker-plugin).
now the sad part ๐ญ โ the current implementation of LTO makes no attempt to generate bytecode that's portable between different types of hosts. the bytecode files are versioned and there's a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC. periodt. keep your versions matched.
also: link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF. just so you know ๐
if you specify the optional n, the optimization and code generation done at link time runs in parallel using n parallel jobs by utilizing an installed make program. the environment variable MAKE may be used to override the program used. cute, right?
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 (don't skip that, it will Not work). this option likely only works if MAKE is GNU make. and even without the option value, GCC tries to automatically detect a running GNU make's job server โ it's giving observant ๐
use -flto=auto to use GNU make's job server if it's available, or otherwise fall back to autodetection of the number of CPU threads present in your system. auto-pilot mode, love that for you โญ
-flto-partition=alg
specify the partitioning algorithm used by the link-time optimizer. the value is either:
1to1โ partitioning that mirrors the original source filesbalancedโ partitioning into equally sized chunks (whenever possible)maxโ create a new partition for every symbol where possible
specifying none as an algorithm disables partitioning and streaming completely. the default value is balanced. while 1to1 can be used as a workaround for various code ordering issues, the max partitioning is intended for internal testing only โ do not come for me if you try it. the value one specifies that exactly one partition should be used, while the value none bypasses partitioning and executes the link-time optimization step directly from the WPA phase. so many options, all valid, pick your fighter ๐
-flto-compression-level=n
this one specifies 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:
- zstd โ valid values are
0(no compression) to19(maximum compression) - zlib โ supports values from
0to9
values outside this range get clamped to either the minimum or maximum of the supported values (so no, -flto-compression-level=1000 isn't gonna do anything extra, it just clamps). if the option isn't given, a default balanced compression setting is used. balanced queen ๐
-fuse-linker-plugin
enables the use of a linker plugin during link-time optimization. this option relies on plugin support in the linker, which is available in gold or in GNU ld 2.21 or newer. so like, check your linker bestie.
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). free upgrade, we love to see it โจ
-ffat-lto-objects
fat LTO objects are object files that contain both the intermediate language and the object code. this makes them usable for both LTO linking and normal linking. this option is effective only when compiling with -flto and is ignored at link time. (fat = thicc with two c's, both payloads inside ๐)
-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO. it requires a linker with linker plugin support for basic functionality. additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. with non fat LTO, makefiles need to be modified to use them. yes, you gotta edit the makefiles. sorry ๐ญ
also note that modern binutils provide a plugin auto-load mechanism. installing the linker plugin into $libdir/bfd-plugins has the same effect as usage of the command wrappers (gcc-ar, gcc-nm and gcc-ranlib). same energy, different route.
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. sneaky efficient, obsessed ๐
this pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete. so like, target-dependent.
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. honestly? tidy.
enabled at levels -O1, -O2, -O3, -Os.
-fprofile-correction
profiles collected using an instrumented binary for multi-threaded programs may be inconsistent due to missed counter updates (the counters simply miss stuff, it happens). 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. no correction, just judgment.
this option is enabled by -fauto-profile.
-fprofile-partial-training
with -fprofile-use, all portions of programs not executed during the train run are optimized aggressively for size rather than speed. in some cases it's just not practical to train all possible hot paths in the program โ for example, the program may contain functions specific to a given hardware, and training may not cover all hardware configurations the program is run on. with -fprofile-partial-training, profile feedback will be ignored for all functions not executed during the train run, which leads them to be optimized as if they were compiled without profile feedback. this leads to better performance when the train run isn't representative, but it also leads to significantly bigger code. tradeoff city, bestie ๐ธ
-fprofile-use
-fprofile-use=path
enable profile feedback-directed optimizations, plus the following optimizations โ many of which are generally profitable only when profile feedback is actually 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. like, actually. it's not optional, the whole thing runs on that data.
so like, by default, GCC throws a whole error message if the feedback profiles don't match the source code ๐ค. You can turn that error into a warning by using -Wno-error=coverage-mismatch โ but bestie, note this may result in poorly optimized code ๐. Also, by default, GCC emits a warning message if the feedback profiles don't exist at all (peep -Wmissing-profile).
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
-fauto-profile,-fauto-profile=path** โ turns on sampling-based feedback-directed optimizations plus this whole squad of optimizations, many of which are generally profitable only when you actually have 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 you omit it, 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 info, see https://perf.wiki.kernel.org/.
E.g.
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then use the create_gcov tool to convert the raw profile data to a format that GCC can use. You also have to 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
okay now we're entering the floating-point zone ๐๐ โ the following options control compiler behavior regarding floating-point arithmetic. They trade off between speed and correctness, and every single one must be specifically enabled (no auto-magic, 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 or C++, if-fexcess-precision=standardis specified then excess precision follows the rules specified in ISO C99 or C++; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas-ffloat-storeonly affects assignments). This option is enabled by default for C or C++ if a strict conformance option such as-std=c99or-std=c++17is 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 or 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.
-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โ do not set"errno"after calling math functions that are executed with a single instruction, e.g.,"sqrt". A program that relies on IEEE exceptions for math error handling may want to use this flag for speed while maintaining IEEE arithmetic compatibility.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
The default is -fmath-errno.
On Darwin systems, the math library never sets "errno". There is therefore no reason for the compiler to consider the possibility that it might, and -fno-math-errno is the default.
-funsafe-math-optimizationsโ allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link time, it may include libraries or startup files that change the default FPU control word or other similar optimizations.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.
The default is -fno-unsafe-math-optimizations.
-fassociative-mathโ allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like"(x + 2**52) - 2**52". May also reorder floating-point comparisons and thus may not be used when ordered comparisons are required. This option requires that both-fno-signed-zerosand-fno-trapping-mathbe in effect. Moreover, it doesn't make much sense with-frounding-math. For Fortran the option is automatically enabled when both-fno-signed-zerosand-fno-trapping-mathare in effect.
The default is -fno-associative-math.
-freciprocal-mathโ allow the reciprocal of a value to be used instead of dividing by the value if this enables optimizations. For example"x / y"can be replaced with"x * (1/y)", which is useful if"(1/y)"is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value.
The default is -fno-reciprocal-math.
-ffinite-math-onlyโ allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
The default is -fno-finite-math-only.
-fno-signed-zerosโ allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct+0.0and-0.0values, which then prohibits simplification of expressions such asx+0.0or0.0*x(even with-ffinite-math-only). This option implies that the sign of a zero result isn't significant.
The default is -fsigned-zeros.
-fno-trapping-mathโ compile code assuming that floating-point operations cannot generate user-visible traps. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that-fno-signaling-nansbe in effect. Setting this option may allow faster code if one relies on "non-stop" IEEE arithmetic, for example.
This option should never be turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions.
The default is -ftrapping-math.
Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used along with -frounding-math to specify the default state for "FENV_ACCESS".
-frounding-mathโ disable transformations and optimizations that assume default floating-point rounding behavior. This is round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. This option should be specified for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. This option disables constant folding of floating-point expressions at compile time (which may be affected by rounding mode) and arithmetic transformations that are unsafe in the presence of sign-dependent rounding modes.
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used along with -ftrapping-math to specify the default state for "FENV_ACCESS".
-fsignaling-nansโ okay so this one says: compile assuming IEEE signaling NaNs might throw user-visible traps during floating-point ops ๐. Turning it on disables the optimizations that could change how many exceptions are visible when signaling NaNs are around. It implies-ftrapping-math. Bonus: it makes the preprocessor macro__SUPPORT_SNAN__get defined โจ. The default is-fno-signaling-nans. And bestie, heads up: this option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior ๐ญ so likeโฆ vibe with caution.-fno-fp-int-builtin-inexactโ this one tells the built-in functionsceil,floor,roundandtrunc(plus theirfloatandlong doublevariants) not to generate code that raises theinexactfloating-point exception for noninteger arguments. Why does that matter? Because ISO C99 and C11 allow these functions to raiseinexact, but ISO/IEC TS 18661-1:2014 (the C bindings to IEEE 754-2008, as integrated into ISO C2X) does not allow them to ๐ธ. The default is-ffp-int-builtin-inexactโ i.e. the exception is allowed โ unless C2X or a later C standard is selected. Ngl this option does literally nothing unless-ftrapping-mathis in effect. And even with-fno-fp-int-builtin-inexact, if the functions generate a call to a library function, theinexactexception may still be raised if the library implementation doesn't follow TS 18661 ๐.-fsingle-precision-constantโ treats floating-point constants as single precision instead of sneakily implicitly converting them to double-precision constants. No cap, that's the whole thing ๐.-fcx-limited-rangeโ when enabled, this option states that a range reduction step is not needed when performing complex division. Also: no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case ๐. Default is-fno-cx-limited-range, but it gets enabled by-ffast-math. It controls the default setting of the ISO C99CX_LIMITED_RANGEpragma โ but the option itself applies to all languages, periodt ๐ .-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. The default is-fno-cx-fortran-rules๐.
The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code ๐ญ โ yes, broken, like actually broken, you've been warned bestie ๐ซถ.
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilitiesto improve optimizations based on 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. (Details about the file naming live in-fprofile-arcs.)
With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently they're only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often ๐
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-useand-fauto-profile.-frename-registersโ attempt to avoid false dependencies in scheduled code by making use of registers left over after register allocation. This optimization most benefits processors with lots of registers ๐. Depending on the debug information format adopted by the target, however, it can make debugging impossible, since variables no longer stay in a "home register" ๐ญ. Enabled by default with-funroll-loops.-fschedule-fusionโ performs a target dependent pass over the instruction stream to schedule instructions of the same type together, because the target machine can execute them more efficiently if they're adjacent to each other in the instruction flow ๐ฆ. Enabled at levels-O2,-O3,-Os.-ftracerโ perform tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, allowing other optimizations to do a better job ๐. Enabled by-fprofile-useand-fauto-profile.-funroll-loopsโ unroll loops whose number of iterations can be determined at compile time or upon entry to the loop.-funroll-loopsimplies-frerun-cse-after-loop,-fweband-frename-registers. It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). This option makes code larger, and may or may not make it run faster ๐ข. Enabled by-fprofile-useand-fauto-profile.-funroll-all-loopsโ unroll all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly ๐.-funroll-all-loopsimplies the same options as-funroll-loops.-fpeel-loopsโ peels loops for which there 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 a small constant number of iterations) ๐. Enabled by-O3,-fprofile-use, and-fauto-profile.-fmove-loop-invariantsโ enables the loop invariant motion pass in the RTL loop optimizer. Enabled at level-O1and higher, except for-Ogโจ.-fmove-loop-storesโ enables the loop store motion pass in the GIMPLE loop optimizer. This moves invariant stores to after the end of the loop in exchange for carrying the stored value in a register across the iteration. Note: for this option to have an effect,-ftree-loop-imhas to be enabled as well ๐. Enabled at level-O1and higher, except for-Og.-fsplit-loopsโ split a loop into two if it contains a condition that's always true for one side of the iteration space and false for the other โ๏ธ. Enabled by-fprofile-useand-fauto-profile.-funswitch-loopsโ move branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (modified according to the result of the condition) ๐. Enabled by-fprofile-useand-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-sectionsand-fdata-sectionsโ place each function or data item into its own section in the output file if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file ๐ท๏ธ.
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.
Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping) ๐.
On ELF/DWARF systems these options do not degenerate the quality of the debug information. There could be issues with other object files/debug info formats.
Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower ๐ญ. These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions.
-fstdarg-optโ optimize the prologue of variadic argument functions with respect to usage of those arguments โจ.-fsection-anchorsโ try to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to reduce the number of GOT entries and GOT accesses on some targets ๐.
For example, the implementation of the following function foo:
static int a, b, c;
int foo (void) { return a + b + c; }
...the compiler usually just calculates the addresses of all three variables, but if you compile with -fsection-anchors, it grabs them from one shared anchor point instead ๐
the effect is basically this pseudocode (which, heads up, isn't valid C):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
and ngl, not every target supports this option ๐
-fzero-call-used-regs=choiceโ zeroes out the call-used registers at function return so your program is more secure ๐ช it does this either by mitigating Return-Oriented Programming (ROP) attacks or by stopping information from leaking through registers. The possible values of choice are the same as for thezero_call_used_regsattribute, and the default isskip. You can control this behaviour for one specific function by using the function attributezero_call_used_regs๐--param name=valueโ so GCC has a bunch of constants hiding inside it that control how much optimization gets done. Like, GCC won't inline functions that contain more than a certain number of instructions, right? Well, you can control some of these constants right from the command line with--paramโจ
The names of the specific parameters, and what their values actually mean, are tied to the compiler's internals, and are subject to change without notice in future releases ๐ (iykyk โ don't build your whole personality on these staying the same).
Wanna see the minimal, maximal and default values of a parameter? Use the --help=param -Q options. Super handy ๐ซถ
In every case, the value is an integer. The following choices of name are recognized for all targets:
predictable-branch-outcomeโ when a branch is predicted to be taken with a probability lower than this threshold (in percent), then it's considered well predictable ๐ธmax-rtl-if-conversion-insnsโ RTL if-conversion tries to remove the conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the max number of instructions in a block that should be considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable, so it's not just vibes ๐max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove the conditional branches around a block and swap them for conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that if-conversion would generate, depending on whether the branch is statically determined to be predictable or not. The units for this parameter are the same as those for the GCC internalseq_costmetric. The compiler will try to provide a reasonable default for this parameter using theBRANCH_COSTtarget macro โจmax-crossjump-edgesโ the max 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. Bumping this value up means more aggressive optimization, which makes compilation time go up with probably only a small improvement in executable size ๐ญmin-crossjump-insnsโ the minimum number of instructions that have to match 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 max number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behaviour in a bunch of passes, GCC factors computed gotos early in the compilation process and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more thanmax-goto-duplication-insnsare unfactored ๐max-delay-slot-insn-searchโ the max number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions get searched, the time savings from filling the delay slot are minimal, so stop searching. Increasing values mean more aggressive optimization, which makes compilation time go up with probably a small improvement in execution time ๐max-delay-slot-live-searchโ when trying to fill delay slots, the max 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 compilation time. This parameter should be removed when the delay slot code gets rewritten to maintain the control-flow graph ๐max-gcse-memoryโ the approximate maximum amount of memory inkBthat can be allocated to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization just doesn't happen ๐คทโโ๏ธmax-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream ๐max-pending-list-lengthโ the max 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 max number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time ๐max-inline-functions-called-once-loop-depthโ maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once โจmax-inline-functions-called-once-insnsโ maximal estimated size of functions produced while inlining functions called once ๐ซถmax-inline-insns-singleโ several parameters control the tree inliner used in GCC. This number sets the max number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++) ๐max-inline-insns-autoโ when you use-finline-functions(which is included in-O3), a lot of functions that would otherwise not be considered for inlining by the compiler get investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto) ๐max-inline-insns-smallโ this is the bound applied to calls which are considered relevant with-finline-small-functions๐ธmax-inline-insns-sizeโ this is the bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization opportunities exposed by inlining โจuninlined-function-insnsโ number of instructions accounted by the inliner for function overhead such as function prologue and epilogue ๐uninlined-function-timeโ extra time accounted by the inliner for function overhead such as the time needed to execute function prologue and epilogue โณinline-heuristics-hint-percentโ the scale (in percents) applied toinline-insns-single,inline-insns-single-O2andinline-insns-autowhen inline heuristics hint that inlining is very profitable (which will enable later optimizations) ๐ฅuninlined-thunk-insns,uninlined-thunk-timeโ same as--param uninlined-function-insnsand--param uninlined-function-timebut applied to function thunks ๐inline-min-speedupโ when the estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on--param max-inline-insns-singleand--param max-inline-insns-auto๐large-function-insnsโ the limit specifying really large functions. For functions larger than this limit after inlining, inlining is constrained by--param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by non-linear algorithms used by the back end ๐ญlarge-function-growthโ specifies maximal growth of a large function caused by inlining, in percents. For example, parameter value100limits large function growth to 2.0 times the original size ๐large-unit-insnsโ the limit specifying a large translation unit. Growth caused by inlining of units larger than this limit is limited by--param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of function A that's inline and B that just calls A three times. If B is small relative to A, the growth of the unit is 300% and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. So for smaller units, the size is increased to--param large-unit-insnsbefore applying--param inline-unit-growth๐lazy-modulesโ max number of concurrently open C++ module files when lazy loading ๐๏ธinline-unit-growthโ specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value20limits unit growth to 1.2 times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size ๐งipa-cp-unit-growthโ specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value10limits unit growth to 1.1 times the original size ๐ipa-cp-large-unit-insnsโ how big a translation unit has to be before the IPA-CP pass is like "okay that's large" ๐large-stack-frameโ the threshold that defines a "large" stack frame. While it's inlining, the algorithm genuinely tries not to blow past this limit too much ๐ซถlarge-stack-frame-growthโ the max growth of large stack frames caused by inlining, in percents. Like, a value of1000caps large stack frame growth at 11 times the original size. math is mathing ๐max-inline-insns-recursive,max-inline-insns-recursive-autoโ the max number of instructions an out-of-line copy of a self-recursive inline function can grow into via recursive inlining.
--param max-inline-insns-recursive is the one for functions declared inline. For functions that aren't declared inline, recursive inlining only happens when -finline-functions (which is included in -O3) is enabled โ and then --param max-inline-insns-recursive-auto applies instead. two flavors, pick your fighter โจ
max-inline-recursive-depth,max-inline-recursive-depth-autoโ the max recursion depth used for recursive inlining.
Same deal as above: --param max-inline-recursive-depth applies to functions declared inline, and for functions not declared inline, recursive inlining only kicks in when -finline-functions (included in -O3) is enabled, in which case --param max-inline-recursive-depth-auto applies instead ๐
min-inline-recursive-probabilityโ recursive inlining is only profitable for functions with deep recursion on average, and it can actually hurt functions with little recursion depth โ like, it bloats the prologue size or makes the function body more complex for the other optimizers ๐ญ
When profile feedback is available (see -fprofile-generate), the actual recursion depth can be guessed from the probability that a function recurses through a given call expression. This parameter limits inlining to only those call expressions whose probability exceeds the given threshold (in percents). threshold queen ๐
early-inlining-insnsโ how much growth the early inliner is allowed to make. Basically it boosts the amount of inlining for code with a large abstraction penalty ๐max-early-inliner-iterationsโ the iteration limit of the early inliner. It basically bounds how many nested indirect calls the early inliner can resolve. Deeper chains still get handled by late inlining, no worries ๐ฆcomdat-sharing-probabilityโ the probability (in percent) that a C++ inline function with comdat visibility gets shared across multiple compilation units ๐ฆmodref-max-bases,modref-max-refs,modref-max-accessesโ the max number of base pointers, references, and accesses stored for a single function by mod/ref analysis ๐๏ธmodref-max-testsโ the max number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref info. This one ought to be bigger than--param modref-max-basesand--param modref-max-refs, so keep that in mind bestie ๐modref-max-depthโ the max depth of the DFS walk used by modref escape analysis. Setting it to0disables the analysis completely. poof, gone ๐modref-max-escape-pointsโ the max number of escape points tracked by modref per SSA-name ๐โโ๏ธ๐จmodref-max-adjustmentsโ the max number of times the access range gets enlarged during modref dataflow analysis ๐profile-func-internal-idโ controls whether to use the function internal id in profile database lookup. If the value is0, the compiler uses an id based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. nostalgic profile data hours ๐min-vect-loop-boundโ the minimum number of iterations under which loops are not vectorized when-ftree-vectorizeis used. After vectorization, the number of iterations needs to be greater than the value specified by this option for vectorization to be allowed ๐gcse-cost-distance-ratioโ a scaling factor in the calculation of the max distance an expression can be moved by GCSE optimizations. Currently this is only supported in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting is with simple expressions โ aka expressions whose cost is less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions ๐ฅgcse-unrestricted-costโ the cost (roughly measured as the cost of a single typical machine instruction) at which GCSE optimizations stop constraining how far an expression can travel. Currently only supported in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying0lets all expressions travel unrestricted distances โ no cap, main character energy ๐max-hoist-depthโ the depth of the search in the dominator tree for expressions to hoist. It exists to avoid quadratic behavior in the hoisting algorithm. A value of0puts no limit on the search, but 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 used to avoid quadratic behavior in tree tail merging ๐ณmax-tail-merge-iterationsโ the max amount of iterations of the pass over the function. This is used to limit compilation time in tree tail merging โณstore-merging-allow-unalignedโ lets the store merging pass introduce unaligned stores if it's legal to do so ๐max-stores-to-mergeโ the max number of stores to attempt to merge into wider stores in the store merging pass ๐งฉmax-store-chains-to-trackโ the max number of store chains to track at the same time while trying to merge them into wider stores in the store merging pass ๐max-stores-to-trackโ the max number of stores to track at the same time in the attempt to merge them into wider stores in the store merging pass ๐max-unrolled-insnsโ the max number of instructions a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled ๐๏ธmax-average-unrolled-insnsโ the max number of instructions, biased by the probabilities of their execution, that a loop may have to be unrolled. 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 ๐max-peeled-insnsโ the max number of instructions a loop may have 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 for it 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-depthโ the max depth of a loop nest to be unswitched ๐lim-expensiveโ the minimum cost of an expensive expression in loop invariant motion ๐ธmin-loop-cond-split-probโ when FDO profile information is available, this specifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split โ๏ธiv-consider-all-candidates-boundโ a bound on the number of candidates for induction variables; below 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 give up on loops containing more induction variable uses ๐ณ๏ธiv-always-prune-cand-set-boundโ if the number of candidates in the set is smaller than this value, always try to remove unnecessary ivs from the set when adding a new one ๐งนavg-loop-niterโ the average number of iterations of a loop ๐dse-max-object-sizeโ the max size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times โ ๏ธdse-max-alias-queries-per-storeโ the max number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores ๐๏ธscev-max-expr-sizeโ a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down ๐ขscev-max-expr-complexityโ a bound on the complexity of expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down too ๐ฎโ๐จmax-tree-if-conversion-phi-argsโ the max number of arguments in a PHI supported by TREE if conversion, unless the loop is marked withsimdpragma ๐ฏvect-max-layout-candidatesโ the max number of possible vector layouts (such as permutations) to consider when optimizing to-be-vectorized code ๐งฎvect-max-version-for-alignment-checksโ the max 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 max number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer ๐ต๏ธโโ๏ธvect-max-peeling-for-alignmentโ the max number of loop peels to enhance access alignment for the vectorizer. A value of-1means no limit ๐max-iterations-to-trackโ the max number of iterations of a loop that the brute-force algorithm (the one analysing how many times a loop runs) will actually bother evaluating. Like, that's the cap on its patience ๐hot-bb-count-fractionโ so this one's the denominator n of the fraction 1/n, taken from the maximal execution count of a basic block across the whole program. A basic block needs at least that much to be considered ๐ฅhot๐ฅ. Default is10000, meaning a basic block is hot if its execution count is greater than 1/10000 of the maximal execution count.0means it's never considered hot. Used in non-LTO mode, iykyk.hot-bb-count-ws-permilleโ the number of most-executed permilles, ranging from0to1000, of the profiled execution of the entire program that a basic block's execution count has to be part of for it to count as hot. Default is990, which means a basic block is hot if its execution count contributes to the upper 990 permilles, aka 99.0%, of the profiled execution of the whole program.0means never hot, periodt. Used in LTO mode.hot-bb-frequency-fractionโ the denominator n of the fraction 1/n of the execution frequency of a function's entry block; a basic block in that function needs at least that much to be considered hot. Default is1000, so a basic block is hot within a function if it's executed more frequently than 1/1000 of the frequency of the function's entry block.0means it's never considered hot, no cap.unlikely-bb-count-fractionโ the denominator n of the fraction 1/n of the number of profiled runs of the entire program, below which a basic block's execution count has to fall for the block to be considered unlikely executed ๐. Default is20, meaning a basic block is unlikely executed if it runs in fewer than 1/20, or 5%, of the program's runs.0means it's always considered unlikely executed โ chaotic but okay.max-predicted-iterationsโ the max number of loop iterations we predict statically. Super useful when a function has one loop with a known bound and another with an unknown bound: the known iteration count gets predicted correctly, while the unknown one averages out to roughly10. Which means the loop with no bounds looks artificially cold next to the other one ๐ฅถ โ not its fault, honestly.builtin-expect-probabilityโ controls the probability of the expression having the specified value. Takes a percentage (i.e.0 ... 100) as input. Slay.builtin-string-cmp-inline-lengthโ the maximum length of a constant string for a builtin string cmp call that's eligible for inlining.align-thresholdโ picks the fraction of the maximal frequency of executions of a basic block in a function, used to align that basic block โจalign-loop-iterationsโ a loop that's expected to iterate at least the selected number of iterations gets aligned.tracer-dynamic-coverage,tracer-dynamic-coverage-feedbackโ this value limits superblock formation once the given percentage of executed instructions is covered. It keeps unnecessary code size expansion in check, bestie ๐
The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. Real profiles (as opposed to statically estimated ones) are much less balanced, which lets the threshold be a larger value.
tracer-max-code-growthโ stops tail duplication once code growth hits the given percentage. It's a pretty artificial limit, because most of the duplicates get eliminated later in cross jumping โ so you can set it to way higher values than the code growth you actually want ๐tracer-min-branch-ratioโ stops 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โ stops forward growth if the best edge's probability is lower than this threshold.
Same energy as tracer-dynamic-coverage: two parameters, one for each situation. tracer-min-branch-probability-feedback is used when compiling with profile feedback, and tracer-min-branch-probability when compiling without. The value for compilation with profile feedback needs to be more conservative (higher) to make tracer effective fr fr.
stack-clash-protection-guard-sizeโ specifies the size of the operating system provided stack guard as 2 raised to num bytes. Higher values may reduce the number of explicit probes, but heads up: a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks ๐ญ
Not me warning you twice โ protect your stack, bestie.
stack-clash-protection-probe-intervalโ stack clash protection involves probing stack space as it's allocated. This param controls the maximum distance between probes into the stack as 2 raised to num bytes. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks ๐ฅmax-cse-path-lengthโ the maximum number of basic blocks on a path that CSE considers.max-cse-insnsโ the maximum number of instructions CSE processes before flushing.ggc-min-expandโ GCC uses a garbage collector to manage its own memory allocation. This parameter specifies the minimum percentage by which the garbage collector's heap should be allowed to expand between collections. Tuning this may improve compilation speed; it has no effect on code generation. ๐ฆ
The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If "getrlimit" is available, the notion of "RAM" is the smallest of actual RAM and "RLIMIT_DATA" or "RLIMIT_AS". If GCC isn't able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity. That is extremely slow, but can be useful for debugging ๐
ggc-min-heapsizeโ minimum size of the garbage collector's heap before it begins bothering to collect garbage. The first collection happens after the heap expands byggc-min-expand%beyondggc-min-heapsize. Again, tuning this may improve compilation speed, and it has no effect on code generation โจ
The default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to make sure RLIMIT_DATA or RLIMIT_AS aren't exceeded โ with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). If GCC can't calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.
max-reload-search-insnsโ the maximum number of instructions reload should look backward for an equivalent register. Increasing values mean more aggressive optimization, which makes compilation time go up with probably slightly better performance. The eternal tradeoff, honestly ๐ซถmax-cselib-memory-locationsโ the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance.max-sched-ready-insnsโ the maximum number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass. Increasing values mean more thorough searches, making the compilation time increase with probably little benefit ๐max-sched-region-blocksโ the maximum number of blocks in a region to be considered for interblock scheduling.max-pipeline-region-blocksโ the maximum number of blocks in a region to be considered for pipelining in the selective scheduler.max-sched-region-insnsโ the maximum number of insns in a region to be considered for interblock scheduling.max-pipeline-region-insnsโ the maximum number of insns in a region to be considered for pipelining in the selective scheduler.min-spec-probโ the minimum probability (in percents) of reaching a source block for interblock speculative scheduling.max-sched-extend-regions-itersโ the maximum number of iterations through CFG to extend regions. A value of0disables region extensions.max-sched-insn-conflict-delayโ the maximum conflict delay for an insn to be considered for speculative motion.sched-spec-prob-cutoffโ the minimal probability of speculation success (in percents), so that speculative insns get scheduled.sched-state-edge-prob-cutoffโ the minimum probability an edge must have for the scheduler to save its state across it.sched-mem-true-dep-costโ minimal distance (in CPU cycles) between a store and a load targeting the same memory locations.selsched-max-lookaheadโ the maximum size of the lookahead window of selective scheduling. It's basically a depth of search for available instructions ๐selsched-max-sched-timesโ the maximum 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 maximum number of best instructions in the ready list that get considered for renaming in the selective scheduler.sms-min-scโ the minimum value of stage count that swing modulo scheduler generates. ๐max-last-value-rtlโ the biggest size, measured as a number of RTLs, that the combiner is allowed to record for a pseudo register as that register's last known value. โจmax-combine-insnsโ the max number of instructions the RTL combiner will try to combine. That's it, that's the whole vibe.integer-share-limitโ little integer constants can share one data structure, which cuts the compiler's memory use and speeds it up. This param sets the ceiling on the value of a shared integer constant. ๐ssp-buffer-sizeโ the minimum size of buffers (like, arrays, bestie) that get stack smashing protection when-fstack-protectoris in play.min-size-for-stack-sharingโ the minimum size of variables that get to take part in stack slot sharing when you're not optimizing. ๐ซถmax-jump-thread-duplication-stmtsโ the maximum number of statements allowed in a block that has to be duplicated when threading jumps.max-jump-thread-pathsโ the maximum number of paths considered when hunting for jump threading opportunities. When you land on a block, incoming edges only get considered if the number of paths searched so far times the number of incoming edges doesn't blow past this specified maximum. Math check, lowkey ๐max-fields-for-field-sensitiveโ the maximum number of fields in a structure that get treated in a field sensitive manner during pointer analysis.prefetch-latencyโ an estimate of the average number of instructions executed before a prefetch finishes. How far ahead it prefetches is proportional to this constant. Heads up though: bumping this number may also mean fewer streams get prefetched โ seesimultaneous-prefetches. ๐ฆsimultaneous-prefetchesโ maximum number of prefetches that can be running at the same time.l1-cache-line-sizeโ the size of a cache line in the L1 data cache, in bytes.l1-cache-sizeโ the size of the L1 data cache, in kilobytes.l2-cache-sizeโ the size of the L2 data cache, in kilobytes.prefetch-dynamic-stridesโ whether the loop array prefetch pass should fire off software prefetch hints for strides that are non-constant. Sometimes that's genuinely a win, but ngl, the fact that the stride is non-constant can make it hard to predict whether there's a clear benefit to issuing those hints at all.
Set it to 1 if prefetch hints should be issued for non-constant strides. Set it to 0 if prefetch hints should only be issued for strides that are known to be constant and below prefetch-minimum-stride.
prefetch-minimum-strideโ the minimum constant stride, in bytes, before we start using prefetch hints at all. If the stride is under this threshold, no prefetch hints for you ๐
This one's a lifesaver for processors with hardware prefetchers โ in that case the hardware prefetchers and software prefetchers can beef with each other. If the hardware prefetchers have a maximum stride they can handle, put it here and the software prefetchers get used way better. ๐
A value of -1 means we have no threshold, so prefetch hints can be issued for any constant stride.
This setting is only useful for strides that are known and constant. Periodt.
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 are the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, the constructive interference size is usually the small end of the range and the destructive size is the large end. ๐
The destructive interference size is meant for layout, and that means it has ABI impact. The default value is not expected to be stable, and on some targets it varies with -mtune, so using this variable anywhere ABI stability matters โ like the public interface of a library โ is strongly discouraged. If you do use it there, users can stabilize the value with this option. ๐ญ
The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure a type fits within a cache line. Cute, low-stakes.
See also -Winterference-size.
loop-interchange-max-num-stmtsโ the maximum number of stmts in a loop that'll be interchanged.loop-interchange-stride-ratioโ the minimum ratio between the strides of two loops for interchange to actually be profitable.min-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches needed to enable prefetching in a loop.prefetch-min-insn-to-mem-ratioโ the minimum ratio between the number of instructions and the number of memory references needed to enable prefetching in a loop.use-canonical-typesโ whether the compiler uses the "canonical" type system. It should always be1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. But if bugs in the canonical type system are making compilation fail, set this to0to disable canonical types. Emergency lever, iykyk ๐จswitch-conversion-max-branch-ratioโ switch initialization conversion refuses to create arrays bigger thanswitch-conversion-max-branch-ratiotimes the number of branches in the switch. Respect the cap โจ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 absolutely run away and eat all the memory on the host machine ๐ This parameter puts a limit on the length of the sets computed, which stops the runaway behavior. Setting a value of0for this parameter allows an unlimited set length โ main character energy, zero guardrails.rpo-vn-max-loop-depthโ maximum loop depth that gets value-numbered optimistically. When the limit hits, the innermostrpo-vn-max-loop-depthloops and the outermost loop in the loop nest are value-numbered optimistically and the remaining ones are not.sccvn-max-alias-queries-per-accessโ maximum number of alias-oracle queries performed when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and the load or store isn't considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry. ๐ira-max-loops-numโ IRA uses regional register allocation by default. If a function contains more loops than this parameter's number, only at most that many of the most frequently-executed loops form regions for regional register allocation.ira-max-conflict-table-sizeโ IRA uses a sophisticated algorithm to compress the conflict table, but that table can still need an excessive amount of memory for huge functions. If a function's conflict table could be bigger than the size in MB given by this parameter, the register allocator instead falls back to a faster, simpler, lower-quality algorithm that doesn't need a pseudo-register conflict table. Trade-off slay ๐ira-loop-reserved-regsโ IRA can be used to evaluate more accurate register pressure in loops when deciding whether to move loop invariants (see-O3). This parameter gives the number of available registers reserved for some other purposes. Default of the parameter is the best one found from numerous experiments. Science! ๐ฅira-consider-dup-in-all-altsโ makes IRA consider matching constraint (duplicated operand number) heavily across all available alternatives for preferred register class. If it's set to zero, IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, IRA will check all available alternatives for preferred register class even after it's found some choice with an appropriate register class โ and then respect the found qualified matching constraint.ira-simple-lra-insn-thresholdโ approximate function insn number in 1K units that triggers simple local RA.lra-inheritance-ebb-probability-cutoffโ LRA tries to reuse values reloaded in registers in subsequent insns. That optimization is called inheritance. EBB is used as the region to do it in. This parameter defines the minimal fall-through edge probability, in percentage, used to add a BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64. Very "we tested this so you don't have to" of them ๐ซถloop-invariant-max-bbs-in-loopโ loop invariant motion can get super expensive, both in compilation time and in the amount of compile-time memory needed, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them.loop-max-datarefs-for-datadepsโ building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that get considered for data dependence analysis. These large loops aren't handled by the optimizations that use loop data dependencies. ๐ธ
max-vartrack-sizeโ this one's the cap on how many hash table slots the variable tracking dataflow analysis is allowed to use for any function ๐. If the limit gets blown while variable tracking at assignments is on, the analysis for that function gets retried without it โ after all the debug insns are yeeted from the function ๐. And if it still gets exceeded even with no debug insns around? Then var tracking analysis is just completely disabled for that function, periodt. Setting this parameter to zero makes it unlimited ๐ซ.max-vartrack-expr-depthโ sets the max number of recursion levels when the compiler tries to map variable names or debug temporaries onto value expressions ๐ง. It's a straight-up trade: compilation time vs. more complete debug info. Set it too low and value expressions that are available and could be represented in debug info may end up not being used ๐ญ. Set it higher and the compiler might find way more complex debug expressions โ but compile time and memory use may grow ๐.max-debug-marker-countโ a threshold on the number of debug markers (thinkbegin stmtmarkers) so we don't get a complexity explosion at inlining or when expanding to RTL ๐. If a function has more such gimple stmts than the set limit, those stmts get dropped from the inlined copy of the function, and from its RTL expansion too.min-nondebug-insn-uidโ nondebug insns get uids starting at this parameter โจ. Everything below it is reserved exclusively for debug insns created by-fvar-tracking-assignmentsโ though debug insns may get (non-overlapping) uids above it if the reserved range runs out ๐.ipa-sra-deref-prob-thresholdโ IPA-SRA only swaps a pointer that's known to not be NULL for one or more new parameters when the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter ๐ฆ.ipa-sra-ptr-growth-factorโ IPA-SRA only replaces a pointer to an aggregate with one or more new parameters when their cumulative size is less than or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter ๐ธ.ipa-sra-ptrwrap-growth-factorโ extra maximum allowed growth of the total size of those new parameters that IPA-SRA replaces a pointer-to-an-aggregate with, in the case where it points to a local variable that the caller only writes to and passes as an argument to other functions ๐ .ipa-sra-max-replacementsโ the max pieces of an aggregate that IPA-SRA tracks ๐ฅ. Which consequently also makes it the maximum number of replacements of a formal parameter.sra-max-scalarization-size-Ospeed,sra-max-scalarization-size-Osizeโ okay so the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) are out here trying to replace scalar parts of aggregates with uses of independent scalar variables ๐ซถ. These parameters control the maximum size, in storage units, of an aggregate that gets considered for replacement when you're compiling for speed (sra-max-scalarization-size-Ospeed) or for size (sra-max-scalarization-size-Osize) respectively.sra-max-propagationsโ the max number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, to help copy propagation along ๐.tm-max-aggregate-sizeโ when making copies of thread-local variables inside a transaction, this parameter sets the size in bytes after which variables get saved with the logging functions instead of save/restore code sequence pairs ๐. Only applies when you're using-fgnu-tm, iykyk.graphite-max-nb-scop-paramsโ to dodge exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded โญ. A value of zero lifts the bound entirely. And btw, a variable whose value is unknown at compilation time and defined outside a SCoP counts as 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 ๐ฆ. You change the strip length with theloop-block-tile-sizeparameter.ipa-jump-function-lookupsโ specifies the number of statements visited during jump function offset discovery ๐.ipa-cp-value-list-sizeโ IPA-CP tries to track all possible values and types passed to a function's parameter so it can propagate them and do devirtualization ๐ซ.ipa-cp-value-list-sizeis the max number of values and types it stores per one formal parameter of a function.ipa-cp-eval-thresholdโ IPA-CP calculates its own score of cloning profitability heuristics and only performs those cloning opportunities whose scores exceedipa-cp-eval-threshold๐.ipa-cp-max-recursive-depthโ max depth of recursive cloning for a self-recursive function ๐.ipa-cp-min-recursive-probabilityโ recursive cloning happens only when the probability of the call being executed exceeds the parameter โจ.ipa-cp-profile-count-baseโ when you're using-fprofile-use, 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โ the percentage penalty recursive functions receive when they're evaluated for cloning ๐.ipa-cp-single-call-penaltyโ the percentage penalty that functions containing a single call to another function receive when they're evaluated for cloning ๐.ipa-max-agg-itemsโ IPA-CP is also capable of propagating a number of scalar values passed in an aggregate ๐.ipa-max-agg-itemscontrols the maximum number of such values per one parameter.ipa-cp-loop-hint-bonusโ when IPA-CP figures out that a cloning candidate would make the number of iterations of a loop known, it adds a bonus ofipa-cp-loop-hint-bonusto the profitability score of that candidate ๐.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โ during its analysis of function bodies, IPA-CP employs alias analysis to track values pointed to by function parameters ๐. But so it doesn't spend forever analyzing huge functions, it gives up and considers all memory clobbered after examiningipa-max-aa-stepsstatements that modify memory ๐ .ipa-max-switch-predicate-boundsโ maximal number of boundary endpoints of case ranges of a switch statement ๐. For a switch that exceeds this limit, IPA-CP will not construct the cloning cost predicate โ the thing used to estimate cloning benefit โ for the default case of the switch statement.ipa-max-param-expr-opsโ IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit of cloning upon a certain constant value ๐ฅ. But if the number of operations in a parameter expression exceedsipa-max-param-expr-ops, the expression gets treated as a complicated one, and IPA analysis doesn't handle it.lto-partitionsโ specify the desired number of partitions produced during WHOPR compilation ๐งฉ. The number of partitions should exceed the number of CPUs used for compilation.lto-min-partitionโ size of the minimal partition for WHOPR (in estimated instructions) ๐. This prevents the expense of splitting very small programs into way too many partitions.lto-max-partitionโ size of the max partition for WHOPR (in estimated instructions), to provide an upper bound for the individual size of a partition ๐ซถ. Meant to be used only with balanced partitioning.lto-max-streaming-parallelismโ maximal number of parallel processes used for LTO streaming ๐.cxx-max-namespaces-for-diagnostic-helpโ the max number of namespaces to consult for suggestions when C++ name lookup fails for an identifier ๐.sink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block that still allows statement sinking of a statement ๐. Larger numbers result in more aggressive statement sinking. A small positive adjustment is applied for statements with memory operands, since those are even more profitable to sink.max-stores-to-sinkโ the max number of conditional store pairs that can be sunk ๐ฆ. Set it to 0 if 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 is 0, 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โ set the maximum number of instructions executed in parallel in a reassociated tree ๐. This parameter overrides target dependent heuristics used by default if it has a non zero value.sched-pressure-algorithmโ picks which of the two implementations of-fsched-pressureyou get. Algorithm 1 is the OG, and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was designed as a compromise between algorithm 1's kinda-conservative vibe and the default scheduler's full-send aggressive energy. It leans way harder on having a regular register file and accurate register pressure classes. More deets live inhaifa-sched.ccin the GCC sources if you're that girl. Default choice? Depends on the target, bestie. ๐max-slsr-cand-scanโ sets the max number of existing candidates that get considered when hunting for a basis for a new straight-line strength reduction candidate.asan-globalsโ turns on buffer overflow detection for global objects. It's on by default if you're using-fsanitize=address. Wanna yeet global objects protection?--param asan-globals=0. โจasan-stackโ buffer overflow detection for stack objects, on by default with-fsanitize=address. Kill stack protection with--param asan-stack=0.asan-instrument-readsโ buffer overflow detection for memory reads. On by default with-fsanitize=address; disable with--param asan-instrument-reads=0.asan-instrument-writesโ buffer overflow detection for memory writes. On by default with-fsanitize=address; disable with--param asan-instrument-writes=0.asan-memintrinโ detection for built-in functions, on by default with-fsanitize=address. Turn it off with--param asan-memintrin=0.asan-use-after-returnโ detection of use-after-return, on by default when you use-fsanitize=address. Disable with--param asan-use-after-return=0.
โ ๏ธ Note, bestie: by default the check is disabled at run time. To actually enable it, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS. Don't forget this part, iykyk ๐
asan-instrumentation-with-call-thresholdโ if the number of memory accesses in the function being instrumented is greater or equal to this number, it uses callbacks instead of inline checks. E.g. to disable inline code use--param asan-instrumentation-with-call-threshold=0.asan-kernel-mem-intrinsic-prefixโ if nonzero, prefixes calls tomemcpy,memsetandmemmovewith__asan_or__hwasan_for-fsanitize=kernel-addressor-fsanitize=kernel-hwaddress, respectively.hwasan-instrument-stackโ enables hwasan instrumentation of statically sized stack-allocated variables. On by default with-fsanitize=hwaddress, off by default with-fsanitize=kernel-hwaddress. Disable stack instrumentation with--param hwasan-instrument-stack=0, enable it with--param hwasan-instrument-stack=1. ๐hwasan-random-frame-tagโ when using stack instrumentation, decides tags for stack variables using a deterministic sequence beginning at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. Enabled by default for-fsanitize=hwaddressand unavailable for-fsanitize=kernel-hwaddress. Disable with--param hwasan-random-frame-tag=0.hwasan-instrument-allocasโ enables hwasan instrumentation of dynamically sized stack-allocated variables. On by default with-fsanitize=hwaddress, off by default with-fsanitize=kernel-hwaddress. Disable instrumentation of such variables with--param hwasan-instrument-allocas=0, enable it with--param hwasan-instrument-allocas=1.hwasan-instrument-readsโ enables hwasan checks on memory reads. Instrumentation of reads is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. Disable with--param hwasan-instrument-reads=0.hwasan-instrument-writesโ enables hwasan checks on memory writes. On by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. Disable with--param hwasan-instrument-writes=0.hwasan-instrument-mem-intrinsicsโ enables hwasan instrumentation of builtin functions. On by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. Disable with--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, it directly poisons (or unpoisons) shadow memory instead of using run-time callbacks.tsan-distinguish-volatileโ emits special instrumentation for accesses to volatiles.tsan-instrument-func-entry-exitโ emits instrumentation calls to__tsan_func_entry()and__tsan_func_exit().max-fsm-thread-path-insnsโ max number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.threader-debugโthreader-debug=[none|all]enables verbose dumping of the threader solver. ๐parloops-chunk-sizeโ chunk size of omp schedule for loops parallelized by parloops.parloops-scheduleโ schedule type of omp schedule for loops parallelized by parloops (static,dynamic,guided,auto,runtime).parloops-min-per-threadโ the minimum number of iterations per thread of an innermost parallelized loop for which the parallelized variant is preferred over the single threaded one. Note that for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two.max-ssa-name-query-depthโ maximum depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion corresponds to following a use-def chain.max-speculative-devirt-maydefsโ the maximum number of may-defs we analyze when looking for a must-def specifying the dynamic type of an object that invokes a virtual call we may be able to devirtualize speculatively.evrp-sparse-thresholdโ maximum number of basic blocks before EVRP uses a sparse cache.ranger-debugโ specifies the type of debug output to be issued for ranges.evrp-switch-limitโ specifies the maximum number of switch cases before EVRP ignores a switch.unroll-jam-min-percentโ the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable.unroll-jam-max-unrollโ the maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.max-rtl-if-conversion-unpredictable-costโ maximum permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that is considered unpredictable.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris used, the maximum number of times that an individual variable will be expanded during loop unrolling.partial-inlining-entry-probabilityโ maximum probability of the entry BB of split region (in percent relative to entry BB of the function) to make partial inlining happen.max-tracked-strlensโ maximum number of strings for which strlen optimization pass will track string lengths.gcse-after-reload-partial-fractionโ the threshold ratio for performing partial redundancy elimination after reload.gcse-after-reload-critical-fractionโ the threshold ratio of critical edges execution count that permit performing redundancy elimination after reload.max-loop-header-insnsโ the maximum number of insns in loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enable loop epilogue vectorization using smaller vector size. ๐ฆvect-partial-vector-usageโ controls when the loop vectorizer considers using partial vector loads and stores as an alternative to falling back to scalar code.0stops the vectorizer from ever using partial vector loads and stores.1allows partial vector loads and stores if vectorization removes the need for the code to iterate.2allows partial vector loads and stores in all loops. The parameter only has an effect on targets that support partial vector loads and stores.vect-inner-loop-cost-factorโ the maximum factor which the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the maximum of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is50.vect-induction-floatโ enable loop vectorization of floating point inductions.avoid-fma-max-bitsโ maximum number of bits for which we avoid creating FMAs.sms-loop-average-count-thresholdโ a threshold on the average loop count considered by the swing modulo scheduler.sms-dfa-historyโ the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.graphite-allow-codegen-errorsโ whether codegen errors should be ICEs when-fchecking.sms-max-ii-factorโ a factor for tuning the upper bound that swing modulo scheduler uses for scheduling a loop. ๐ฅlra-max-considered-reload-pseudosโ the max number of reload pseudos that get considered while we're spilling a non-reload pseudo ๐max-pow-sqrt-depthโ maximum depth of sqrt chains 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, no cap frasan-instrument-allocasโ turns on asan allocas/VLAs protection โจmax-iterations-computation-costโ the bound on the cost of an expression to compute the number of iterationsmax-isl-operationsโ maximum number of isl operations, and0means unlimited ๐ฆgraphite-max-arrays-per-scopโ maximum number of arrays per scopmax-vartrack-reverse-op-sizeโ max size of loc list for which reverse ops should be addedfsm-scale-path-stmtsโ scale factor to apply to the number of statements in a threading path crossing a loop backedge, when comparing against--param=max-jump-thread-duplication-stmtsuninit-control-dep-attemptsโ maximum number of nested calls to search for control dependencies during uninitialized variable analysisuninit-max-chain-lenโ maximum number of predicates anded for each predicate ored in the normalized predicate chainuninit-max-num-chainsโ maximum number of predicates ored in the normalized predicate chainsched-autopref-queue-depthโ hardware autoprefetcher scheduler model control flag ๐ number of lookahead cycles the model looks into; at' 'only enable instruction sorting heuristicloop-versioning-max-inner-insnsโ the maximum number of instructions an inner loop can have before the loop versioning pass decides it's too big to copyloop-versioning-max-outer-insnsโ the maximum number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy, discounting any instructions in inner loops that directly benefit from versioningssa-name-def-chain-limitโ the maximum number ofSSA_NAMEassignments to follow when determining a property of a variable, like its value. This caps the number of iterations or recursive calls GCC does when optimizing certain statements, or when determining their validity before issuing diagnostics ๐store-merging-max-sizeโ maximum size of a single store merging region, in byteshash-table-verification-limitโ the number of elements for which hash table verification is done, for each searched elementmax-find-base-term-valuesโ maximum number ofVALUEs handled during a singlefind_base_termcallanalyzer-max-enodes-per-program-pointโ the maximum number of exploded nodes per program point inside the analyzer, before it terminates analysis of that point ๐analyzer-max-constraintsโ the maximum number of constraints per stateanalyzer-min-snodes-for-call-summaryโ the minimum number of supernodes within a function for the analyzer to even consider summarizing its effects at call sitesanalyzer-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 formatanalyzer-max-recursion-depthโ the maximum number of times a callsite can appear in a call stack within the analyzer, before it terminates analysis of a call that would recurse deeperanalyzer-max-svalue-depthโ the maximum depth of a symbolic value, before the value gets approximated as unknownanalyzer-max-infeasible-edgesโ the maximum number of infeasible edges to reject before declaring a diagnostic as infeasiblegimple-fe-computed-hot-bb-thresholdโ the number of executions of a basic block that counts as hot ๐ฅ this parameter is used only in GIMPLE FEanalyzer-bb-explosion-factorโ the maximum number of 'after supernode' exploded nodes within the analyzer per supernode, before terminating analysisranger-logical-depthโ maximum depth of logical expression evaluation the ranger will look through when evaluating outgoing edge rangesranger-recompute-depthโ maximum depth of instruction chains to consider for recomputation in the outgoing range calculatorrelation-block-limitโ maximum number of relations the oracle will register in a basic blockmin-pagesizeโ minimum page size for warning purposesopenacc-kernelsโ specifies the mode of OpenACCkernelsconstructs handling. With--param=openacc-kernels=decompose, OpenACCkernelsconstructs are decomposed into parts โ a sequence of compute constructs, each then handled individually. This one's work in progress, heads up ๐ง With--param=openacc-kernels=parloops, OpenACCkernelsconstructs are handled by the parloops pass, en bloc. And that's the current default.openacc-privatizationโ controls whether the-fopt-info-omp-noteand applicable-fdump-tree-*-detailsoptions emit OpenACC privatization diagnostics. With--param=openacc-privatization=quiet, don't diagnose (and that's the current default). With--param=openacc-privatization=noisy, do diagnose ๐ฃ๏ธ
The following choices of name are available on AArch64 targets, bestie ๐
aarch64-sve-compare-costsโ when vectorizing for SVE, consider using "unpacked" vectors for smaller elements and let the cost model pick the cheapest approach โจ also use the cost model to choose between SVE and Advanced SIMD vectorization.
Using unpacked vectors includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores.
aarch64-float-recp-precisionโ the number of Newton iterations for calculating the reciprocal forfloattype. The precision of division is proportional to this param when division approximation is enabled. Default value is1.aarch64-double-recp-precisionโ the number of Newton iterations for calculating the reciprocal fordoubletype. The precision of division is propotional to this param when division approximation is enabled. Default value is2.aarch64-autovec-preferenceโ forces an ISA selection strategy for auto-vectorization ๐ช accepts values from0to4, inclusive:0โ use the default heuristics.1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE. Prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE. Prefer SVE when the costs are deemed equal.
The default value is 0.
aarch64-loop-vect-issue-rate-nitersโ the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. If this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations ๐aarch64-vect-unroll-limitโ the vectorizer will use available tuning information to figure out whether unrolling the main vectorized loop would be beneficial, and by how much. This parameter set's the upper bound of how much the vectorizer will unroll the main loop. Default value isfour.
The following choices of name are available on i386 and x86_64 targets ๐
x86-stlf-window-ninsnsโ instructions number above which STFL stall penalty can be compensatedx86-stv-max-visitsโ the maximum number of use and def visits when discovering a STV chain, before the discovery gets aborted ๐
๐ Program Instrumentation Options ๐
GCC supports a bunch of command-line options that control adding run-time instrumentation to the code it normally generates. Like, one purpose of instrumentation is collecting profiling statistics so you can find program hot spots, do code coverage analysis, or run profile-guided optimizations โจ Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses โ plus deliberately hostile attacks such as stack smashing or C++ vtable hijacking ๐ค There's also a general hook you can use to implement other forms of tracing or function-level instrumentation, for debug or program analysis purposes. iykyk.
-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 ๐
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's not the final executable โ otherwise it's 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) ๐ซถ
๐ก ok bestie, tiny note first: if a command line directly links source files, the corresponding.gcdafiles get prefixed with the unsuffixed name of the output file. E.g.gcc a.c b.c -o binarywould generatebinary-a.gcdaandbinary-b.gcdafiles. no cap.
--coverageโ this one is for compiling and linking code thatโs instrumented for coverage analysis. Itโs literally a synonym for-fprofile-arcs-ftest-coveragewhen compiling, and-lgcovwhen linking. See those optionsโ docs for the full tea. ๐ซถ- 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 letsgcovfind the correct sources in projects where compilations happen 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. slay, honestly. ๐
-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 ofauxnameand 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 freestanding environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. ๐ง
The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:
.gcov_info :
{
PROVIDE (__gcov_info_start = .);
KEEP (*(.gcov_info))
PROVIDE (__gcov_info_end = .);
}
The program could dump the profiling information registered in this linker set for example like this:
#include <gcov.h>
#include <stdio.h>
#include <stdlib.h>
extern const struct gcov_info *const __gcov_info_start[];
extern const struct gcov_info *const __gcov_info_end[];
static void
dump (const void *d, unsigned n, void *arg)
{
const unsigned char *c = d;
for (unsigned i = 0; i < n; ++i)
printf ("%02x", c[i]);
}
static void
filename (const char *f, void *arg)
{
__gcov_filename_to_gcfn (f, dump, arg );
}
static void *
allocate (unsigned length, void *arg)
{
return malloc (length);
}
static void
dump_gcov_info (void)
{
const struct gcov_info *const *info = __gcov_info_start;
const struct gcov_info *const *end = __gcov_info_end;
/* Obfuscate variable to prevent compiler optimizations. */
__asm__ ("" : "+r" (info));
while (info != end)
{
void *arg = NULL;
__gcov_info_to_gcda (*info, filename, dump, allocate, arg);
putchar ('\n');
++info;
}
}
int
main (void)
{
dump_gcov_info ();
return 0;
}
The merge-stream subcommand of gcov-tool may be used to deserialize the data stream generated by the __gcov_filename_to_gcfn and __gcov_info_to_gcda functions and merge the profile information into .gcda files on the host filesystem. ๐ฆ
-fprofile-note=pathโ if path is specified, GCC saves.gcnofile into path location.
โ ๏ธ if you combine the option with multiple source files, the .gcno file will be overwritten. bestie, donโt say I didnโt warn you. ๐
-fprofile-prefix-path=pathโ this option can be used in combination withprofile-generate=profile_dirandprofile-use=profile_dirto inform GCC where is the base directory of built source tree. By defaultprofile_dirwill contain files with mangled absolute paths of all object files in the built project. This is not desirable when directory used to build the instrumented binary differs from the directory used to build the binary optimized with profile feedback because the profile data will not be found during the optimized build. In such setups-fprofile-prefix-path=pathwith path pointing to the base directory of the build can be used to strip the irrelevant part of the path and keep all file names relative to the main build directory. ๐ธ-fprofile-prefix-map=old=newโ when compiling files residing in directory old, record profiling information (with--coverage) describing them as if the files resided in directory new instead. See also-ffile-prefix-mapand-fcanon-prefix-map. ๐-fprofile-update=methodโ alter the update method for an application instrumented for profile feedback based optimization. The method argument should be one ofsingle,atomicorprefer-atomic. The first one is useful for single-threaded applications, while the second one prevents profile corruption by emitting thread-safe code.
โ ๏ธ Warning: When an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted.
Using prefer-atomic would be transformed either to atomic, when supported by a target, or to single otherwise. The GCC driver automatically selects prefer-atomic when -pthread is present in the command line. ๐
-fprofile-filter-files=regexโ instrument only functions from files whose name matches any of the regular expressions (separated by semi-colons). ๐
For example, -fprofile-filter-files=main\.c;module.*\.c will instrument only main.c and all C files starting with 'module'.
-fprofile-exclude-files=regexโ instrument only functions from files whose name does not match any of the regular expressions (separated by semi-colons). ๐
For example, -fprofile-exclude-files=/usr/.* will prevent instrumentation of all files that are located in the /usr/ folder. periodt. ๐
-fprofile-reproducible=[multithreaded|parallel-runs|serial]โ bestie, this one controls how reproducible the profile is that-fprofile-generategathers ๐. Why do we care? Because it lets you rebuild the program with the same outcome, which is lowkey a whole thing for stuff like distribution packages.
With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded, and profile data streaming is always done in the same order. Small note: profile streaming happens at the end of the program run but also before the fork function is invoked ๐.
Also be aware it's quite common that execution counts of some part of programs depend on stuff like the length of temporary file names or memory space randomization (which may affect hash-table collision rate). Such non-reproducible parts of programs may be annotated by the no_instrument_function function attribute โจ. And gcov-dump with -l can be used to dump gathered data and verify that they are indeed reproducible, slay.
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 (like with make -j). Trade-off though: it reduces the quality of 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. This option enables-fsanitize-address-use-after-scope. More deets at <https://github.com/google/sanitizers/wiki/AddressSanitizer>. The run-time behavior can be influenced using theASAN_OPTIONSenvironment variable โ when it's set tohelp=1, the available options are shown at startup of the instrumented program. Full list of supported options lives at <https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags>. The option cannot be combined with-fsanitize=threador-fsanitize=hwaddress. And note: the only targets-fsanitize=hwaddressis currently supported on are x86-64 (only with-mlam=u48or-mlam=u57options) and AArch64 โ and in both cases only in ABIs with 64-bit pointers.
To get more accurate stack traces, you can use options such as -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which prevents optimizing sibling and tail recursive calls; this option is implicit for -O0, -O1, or -Og), or -fno-ipa-icf (which disables Identical Code Folding for functions). And since multiple runs of the program may yield backtraces with different addresses due to ASLR (Address Space Layout Randomization), it may be desirable to turn ASLR off โ on Linux, this can be achieved with:
setarch `uname -m` -R ./prog
-fsanitize=kernel-addressโ enables AddressSanitizer for the Linux kernel ๐ง. More at <https://github.com/google/kernel-sanitizers>.-fsanitize=hwaddressโ enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer so it can detect memory errors with 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. More at <https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html>. The run-time behavior can be influenced using theHWASAN_OPTIONSenvironment variable โ set tohelp=1, and the available options are shown at startup of the instrumented program. This 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. Those differences exist to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte.
Heads up: this option has different defaults to-fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but are still possible by specifying the command-line options--param hwasan-instrument-stack=1and--param hwasan-instrument-allocas=1respectively. Using a random frame tag is not implemented for kernel instrumentation.
-fsanitize=pointer-compareโ instruments comparison operation (<,<=,>,>=) with pointer operands ๐ฆ. The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread. Note: by default the check is disabled at run time โ to enable it, adddetect_invalid_pointer_pairs=2to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1detects 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, adddetect_invalid_pointer_pairs=2to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1detects 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, then 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's specifically designed for Linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc ๐ญ โ so if you wanna use this feature in user space, you need to provide your own runtime support. And it should be noted that this may cause the ABI rules to be broken.
On aarch64, the instrumentation makes use of the platform register x18. This generally means that any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 โ otherwise functions compiled without -ffixed-x18 might clobber x18 and so corrupt the shadow stack pointer ๐.
Also, because there's no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. Use -fno-exceptions to turn off exceptions.
See <https://clang.llvm.org/docs/ShadowCallStack.html> for more details.
-fsanitize=threadโ enables ThreadSanitizer, a fast data race detector ๐ฅ. Memory access instructions are instrumented to detect data race bugs. More at <https://github.com/google/sanitizers/wiki#threadsanitizer>. The run-time behavior can be influenced using theTSAN_OPTIONSenvironment variable โ full list of supported options at <https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags>. The option cannot be combined with-fsanitize=addressor-fsanitize=leak.
Note: sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
-fsanitize=leakโ enables LeakSanitizer, a memory leak detector ๐. This option only matters for linking of executables โ the executable gets linked against a library that overridesmallocand other allocator functions. More at <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>. The run-time behavior can be influenced using theLSAN_OPTIONSenvironment variable. The option cannot be combined with-fsanitize=thread.-fsanitize=undefinedโ enables UndefinedBehaviorSanitizer, a fast undefined behavior detector โจ. Various computations are instrumented to detect undefined behavior at runtime. More at <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>. The run-time behavior can be influenced using theUBSAN_OPTIONSenvironment variable. Current suboptions are:-fsanitize=shiftโ this option enables checking that the result of a shift operation is not undefined ๐. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc. This option has two suboptions:-fsanitize=shift-baseand-fsanitize=shift-exponent.-fsanitize=shift-exponentโ this option enables checking that the second argument of a shift operation is not negative and is smaller than the precision of the promoted first argument ๐ .-fsanitize=shift-baseโ if the second argument of a shift operation is within range, check that the result of a shift operation is not undefined ๐ฆ. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc.-fsanitize=integer-divide-by-zeroโ detects integer division by zero ๐ค.-fsanitize=unreachableโ with this option, the compiler turns the__builtin_unreachablecall into a diagnostics message call instead. When reaching the__builtin_unreachablecall, the behavior is undefined ๐.-fsanitize=vla-boundโ this option instructs the compiler to check that the size of a variable length array is positive ๐ธ.-fsanitize=nullโ this option enables pointer checking ๐. Particularly, the application built with this option turned on will issue an error message when it tries to dereference aNULLpointer, or if a reference (possibly an rvalue reference) is bound to aNULLpointer, or if a method is invoked on an object pointed by aNULLpointer.
-fsanitize=returnโ this one's the return-statement bouncer ๐ . Programs built with it will throw an error message the moment the end of a non-void function gets reached without actually returning a value. C++ only, bestie โ don't come looking for it in C.-fsanitize=signed-integer-overflowโ signed integer overflow checking, bestie! We check that the result of+,*, and both unary and binary-doesn't overflow in signed arithmetics. It also catchesINT_MIN / -1signed division ๐ฅ. Note tho: integer promotion rules must be taken into account. Which means this is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ instruments array bounds, so various out-of-bounds accesses get detected ๐. Not instrumented: flexible array members, flexible array member-like arrays, and initializers of variables with static storage โ the one exception being flexible array member-like arrays for which the-fstrict-flex-arraysor-fstrict-flex-arrays=options orstrict_flex_arrayattributes say they shouldn't be treated like flexible array member-like arrays. Ik, that's a mouthful, but it's exactly what it says ๐.-fsanitize=bounds-strictโ strict instrumentation of array bounds. Most out-of-bounds accesses get detected, including flexible array member-like arrays. Initializers of variables with static storage are not instrumented.-fsanitize=alignmentโ checks the alignment of pointers when they get dereferenced, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object ๐ฏ.-fsanitize=object-sizeโ instruments memory references using the__builtin_dynamic_object_sizefunction, so various out-of-bounds pointer accesses get detected.-fsanitize=float-divide-by-zeroโ detects floating-point division by zero. And unlike the other similar options, this one is not enabled by-fsanitize=undefined, because floating-point division by zero can legitimately be how you obtain infinities and NaNs ๐. Divas have range, okay?-fsanitize=float-cast-overflowโ floating-point type to integer conversion checking. We check the result of the conversion doesn't 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โ instruments calls, checking whether null values are not passed to arguments marked as requiring a non-null value by thenonnullfunction attribute ๐ซ.-fsanitize=returns-nonnull-attributeโ instruments return statements in functions marked with thereturns_nonnullfunction attribute, to detect returning null values from those functions. no cap, don't return null from a nonnull function.-fsanitize=boolโ instruments loads from bool. If a value other than 0/1 gets loaded, a run-time error is issued. That's it. That's the whole vibe check โจ.-fsanitize=enumโ instruments loads from an enum type. If a value outside the range of values for the enum type gets loaded, a run-time error is issued ๐.-fsanitize=vptrโ instruments C++ member function calls, member accesses, and some conversions between pointers to base and derived classes, to verify the referenced object has the correct dynamic type. main character energy only, fr fr ๐.-fsanitize=pointer-overflowโ instruments pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued ๐ฅ.-fsanitize=builtinโ instruments arguments to selected builtin functions. If an invalid value gets passed to those arguments, a run-time error is issued. E.g. passing0as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and is diagnosed by this option ๐.
Heads up bestie ๐ซถ: sanitizers tend to increase the rate of false positive warnings, most notably those around-Wmaybe-uninitialized. We recommend against combining-Werrorand [the use of] sanitizers. Like, don't do it, it's giving chaos.
Also while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message instead. This currently works only for the C family of languages.
-fno-sanitize=allโ disables all previously enabled sanitizers. And no,-fsanitize=allis not allowed, because some sanitizers cannot be used together ๐. It's giving exclusive friend group.-fasan-shadow-offset=numberโ forces GCC to use a custom shadow offset in AddressSanitizer checks. Useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer ๐ง.-fsanitize-sections=s1,s2,...โ sanitize global variables in selected user-defined sections.simay contain wildcards. cute and targeted โจ.-fsanitize-recover[=opts]โ-fsanitize-recover=controls error recovery mode for the sanitizers mentioned in the comma-separated list of opts. Enabling this option for a sanitizer component causes it to attempt to continue running the program as if no error happened. Which means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors have been reported ๐ญ. The-fno-sanitize-recover=option can be used to alter this behavior: only the first detected error is reported and the program then exits with a non-zero exit code.
Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental ๐. -fsanitize-recover=all and -fno-sanitize-recover=all are also accepted โ the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.
Even if a recovery mode is turned on the compiler side, it needs to be also enabled on the runtime library side, otherwise the failures are still fatal ๐. The runtime library defaults to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. This can be overridden through setting the halt_on_error flag in the corresponding environment variable.
Syntax without an explicit opts parameter is deprecated ๐จ. It is equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scopeโ enables sanitization of local variables to detect use-after-scope bugs. The option sets-fstack-reusetonone. obsessed with the thoroughness ๐.-fsanitize-trap[=opts]โ instructs the compiler to report for sanitizers mentioned in the comma-separated list of opts undefined behavior using__builtin_traprather than alibubsanlibrary routine. If this option is enabled for a certain sanitizer, it takes precedence over the-fsanitizer-recover=for that sanitizer โ__builtin_trapwill be emitted and be fatal regardless of whether recovery is enabled or disabled using-fsanitize-recover=๐ฅ.
The advantage? The libubsan library is not needed and is not linked in, so this is usable even in freestanding environments. slay ๐
.
Currently this feature works with -fsanitize=undefined (and its suboptions except for -fsanitize=vptr), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. -fsanitize-trap=all can also be specified, which enables it for undefined suboptions, -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. If -fsanitize-trap=undefined or -fsanitize-trap=all is used and -fsanitize=vptr is enabled on the command line, the instrumentation is silently ignored as the instrumentation always needs libubsan support โ and -fsanitize-trap=vptr is not allowed ๐
.
-fsanitize-undefined-trap-on-errorโ deprecated equivalent of-fsanitize-trap=all. old news, bestie, but it's still here ๐ธ.-fsanitize-coverage=trace-pcโ enables coverage-guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_pcinto every basic block ๐.-fsanitize-coverage=trace-cmpโ enables dataflow guided fuzzing code instrumentation. Inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8for integral comparison with both operands variable, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8for integral comparison with one operand constant,__sanitizer_cov_trace_cmpfor__sanitizer_cov_trace_cmpdfor float or double comparisons, and__sanitizer_cov_trace_switchfor switch statements. the way it has a function for every comparisonโฆ meticulous queen ๐ง.-fcf-protection=[full|branch|return|none|check]โ enables code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid ๐ก๏ธ. This prevents diverting the flow of control to an unexpected target. It's intended to protect against threats like Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP). literally the bodyguard of your control flow, ngl.
The value branch tells the compiler to implement checking of validity of control-flow transfer at the point of indirect branch instructions, i.e. call/jmp instructions. The value return implements checking of validity at the point of returning from a function. The value full is an alias for specifying both branch and return. The value none turns off instrumentation ๐.
The value "check" is for that final link step with link-time optimization (LTO) ๐
โ if your LTO object files got compiled with different -fcf-protection values, it throws an error at you. And at compile time? The "check" value is just ignored, like it's not even there ๐.
The macro __CET__ gets defined whenever you use -fcf-protection. First bit of __CET__ = 1 for the value "branch", second bit = 1 for the "return" โจ.
You can also slap the "nocf_check" attribute on stuff to mark which functions and calls should get skipped from instrumentation, super handy ๐ซถ.
Currently the x86 GNU/Linux target is the one serving us an implementation based on Intel Control-flow Enforcement Technology (CET), and it 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 (think: conditions tested for conditional moves, or ones stored in boolean variables), it emits extra code to compute and verify the reversed condition, and calls"__builtin_trap"if the results don't match ๐ญ. Pair it with-fharden-conditional-branchesto cover absolutely all the conditionals, no gaps.-fharden-conditional-branchesโ for every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and calls"__builtin_trap"if the result is unexpected ๐. Bestie, use it with-fharden-comparesso all your conditionals are covered.-fstack-protectorโ emits extra code to check for buffer overflows, like those stack smashing attacks ๐ค. How? By adding a guard variable to functions with vulnerable objects โ and that includes functions that call"alloca", plus functions with buffers larger than or equal to 8 bytes. The guards get initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits, periodt ๐ฅ. Only variables actually allocated on the stack count, so optimized-away variables or variables allocated in registers don't count, sorry not sorry.-fstack-protector-allโ literally-fstack-protectorbut all functions get protected, no exceptions ๐ .-fstack-protector-strongโ like-fstack-protectorbut it also includes extra functions to be protected: the ones that have local array definitions, or have references to local frame addresses ๐. Same deal as before โ only variables actually allocated on the stack are considered; optimized-away variables and register-allocated variables don't count.-fstack-protector-explicitโ like-fstack-protectorbut it only protects those functions which have the"stack_protect"attribute ๐ธ.-fstack-checkโ generates code to verify you're not going 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, because stack overflow is automatically detected on nearly all systems when there's only one stack.
Note that this switch does not actually cause checking to be done โ the operating system or the language runtime has to do that. The switch causes generation of code to ensure that they see the stack being extended ๐.
You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, and specific means use the best checking method, which is equivalent to bare -fstack-check.
Old-style checking is a generic mechanism that needs no specific target support in the compiler, but bestie, it comes with these drawbacks ๐ญ:
- Modified allocation strategy for large objects: they're 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's 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 โ for 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 prevents allocations from jumping over any stack guard page that the operating system provides.
Most targets don't fully support stack clash protection, ngl. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. It may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.
-fstack-limit-register=reg,-fstack-limit-symbol=sym,-fno-stack-limitโ generates code to ensure 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 gets raised before the stack overruns the boundary, so you can catch that signal without taking special precautions โ iconic behavior honestly.
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 โ so basically, good luck overflowing it. 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. Currently it's only implemented for the x86 targets running GNU/Linux.
When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for that latter code to run ๐ฌ. If compiling all code โ including library code โ with -fsplit-stack isn't an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later โจ.
-fvtable-verify=[std|preinit|none]โ this one's C++ only, bestie ๐ . 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 ๐.
This option causes run-time data structures to be built at program startup, which are then used for verifying the vtable pointers. The options std and preinit control the timing of when those data structures get built. In both cases they're built before execution reaches "main". Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized; -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized.
If this option shows up multiple times on the command line with different values specified: none takes highest priority over both std and preinit, and preinit takes priority over std ๐.
-fvtv-debugโ when used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called ๐. This flag also causes the compiler to log info about which vtable pointers it finds for each class. That info gets written to a file namedvtv_set_ptr_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise.
Note: this feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one first ๐.
-fvtv-countsโ this is a debugging flag ๐. When used with-fvtable-verify=stdor-fvtable-verify=preinit, it causes the compiler to keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts, and logs this info for each compilation unit. The compiler writes this info to a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class, and writes that tovtv_class_set_sizes.login the same directory ๐.
Note: this feature appends data to the log files. To get fresh log files, be sure to delete any existing ones ๐ธ.
-finstrument-functionsโ 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. (On some platforms,"__builtin_return_address"doesn't work beyond the current function, so the call site info may not be available to the profiling functions otherwise ๐.)
void __cyg_profile_func_enter (void *this_fn,
void *call_site);
void __cyg_profile_func_exit (void *this_fn,
void *call_site);
The first argument is the address of the start of the current function, which you can look up exactly in the symbol table โจ.
okay so bestie, 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.) ๐ญ
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). ๐ซถ
-finstrument-functions-onceโ this is similar to-finstrument-functions, but the profiling functions are called only once per instrumented function, i.e. the first profiling function is called after the first entry into the instrumented function and the second profiling function is called before the exit corresponding to this first entry. ๐- The definition of โonceโ for the purpose of this option is a little vague because the implementation is not protected against data races. As a result, the implementation only guarantees that the profiling functions are called at least once per process and at most once per thread, but the calls are always paired, that is to say, if a thread calls the first function, then it will call the second function, unless it never reaches the exit of the instrumented function. ๐
-finstrument-functions-exclude-file-list=file,file,...โ set 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 is considered to be a match. ๐ฆ- For example:
-finstrument-functions-exclude-file-list=/bits/stl,include/sysexcludes any inline function defined in files whose pathnames contain/bits/stlorinclude/sys. โจ - If, for some reason, you want to include letter
,in one of sym, write,. For example,-finstrument-functions-exclude-file-list=',,tmp'(note the single quote surrounding the option). ๐
- For example:
-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 as
vector<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 is 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. ๐
- The function name to be matched is its user-visible name, such as
-fpatchable-function-entry=N[,M]โ generateNNOPs right at the beginning of each function, with the function entry point before theMth NOP. IfMis omitted, it defaults to0so the function entry points to the address just at the first NOP. ๐ฅ- The NOP instructions reserve extra space which 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 interface
gen_nop. This behavior is target-specific and may also depend on the architecture variant and/or other compilation options. ๐ง - For run-time identification, the starting addresses of these areas, which correspond to their respective function entries minus
M, are additionally collected in the__patchable_function_entriessection of the resulting binary. ๐ - Note that the value of
__attribute__ ((patchable_function_entry (N,M)))takes precedence over 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. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the local entry point is this function entry address by default. See the-msplit-patch-nopsoption to change this. ๐ - The maximum value of
NandMis65535. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the supported values forMare0,2,6and14when not using-msplit-patch-nops. ๐
- The NOP instructions reserve extra space which 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 interface
๐ Options Controlling the Preprocessor ๐
These options control the C preprocessor, which is run on each C source file before actual compilation. โจ
If you use the -E option, nothing is done except preprocessing. Some of these options make sense only together with -E because they cause the preprocessor output to be unsuitable for actual compilation. ๐ญ
In addition to the options listed here, there are a number of options to control search paths for include files documented in Directory Options. Options to control preprocessor diagnostics are listed in Warning Options. ๐ซถ
-D nameโ predefine name as a macro, with definition1. ๐-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. ๐- If you are 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
shandcsh,-D'name(args...)=definition'works. โจ -Dand-Uoptions are processed in the order they are given on the command line. All-imacros fileand-include fileoptions are processed after all-Dand-Uoptions. ๐ฅ
-U nameโ cancel any previous definition of name, either built in or provided with a-Doption. ๐-include fileโ 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 is searched for in the remainder of the#include "..."search chain as normal. ๐ธ- If multiple
-includeoptions are given, the files are included in the order they appear on the command line. ๐ฆ
- If multiple
-imacros fileโ 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. ๐ง- All files specified by
-imacrosare processed before all files specified by-include. ๐
- All files specified by
-undefโ do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined. ๐-pthreadโ define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. ๐-Mโ instead of outputting the result of preprocessing, output a rule suitable formakedescribing the dependencies of the main source file. The preprocessor outputs onemakerule containing the object file name for that source file, a colon, and the names of all the included files, including those coming from-includeor-imacroscommand-line options. โญ- Unless specified explicitly (with
-MTor-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 likeDEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal. ๐ - Passing
-Mto the driver implies-E, and suppresses warnings with an implicit-w. ๐ญ
- Unless specified explicitly (with
-MMโ like-Mbut do not mention header files that are found in system header directories, nor header files that are included, directly or indirectly, from such a header. ๐ธ- This implies that the choice of angle brackets or double quotes in an
#includedirective does not in itself determine whether that header appears in-MMdependency output. ๐ซถ
- This implies that the choice of angle brackets or double quotes in an
-MF fileโ when used with-Mor-MM, specifies a file to write the dependencies to. If no-MFswitch is given the preprocessor sends the rules to the same place it would send preprocessed output. โจ- When used with the driver options
-MDor-MMD,-MFoverrides the default dependency output file. ๐ - If file is
-, then the dependencies are written tostdout. ๐
- When used with the driver options
-MGโ in conjunction with an option such as-Mrequesting dependency generation,-MGassumes missing header files are generated files and adds them to the dependency list without raising an error. The dependency filename is taken directly from the#includedirective without prepending any path.-MGalso suppresses preprocessed output, as a missing header file renders this useless. ๐ฅ- This feature is used in automatic updating of makefiles. ๐ฆ
-Mno-modulesโ disable dependency generation for compiled module interfaces. ๐-MPโ tells CPP to add a phony target for every dependency except the main file, so each one depends on nothing. These dummy rules are the fix for the errorsmakethrows when you delete header files without updating theMakefileto match. This is typical output:
test.o: test.c test.h
test.h:
-MT targetโ changes the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as.c, and appends the platformโs usual object suffix. That result is the target. An-MToption sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to-MT, or use multiple-MToptions. For example,-MT '$(objpfx)foo.o'might give:
$(objpfx)foo.o: foo.c
-MQ targetโ same as-MT, but it quotes any characters which are special to Make.-MQ '$(objpfx)foo.o'gives:
$$(objpfx)foo.o: foo.c
The default target is automatically quoted, as if it were given with -MQ.
-MDโ-MDis equivalent to-M -MF file, except that-Eis not implied. The driver determines file based on whether an-ooption is given. If it is, the driver uses its argument but with a suffix of.d; otherwise it takes the name of the input file, removes any directory components and suffix, and applies a.dsuffix.
If -MD is used in conjunction with -E, any -o switch is understood to specify the dependency output file, but if used without -E, each -o is understood to specify a target object file.
Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process.
-MMDโ like-MDexcept mention only user header files, not system header files.-fpreprocessedโ tells the preprocessor the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments, so you can pass a file preprocessed with-Cto the compiler without problems. In this mode the integrated preprocessor is little more than a tokenizer for the front ends.
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions that GCC uses for preprocessed files created by -save-temps.
-fdirectives-onlyโ when preprocessing, handle directives, but do not expand macros. The optionโs behavior depends on the-Eand-fpreprocessedoptions.
With -E, preprocessing is limited to the handling of directives such as "#define", "#ifdef", and "#error". Other preprocessor operations, such as macro expansion and trigraph conversion, are not performed. In addition, the -dD option is implicitly enabled.
With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as "__LINE__", which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with "-E -fdirectives-only".
With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with "-E -fdirectives-only".
-fdollars-in-identifiersโ accept$in identifiers. ๐ธ-fextended-identifiersโ accept universal character names and extended characters in identifiers. This option is enabled by default for C99 (and later C standard versions) and C++.-fno-canonical-system-headersโ when preprocessing, do not shorten system header paths with canonicalization.-fmax-include-depth=depthโ set the maximum depth of the nested#include. The default is 200.-ftabstop=widthโ set the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. If the value is less than 1 or greater than 100, the option is ignored. The default is 8.-ftrack-macro-expansion[=level]โ track locations of tokens across macro expansions. This allows the compiler to emit diagnostics about the current macro expansion stack when a compilation error occurs in a macro expansion. Using this option makes the preprocessor and the compiler consume more memory. The level parameter can be used to choose the level of precision of token location tracking, thus decreasing memory consumption if necessary. Value 0 of level de-activates this option. Value 1 tracks token locations in a degraded mode for the sake of minimal memory overhead; in this mode all tokens resulting from the expansion of an argument of a function-like macro have the same location. Value 2 tracks token locations completely; this value is the most memory hungry. When this option is given no argument, the default parameter value is 2.
Note that "-ftrack-macro-expansion=2" is activated by default.
-fmacro-prefix-map=old=newโ when preprocessing files residing in directory old, expand the"__FILE__"and"__BASE_FILE__"macros as if the files resided in directory new instead. This can be used to change an absolute path to a relative path by using.for new, which can result in more reproducible builds that are location independent. This option also affects"__builtin_FILE()"during compilation. See also-ffile-prefix-mapand-fcanon-prefix-map.-fexec-charset=charsetโ set the execution character set, used for string and character constants. The default is UTF-8. charset can be any encoding supported by the systemโs"iconv"library routine.-fwide-exec-charset=charsetโ set the wide execution character set, used for wide string and character constants. The default is one of UTF-32BE, UTF-32LE, UTF-16BE, or UTF-16LE, whichever corresponds to the width of"wchar_t"and the big-endian or little-endian byte order being used for code generation. As with-fexec-charset, charset can be any encoding supported by the systemโs"iconv"library routine; however, you will have problems with encodings that do not fit exactly in"wchar_t".-finput-charset=charsetโ set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default is UTF-8. This can be overridden by either the locale or this command-line option. Currently the command-line option takes precedence if thereโs a conflict. charset can be any encoding supported by the systemโs"iconv"library routine.-fpch-depsโ when using precompiled headers, this flag causes the dependency-output flags to also list the files from the precompiled headerโs dependencies. If not specified, only the precompiled header is listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used.-fpch-preprocessโ this option allows use of a precompiled header together with-E. It inserts a special"#pragma", specifically"#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 is switched on by -save-temps.
You should not write this "#pragma" in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCCโs current directory.
-fworking-directoryโ enable generation of linemarkers in the preprocessor output that let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory, when itโs present in the preprocessed input, as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debugging information is enabled, but this can be inhibited with the negated form-fno-working-directory. If the-Pflag is present in the command line, this option has no effect, since no"#line"directives are emitted whatsoever.-A predicate=answerโ make an assertion with the predicate predicate and answer answer. This form is preferred to the older form-A predicate(answer), which is still supported, because it does not use shell special characters.-A -predicate=answerโ cancel an assertion with the predicate predicate and answer answer.-Cโ do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive.
You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #.
-CCโ do not discard comments, including during macro expansion. This is like-C, except that comments contained within macros are also passed through to the output file where the macro is expanded.
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 -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.-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.
quick note first, bestie: GCC does not otherwise try to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when you invoke CPP explicitly.
-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.-Hโ Print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the#includestack it is. Precompiled header files are also printed, even if they are found to be invalid; an invalid precompiled header file is printed with...xand a valid one with...!.-dlettersโ Says to make debugging dumps during compilation as specified by letters. The flags documented here are those relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and so are silently ignored.
If you specify letters whose behavior conflicts, the result is undefined.
-dMโ Instead of the normal output, generate a list of#definedirectives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no filefoo.h, the command
touch foo.h; cpp -dM foo.h
shows all the predefined macros.
If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.
-dDโ Like-dMexcept in two respects: it does not include the predefined macros, and it outputs both the#definedirectives and the result of preprocessing. Both kinds of output go to the standard output file.-dNโ Like-dD, but emit only the macro names, not their expansions.-dIโ Output#includedirectives in addition to the result of preprocessing.-dUโ Like-dDexcept that only macros that are expanded, or whose definedness is tested in preprocessor directives, are output; the output is delayed until the use or test of the macro; and#undefdirectives are also output for macros tested but undefined at the time.
-fdebug-cppโ This option is only useful for debugging GCC. When used from CPP or with-E, it dumps debugging information about location maps. Every token in the output is preceded by the dump of the map its location belongs to.
When used from GCC without -E, this option has no effect.
-Wp,optionโ You can use-Wp,optionto bypass the compiler driver and pass option directly through to the preprocessor. If option contains commas, it is split into multiple options at the commas. However, many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and-Wpforcibly bypasses this phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid using-Wpand let the driver handle the options instead.-Xpreprocessoroption โ Pass option as an option to the preprocessor. You can use this to supply system-specific preprocessor options that GCC does not recognize.
If you want to pass an option that takes an argument, you must use -Xpreprocessor twice, once for the option and once for the argument.
-no-integrated-cppโ Perform preprocessing as a separate pass before compilation. By default, GCC performs preprocessing as an integrated part of input tokenization and parsing. If this option is provided, the appropriate language front end (cc1,cc1plus, orcc1objfor C, C++, and Objective-C, respectively) is instead invoked twice, once for preprocessing only and once for actual compilation of the preprocessed input. This option may be useful in conjunction with the-Bor-wrapperoptions to specify an alternate preprocessor or perform additional processing of the program source between normal preprocessing and compilation.-flarge-source-filesโ Adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage.
Specifically, GCC normally tracks both column numbers and line numbers within source files and it normally prints both of these numbers in diagnostics. However, once it has processed a certain number of source lines, it stops tracking column numbers and only tracks line numbers. This means that diagnostics for later lines do not include column numbers. It also means that options like -Wmisleading-indentation cease to work at that point, although the compiler prints a note if this happens. Passing -flarge-source-files significantly increases the number of source lines that GCC can process before it stops tracking columns.
โจ Passing Options to the Assembler โจ
You can pass options to the assembler, bestie. ๐
-Wa,optionโ Pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas.-Xassembleroption โ Pass option as an option to the assembler. You can use this to supply system-specific assembler options that GCC does not recognize.
If you want to pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument.
๐ Options for Linking ๐
These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step.
object-file-nameโ A file name that does not end in a special recognized suffix is considered to name an object file or library. (Object files are distinguished from libraries by the linker according to the file contents.) If linking is done, these object files are used as input to the linker.-c,-S,-Eโ If any of these options is used, then the linker is not run, and object file names should not be used as arguments.-flinker-output=typeโ This option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. For debugging the compiler and if incremental linking with a non-LTO object file is desired, it may be useful to control the type manually.
If type is exec, code generation produces a static binary. In this case -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.
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.
During the incremental link (by -r) the linker plugin defaults to rel. With current interfaces to GNU Binutils it is however not possible to incrementally link LTO objects and non-LTO objects into a single mixed object file. If any of object files in incremental link cannot be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it is recommended to link such objects into static library instead. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects.
-fuse-ld=bfdโ Use the bfd linker instead of the default linker.-fuse-ld=goldโ Use the gold linker instead of the default linker.-fuse-ld=lldโ Use the LLVM lld linker instead of the default linker.-fuse-ld=moldโ Use the Modern Linker (mold) instead of the default linker.-llibrary,-l libraryโ Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)
The -l option is passed directly to the linker by GCC. Refer to your linker documentation for exact details. The general description below applies to the GNU linker.
The linker searches a standard list of directories for the library. The directories searched include several standard system directories plus any that you specify with -L.
Static libraries are archives of object files, and have file names like liblibrary.a. Some targets also support shared libraries, which typically have names like liblibrary.so. If both static and shared libraries are found, the linker gives preference to linking with the shared library unless the -static option is used.
Okay so the order thing โ it fr fr matters where in the command you write this option, like placement is everything bestie ๐
. The linker searches and processes libraries and object files in the order they're specified. So foo.o -lz bar.o searches library z after file foo.o but before bar.o. And if bar.o refers to functions in zโฆ those functions may not be loaded ๐ญ. It's giving "read the room, in order."
-lobjcโ bestie you need this special case of the-loption specifically to link an Objective-C or Objective-C++ program ๐.-nostartfilesโ nope, don't use the standard system startup files when linking ๐. The standard system libraries are still used normally, unless-nostdlib,-nolibc, or-nodefaultlibsis used too.-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, such as-static-libgccor-shared-libgcc, are ignored (sorry queen, they're just not invited). The standard startup files are used normally, unless-nostartfilesis used.
The compiler may generate calls to memcmp, memset, memcpy and memmove โ and those entries are usually resolved by entries in libc. But when this option is specified, those entry points should be supplied through some other mechanism ๐ฅ.
-nolibcโ don't 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, plus system libraries that normally go with it and become meaningless when absence of a C library is assumed (for example-lpthreador-lmin some configurations). It's intended for bare-board targets when there is indeed no C library available โ main character bare-metal energy ๐ง.-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.
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 -nostdlib and -nodefaultlibs is libgcc.a โ a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages ๐
In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, used to ensure C++ constructors are called.) No cap, don't skip this one ๐ซถ.
-nostdlib++โ do not implicitly link with standard C++ libraries ๐ธ.-eentry,--entry=`entry โ specify that the program entry point is entry ๐. The argument is interpreted by the linker; the GNU linker accepts either a symbol name or an address.-pieโ produce a dynamically linked position independent executable on targets that support it ๐. For predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option โ consistency is the vibe check.-no-pieโ don't produce a dynamically linked position independent executable ๐ .-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 (yes, both, don't half-ass it).-rโ produce a relocatable object as output ๐ฅ. This is also known as partial linking.-rdynamicโ pass the flag-export-dynamicto the ELF linker, on targets that support it โญ. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses ofdlopenor to allow obtaining backtraces from within a program โ very "I want receipts from inside the program" of it.-sโ remove all symbol table and relocation information from the executable โ๏ธ๐. Gone, deleted, not invited to the group chat.-staticโ on systems that support dynamic linking, this overrides-pieand prevents linking with the shared libraries ๐. On other systems, this option has no effect.-sharedโ produce a shared object which can then be linked with other objects to form an executable ๐. Not all systems support this option. For predictable results, you must also specify the same set of options used for compilation (-fpic,-fPIC, or model suboptions) when you specify this linker option.[1]-shared-libgcc,-static-libgccโ on systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively ๐ธ. If no shared version of libgcc was built when the compiler was configured, these options have no effect (sad, but true).
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 ๐.
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.
However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc ๐
.
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links against libasan ๐. If libasan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libasan. The-static-libasanoption directs the GCC driver to link libasan statically, without necessarily linking other libraries statically.-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links against libtsan ๐งต. If libtsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libtsan. The-static-libtsanoption directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically.-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links against liblsan ๐ง. If liblsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of liblsan. The-static-liblsanoption directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically.-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links against libubsan ๐ฆ. If libubsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libubsan. The-static-libubsanoption directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically.-static-libstdc++โ when the g++ program is used to link a C++ program, it normally automatically links against libstdc++ ๐. If libstdc++ is available as a shared library, and the-staticoption is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link ๐ง. The-static-libstdc++option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically.-symbolicโ bind references to global symbols when building a shared object ๐. Warn about any unresolved references (unless overridden by the link editor option-Xlinker -z -Xlinker defs). Only a few systems support this option.-Tscript โ use script as the linker script ๐. This option is supported by most systems using the GNU linker. On some targets, such as bare-board targets without an operating system, the-Toption may be required when linking to avoid references to undefined symbols.-Xlinkeroption โ pass option as an option to the linker ๐ซถ. You can use this to supply system-specific linker options that GCC does not recognize.
If you want to pass an option that takes a separate argument, you must use -Xlinker twice โ once for the option and once for the argument. For example, to pass -assert definitions, you must write -Xlinker -assert -Xlinker definitions. It does not work to write -Xlinker "-assert definitions", because this passes the entire string as a single argument, which is not what the linker expects ๐ญ โ like texting the whole sentence as one word, the linker is not gonna parse that bestie.
When you're working with the GNU linker, it's usually wayyy more convenient to hand linker options their arguments with the option=value syntax instead of passing them as separate args. Like, you can write -Xlinker -Map=output.map instead of the whole -Xlinker -Map -Xlinker output.map situation. Ngl though, other linkers might not support this syntax for command-line options, so don't @ me. ๐
-Wl,optionโ passes option straight through as an option to the linker. And if option has commas in it? It gets split into multiple options at the commas, bestie. You can use this syntax to pass an argument to the option too โ for example-Wl,-Map,output.mappasses-Map output.mapto the linker. And when you're using the GNU linker, you can get the exact same effect with-Wl,-Map=output.map. โจ-u symbolโ pretends that the symbol symbol is undefined, which forces the linking of library modules to define it. You can use-umultiple times with different symbols to force loading of even more library modules. Iconic, honestly. ๐-z keywordโ-zgets passed directly on to the linker along with the keyword keyword. Peep the section in your linker's documentation for what values are permitted and what they mean (iykyk). ๐
๐ Options for Directory Search ๐
These options tell the compiler where to go looking for header files, libraries, and parts of the compiler itself. Think of it as setting up the group chat invite list, but for directories: ๐
-I dir,-iquote dir,-isystem dir,-idirafter dirโ adds the directory dir to the list of directories searched for header files during preprocessing. If dir begins with=or$SYSROOT, then the=or$SYSROOTgets replaced by the sysroot prefix โ check out--sysrootand-isysrootfor the lore.
Directories specified with -iquote apply only to the quote form of the directive, #include "file". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the #include "file" and #include <file> directives.
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 goes like this, and yes, you should absolutely memorize it:
- 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 are searched before the standard system header file directories. BUT โ and this is a big but โ you should not use this option to add directories that contain vendor-supplied system header files; use -isystem for that. Respect the system headers, bestie. ๐
The -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment that's applied to the standard system directories. Fancy. โจ
If a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option is ignored. The directory is still searched, but as a system directory at its normal position in the system include chain. Why? To make sure GCC's procedure to fix buggy system headers and the ordering for the #include_next directive don't get inadvertently changed. If you really, truly need to change the search order for system directories, use the -nostdinc and/or -isystem options. Periodt. ๐
-I-โ splits the include path. โ ๏ธ Heads up: this option has been deprecated. Please use-iquoteinstead for-Idirectories before the-I-, and remove the-I-option entirely.
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.
Also, -I- inhibits the use of the directory of the current file directory as the first search directory for #include "file". And there is no way to override this effect of -I-. Like, none. ๐ญ
-iprefix prefixโ specifies prefix as the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final/. Don't forget it, or it's giving broken path energy. ๐ซถ-iwithprefix dir,-iwithprefixbefore dirโ appends dir to the prefix specified previously with-iprefix, and adds the resulting directory to the include search path.-iwithprefixbeforeputs it in the same place-Iwould;-iwithprefixputs it where-idirafterwould. Two little twins, different vibes. ๐ง-isysroot dirโ this option is like the--sysrootoption, but applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the--sysrootoption for more info. ๐-imultilib dirโ uses dir as a subdirectory of the directory containing target-specific C++ headers.-nostdincโ do not search the standard system directories for header files. Only the directories explicitly specified with-I,-iquote,-isystem, and/or-idirafteroptions (and the directory of the current file, if appropriate) are searched. No defaults, no filler. ๐-nostdinc++โ do not 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 โ so if you're not doing that, mind your business.) ๐ธ-iplugindir=dirโ sets 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, but only passed by the driver. So like... hands off, bestie. ๐ โโ๏ธ-Ldirโ adds directory dir to the list of directories to be searched for-l. Simple, clean, iconic. โจ-Bprefixโ this option specifies where to find the executables, libraries, include files, and data files of the compiler itself. Big main character energy. ๐
The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.
For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name isn't found, or if -B wasn't specified, the driver tries two standard prefixes: /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that's found, the unmodified program name is searched for using the directories specified in your PATH environment variable. It's giving "try everything until something hits." ๐
The compiler checks to see if the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.
-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.
The runtime support file libgcc.a can also be searched for using the -B prefix, if needed. If it's not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it's not found by those means. No cap. ๐ญ
Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.
And 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. Weird? Yes. Canon? Also yes. ๐ฆ
-no-canonical-prefixesโ do not expand any symbolic links, resolve references to/../or/./, or make the path absolute when generating a relative prefix. Just... leave the path exactly as it is. ๐--sysroot=dirโ uses 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. It's the "imagine this is the root" option. ๐
If you use both this option and the -isysroot option, then --sysroot applies to libraries, but -isysroot 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. Half the slay, unfortunately. ๐
--no-sysroot-suffixโ for some targets, a suffix is added to the root directory specified with--sysroot, depending on the other options used, so that headers may for example be found indir/suffix/usr/includeinstead ofdir/usr/include. This option disables the addition of such a suffix. Bye bye extra suffix. ๐
๐ฅ Options for Code Generation Conventions ๐ฅ
These machine-independent options control the interface conventions used in code generation. Very "the rules of the universe" of it all. ๐
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. Iyk what I mean. ๐
-fstack-reuse=reuse-levelโ this option controls stack space reuse for user declared local/auto variables and compiler generated temporaries. reuse_level can beall,named_vars, ornone.
all enables stack reuse for all local variables and temporaries, named_vars enables the reuse only for user defined local variables with names, and none disables stack reuse completely. The default value is all. ๐ซถ
The option is needed when the program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization. โ ๏ธ So like... be careful. This is the danger zone.
For example:
int *p;
{
int local1;
p = &local1;
local1 = 10;
....
}
{
int local2;
local2 = 20;
...
}
if (*p == 10) // out of scope use of local1
{
}
โฆand here's the other one, bestie:
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?
}
So like, the lifetime of a compiler generated temporary is well defined by the C++ standard, no cap ๐ . When a temporary's lifetime ends โ and if that temporary lives in memory โ the optimizing compiler is lowkey free to reuse its stack space with other temporaries or with scoped local variables whose live range doesn't overlap with it. Iconic, efficient, all that. BUT some legacy code relies on how older compilers behaved, where temporaries' stack space was not reused, and aggressive stack reuse can lead to runtime errors ๐ญ. This option is literally the dial you use to control the temporary stack reuse optimization. ๐
-ftrapvโ this one generates traps for signed overflow on addition, subtraction and multiplication operations ๐จ. Heads up:-ftrapvand-fwrapvoverride each other, so putting-ftrapv -fwrapvon the command line means-fwrapvis the one that ends up effective. And ngl, only active options override โ so-ftrapv -fwrapv -fno-wrapvon the command line? That one results in-ftrapvbeing effective. ๐ซถ-fwrapvโ this tells the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation ๐. This flag enables some optimizations and disables others. And same rule as above:-ftrapvand-fwrapvoverride each other, so-ftrapv -fwrapvon the command line gives you-fwrapveffective. Also only active options override, so-ftrapv -fwrapv -fno-wrapvon the command line results in-ftrapvbeing effective. iykyk ๐-fwrapv-pointerโ this instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation. This flag disables some optimizations which assume pointer overflow is invalid. ๐ฆ-fstrict-overflowโ implies-fno-wrapv -fno-wrapv-pointer, and when negated it implies-fwrapv -fwrapv-pointer. Cute little bundle, periodt. โจ-fexceptionsโ enable exception handling. It generates the extra code needed to propagate exceptions. For some targets this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead โ although it does not affect execution, so breathe ๐ฎโ๐จ. If you don't specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that don't normally require it. That said, you may need to enable it when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you're compiling older C++ programs that don't use exception handling. ๐-fnon-call-exceptionsโ generate code that allows trapping instructions to throw exceptions. Lowkey important caveat: this requires platform-specific runtime support that does not exist everywhere ๐. And more than that, it only allows trapping instructions to throw exceptions โ like memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such asSIGALRM. This enables-fexceptions.-fdelete-dead-exceptionsโ consider that instructions that may throw exceptions but don't otherwise contribute to the execution of the program can be optimized away ๐๏ธ. This does not affect calls to functions except those with thepureorconstattributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. โญ-funwind-tablesโ similar to-fexceptions, except it just generates any needed static data, but does not affect the generated code in any other way. You normally do not need to enable this option; instead, a language processor that needs this handling enables it on your behalf ๐ซถ.-fasynchronous-unwind-tablesโ generate unwind table in DWARF format, if supported by the target machine ๐. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as a debugger or a garbage collector). iconic.-fno-gnu-uniqueโ okay so 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 are unique even in the presence ofRTLD_LOCAL. That's necessary to avoid problems with a library used by two differentRTLD_LOCALplugins depending on a definition in one of them, and therefore disagreeing with the other one about the binding of the symbol ๐ง . But this causesdlcloseto be ignored for affected DSOs. So if your program relies on reinitialization of a DSO viadlcloseanddlopen, you can use-fno-gnu-unique. slay, problem solved ๐-fpcc-struct-returnโ returnshortstructandunionvalues in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers, particularly the Portable C Compiler (pcc) ๐ค.
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the-fpcc-struct-returnswitch is not binary compatible with code compiled with the-freg-struct-returnswitch. Use it to conform to a non-default application binary interface. ๐ฌ
-freg-struct-returnโ returnstructandunionvalues in registers when possible. This is more efficient for small structures than-fpcc-struct-returnโก.
If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there is no standard convention, GCC defaults to -fpcc-struct-return, except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative. main character decision-making fr ๐
Warning: code compiled with the-freg-struct-returnswitch is not binary compatible with code compiled with the-fpcc-struct-returnswitch. Use it to conform to a non-default application binary interface. ๐ญ
-fshort-enumsโ allocate to anenumtype only as many bytes as it needs for the declared range of possible values. Specifically, theenumtype is equivalent to the smallest integer type that has enough room. tiny queen energy ๐
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
-fshort-wcharโ override the underlying type forwchar_tto beshort unsigned intinstead of the default for the target. This option is useful for building programs to run under WINE ๐ท.
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
-fcommonโ in C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with theexternkeyword, which do not allocate storage ๐ง.
The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker, so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit ๐.
The -fcommon places uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This behavior is inconsistent with C++, and on many targets implies a speed and code size penalty on global variable references ๐. It is mainly useful to enable legacy code to link without errors. we love a legacy-code rescue mission ๐ซถ
-fno-identโ ignore the#identdirective. bye felicia ๐-finhibit-size-directiveโ don't output a.sizeassembler directive, or anything else that would cause trouble if the function is split in the middle, and the two halves are placed at locations far apart in memory. This option is used when compilingcrtstuff.c; you should not need to use it for anything else. like, seriously, that's its whole job ๐-fverbose-asmโ put extra commentary information in the generated assembly code to make it more readable โจ. This option is generally only of use to those who actually need to read the generated assembly code (perhaps while debugging the compiler itself). nerd hours, and honestly, respect ๐ง
-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing 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.
For example, given this C source file:
int test (int n)
{
int i;
int total = 0;
for (i = 0; i < n; i++)
total += i * i;
return total;
}
so like, compiling to (x86_64) assembly via -S and yeeting the result straight to stdout via -o -, like this:
gcc -S test.c -fverbose-asm -Os -o -
gives you output that's giving pretty much 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
bestie, those comments are for humans not machines, so the exact format of them is literally subject to change โ don't go parsing them, ok? ๐
-frecord-gcc-switchesโ this one makes the command line you used to invoke the compiler get recorded right there into the object file being created ๐. ngl 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-fverbose-asm, except that switch 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 is part of the operating system โ not our department fr). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker indicating that-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, and therefore works only on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.
-fPICโ if supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table ๐. This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Position-independent code requires special support, and therefore works only on certain machines.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 2.
-fpie,-fPIEโ these are basically the little siblings of-fpicand-fPIC๐ซถ, except the generated position-independent code can only be linked into executables. Usually these are used to compile code that's gonna be linked using the-pieGCC option.
-fpie and -fPIE both define the macros "__pie__" and "__PIE__". The macros have the value 1 for -fpie and 2 for -fPIE.
-fno-pltโ do not use the PLT for external function calls in position-independent code. Instead, load the callee address at call sites from the GOT and branch to it ๐ฅ. This leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures such as 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives more register allocation freedom to the compiler. Lazy binding requires use of the PLT; with-fno-pltall external symbols are resolved at load time. โฐ
Alternatively, the function attribute "noplt" can be used to avoid calls through the PLT for specific external functions.
In position-dependent code, a few targets also convert calls to functions that are marked to not use the PLT to use the GOT instead.
-fno-jump-tablesโ do not use jump tables forswitchstatements even where it would be more efficient than other code generation strategies ๐ซ. This option is of use in conjunction with-fpicor-fPICfor building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables do not require a GOT and this option is not needed. iykyk ๐-fno-bit-testsโ do not use bit tests forswitchstatements even where it would be more efficient than other code generation strategies. periodt.-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. no -fno- version for you, sorry 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. ๐ซฃ like, catastrophic. don't.
This flag does not have a negative form, because it specifies a three-way choice.
-fcall-saved-regโ treat the register named reg as an allocable register saved by functions ๐ธ. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the register reg if they use it.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
And a different sort of disaster results from the use of this flag for a register in which function values may be returned. ๐ literally two flavors of chaos.
This flag does not have a negative form, because it specifies a three-way choice.
-fpack-struct[=n]โ with no value specified, pack all structure members together 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โ for targets that normally need trampolines for nested functions, always generate them instead of using descriptors ๐ช. Otherwise, for targets that do not need them, like for example HP-PA or IA-64, do 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. ๐ฌ yes, that kind of executable.
-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-ftrampolinesand code compiled with-fno-trampolinesare 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, whole-program or nothing, bestie.
For languages other than Ada, the "-ftrampolines" and "-fno-trampolines" options currently have no effect, and trampolines are always generated on platforms that need them for nested functions. ๐
-fvisibility=[default|internal|hidden|protected] โ okay so this one sets the default ELF image symbol visibility to whatever you pick, and likeโฆ every symbol gets stamped with it unless something inside the code overrides it. Bestie, this is such a glow-up for shared object libraries: it can very substantially improve linking and load times, produce more optimized code, give you near-perfect API export, and prevent symbol clashes. It is strongly recommended that you use this in any shared objects you distribute. Periodt.
Despite the nomenclature (fancy word, love that for us), default always means public โ like, 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. And if you don't specify -fvisibility at all, the default is default, i.e. make every symbol public ๐.
A good explanation of the benefits of correct ELF symbol visibility is in "How To Write Shared Libraries" by Ulrich Drepper, which you can find at <https://www.akkadia.org/drepper/> โ however, there's a superior solution this option makes possible: instead of marking things hidden when the default is public, you flip it and make the default hidden and mark things public. This is the norm with DLLs on Windows, and with -fvisibility=hidden plus "__attribute__ ((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. Genuinely a great boon to those working with cross-platform projects ๐
.
If you're adding visibility support to existing code, "#pragma GCC visibility" may be of use โ you enclose the declarations you want to set visibility for with, for example, "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Bear in mind: symbol visibility should be viewed as part of the API interface contract, so all new code should always specify visibility when it isn't the default. Like, declarations only for use within the local DSO should always be marked explicitly as hidden so you avoid PLT indirection overheads โ and making it abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, "operator new" and "operator delete" must always be of default visibility. Sorry, no hiding those ๐ซถ.
Heads up: headers from outside your project โ in particular system headers and headers from any other library you use โ may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers.
"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with zero modifications. However โ and this is the catch โ it means calls to "extern" functions with no explicit visibility use the PLT, so it's more effective to use "__attribute ((visibility))" and/or "#pragma GCC visibility" to tell the compiler which "extern" declarations should be treated as hidden.
Also note that -fvisibility does affect C++ vague linkage entities. Which means, for instance, an exception class that is thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. Iconic behaviour, honestly.
An overview of these techniques, their benefits and how to use them lives at <https://gcc.gnu.org/wiki/Visibility> โญ
-fstrict-volatile-bitfields โ use this if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. For example, targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide; with this flag you can declare all peripheral bit-fields as "unsigned short" (assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access.
If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction โ even though that accesses bytes that don't contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated ๐.
In some cases, such as when the "packed" attribute is applied to a structure field, it may not be possible to access the field with a single read or write that's correctly aligned for the target machine. In this case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time. No cap.
Note: Due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It's therefore recommended to define all bits of the field's type as bit-field members ๐ธ.
The default value of this option is determined by the application binary interface for the target processor.
-fsync-libcalls โ this one controls whether any out-of-line instance of the "__sync" family of functions may be used to implement the C++11 "__atomic" family of functions.
The default value of this option is enabled, so the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library โจ.
๐ GCC Developer Options ๐
This section is for the GCC devs themselves โ options that are primarily of interest to GCC developers, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That includes options that produce debug dumps at various points in the compilation, options that print statistics such as memory use and execution time, and options that print information about GCC's configuration, such as where it searches for libraries. Bestie, you should rarely need any of these for ordinary compilation and linking tasks. This is backstage-pass territory ๐.
Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error.
If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, phase letter, and pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it's the source file name. The pass number is determined by the order passes are registered with the compiler's pass manager โ generally the same as the order of execution, but passes registered by plugins, target-specific passes, or passes that are otherwise registered late are numbered higher than the pass named final, even if they're executed earlier. The phase letter is one of i (inter-procedural analysis), l (language-specific), r (RTL), or t (tree). The files are created in the directory of the output file ๐ฆ.
-fcallgraph-info -fcallgraph-info=MARKERS
Makes the compiler output callgraph information for the program, on a per-object-file basis. The info is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information, if a list of comma-separated markers is additionally specified. When the "su" marker is specified, the callgraph is decorated with stack usage information โ it's equivalent to -fstack-usage. When the "da" marker is specified, the callgraph is decorated with information about dynamically allocated objects.
When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files ๐.
-dletters -fdump-rtl-pass -fdump-rtl-pass=filename
Says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.
Some -dletters switches have different meaning when -E is used for preprocessing.
Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings ๐
-fdump-rtl-alignmentsโ Dump after branch alignments have been computed.-fdump-rtl-asmconsโ Dump after fixing rtl statements that have unsatisfied in/out constraints.-fdump-rtl-auto_inc_decโ Dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.-fdump-rtl-barriersโ Dump after cleaning up the barrier instructions.-fdump-rtl-bbpartโ Dump after partitioning hot and cold basic blocks.-fdump-rtl-bbroโ Dump after block reordering.-fdump-rtl-btl1,-fdump-rtl-btl2โ these enable dumping after the two branch target load optimization passes.-fdump-rtl-bypassโ Dump after jump bypassing and control flow optimizations.-fdump-rtl-combineโ Dump after the RTL instruction combination pass.-fdump-rtl-compgotosโ Dump after duplicating the computed gotos.-fdump-rtl-ce1,-fdump-rtl-ce2,-fdump-rtl-ce3โ these enable dumping after the three if conversion passes.-fdump-rtl-cprop_hardregโ Dump after hard register copy propagation.-fdump-rtl-csaโ Dump after combining stack adjustments.-fdump-rtl-cse1,-fdump-rtl-cse2โ these enable dumping after the two common subexpression elimination passes.-fdump-rtl-dceโ Dump after the standalone dead code elimination passes.-fdump-rtl-dbrโ Dump after delayed branch scheduling.-fdump-rtl-dce1,-fdump-rtl-dce2โ these enable dumping after the two dead store elimination passes.-fdump-rtl-ehโ Dump after finalization of EH handling code.-fdump-rtl-eh_rangesโ Dump after conversion of EH handling range regions.-fdump-rtl-expandโ Dump after RTL generation.-fdump-rtl-fwprop1,-fdump-rtl-fwprop2โ bestie these two turn on dumping right after the two forward propagation passes ๐-fdump-rtl-gcse1,-fdump-rtl-gcse2โ these enable dumping after global common subexpression elimination โจ-fdump-rtl-init-regsโ dump after the registers get initialized ๐-fdump-rtl-initvalsโ dump after the initial value sets are computed ๐ฆ-fdump-rtl-into_cfglayoutโ dump after converting to cfglayout mode, slay ๐-fdump-rtl-iraโ dump after iterated register allocation ๐ธ-fdump-rtl-jumpโ dump after the second jump optimization ๐ซถ-fdump-rtl-loop2โ this one enables dumping after the rtl loop optimization passes ๐ฅ-fdump-rtl-machโ dump after the machine dependent reorganization pass runs โ but only if that pass even exists on your target, iykyk ๐-fdump-rtl-mode_swโ dump after removing redundant mode switches ๐-fdump-rtl-rnregโ dump after register renumbering โญ-fdump-rtl-outof_cfglayoutโ dump after converting from cfglayout mode ๐-fdump-rtl-peephole2โ dump after the peephole pass ๐ง-fdump-rtl-postreloadโ dump after post-reload optimizations ๐-fdump-rtl-pro_and_epilogueโ dump after generating the function prologues and epilogues ๐-fdump-rtl-sched1,-fdump-rtl-sched2โ these enable dumping after the basic block scheduling passes โจ-fdump-rtl-reeโ dump after sign/zero extension elimination ๐ฆ-fdump-rtl-seqabstrโ dump after common sequence discovery ๐-fdump-rtl-shortenโ dump after shortening branches ๐ธ-fdump-rtl-siblingโ dump after sibling call optimizations ๐ซถ-fdump-rtl-split1,-fdump-rtl-split2,-fdump-rtl-split3,-fdump-rtl-split4,-fdump-rtl-split5โ these bad boys enable dumping after five whole rounds of instruction splitting, periodt ๐ฅ-fdump-rtl-smsโ dump after modulo scheduling. heads up tho: this pass is only run on some architectures ๐-fdump-rtl-stackโ dump after converting from GCC's "flat register file" registers to the x87's stack-like registers. and ngl, this pass is only run on x86 variants ๐-fdump-rtl-subreg1,-fdump-rtl-subreg2โ these two enable dumping after the two subreg expansion passes ๐-fdump-rtl-unshareโ dump after all rtl has been unshared โญ-fdump-rtl-vartrackโ dump after variable tracking ๐-fdump-rtl-vregsโ dump after converting virtual registers to hard registers ๐ง-fdump-rtl-webโ dump after live range splitting ๐-fdump-rtl-regclass,-fdump-rtl-subregs_of_mode_init,-fdump-rtl-subregs_of_mode_finish,-fdump-rtl-dfinit,-fdump-rtl-dfinishโ okay so these dumps are defined but they always produce empty files ๐ญ like literally nothing in them, that's the whole vibe-da,-fdump-rtl-allโ produce all the dumps listed above. all of them. the whole collection ๐-dAโ annotate the assembler output with miscellaneous debugging information โจ-dDโ dump all macro definitions at the end of preprocessing, on top of the normal output ๐ฆ-dHโ produce a core dump whenever an error occurs ๐ dramatic but okay-dpโ annotate the assembler output with a comment indicating which pattern and alternative is used. the length and cost of each instruction also get printed ๐-dPโ dump the RTL in the assembler output as a comment before each instruction. this one also turns on-dpannotation ๐ธ-dxโ just generate RTL for a function instead of compiling it. usually you'd pair it with-fdump-rtl-expand๐ซถ
-fdump-debugโ dump the debugging information generated during the debug generation phase ๐ฅ-fdump-earlydebugโ dump the debugging information generated during the early debug generation phase โญ-fdump-noaddrโ when you're doing debugging dumps, this suppresses address output. the whole point? it makes it way more feasible to rundiffon debugging dumps from compiler invocations that use different compiler binaries and/or different text / bss / data / heap / stack / dso start locations ๐-freport-bugโ collects and dumps debug information into a temporary file if an internal compiler error (ICE) occurs. honestly a lifesaver when things go sideways ๐ญ-fdump-unnumberedโ when doing debugging dumps, this suppresses instruction numbers and address output. again, this makes usingdiffon debugging dumps way more feasible for compiler invocations with different options โ especially with and without-g๐ง-fdump-unnumbered-linksโ when doing debugging dumps (see the-doption up there โ), this suppresses instruction numbers for the links to the previous and next instructions in a sequence ๐-fdump-ipa-switch,-fdump-ipa-switch-optionsโ these control the dumping at various stages of the 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 gets created in the same directory as the output file. the following dumps are possible:allโ enables all inter-procedural analysis dumps ๐cgraphโ dumps information about call-graph optimization, unused function removal, and inlining decisions ๐inlineโ dump after function inlining โจ
additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized.
for example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined ๐
by default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis ๐
-fdump-ipa-clonesโ creates a dump file with info about the creation of call graph node clones and removals of call graph nodes during inter-procedural optimizations and transformations. its main intended use is that tools which create live-patches can figure out the set of functions that need to be live-patched to completely replace a particular function (see-flive-patching). the file name is generated by appending the suffix"ipa-clones"to the source file name, and the file is created in the same directory as the output file. each entry in the file is on a separate line containing semicolon separated fields ๐ฆ
in the case of call graph clone creation, the individual fields are:
- String
"Callgraph clone". - Name of the function being cloned as it is presented to the assembler.
- A number that uniquely represents the function being cloned in the call graph. note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases ๐
- The file name of the source file where the function is defined.
- The line on which the function definition is located.
- The column where the function definition is located.
- Name of the new function clone as it is presented to the assembler.
- A number that uniquely represents the new function clone in the call graph. note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases ๐
- The file name of the source file where the source code location of the new clone points to.
- The line to which the source code location of the new clone points to.
- The column to which the source code location of the new clone points to.
- A string that determines the reason for cloning.
in the case of call graph clone removal, the individual fields are:
- String
"Callgraph removal". - Name of the function being removed as it would be presented to the assembler.
- A number that uniquely represents the function being cloned in the call graph. note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases ๐
- The file name of the source file where the function is defined.
- The line on which the function definition is located.
- The column where the function definition is located.
-fdump-langโ dump language-specific information. the file name is made by appending.langto the source file name ๐-fdump-lang-all,-fdump-lang-switch,-fdump-lang-switch-options,-fdump-lang-switch-options=filenameโ these control the dumping of language-specific information. theoptionsandfilenameportions behave exactly 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โ prints onstderrthe list of optimization passes that are turned on and off by the current command-line options. lowkey a cheat code for knowing what's actually happening ๐ฅ-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โ okay so these bad boys let you control the dumping at basically every stage of processing the intermediate language tree, straight into a file. ๐ If you use the-optionsform, then options is a list of-separated options that control the details of the dump. Lowkey not every option works for every dump tho โ the ones that aren't meaningful just get silently ignored, no drama. Here's the full menu of what you can pick:addressโ prints the address of every node. Ngl this is usually not meaningful bc it shifts around depending on your environment and source file. Its main character energy is in tying a dump file to a debug environment.asmnameโ ifDECL_ASSEMBLER_NAMEhas been set for a given decl, use that in the dump instead ofDECL_NAME. Its whole point is making it easy to work backward from mangled names in the assembly file. iykyk.slimโ when you're dumping front-end intermediate representations, this stops the dumping of members of a scope or body of a function just because that scope has been reached. It only dumps those items when they're directly reachable by some other path. When dumping pretty-printed trees, this option stops the bodies of control structures from being dumped. When dumping RTL, it prints the RTL in slim (condensed) form instead of the default LISP-like representation. slay.rawโ prints a raw representation of the tree. By default, trees get pretty-printed into a C-like representation.detailsโ enables more detailed dumps (not honored by every dump option, sad). Also pulls in information from the optimization passes.statsโ enables dumping of various statistics about the pass (again, not honored by every dump option).blocksโ enables showing basic block boundaries (disabled in raw dumps).graphโ for each of the other indicated dump files (-fdump-rtl-pass), it dumps a representation of the control flow graph that's suitable for viewing with GraphViz to file.passid.pass.dot. Each function in the file is pretty-printed as a subgraph, so GraphViz can render them all in a single plot. ๐ Heads up: this option currently only works for RTL dumps, and the RTL is always dumped in slim form.vopsโ enables showing virtual operands for every statement.linenoโ enables showing line numbers for statements.uidโ enables showing the unique ID (DECL_UID) for each variable.verboseโ enables showing the tree dump for each statement.ehโ enables showing the EH region number holding each statement.scevโ enables showing scalar evolution analysis details.optimizedโ enables showing optimization information (only available in certain passes).missedโ enables showing missed optimization information (only available in certain passes).noteโ enables other detailed optimization information (only available in certain passes).allโ turns on all options, exceptraw,slim,verboseandlineno.optallโ turns on all optimization options, i.e.optimized,missed, andnote.
โจ So to figure out what tree dumps are even available, or to find the dump for a pass you're obsessed with, follow these steps bestie:
- Invoke GCC with
-fdump-passesand in the stderr output look for a code that corresponds to the pass you're interested in. For example, the codestree-evrp,tree-vrp1, andtree-vrp2correspond to the three Value Range Propagation passes. The number at the end distinguishes distinct invocations of the same pass. ๐ฅ - To enable the creation of the dump file, append the pass code to the
-fdump-option prefix and invoke GCC with it. 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. ๐ซถ Note that the numeric codes are not stable and may change from one version of GCC to another โ so don't hardcode them, bestie.
-fopt-info,-fopt-info-options,-fopt-info-options=filenameโ controls optimization dumps from the various optimization passes. ๐ If you use the-optionsform, options is a list of-separated option keywords that pick the dump details and optimizations.
The options split into three groups:
- options describing what kinds of messages should be emitted,
- options describing the verbosity of the dump, and
- options describing which optimizations should be included.
You can freely mix options from each group since they're non-overlapping. But if there's any conflict, the later options override the earlier ones on the command line. Periodt.
๐ Which kinds of messages get emitted
optimizedโ prints info when an optimization is successfully applied. It's up to a pass to decide which info is relevant. For example, the vectorizer passes print the source location of loops that got successfully vectorized. ๐missedโ prints info about missed optimizations. Individual passes control which info goes into the output.noteโ prints verbose info about optimizations, like certain transformations and more detailed messages about decisions etc.allโ prints detailed optimization information. This includesoptimized,missed, andnote.
๐ The verbosity knob
internalsโ by default only "high-level" messages get emitted. This option enables extra, more detailed messages, which are likely only interesting to GCC developers. Fr fr, it's giving deep lore.
๐ฆ Which optimizations to include
One or more of these keywords can describe a group of optimizations:
ipaโ enable dumps from all interprocedural optimizations.loopโ enable dumps from all loop optimizations.inlineโ enable dumps from all inlining optimizations.ompโ enable dumps from all OMP (Offloading and Multi Processing) optimizations.vecโ enable dumps from all vectorization optimizations.optallโ enable dumps from all optimizations. This is a superset of the optimization groups listed above.
If options is omitted, it defaults to optimized-optall, which means dump messages about successful optimizations from all the passes, leaving out messages that are treated as "internals". โจ
If filename is provided, then the dumps from all the applicable optimizations get concatenated into filename. Otherwise the dump goes out onto stderr. Even though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided, then all but the first such option are ignored. ๐
Note that the output filename gets overwritten in the case of multiple translation units. If you want a combined output from multiple translation units, use stderr instead. ๐
In the following example, the optimization info goes 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 info 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 doesn't matter. ๐ง
As another example,
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs info about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
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. ๐ญ
-fsave-optimization-recordโ writes a SRCFILE.opt-record.json.gzfile detailing what optimizations were performed, for those optimizations that support-fopt-info. ๐ธ
This option is experimental and the format of the data inside the compressed JSON file is subject to change. Don't @ me.
It's roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, plus these extra bits of data for each message:
- the execution count of the code being optimized, along with metadata about whether this came from actual profile data or was just an estimate, letting consumers prioritize messages by code hotness, ๐ฅ
- the function name of the code being optimized, where applicable,
- the "inlining chain" for the code being optimized, so that when a function is inlined into several different places (which might themselves be inlined), the reader can tell the copies apart,
- objects identifying those parts of the message that refer to expressions, statements or symbol-table nodes, which of these categories they are, and, when available, their source code location,
- the GCC pass that emitted the message, and
- the location in GCC's own code from which the message was emitted.
Additionally, some messages are logically nested within other messages, reflecting implementation details of the optimization passes. ๐
-fsched-verbose=nโ on targets that actually use instruction scheduling, this controls how much debugging output the scheduler prints into the dump files. For n greater than zero,-fsched-verboseoutputs the same info as-fdump-rtl-sched1and-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-verbosealso includes dependence info. scheduler lore unlocked ๐-fenable-kind-pass,-fdisable-kind-pass=range-listโ this is the whole set of options used to explicitly disable/enable optimization passes. Important vibe check: these are intended for use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead.-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โ Disable RTL pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon. The range is inclusive in both ends. If the range is trivial, the number pair can be simplified as a single number. If the function's call graph node's uid falls within one of the specified ranges, the pass is disabled for that function. The uid is shown in the function header of a dump file, and the pass names can be dumped by using option-fdump-passes.-fdisable-tree-pass,-fdisable-tree-pass=range-listโ Disable tree pass pass. See-fdisable-rtlfor the description of option arguments.-fenable-ipa-passโ Enable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.-fenable-rtl-pass,-fenable-rtl-pass=range-listโ Enable RTL pass pass. See-fdisable-rtlfor option argument description and examples.-fenable-tree-pass,-fenable-tree-pass=range-listโ Enable tree pass pass. See-fdisable-rtlfor the description of option arguments.
Here are some examples showing uses of these options โ copy these exactly, bestie:
# disable ccp1 for all functions
-fdisable-tree-ccp1
# disable complete unroll for function whose cgraph node uid is 1
-fenable-tree-cunroll=1
# disable gcse2 for functions at the following ranges [1,1],
# [300,400], and [400,1000]
# disable gcse2 for functions foo and foo2
-fdisable-rtl-gcse2=foo,foo2
# disable early inlining
-fdisable-tree-einline
# disable ipa inlining
-fdisable-ipa-inline
# enable tree full unroll
-fenable-tree-unroll
-fchecking,-fchecking=nโ Enable internal consistency checking. The default depends on the compiler configuration.-fchecking=2enables further internal consistency checking that might affect code generation. so yes, it can change the output โ respect it ๐ซถ-frandom-seed=stringโ This option provides a seed that GCC uses in place of random numbers in generating certain symbol names that have to be different in every compiled file. It is also used to place unique stamps in coverage data files and the object files that produce them. You can use the-frandom-seedoption to produce reproducibly identical object files. The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it's converted to a number by computing CRC32). The string should be different for every file you compile. reproducible build girlies stay winning โจ-save-tempsโ Store the usual "temporary" intermediate files permanently; name them as auxiliary output files, as specified described under-dumpbaseand-dumpdir. When used in combination with the-xcommand-line option,-save-tempsis sensible enough to avoid overwriting an input source file with the same extension as an intermediate file. The corresponding intermediate file may be obtained by renaming the source file before using-save-temps.-save-temps=cwdโ Equivalent to-save-temps -dumpdir ./. short and iconic ๐-save-temps=objโ Equivalent to-save-temps -dumpdir outdir/, where outdir/ is the directory of the output file specified after the-ooption, including any directory separators. If the-ooption is not used, the-save-temps=objswitch behaves like-save-temps=cwd.-time[=file]โ Report the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and assembler (plus the linker if linking is done). Without the specification of an output file, the output looks like this:
# cc1 0.12 0.01
# as 0.00 0.01
The first number on each line is the "user time", that is time spent executing the program itself. The second number is "system time", time spent executing operating system routines on behalf of the program. Both numbers are in seconds.
With the specification of an output file, the output is appended to the named file, and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
The "user time" and the "system time" are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options. receipts: kept ๐
-fdump-final-insns[=file]โ Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is.), the name of the dump file is determined by appending.gkdto the dump base name, see-dumpbase.-fcompare-debug[=opts]โ If no error occurs during compilation, run the compiler a second time, adding opts and-fcompare-debug-secondto the arguments passed to the second compilation. Dump the final internal representation in both compilations, and print an error if they differ. If the equal sign is omitted, the default-gtoggleis used. The environment variableGCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables-fcompare-debug. IfGCC_COMPARE_DEBUGis defined to a string starting with a dash, then it is used for opts, otherwise the default-gtoggleis used.-fcompare-debug=, with the equal sign but without opts, is equivalent to-fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing evenGCC_COMPARE_DEBUGfrom taking effect. To verify full coverage during-fcompare-debugtesting, setGCC_COMPARE_DEBUGto say-fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning, settingGCC_COMPARE_DEBUGto-w%n-fcompare-debug not overriddenwill do. this is compiler-dev deep magic, no cap ๐ง-fcompare-debug-secondโ This option is implicitly passed to the compiler for the second compilation requested by-fcompare-debug, along with options to silence warnings, and omitting other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files are renamed so as to contain the.gkadditional extension during the second compilation, to avoid overwriting those generated by the first. 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. The position of this argument in the command line does not matter; it takes effect after all other options are processed, and it does so only once, no matter how many times it is given. This is mainly intended to be used with-fcompare-debug. one toggle, one job ๐-fvar-tracking-assignments-toggleโ Toggle-fvar-tracking-assignments, in the same way that-gtoggletoggles-g.-Qโ Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes. chaotic but useful โจ-ftime-reportโ Makes the compiler print some statistics about the time consumed by each pass when it finishes.-ftime-report-detailsโ Record the time consumed by infrastructure parts separately for each pass.-fira-verbose=nโ Control the verbosity of the dump file for the integrated register allocator. The default value is 5. If the value n is greater or equal to 10, the dump output is sent tostderrusing 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 is 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 print for the WPA phase of link-time optimization.-fmem-reportโ Makes the compiler print some statistics about permanent memory allocation when it finishes.-fmem-report-wpaโ Makes the compiler print some statistics about permanent memory allocation for the WPA phase only.-fpre-ipa-mem-report,-fpost-ipa-mem-reportโ Makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization.-fmultiflagsโ This option enables multilib-aware "TFLAGS" to be used to build target libraries with options different from those the compiler is configured to use by default, through the use of specs.
Like TFLAGS, this lets the target libraries get built for portable baseline environments while the compiler itself defaults to the more demanding ones. Thatโs lowkey useful because users can easily override the defaults the compiler is configured to use to build their own programs โ if those defaults arenโt ideal for their target environment โ whereas rebuilding the runtime libraries is usually not as easy or desirable. ๐
Unlike TFLAGS, using specs lets different flags get selected for different multilibs. The way to accomplish that is to build with make TFLAGS=-fmultiflags, after configuring --with-specs=%{fmultiflags:...}. โจ
This option is discarded by the driver once itโs done processing driver self spec. (iykyk ๐ซถ)
Itโs also useful to check that TFLAGS are being used to build all target libraries, by configuring a non-bootstrap compiler with --with-specs='%{!fmultiflags:%emissing TFLAGS}' and building the compiler and target libraries. ๐
-fprofile-reportโ makes the compiler print some statistics about consistency of the (estimated) profile and effect of individual passes. Itโs giving โreport card for your optimization eraโ ๐-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 theauxname.auxnameis generated from the name of the output file, if explicitly specified and it is not an executable, otherwise it is the basename of the source file. An entry is made up of three fields:- the name of the function.
- a number of bytes.
- one or more qualifiers:
static,dynamic,bounded.
The qualifier static means 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; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes.
The qualifier dynamic means that the function manipulates the stack dynamically: in addition to the static allocation described above, stack adjustments are made in the body of the function, for example to push/pop arguments around function calls. If the qualifier bounded is also present, the amount of these adjustments is bounded at compile time and the second field is an upper bound of the total amount of stack used by the function. If it is not present, the amount of these adjustments is not bounded at compile time and the second field only represents the bounded part. ๐ซง
-fstatsโ emit statistics about front-end processing at the end of the compilation. This option is supported only by the C++ front end, and the information is generally only useful to the G++ development team. ๐-fdbg-cnt-listโ print the name and the counter upper bound for all debug counters. Debug-counter tea, served hot โ-fdbg-cnt=counter-value-listโ set the internal debug counter lower and upper bound.counter-value-listis a comma-separated list ofname:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...]tuples which sets the name of the counter and list of closed intervals. Thelower_boundis optional and is zero initialized if not set. For example, with-fdbg-cnt=dce:2-4:10-11,tail_call:10,dbg_cnt(dce)returns true only for second, third, fourth, tenth and eleventh invocation. Fordbg_cnt(tail_call)true is returned for first 10 invocations. ๐-print-file-name=libraryโ print the full absolute name of the library filelibrarythat would be used when linking โ and donโt do anything else. With this option, GCC does not compile or link anything; it just prints the file name. No cap, itโs literally just the name ๐-print-multi-directoryโ print the directory name corresponding to the multilib selected by any other switches present in the command line. This directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ print the mapping from multilib directory names to compiler switches that enable them. The directory name is separated from the switches by;, and each switch starts with an@instead of the-, without spaces between multiple switches. This is supposed to ease shell processing. ๐-print-multi-os-directoryโ print the path to OS libraries for the selected multilib, relative to somelibsubdirectory. If OS libraries are present in thelibsubdirectory and no multilibs are used, this is usually just., if OS libraries are present in libsuffix sibling directories this prints e.g.../lib64,../libor../lib32, or if OS libraries are present inlib/subdirsubdirectories it prints e.g.amd64,sparcv9orev6. ๐๏ธ-print-multiarchโ print the path to OS libraries for the selected multiarch, relative to somelibsubdirectory.-print-prog-name=programโ like-print-file-name, but searches for a program such ascpp. Finding programs core ๐-print-libgcc-file-nameโ same as-print-file-name=libgcc.a.
This is useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a. You can do:
gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
-print-search-dirsโ print the name of the configured installation directory and a list of program and library directories gcc searches โ and donโt do anything else.
This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Donโt forget the trailing /. ๐จ
-print-sysrootโ print the target sysroot directory that 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โ print the suffix added to the target sysroot when searching for headers, or give an error if the compiler is not configured with such a suffix โ and donโt do anything else. ๐-dumpmachineโ print the compilerโs target machine (for example,i686-pc-linux-gnu) โ and donโt do anything else.-dumpversionโ print the compiler version (for example,3.0,6.3.0or7) โ and donโt do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured it can be just a single number (major version), two numbers separated by a dot (major and minor version) or three numbers separated by dots (major, minor and patchlevel version). ๐ข-dumpfullversionโ print the full compiler version โ and donโt do anything else. The output is always three numbers separated by dots, major, minor and patchlevel version. โจ-dumpspecsโ print the compilerโs built-in specs โ and donโt do anything else. (This is used when GCC itself is being built.) ๐ ๏ธ
๐ ๏ธ Machine-Dependent Options ๐ ๏ธ
Each target machine supported by GCC can have its own options โ for example, to allow you to compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m. ๐ง
Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform. ๐
๐ฆ AArch64 Options ๐ฆ
These options are defined for AArch64 implementations:
-mabi=nameโ generate code for the specified data model. Permissible values areilp32for SysV-like data model whereint,long intand pointers are 32 bits, andlp64for 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โ generate big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target.-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. ๐-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for anaarch64-*-*but not anaarch64_be-*-*target.-mcmodel=tinyโ generate code for the tiny code model. The program and its statically defined symbols must be within 1MB of each other. Programs can be statically or dynamically linked.-mcmodel=smallโ generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. ๐-mcmodel=largeโ generate code for the large code model. This makes no assumptions about addresses and sizes of sections. Programs can be statically linked only. The-mcmodel=largeoption is incompatible with-mabi=ilp32,-fpicand-fPIC. ๐-mstrict-align,-mno-strict-alignโ avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. ๐-momit-leaf-frame-pointer,-mno-omit-leaf-frame-pointerโ omit or keep the frame pointer in leaf functions. The former behavior is the default. ๐-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ generate stack protection code using canary atguard. Supported locations areglobalfor a global canary orsysregfor a canary in an appropriate system register.
With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which system register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel. ๐ง
-mtls-dialect=descโ use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default. ๐งต-mtls-dialect=traditionalโ bestie, this tells it to use traditional TLS as the thread-local storage mechanism whenever it does dynamic accesses of TLS variables. Old school, but it works ๐-mtls-size=sizeโ sets the bit size of immediate TLS offsets. Valid values are12,24,32,48. Heads up though: this one needs binutils 2.26 or newer, no cap โจ-mfix-cortex-a53-835769,-mno-fix-cortex-a53-835769โ turns the workaround for the ARM Cortex-A53 erratum number 835769 on or off. What does the workaround do, you ask? It literally inserts aNOPinstruction between memory instructions and 64-bit integer multiply-accumulate instructions. Iconic little band-aid ๐ฉน-mfix-cortex-a53-843419,-mno-fix-cortex-a53-843419โ same energy, different erratum: enables or disables the workaround for the ARM Cortex-A53 erratum number 843419. Plot twist: this workaround is made at link time, so all this does is pass the corresponding flag to the linker. Middle-man behavior fr fr ๐ญ-mlow-precision-recip-sqrt,-mno-low-precision-recip-sqrtโ enables or disables the reciprocal square root approximation. Lowkey important: this option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling it reduces precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. So, faster but slightly blurrier ๐ฆ-mlow-precision-sqrt,-mno-low-precision-sqrtโ enables or disables the square root approximation. Same deal: it only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling reduces precision of square root results to about 16 bits for single precision and to 32 bits for double precision. And the fun part โ if enabled, it implies-mlow-precision-recip-sqrt๐-mlow-precision-div,-mno-low-precision-divโ enables or disables the division approximation. You already know the rule: only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling reduces precision of division results to about 16 bits for single precision and to 32 bits for double precision โจ-mtrack-speculation,-mno-track-speculationโ enables or disables generation of extra code to track speculative execution through conditional branches. The tracking state can then be used by the compiler when expanding calls to__builtin_speculation_safe_copyso it can generate a more efficient code sequence. Detective mode ๐-moutline-atomics,-mno-outline-atomicsโ enables or disables calls to out-of-line helpers to implement atomic operations. These helpers will, at runtime, figure out if the LSE instructions from ARMv8.1-A can be used; if not, they'll fall back to the load/store-exclusive instructions that are present in the base ARMv8.0 ISA. Adaptive queen ๐
Also: this option is only applicable when compiling for the base ARMv8.0 instruction set. If you're using a later revision, e.g. -march=armv8.1-a or -march=armv8-a+lse, the ARMv8.1-Atomics instructions will be used directly. Same applies when using -mcpu= and the selected cpu supports the lse feature. And yes โ this option is on by default ๐
-march=nameโ specify the name of the target architecture and, optionally, one or more feature modifiers. The form is:
-march=arch{+[no]feature}*
Here's the run-down of permissible values for arch and the features they enable by default:
armv8-a: Armv8-A : includes+fp,+simdby defaultarmv8.1-a: Armv8.1-A : includesarmv8-a,+crc,+lse,+rdmaarmv8.2-a: Armv8.2-A : includesarmv8.1-aarmv8.3-a: Armv8.3-A : includesarmv8.2-a,+pautharmv8.4-a: Armv8.4-A : includesarmv8.3-a,+flagm,+fp16fml,+dotprodarmv8.5-a: Armv8.5-A : includesarmv8.4-a,+sb,+ssbs,+predresarmv8.6-a: Armv8.6-A : includesarmv8.5-a,+bf16,+i8mmarmv8.7-a: Armv8.7-A : includesarmv8.6-a,+ls64armv8.8-a: Armv8.8-a : includesarmv8.7-a,+mopsarmv9-a: Armv9-A : includesarmv8.5-a,+sve,+sve2armv9.1-a: Armv9.1-A : includesarmv9-a,+bf16,+i8mmarmv9.2-a: Armv9.2-A : includesarmv9.1-a,+ls64armv9.3-a: Armv9.3-A : includesarmv9.2-a,+mopsarmv8-r: Armv8-R : includesarmv8-r
The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. Real talk though โ this option has no effect if the compiler is unable to recognize the architecture of the host system.
The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used. Right-most wins, always ๐
GCC uses name to determine what kind of instructions it can emit when generating assembly code. And if -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture. Versatile icon โจ
-mtune=nameโ specify the name of the target processor for which GCC should tune the performance of the code. Permissible values for this option are:generic,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,cortex-a76,cortex-a76ae,cortex-a77,cortex-a65,cortex-a65ae,cortex-a34,cortex-a78,cortex-a78ae,cortex-a78c,ares,exynos-m1,emag,falkor,neoverse-512tvb,neoverse-e1,neoverse-n1,neoverse-n2,neoverse-v1,neoverse-v2,grace,qdf24xx,saphira,phecda,xgene1,vulcan,octeontx,octeontx81,octeontx83,octeontx2,octeontx2t98,octeontx2t96octeontx2t93,octeontx2f95,octeontx2f95n,octeontx2f95mm,a64fx,thunderx,thunderxt88,thunderxt88p1,thunderxt81,tsv110,thunderxt83,thunderx2t99,thunderx3t110,zeus,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53,cortex-a75.cortex-a55,cortex-a76.cortex-a55,cortex-r82,cortex-x1,cortex-x1c,cortex-x2,cortex-x3,cortex-a510,cortex-a710,cortex-a715,ampere1,ampere1a,cobalt-100andnative.
The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 specify that GCC should tune for a big.LITTLE system. Cute little duo ๐ซถ
The value neoverse-512tvb specifies that GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. In other words, the option tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle and 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 is more specific than the default tuning described below ๐ฅ
Additionally, on native AArch64 GNU/Linux systems the value native tunes performance to the host system. This option has no effect if the compiler is unable to recognize the processor of the host system.
Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.
Heads up bestie: this option cannot be suffixed by feature modifiers. Periodt.
-mcpu=nameโ specify the name of the target processor, optionally suffixed by one or more feature modifiers. The form is:
-mcpu=cpu{+[no]feature}*
where the permissible values for cpu are the same as those available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used ๐
GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. They're the main characters here, ngl.
-mcpu=neoverse-512tvb is special in that it does not refer to a specific core, but instead refers to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless overridden by -march, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with these properties. And unless overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb ๐
-moverride=stringโ overrides tuning decisions made by the back-end in response to a-mtune=switch. Big caveat babe: the syntax, semantics, and accepted values forstringin this option are not guaranteed to be consistent across releases. So don't get attached ๐ญ
This option is only intended to be useful when developing GCC. It's for the devs, not for us.
-mverbose-cost-dumpโ enables verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler. Compiler-dev exclusive โจ-mpc-relative-literal-loads,-mno-pc-relative-literal-loadsโ enable or disable PC-relative literal loads. With this option literal pools are accessed using a single instruction and emitted after each function. That limits the maximum size of functions to1MB. And fun fact: this is enabled by default for-mcmodel=tiny๐-msign-return-address=scopeโ select the function scope on which return address signing will be applied. Permissible values arenone, which disables return address signing,non-leaf, which enables pointer signing for functions which are not leaf functions, andall, which enables pointer signing for all functions. The default value isnone.
Ngl this one's been deprecated by -mbranch-protection. Upgrade your faves bestie ๐
-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ select the branch protection features to use.noneis the default and turns off all types of branch protection.standardturns on all types of branch protection features โ and 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. Andbtiturns on branch target identification mechanism. Protect yourself queen ๐ก๏ธ-mharden-sls=optsโ enables compiler hardening against straight line speculation (SLS).optsis a comma-separated list of the following options:retbrblr
Ngl bestie, the SLS hardening situation is literally just two vibes: -mharden-sls=all turns every SLS hardening on, and -mharden-sls=none turns all of it off. That's the whole story, no cap. ๐
-msve-vector-bits=bitsโ tells GCC exactly how many bits live in an SVE vector register. Heads up though: this only does anything when SVE is actually enabled, so don't expect magic otherwise. โจ
So here's the tea on SVE codegen: GCC supports two whole forms of it. There's "vector-length agnostic" output, which works no matter what size your vector register is, and "vector-length specific" output, which lets GCC make assumptions about the vector length whenever that's useful for optimization reasons. ๐
The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Pick scalable and you get vector-length agnostic output. Lowkey important: at present -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. Every other value generates vector-length specific code. ๐ฆ
Fr fr though: 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. Like, don't build your whole personality on it. ๐ญ
The default is -msve-vector-bits=scalable, which produces vector-length agnostic code. Iconic, honestly.
โจ -march and -mcpu Feature Modifiers โจ
Feature modifiers used with -march and -mcpu can be any of the following and their inverses nofeature. Yes bestie, every single one has an inverse, go wild. ๐
crcโ enable the CRC extension. This is on by default for-march=armv8.1-a.cryptoโ enable the Crypto extension. This also enables Advanced SIMD and floating-point instructions.fpโ enable floating-point instructions. This is on by default for all possible values for options-marchand-mcpu.simdโ enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for options-marchand-mcpu.sveโ enable Scalable Vector Extension instructions. This also enables Advanced SIMD and floating-point instructions.lseโ enable Large System Extension instructions. This is on by default for-march=armv8.1-a.rdmaโ enable Round Double Multiply Accumulate instructions. This is on by default for-march=armv8.1-a.fp16โ enable the FP16 extension. This also enables floating-point instructions.fp16fmlโ enable the FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. This option is enabled by default for-march=armv8.4-a. Use of this option with architectures prior to Armv8.2-A is not supported. ๐ซถrcpcโ enable the RCpc extension. This enables the use of theLDAPRinstructions for load-acquire atomic semantics, and passes it on to the assembler, enabling inline asm statements to use instructions from the RCpc extension.dotprodโ enable the Dot Product extension. This also enables Advanced SIMD instructions.aesโ enable the Armv8-a aes and pmull crypto extension. This also enables Advanced SIMD instructions.sha2โ enable the Armv8-a sha2 crypto extension. This also enables Advanced SIMD instructions.sha3โ enable the sha512 and sha3 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.sm4โ enable the sm3 and sm4 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.profileโ enable the Statistical Profiling extension. Careful: this option is only to enable the extension at the assembler level and does not affect code generation. ๐rngโ enable the Armv8.5-a Random Number instructions. Same deal โ this option is only to enable the extension at the assembler level and does not affect code generation.memtagโ enable the Armv8.5-a Memory Tagging Extensions. Use of this option with architectures prior to Armv8.5-A is not supported.sbโ enable the Armv8-a Speculation Barrier instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.ssbsโ enable the Armv8-a Speculative Store Bypass Safe instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.predresโ enable the Armv8-a Execution and Data Prediction Restriction instructions. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.sve2โ enable the Armv8-a Scalable Vector Extension 2. This also enables SVE instructions.sve2-bitpermโ enable SVE2 bitperm instructions. This also enables SVE2 instructions.sve2-sm4โ enable SVE2 sm4 instructions. This also enables SVE2 instructions.sve2-aesโ enable SVE2 aes instructions. This also enables SVE2 instructions.sve2-sha3โ enable SVE2 sha3 instructions. This also enables SVE2 instructions.tmeโ enable the Transactional Memory Extension. ๐คi8mmโ enable 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.f32mmโ enable 32-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.f64mmโ enable 64-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.bf16โ enable brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.ls64โ enable the 64-byte atomic load and store instructions for accelerators. This option is enabled by default for-march=armv8.7-a.mopsโ enable the instructions to accelerate memory operations likememcpy,memmove,memset. This option is enabled by default for-march=armv8.8-aflagmโ enable the Flag Manipulation instructions Extension.pauthโ enable the Pointer Authentication Extension.csscโ enable the Common Short Sequence Compression instructions.
Feature crypto implies aes, sha2, and simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It's giving chain reaction, honestly. ๐
๐ธ 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. Very "make it work on the cheap one" of it. ๐-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. Coin flip energy, lowkey.-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. Just... vibe padding. ๐-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 of8means that the eight bytes in the rangesp+0...sp+7can be used by leaf functions without stack allocation. Values other than8or16are untested and unlikely to work.
Big warning bestie: 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=num option. ๐ญ
-mno-round-nearestโ make the scheduler assume that the rounding mode has been set to truncating. The default is-mround-nearest.-mlong-callsโ if not otherwise specified by an attribute, assume all calls might be beyond the offset range of theb/blinstructions, and therefore load the function address into a register before performing a (otherwise direct) call. This is the default.-mshort-callsโ if not otherwise specified by an attribute, assume all direct calls are in the range of theb/blinstructions, so use these instructions for direct calls. The default is-mlong-calls.-msmall16โ assume addresses can be loaded as 16-bit unsigned values. 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. Efficiency slay. โญ
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โ the mode for floating-point math that truncates, aka rounds toward zero ๐ซถ and yeah, that includes converting from floating-point to integer.round-nearestโ the mode for floating-point math with round-to-nearest-or-even rounding. classic, balanced, no drama ๐intโ the mode for doing integer math in the FPU, like integer multiply, or integer multiply-and-accumulate. yes bestie, the FPU does integers sometimes, it's giving versatile โจ
The default is -mfp-mode=caller.
-mno-split-lohi,-mno-postinc,-mno-postmodifyโ codegen tweaks that turn off, respectively: splitting of 32-bit loads, generation of post-increment addresses, and generation of post-modify addresses. The defaults aremsplit-lohi,-mpost-inc, and-mpost-modify.-mnovect-doubleโ switches the preferred SIMD mode toSImode. The default is-mvect-double, which usesDImodeas the preferred SIMD mode.-max-vect-align=numโ the maximum alignment for SIMD vector mode types. num can be4or8. Default is8. Heads up though โ this is an ABI change, even though lots of library function interfaces are unaffected if they don't use SIMD vector modes anywhere that messes with the size and/or alignment of the relevant types ๐-msplit-vecmove-earlyโ splits vector moves into single word moves before reload. In theory this gives better register allocation, but so far the reverse seems to be generally the case. not the serve anyone expected ๐ญ-m1reg-regโ pick a register to hold the constant-1, which makes loading small negative constants and certain bitmasks faster. Allowed values for reg arer43andr63(which mean use that register as a fixed register), andnone(which means no register is used for this). The default is-m1reg-none.
๐ AMD GCN Options
These options are defined specifically for the AMD GCN port.
-march=gpu-mtune=gpuโ set the architecture type or tuning for gpu. Supported values for gpu are:fijiโ compile for GCN3 Fiji devices (gfx803). Support deprecated; availability depends on how GCC has been configured, see--with-archand--with-multilib-list.gfx900โ compile for GCN5 Vega 10 devices (gfx900).gfx906โ compile for GCN5 Vega 20 devices (gfx906).gfx908โ compile for CDNA1 Instinct MI100 series devices (gfx908).gfx90aโ compile for CDNA2 Instinct MI200 series devices (gfx90a).
-msram-ecc=on-msram-ecc=off-msram-ecc=anyโ compile binaries suitable for devices with the SRAM-ECC feature enabled, disabled, or either mode. On some devices this feature can be enabled per-process. The compiled code must match the device mode. The default isany, for devices that support it.-mstack-size=bytesโ how manybytesof stack space each GPU thread (wave-front) gets requested. Beware: there may be a lot of threads and only limited memory available ๐ฌ The size of the stack allocation can also affect run-time performance. The default is32KBwhen using OpenACC or OpenMP, and1MBotherwise.-mxnackโ compile binaries suitable for devices with the XNACK feature enabled. Some devices always require XNACK and some let the user configure XNACK. The compiled code must match the device mode. The default is-mno-xnack. Right now this option is a placeholder for support that is not yet implemented โ it's giving coming soon ๐
๐น ARC Options
The following options control the architecture variant for which code is being compiled:
-mbarrel-shifterโ generate instructions supported by the barrel shifter. This is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect.-mjli-alwaysโ force a call to a function using thejli_sinstruction. Only valid for the ARCv2 architecture.-mcpu=cpuโ set the architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options available for backward compatibility and convenience. Supported values for cpu are:arc600โ compile for ARC600. Aliases:-mA6,-mARC600.arc601โ compile for ARC601. Alias:-mARC601.arc700โ compile for ARC700. Aliases:-mA7,-mARC700. This is the default when configured with--with-cpu=arc700.arcemโ compile for ARC EM.archsโ compile for ARC HS.emโ compile for ARC EM CPU with no hardware extensions.em4โ compile for ARC EM4 CPU.em4_dmipsโ compile for ARC EM4 DMIPS CPU.em4_fpusโ compile for ARC EM4 DMIPS CPU with the single-precision floating-point extension.em4_fpudaโ compile for ARC EM4 DMIPS CPU with single-precision floating-point and double assist instructions.hsโ compile for ARC HS CPU with no hardware extensions except the atomic instructions.hs34โ compile for ARC HS34 CPU.hs38โ compile for ARC HS38 CPU.hs38_linuxโ compile for ARC HS38 CPU with all hardware extensions on.hs4xโ compile for ARC HS4x CPU.hs4xdโ compile for ARC HS4xD CPU.hs4x_rel31โ compile for ARC HS4x CPU release 3.10a.arc600_normโ compile for ARC 600 CPU with "norm" instructions enabled.arc600_mul32x16โ compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.arc601_normโ compile for ARC 601 CPU with "norm" instructions enabled.arc601_mul32x16โ compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring reduced register set.
-mdpfp-mdpfp-compactโ generate double-precision FPX instructions, tuned for the compact implementation.-mdpfp-fastโ generate double-precision FPX instructions, tuned for the fast implementation.-mno-dpfp-lrsrโ stop 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โ don't generatempy-family instructions for ARC700. This option is deprecated โ ๏ธ-mmul32x16โ generate 32x16-bit multiply and multiply-accumulate instructions.-mmul64โ generatemul64andmulu64instructions. Only valid for-mcpu=ARC600.-mnormโ generatenorminstructions. This is the default if-mcpu=ARC700is in effect.-mspfp-mspfp-compactโ generate single-precision FPX instructions, tuned for the compact implementation.-mspfp-fastโ generate single-precision FPX instructions, tuned for the fast implementation.-msimdโ enable generation of ARC SIMD instructions via target-specific builtins. Only valid for-mcpu=ARC700.-msoft-floatโ this option is ignored; it'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โ 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 the thread pointer register number.-mmpy-option=multoโ compile ARCv2 code with a multiplier design option. You can specify multo as either a string or a numeric value.wlh1is the default value. The recognized values are:0,noneโ no multiplier available.1,wโ 16x16 multiplier, fully pipelined. Enables these instructions:mpywandmpyuw.2,wlh1โ 32x32 multiplier, fully pipelined (1 stage). Additionally enables:mpy,mpyu,mpym,mpymu, andmpy_s.3,wlh2โ 32x32 multiplier, fully pipelined (2 stages). Additionally enables:mpy,mpyu,mpym,mpymu, andmpy_s.4,wlh3โ two 16x16 multipliers, blocking, sequential. Additionally enables:mpy,mpyu,mpym,mpymu, andmpy_s.5,wlh4โ one 16x16 multiplier, blocking, sequential. Additionally enables:mpy,mpyu,mpym,mpymu, andmpy_s.6,wlh5โ one 32x4 multiplier, blocking, sequential. Additionally enables:mpy,mpyu,mpym,mpymu, andmpy_s.7,plus_dmpyโ ARC HS SIMD support.8,plus_macdโ ARC HS SIMD support.9,plus_qmacwโ ARC HS SIMD support.
This option is only available for ARCv2 cores.
-mfpu=fpuโ enables support for specific floating-point hardware extensions for ARCv2 cores. Supported values for fpu are:fpusโ enables support for single-precision floating-point hardware extensions.fpudโ enables support for double-precision floating-point hardware extensions. Single-precision floating-point extension is also enabled. Not available for ARC EM.
fpudaโ turns on support for double-precision floating-point hardware extensions via double-precision assist instructions ๐ the single-precision floating-point extension gets switched on too. This one's only available for ARC EM, no cap.fpuda_divโ same double-precision-assist deal, but bestie it also brings single-precision floating-point, square-root, and divide extensions along for the ride โจ Only available for ARC EM.fpuda_fmaโ double-precision FP hardware extensions through double-precision assist instructions, plus single-precision floating-point and fused multiply and add hardware extensions are enabled too ๐ฅ Only available for ARC EM.fpuda_allโ the whole double-precision assist situation, and all single-precision floating-point hardware extensions are enabled as well ๐ 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. Heads up: 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โ tells the compiler which general-purpose registers the processor automatically saves/restores on interrupt entry and exit ๐ซถ register-range is written as two registers separated by a dash. The range always starts with"r0"and the upper limit is the"fp"register.blinkandlp_countare optional. This option is only valid for ARC EM and ARC HS cores, periodt.-mrgf-banked-regs=number โ sets how many registers get replicated in the second register bank when a fast interrupt comes in ๐ง Fast interrupts are the ones with the highest priority level P0. These interrupts save only the PC and STATUS32 registers, specifically to dodge memory transactions during interrupt entry and exit sequences. Use this when you're running fast interrupts on an ARC V2 family processor. Permitted values are4,8,16, and32.-mlpc-width=width โ sets the width of the"lp_count"register ๐ Valid values for width are8,16,20,24,28and32bits. Default width is locked in at32bits. If the width is less than 32, the compiler won't try to transform loops in your program to use the zero-delay loop mechanism unless it knows the"lp_count"register can hold the required loop-counter value. Depending on the width you pick, the compiler and run-time library might still use the loop mechanism for various needs, so yeah. This option defines macro"__ARC_LPC_WIDTH__"with the value of width.-mrf16โ instructs the compiler to generate code for a 16-entry register file ๐ This option defines the"__ARC_RF16__"preprocessor macro.-mbranch-indexโ enables use of"bi"or"bih"instructions to implement jump tables ๐ฅ
The following options get passed straight through to the assembler, and they also define preprocessor macro symbols ๐
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol"__Xdsp_packa". Heads up bestie: this option is deprecated ๐-mdvbfโ passed down to the assembler to enable the dual Viterbi butterfly extension. Also sets the preprocessor symbol"__Xdvbf". This option is deprecated ๐-mlockโ passed down to the assembler to enable the locked load/store conditional extension. Also sets the preprocessor symbol"__Xlock"๐-mmac-d16โ passed down to the assembler. Also sets the preprocessor symbol"__Xxmac_d16". This option is deprecated ๐-mmac-24โ passed down to the assembler. Also sets the preprocessor symbol"__Xxmac_24". This option is deprecated ๐-mrtscโ passed down to the assembler to enable the 64-bit time-stamp counter extension instruction. Also sets the preprocessor symbol"__Xrtsc". This option is deprecated ๐-mswapeโ passed down to the assembler to enable the swap byte ordering extension instruction. Also sets the preprocessor symbol"__Xswape"โจ-mtelephonyโ passed down to the assembler to enable dual- and single-operand instructions for telephony. Also sets the preprocessor symbol"__Xtelephony". This option is deprecated ๐-mxyโ passed down to the assembler to enable the XY memory extension. Also sets the preprocessor symbol"__Xxy"๐ธ
The following options control how the assembly code gets annotated ๐๏ธ
-misizeโ annotates assembler instructions with estimated addresses.-mannotate-alignโ explains what alignment considerations led to the decision to make an instruction short or long ๐
The following options are passed through to the linker ๐
-marclinuxโ passed through to the linker to specify use of the"arclinux"emulation. This one's enabled by default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is not requested.-marclinux_profโ passed through to the linker to specify use of the"arclinux_prof"emulation. This is the default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is requested ๐
The following options control the semantics of the generated code ๐ง
-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 is suppressed so the 25-bit range can be used instead of the 21-bit range you'd get with conditional branch-and-link. This is the default for tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets.-Gnum โ puts definitions of externally-visible data in a small data section if that data is no bigger than num bytes. The default value of num is4for any ARC configuration, or8when there are double load/store operations ๐-mno-sdataโ don't generate sdata references. This is the default for tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets.-mvolatile-cacheโ uses ordinarily cached memory accesses for volatile references. This is the default โญ-mno-volatile-cacheโ enables cache bypass for volatile references ๐ฆ
The following options fine tune code generation, iykyk ๐ง
-malign-callโ does nothing. Preserved for backward compatibility ๐-mauto-modify-regโ enables the use of pre/post modify with register displacement.-mbbit-peepholeโ enables bbit peephole2.-mno-brccโ disables a target-specific pass in arc_reorg that generates compare-and-branch ("brcc") instructions. It has no effect on generation of these instructions driven by the combiner pass ๐-mcase-vector-pcrelโ uses PC-relative switch case tables so case tables can be shortened. This is the default for-Osโจ-mcompact-casesiโ enables the compact"casesi"pattern. This is the default for-Os, and it's only available for ARCv1 cores. Heads up: this option is deprecated ๐-mno-cond-execโ disables the ARCompact-specific pass that generates conditional execution instructions.
Okay so, real talk: because of delay slot scheduling and the interactions between operand numbers, literal sizes, instruction lengths, and support for conditional execution, the target-independent pass for generating conditional execution is often lacking ๐ญ That's why the ARC port keeps a special pass around that hunts for more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have already happened. This pass generally (but not always!) improves performance and code size, at the cost of extra compilation time โ which is exactly why there's an option to switch it off. And if you're hitting problems with call instructions exceeding their allowable offset range because they got conditionalized, you should consider using -mmedium-calls instead ๐ซถ
-mearly-cbranchsiโ enables pre-reload use of the"cbranchsi"pattern.-mexpand-adddiโ expands"adddi3"and"subdi3"at RTL generation time into"add.f","adc"etc. This option is deprecated ๐-mindexed-loadsโ enables the use of indexed loads. Lowkey this can be problematic, because some optimizers then assume indexed stores exist โ which is not the case ๐ฌ-mlraโ enables Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e.-mno-lra).-mlra-priority-noneโ don't indicate any priority for target registers.-mlra-priority-compactโ indicate target register priority forr0..r3 / r12..r15.-mlra-priority-noncompactโ reduce target register priority forr0..r3 / r12..r15.-mmillicodeโ when optimizing for size (using-Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by calling a special function in libgcc โ that's called a millicode call ๐ Since these calls can pose performance issues and/or cause linking issues when you link in a nonstandard way, this option exists so you can turn millicode call generation on or off.-mcode-density-frameโ lets the compiler emit"enter"and"leave"instructions. These are only valid for CPUs with the code-density feature ๐ฅ-mmixed-codeโ does nothing. Preserved for backward compatibility ๐-mq-classโ bestie, this oneโs deprecated ๐ซ . It enables q instruction alternatives, and itโs the default for-Os.-mRcqโ literally does nothing. Preserved for backward compatibility, periodt. ๐-mRcwโ also does nothing. Preserved for backward compatibility. We love a harmless icon. โจ-msize-level=levelโ fine-tune size optimization with regards to instruction lengths and alignment. The recognized values for level are:0โ no size optimization. This level is deprecated and treated like1.1โ short instructions are used opportunistically.2โ in addition, alignment of loops and of code after barriers are dropped.3โ in addition, optional data alignment is dropped, and the optionOsis enabled.
This defaults to 3 when -Os is in effect. Otherwise, the behavior when this is not set is equivalent to level 1. ๐
-mtune=cpuโ set instruction scheduling parameters for cpu, overriding any implied by-mcpu=. Supported values for cpu are:ARC600โ tune for ARC600 CPU.ARC601โ tune for ARC601 CPU.ARC700โ tune for ARC700 CPU with standard multiplier block.ARC700-xmacโ tune for ARC700 CPU with XMAC block.ARC725Dโ tune for ARC725D CPU.ARC750Dโ tune for ARC750D CPU.core3โ tune for ARCv2 core3 type CPU. This option enable usage of"dbnz"instruction.release31aโ tune for ARC4x release 3.10a.
-mmultcost=numโ cost to assume for a multiply instruction, with4being equal to a normal instruction.-munalign-prob-threshold=probabilityโ does nothing. Preserved for backward compatibility. ๐ซถ
โ ๏ธ The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release:
-margonautโ obsolete FPX.-mbig-endian,-EBโ compile code for big-endian targets. Use of these options is now deprecated. Big-endian code is supported by configuring GCC to 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.-mEAโ replaced by-mea.-mmac_24โ replaced by-mmac-24.-mmac_d16โ replaced by-mmac-d16.-mspfp_compactโ replaced by-mspfp-compact.-mspfp_fastโ replaced by-mspfp-fast.-mtune=cpuโ valuesarc600,arc601,arc700andarc700-xmacfor cpu are replaced byARC600,ARC601,ARC700andARC700-xmacrespectively.-multcost=numโ replaced by-mmultcost.
๐ช ARM Options ๐ช
These -m options are defined for the ARM port, bestie. Letโs get into it. ๐ฆ
-mabi=nameโ generate code for the specified ABI. Permissible values are:apcs-gnu,atpcs,aapcs,aapcs-linuxandiwmmxt.-mapcs-frameโ generate a stack frame that is compliant with the ARM Procedure Call Standard for all functions, even if this is not strictly necessary for correct execution of the code. Specifying-fomit-frame-pointerwith this option causes the stack frames not to be generated for leaf functions. The default is-mno-apcs-frame. This option is deprecated. ๐ญ-mapcsโ this is a synonym for-mapcs-frameand is deprecated.-mthumb-interworkโ generate code that supports calling between the ARM and Thumb instruction sets. Without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. The default is-mno-thumb-interwork, since slightly larger code is generated when-mthumb-interworkis specified. In AAPCS configurations this option is meaningless. ๐ซ-mno-sched-prologโ prevent the reordering of instructions in the function prologue, or the merging of those instruction with the instructions in the functionโs body. This means that all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this information can be used to locate the start of functions inside an executable piece of code. The default is-msched-prolog. ๐-mfloat-abi=nameโ specifies which floating-point ABI to use. Permissible values are:soft,softfpandhard.- Specifying
softcauses GCC to generate output containing library calls for floating-point operations. softfpallows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions.hardallows generation of floating-point instructions and uses FPU-specific calling conventions.
- Specifying
The default depends on the specific target configuration. Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. No cap, this one matters. โ ๏ธ
-mgeneral-regs-onlyโ generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. ๐-mlittle-endianโ generate code for a processor running in little-endian mode. This is the default for all standard configurations. Slay. โจ-mbig-endianโ generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.-mbe8,-mbe32โ when linking a big-endian image select between BE8 and BE32 formats. The option has no effect for little-endian images and is ignored. The default is dependent on the selected target architecture. For ARMv6 and later architectures the default is BE8, for older architectures the default is BE32. BE32 format has been deprecated by ARM. ๐ซก-march=name[+extension...]โ this specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. This option can be used in conjunction with or instead of the-mcpu=option.
Permissible names are: armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, armv9-a, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, armv9-a, iwmmxt and iwmmxt2.
Additionally, the following architectures, which lack support for the Thumb execution state, are recognized but support is deprecated: armv4.
Many of the architectures support extensions. These can be added by appending +extension to the architecture name. Extension options are processed in order and capabilities accumulate. An extension will also enable any necessary base extensions upon which it depends. For example, the +crypto extension will always enable the +simd extension. The exception to the additive construction is for extensions that are prefixed with +no...: these extensions disable the specified option and any other extensions that may depend on the presence of that extension.
For example, -march=armv7-a+simd+nofp+vfpv4 is equivalent to writing -march=armv7-a+vfpv4 since the +simd option is entirely disabled by the +nofp option that follows it. Iconic behavior, honestly. ๐
Most extension names are generically named, but have an effect that is dependent upon the architecture to which it is applied. For example, the +simd option can be applied to both armv7-a and armv8-a architectures, but will enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a and the ARMv8-A variant for armv8-a. ๐
The table below lists the supported extensions for each architecture. Architectures not mentioned do not support any extensions.
armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk
+fpโ the VFPv2 floating-point instructions. The extension+vfpv2can be used as an alias for this extension.+nofpโ disable the floating-point instructions.
armv7
The common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures.
+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension. Note that floating-point is not supported by the base ARMv7-M architecture, but is compatible with both the ARMv7-A and ARMv7-R architectures.+nofpโ disable the floating-point instructions.
armv7-a
+mpโ the multiprocessing extension.+secโ the security extension.+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension.+simdโ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. The extensions+neonand+neon-vfpv3can be used as aliases for this extension.+vfpv3โ the VFPv3 floating-point instructions, with 32 double-precision registers.+vfpv3-d16-fp16โ the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.+vfpv3-fp16โ the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.+vfpv4-d16โ the VFPv4 floating-point instructions, with 16 double-precision registers.+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers.+neon-fp16โ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.+neon-vfpv4โ the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions ๐+nosimdโ turns off the Advanced SIMD instructions (and no, it does not disable floating point, bestie) ๐ซถ+nofpโ turns off the floating-point and Advanced SIMD instructions, periodt ๐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โ turns off the Advanced SIMD instructions (still not disabling floating point, iykyk) ๐+nofpโ turns off the floating-point and Advanced SIMD instructions. ๐
armv8-aโ the ARMv8-A vibe, with its own extension menu ๐+crcโ the Cyclic Redundancy Check (CRC) instructions. ๐ฅ+simdโ the ARMv8-A Advanced SIMD and floating-point instructions. โจ+cryptoโ the cryptographic instructions. ๐+nocryptoโ turns off the cryptographic instructions. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐ง
armv8.1-aโ the next glow-up of the ARMv8 menu ๐ฆ+simdโ the ARMv8.1-A Advanced SIMD and floating-point instructions. โจ+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions. ๐+nocryptoโ turns off the cryptographic instructions. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐ง
armv8.2-a,armv8.3-aโ both of these share the exact same extension lineup, no cap ๐+fp16โ the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions. ๐+fp16fmlโ the half-precision floating-point fmla extension. This also enables the half-precision floating-point extension and Advanced SIMD and floating-point instructions. ๐ธ+simdโ the ARMv8.1-A Advanced SIMD and floating-point instructions. โจ+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions. ๐+dotprodโ enables the Dot Product extension. This also enables Advanced SIMD instructions. ๐งฎ+nocryptoโ turns off the cryptographic extension. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐ง+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. ๐ข+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. ๐ง ๐
armv8.4-aโ more ARMv8 flavor, and yes the list is iconic ๐+fp16โ the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension. ๐+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. โจ+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. ๐+nocryptoโ turns off the cryptographic extension. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+sbโ Speculation Barrier Instruction. ๐ก๏ธ+predresโ Execution and Data Prediction Restriction Instructions. ๐ง+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. ๐ข+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. ๐ง ๐
armv8.5-aโ this one gets the same extension set as 8.4-a, periodt ๐+fp16โ the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension. ๐+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. โจ+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. ๐+nocryptoโ turns off the cryptographic extension. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. ๐ข+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. ๐ง ๐
armv8.6-aโ same lineup as 8.5-a again, bestie, keep scrolling ๐ฆ+fp16โ the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension. ๐+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension. โจ+cryptoโ the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension. ๐+nocryptoโ turns off the cryptographic extension. ๐ โโ๏ธ+nofpโ turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. ๐ข+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions. ๐ง ๐
armv7-rโ the ARMv7-R menu, real-time bestie energy โญ+fp.spโ the single-precision VFPv3 floating-point instructions. The extension+vfpv3xdcan be used as an alias for this extension. ๐+fpโ the VFPv3 floating-point instructions with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension. ๐+vfpv3xd-d16-fp16โ the single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. ๐ฆ+vfpv3-d16-fp16โ the VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. ๐ธ+nofpโ turns off the floating-point extension. ๐ โโ๏ธ+idivโ the ARM-state integer division instructions. โ+noidivโ turns off the ARM-state integer division extension. ๐
armv7e-mโ microcontroller vibes, but make it floating-point ๐ง+fpโ the single-precision VFPv4 floating-point instructions. ๐+fpv5โ the single-precision FPv5 floating-point instructions. โจ+fp.dpโ the single- and double-precision FPv5 floating-point instructions. ๐+nofpโ turns off the floating-point extensions. ๐ โโ๏ธ
armv8.1-m.mainโ the M-profile main-character architecture ๐+dspโ the DSP instructions. ๐๏ธ+mveโ the M-Profile Vector Extension (MVE) integer instructions. ๐งฎ+mve.fpโ the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions. ๐+fpโ the single-precision floating-point instructions. ๐+fp.dpโ the single- and double-precision floating-point instructions. โจ+nofpโ turns off the floating-point extension. ๐ โโ๏ธ
+cdecp0,+cdecp1, ... ,+cdecp7โ turns the Custom Datapath Extension (CDE) ON for whichever coprocessors you name, and the numbers you give have to be in the range0to7๐+pacbtiโ enables the Pointer Authentication and Branch Target Identification Extension, iconic security behavior honestly ๐ซถ
armv8-m.main
+dspโ the DSP instructions, yes ma'am โจ+nodspโ disables that DSP extension. we contain multitudes ๐+fpโ the single-precision floating-point instructions.+fp.dpโ the single- and double-precision floating-point instructions. go big ๐ธ+nofpโ disables the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ enables the Custom Datapath Extension (CDE) on the selected coprocessors, per the numbers in the options, range0to7๐
armv8-r
+crcโ the Cyclic Redundancy Check (CRC) instructions โจ+fp.spโ the single-precision FPv5 floating-point instructions.+simdโ the ARMv8-A Advanced SIMD and floating-point instructions.+cryptoโ the cryptographic instructions ๐ฅ+nocryptoโ disables the cryptographic instructions.+nofpโ disables the floating-point, Advanced SIMD and cryptographic instructions. all of them. gone. ๐
-march=native makes the compiler 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. like it just shrugs and moves on, no cap ๐ญ
-mtune=name ๐
This one tells GCC the name of the target ARM processor it should tune the performance of the code for. For some ARM implementations you genuinely get better performance by using this option โ it's giving "dress for the job you want" but for codegen ๐
Permissible names are:
arm7tdmi, arm7tdmi-s, arm710t,
arm720t, arm740t, strongarm, strongarm110, strongarm1100,
strongarm1110, arm8, arm810, arm9, arm9e, arm920, arm920t, arm922t,
arm946e-s, arm966e-s, arm968e-s, arm926ej-s, arm940t, arm9tdmi,
arm10tdmi, arm1020t, arm1026ej-s, arm10e, arm1020e, arm1022e,
arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1156t2-s,
arm1156t2f-s, arm1176jz-s, arm1176jzf-s, generic-armv7-a, cortex-a5,
cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17,
cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57,
cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae,
cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710,
ares, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8,
cortex-r52, cortex-r52plus, cortex-m0, cortex-m0plus, cortex-m1,
cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33,
cortex-m35p, cortex-m55, cortex-m85, cortex-x1, cortex-x1c,
cortex-m1.small-multiply, cortex-m0.small-multiply,
cortex-m0plus.small-multiply, exynos-m1, marvell-pj4, neoverse-n1,
neoverse-n2, neoverse-v1, xscale, iwmmxt, iwmmxt2, ep9312, fa526,
fa626, fa606te, fa626te, fmp626, fa726te, star-mc1, xgene1.
That list is long bestie, like a group chat read receipt list, but every single one is valid ๐
On top of that, this option can also say "tune the performance of the code for a big.LITTLE system." Permissible names for that are:
cortex-a15.cortex-a7, cortex-a17.cortex-a7,
cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35,
cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55.
-mtune=generic-arch says GCC should tune for a blend of processors within architecture arch ๐ The aim is to generate code that runs well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range and avoiding performance pitfalls of other CPUs. Heads up though: the effects of this option may change in future GCC versions as CPU models come and go ๐
-mtune permits the same extension options as -mcpu, but lowkey the extension options do not affect the tuning of the generated code. they're just there. vibes only โจ
-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 ๐ญ
-mcpu=name[+extension...] ๐ฆ
This specifies the name of the target ARM processor. GCC uses this name to derive the name of the target ARM architecture (as if specified by -march) and the ARM processor type for which to tune for performance (as if specified by -mtune) โจ So it's kind of the overachiever of the family, doing two jobs at once.
Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. periodt ๐
Many of the supported CPUs implement optional architectural extensions. Where this is so, the architectural extensions are normally enabled by default. If implementations that lack the extension exist, then the extension syntax can be used to disable those extensions that have been omitted ๐
For floating-point and Advanced SIMD (Neon) instructions, the settings of the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions. iykyk ๐
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. yes, the whole giant list again. copy paste energy, honestly ๐
The following extension options are common to the listed CPUs:
+nodsp
Disable the DSP instructions on cortex-m33, cortex-m35p, cortex-m55 and cortex-m85. Also disables the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions on cortex-m55 and cortex-m85 ๐ฅ
+nopacbti
Disable the Pointer Authentication and Branch Target Identification Extension on cortex-m85.
+nomve
Disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions on cortex-m55 and cortex-m85.
+nomve.fp
Disable the M-Profile Vector Extension (MVE) single precision floating-point instructions on cortex-m55 and cortex-m85.
+cdecp0, +cdecp1, ... , +cdecp7
Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7 on cortex-m55 ๐
+nofp
Disables the floating-point instructions on arm9e, arm946e-s, arm966e-s, arm968e-s, arm10e, arm1020e, arm1022e, arm926ej-s, arm1026ej-s, cortex-r5, cortex-r7, cortex-r8, cortex-m4, cortex-m7, cortex-m33, cortex-m35p cortex-m4, cortex-m7, cortex-m33, cortex-m35p, cortex-m55 and cortex-m85. Disables the floating-point and SIMD instructions on generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a32, cortex-a35, cortex-a53 and cortex-a55.
+nofp.dp
Disables the double-precision component of the floating-point instructions on cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus and cortex-m7.
+nosimd
Disables the SIMD (but not floating-point) instructions on generic-armv7-a, cortex-a5, cortex-a7 and cortex-a9 ๐
+crypto
Enables the cryptographic instructions on cortex-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-a53 and cortex-a75.cortex-a55 ๐
Additionally, the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a โจ
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information ๐ซถ
-mcpu=native makes the compiler auto-detect the CPU of the build computer. At present this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect ๐ญ
-mfpu=name ๐ธ
This one specifies what floating-point hardware (or hardware emulation) is available on the target. Permissible names are: auto, vfpv2, vfpv3, vfpv3-fp16, vfpv3-d16, vfpv3-d16-fp16, vfpv3xd, vfpv3xd-fp16, neon-vfpv3, neon-fp16, vfpv4, vfpv4-d16, fpv4-sp-d16, neon-vfpv4, fpv5-d16, fpv5-sp-d16, fp-armv8, neon-fp-armv8 and crypto-neon-fp-armv8.
Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2 ๐
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-optimizationsis also specified. This is because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so the use of NEON instructions may lead to a loss of precision. not me warning you about the math, but like, precision loss is real bestie ๐ญ
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 are none, ieee, and alternative; the default is none, in which case the "__fp16" type is not defined ๐
-mstructure-size-boundary=nโ okay so this one rounds the size of all structures and unions 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.
๐จ deprecated alert ๐จ This option is deprecated. iykyk
-mabort-on-noreturnโ generate a call to the functionabortat the end of anoreturnfunction. It is executed if the function tries to return. so it's like a little "bestie, no" at the end of the function ๐-mlong-calls,-mno-long-callsโ tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction.
Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the short_call attribute, functions that are inside the scope of a #pragma no_long_calls directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the long_call attribute or the section attribute, and functions that are within the scope of a #pragma long_calls directive are always turned into long calls.
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a #pragma long_calls_off directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers. fr fr, pointer calls are doing their own thing โจ
-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. runtime's main character moment ๐ซถ-mpic-register=regโ specify the register to be used for PIC addressing. For standard PIC base case, the default is any suitable register determined by compiler. For single PIC base case, the default isR9if target is EABI based or stack-checking is enabled, otherwise the default isR10.-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. This permits using PC-relative addressing operations to access data known to be in the data segment. For non-VxWorks RTP targets, this option is enabled by default. When disabled on such targets, it will enable-msingle-pic-baseby default. the way that default flips is so specific ๐-mpoke-function-nameโ write the name of each function into the text section, directly preceding the function prologue. The generated code is similar to this:
t0
.ascii "arm_poke_function_name", 0
.align
t1
.word 0xff000000 + (t1 - t0)
arm_poke_function_name
mov ip, sp
stmfd sp!, {fp, ip, lr, pc}
sub fp, ip, #4
When performing a stack backtrace, code can inspect the value of pc stored at fp + 0. If the trace function then looks at location pc - 12 and the top 8 bits are set, then we know that there is a function name embedded immediately preceding this location and has length ((pc[-3]) & 0xff000000). literally a name tag for your stack frame ๐
-mthumb,-marmโ select between generating code that executes in ARM and Thumb states. The default for most configurations is to generate code that executes in ARM state, but the default can be changed by configuring GCC with the--with-mode=stateconfigure option.
You can also override the ARM and Thumb mode for each function by using the target("thumb") and target("arm") function attributes or pragmas.
-mflip-thumbโ switch ARM/Thumb modes on alternating functions. This option is provided for regression testing of mixed Thumb/ARM code generation, and is not intended for ordinary use in compiling code. do not use this for real code, bestie ๐ญ-mtpcs-frameโ generate a stack frame that is compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that does not call any other functions.) The default is-mno-tpcs-frame.-mtpcs-leaf-frameโ generate a stack frame that is compliant with the Thumb Procedure Call Standard for all leaf functions. (A leaf function is one that does not call any other functions.) The default is-mno-apcs-leaf-frame. yes, that's the default named right there โ keep it exactly as written ๐-mcallee-super-interworkingโ gives all externally visible functions in the file being compiled an ARM instruction set header which switches to Thumb mode before executing the rest of the function. This allows these functions to be called from non-interworking code. This option is not valid in AAPCS configurations because interworking is enabled by default.-mcaller-super-interworkingโ allows calls via function pointers (including virtual functions) to execute correctly regardless of whether the target code has been compiled for interworking or not. There is a small overhead in the cost of executing a function pointer if this option is enabled. This option is not valid in AAPCS configurations because interworking is enabled by default.-mtp=nameโ specify the access model for the thread local storage pointer. The valid models aresoft, which generates calls to__aeabi_read_tp,cp15, which fetches the thread pointer fromcp15directly (supported in thearm6karchitecture), andauto, which uses the best available method for the selected processor. The default setting isauto. auto is lowkey the main character here โจ-mtls-dialect=dialectโ specify the dialect to use for accessing thread local storage. Two dialects are supported:gnuandgnu2. Thegnudialect selects the original GNU scheme for supporting local and global dynamic TLS models. Thegnu2dialect selects the GNU descriptor scheme, which provides better performance for shared libraries. The GNU descriptor scheme is compatible with the original scheme, but does require new assembler, linker and library support. Initial and local exec TLS models are unaffected by this option and always use the original scheme.-mword-relocationsโ only generate absolute relocations on word-sized values (i.e.R_ARM_ABS32). This is enabled by default on targets (uClinux,SymbianOS) where the runtime loader imposes this restriction, and when-fpicor-fPICis specified. This option conflicts with-mslow-flash-data. conflict noted, no cap โ ๏ธ-mfix-cortex-m3-ldrdโ some Cortex-M3 cores can cause data corruption whenldrdinstructions with overlapping destination and base registers are used. This option avoids generating these instructions. This option is enabled by default when-mcpu=cortex-m3is specified. data corruption is not the vibe ๐ญ-mfix-cortex-a57-aes-1742098,-mno-fix-cortex-a57-aes-1742098,-mfix-cortex-a72-aes-1655431,-mno-fix-cortex-a72-aes-1655431โ enable (disable) mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions. This option is enabled by default when either-mcpu=cortex-a57or-mcpu=cortex-a72is specified.-munaligned-access,-mno-unaligned-accessโ enables (or disables) reading and writing of 16- and 32-bit values from addresses that are not 16- or 32-bit aligned. By default unaligned access is disabled for all pre-ARMv6, all ARMv6-M and for ARMv8-M Baseline architectures, and enabled for all other architectures. If unaligned access is not enabled then words in packed data structures are accessed a byte at a time.
The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending upon the setting of this option. If unaligned access is enabled then the preprocessor symbol __ARM_FEATURE_UNALIGNED is also defined. byte-at-a-time is giving slow era, honestly ๐
-mneon-for-64bitsโ this option is deprecated and has no effect. deprecated + no effect = ghosted ๐ป-mslow-flash-dataโ assume loading data from flash is slower than fetching instruction. Therefore literal load is minimized for better performance. This option is only supported when compiling for ARMv7 M-profile and off by default. It conflicts with-mword-relocations.-masm-syntax-unifiedโ assume inline assembler is using unified asm syntax. The default is currently off which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated. future GCC may switch it up, so stay tuned ig ๐-mrestrict-itโ restricts generation of IT blocks to conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This option is on by default for ARMv8-A Thumb mode.-mprint-tune-infoโ print CPU tuning information as comment in assembler file. This is an option used only for regression testing of the compiler and not intended for ordinary use in compiling code. This option is disabled by default. compiler debugging only, bestie โ not for your everyday build ๐ซถ-mverbose-cost-dumpโ enable verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler.-mpure-codeโ do not allow constant data to be placed in code sections. Additionally, when compiling for ELF object format give all text sections the ELF processor-specific section attributeSHF_ARM_PURECODE. This option is only available when generating non-pic code for M-profile targets.-mcmseโ generate secure code as per theARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification, which can be found onhttps://developer.arm.com/documentation/ecm0359818/latest/. secure code era, slay ๐โจ-mfix-cmse-cve-2021-35465โ okay so there's a potential security issue with theVLLDMinstruction on some M-profile devices when you're using CMSE (CVE-2021-365465), and this option mitigates it ๐ It's on by default when-mcpu=is used withcortex-m33,cortex-m35p,cortex-m55,cortex-m85orstar-mc1. And if you ever need to turn the mitigation back off, that's what-mno-fix-cmse-cve-2021-35465is for ๐ซถ-mstack-protector-guard=guardโ generates stack protection code with the canary living at guard. The supported locations areglobal(for a global canary) ortls(for a canary you can get at via the TLS register), bestie.-mstack-protector-guard-offset=offsetโ pairs up with the one above. Heads up though: this one is for use with-fstack-protector-guard=tlsand not for use in user-land code ๐-mfdpic,-mno-fdpicโ picks the FDPIC ABI, which represents pointers to functions with 64-bit function descriptors. When the compiler is configured forarm-*-uclinuxfdpiceabitargets, this is on by default and it implies-fPIEif you didn't give any of the PIC/PIE-related options. On other targets it only switches on the FDPIC-specific code generation bits, so you gotta explicitly hand it the PIC/PIE-related options yourself, no cap.
โ ๏ธ Heads up: static linking is not supported here, because it would still involve the dynamic linker when the program self-relocates. If that behavior is actually acceptable to you, use-staticand-Wl,-dynamic-linkeroptions.
The opposite -mno-fdpic option is useful (and required, fr) to build the Linux kernel using the same arm-*-uclinuxfdpiceabi toolchain as the one used to build the userland programs.
-mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]]โ enables branch protection features (armv8.1-m.main only โญ). Breaking it down:noneโ generate code with no branch protection and no return address signing.standard[+leaf]โ generate code with all branch protection features on at their standard level.pac-ret[+leaf]โ generate code with return address signing at its standard level, which means signing all functions that save the return address to memory.leafโ when return address signing is enabled, also sign leaf functions even if they don't write the return address to memory.+btiโ add landing-pad instructions at the permitted targets of indirect branch instructions.
If the +pacbti architecture extension isn't enabled, then all branch protection and return address signing operations are constrained to use only the instructions defined in the architectural-NOP space ๐ญ The generated code stays backwards-compatible with earlier versions of the architecture, but you can flip the extra security on at run time on processors that support the PACBTI extension.
Branch target enforcement using BTI can only be enabled at runtime if all code in the application has been compiled with at least -mbranch-protection=bti.
Any setting other than none is supported only on armv8-m.main or later.
The default is to generate code without branch protection or return address signing ๐
๐ฝ AVR Options ๐ฝ
These options are defined for AVR implementations, bestie:
-mmcu=mcuโ specify the AVR instruction set architecture (ISA) or device type. The default for this option isavr2.
The following AVR devices and ISAs are supported. Note: a complete device support consists of startup code crtmcu.o, a device header avr/io*.h, a device library libmcu.a and a device-specs file specs-mcu (https://gcc.gnu.org/wiki/avr-gcc#spec-files). Only the latter is provided by the compiler according to the supported mcus below โ the rest is supported by AVR-LibC (https://www.nongnu.org/avr-libc/), or by means of atpack files from the hardware manufacturer (https://gcc.gnu.org/wiki/avr-gcc#atpack) ๐ซถ
avr2โ "Classic" devices with up to 8 KiB of program memory. mcu =attiny22,attiny26,at90s2313,at90s2323,at90s2333,at90s2343,at90s4414,at90s4433,at90s4434,at90c8534,at90s8515,at90s8535.avr25โ "Classic" devices with up to 8 KiB of program memory and with theMOVWinstruction. mcu =attiny13,attiny13a,attiny24,attiny24a,attiny25,attiny261,attiny261a,attiny2313,attiny2313a,attiny43u,attiny44,attiny44a,attiny45,attiny48,attiny441,attiny461,attiny461a,attiny4313,attiny84,attiny84a,attiny85,attiny87,attiny88,attiny828,attiny841,attiny861,attiny861a,ata5272,ata6616c,at86rf401.avr3โ "Classic" devices with 16 KiB up to 64 KiB of program memory. mcu =at76c711,at43usb355.avr31โ "Classic" devices with 128 KiB of program memory. mcu =atmega103,at43usb320.avr35โ "Classic" devices with 16 KiB up to 64 KiB of program memory and with theMOVWinstruction. mcu =attiny167,attiny1634,atmega8u2,atmega16u2,atmega32u2,ata5505,ata6617c,ata664251,at90usb82,at90usb162.avr4โ "Enhanced" devices with up to 8 KiB of program memory. mcu =atmega48,atmega48a,atmega48p,atmega48pa,atmega48pb,atmega8,atmega8a,atmega8hva,atmega88,atmega88a,atmega88p,atmega88pa,atmega88pb,atmega8515,atmega8535,ata5795,ata6285,ata6286,ata6289,ata6612c,at90pwm1,at90pwm2,at90pwm2b,at90pwm3,at90pwm3b,at90pwm81.avr5โ "Enhanced" devices with 16 KiB up to 64 KiB of program memory. mcu =atmega16,atmega16a,atmega16hva,atmega16hva2,atmega16hvb,atmega16hvbrevb,atmega16m1,atmega16u4,atmega161,atmega162,atmega163,atmega164a,atmega164p,atmega164pa,atmega165,atmega165a,atmega165p,atmega165pa,atmega168,atmega168a,atmega168p,atmega168pa,atmega168pb,atmega169,atmega169a,atmega169p,atmega169pa,atmega32,atmega32a,atmega32c1,atmega32hvb,atmega32hvbrevb,atmega32m1,atmega32u4,atmega32u6,atmega323,atmega324a,atmega324p,atmega324pa,atmega324pb,atmega325,atmega325a,atmega325p,atmega325pa,atmega328,atmega328p,atmega328pb,atmega329,atmega329a,atmega329p,atmega329pa,atmega3250,atmega3250a,atmega3250p,atmega3250pa,atmega3290,atmega3290a,atmega3290p,atmega3290pa,atmega406,atmega64,atmega64a,atmega64c1,atmega64hve,atmega64hve2,atmega64m1,atmega64rfr2,atmega640,atmega644,atmega644a,atmega644p,atmega644pa,atmega644rfr2,atmega645,atmega645a,atmega645p,atmega649,atmega649a,atmega649p,atmega6450,atmega6450a,atmega6450p,atmega6490,atmega6490a,atmega6490p,ata5790,ata5790n,ata5791,ata6613c,ata6614q,ata5782,ata5831,ata8210,ata8510,ata5787,ata5835,ata5700m322,ata5702m322,at90pwm161,at90pwm216,at90pwm316,at90can32,at90can64,at90scr100,at90usb646,at90usb647,at94k,m3000.avr51โ "Enhanced" devices with 128 KiB of program memory. mcu =atmega128,atmega128a,atmega128rfa1,atmega128rfr2,atmega1280,atmega1281,atmega1284,atmega1284p,atmega1284rfr2,at90can128,at90usb1286,at90usb1287.avr6โ "Enhanced" devices with 3-byte PC, i.e. with more than 128 KiB of program memory. mcu =atmega256rfr2,atmega2560,atmega2561,atmega2564rfr2.avrxmega2โ "XMEGA" devices with more than 8 KiB and up to 64 KiB of program memory. mcu =atxmega8e5,atxmega16a4,atxmega16a4u,atxmega16c4,atxmega16d4,atxmega16e5,atxmega32a4,atxmega32a4u,atxmega32c3,atxmega32c4,atxmega32d3,atxmega32d4,atxmega32e5,avr64da28,avr64da28s,avr64da32,avr64da32s,avr64da48,avr64da48s,avr64da64,avr64da64s,avr64db28,avr64db32,avr64db48,avr64db64,avr64dd14,avr64dd20,avr64dd28,avr64dd32,avr64du28,avr64du32,avr64ea28,avr64ea32,avr64ea48,avr64sd28,avr64sd32,avr64sd48.avrxmega3โ "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space โจ mcu =attiny202,attiny204,attiny212,attiny214,attiny402,attiny404,attiny406,attiny412,attiny414,attiny416,attiny416auto,attiny417,attiny424,attiny426,attiny427,attiny804,attiny806,attiny807,attiny814,attiny816,attiny817,attiny824,attiny826,attiny827,attiny1604,attiny1606,attiny1607,attiny1614,attiny1616,attiny1617,attiny1624,attiny1626,attiny1627,attiny3214,attiny3216,attiny3217,attiny3224,attiny3226,attiny3227,atmega808,atmega809,atmega1608,atmega1609,atmega3208,atmega3209,atmega4808,atmega4809,avr16dd14,avr16dd20,avr16dd28,avr16dd32,avr16du14,avr16du20,avr16du28,avr16du32,avr16ea28,avr16ea32,avr16ea48,avr16eb14,avr16eb20,avr16eb28,avr16eb32,avr16la14,avr16la20,avr16la28,avr16la32,avr32da28,avr32da28s,avr32da32,avr32da32s,avr32da48,avr32da48s,avr32db28,avr32db32,avr32db48,avr32dd14,avr32dd20,avr32dd28,avr32dd32,avr32du14,avr32du20,avr32du28,avr32du32,avr32ea28,avr32ea32,avr32ea48,avr32eb14,avr32eb20,avr32eb28,avr32eb32,avr32la14,avr32la20,avr32la28,avr32la32,avr32sd20,avr32sd28,avr32sd32."avrxmega4"โ "XMEGA" girlies with more than 64 KiB and up to 128 KiB of program memory ๐mcu="atxmega64a3","atxmega64a3u","atxmega64a4u","atxmega64b1","atxmega64b3","atxmega64c3","atxmega64d3","atxmega64d4","avr128da28","avr128da28s","avr128da32","avr128da32s","avr128da48","avr128da48s","avr128da64","avr128da64s","avr128db28","avr128db32","avr128db48","avr128db64"."avrxmega5"โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM (she's got the whole package, no cap โจ).mcu="atxmega64a1","atxmega64a1u"."avrxmega6"โ "XMEGA" devices with more than 128 KiB of program memory, like, a lot of it ๐ซถ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. main character energy fr ๐mcu="atxmega128a1","atxmega128a1u","atxmega128a4u"."avrtiny"โ "TINY" Tiny core devices with 512 B up to 4 KiB of program memory. smol but mighty ๐ฃmcu="attiny4","attiny5","attiny9","attiny10","attiny102","attiny104","attiny20","attiny40"."avr1"โ this ISA is implemented by the minimal AVR core and it's supported for assembler only. no C compiler shenanigans here, bestie.mcu="attiny11","attiny12","attiny15","attiny28","at90s1200".
-mabsdataโ assume that all data in static storage can be accessed byLDS/STSinstructions. Heads up: this option only does anything on reduced Tiny devices like ATtiny40. Also peep theabsdataAVR Variable Attributes variable attribute if you wanna know more ๐-maccumulate-argsโ accumulate outgoing function arguments and acquire/release the needed stack space for them once, in the function prologue/epilogue. Without this option, outgoing arguments are pushed before calling a function and popped afterwards.
Popping the arguments after the function call can be expensive on AVR, so accumulating the stack space might lead to smaller executables, because the arguments don't need to be removed from the stack after such a function call ๐
This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack โ like calls to printf-like functions. iykyk.
- *
-mbranch-cost=cost* โ set the branch costs for conditional branch instructions to cost. Reasonable values for cost are small, non-negative integers. The default branch cost is0. periodt. -mcall-prologuesโ function prologues/epilogues are expanded as calls to appropriate subroutines. Code size gets smaller. it's giving minimalism โจ- *
-mdouble=bits*-mlong-double=bits โ set the size (in bits) of thedoubleorlong doubletype, respectively. Possible values for bits are32and64. Whether or not a specific value for bits is allowed depends on the--with-double=and--with-long-double=configure options (https://gcc.gnu.org/install/configure.html#avr), and the same applies for the default values of the options. so like, check your build first, bestie ๐ -mgas-isr-prologuesโ interrupt service routines (ISRs) may use the__gcc_isrpseudo instruction supported by GNU Binutils. If this option is on, the feature can still be disabled for individual ISRs by means of theno_gccisrfunction attribute (AVR Function Attributes). This feature is activated per default if optimization is on (but not with-Og,@pxref{Optimize Options}), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683).-mint8โ assumeintto be 8-bit integer. This affects the sizes of all types: acharis 1 byte, anintis 1 byte, alongis 2 bytes, andlong longis 4 bytes. ๐ซข Please note that this option does not conform to the C standards, but it results in smaller code size. so like, iconic but unhinged.-mmain-is-OS_taskโ do not save registers inmain. The effect is the same like attaching attributeOS_task(AVR Function Attributes) tomain. It is activated per default if optimization is on.-mno-interruptsโ generated code is not compatible with hardware interrupts. Code size is smaller. pick your fighter ๐-mrelaxโ try to replaceCALLresp.JMPinstruction by the shorterRCALLresp.RJMPinstruction if applicable. Setting-mrelaxjust adds the--mlink-relaxoption to the assembler's command line and the--relaxoption to the linker's command line.
Jump relaxing is performed by the linker, because jump offsets are not known before code is located. Therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from instructions in the assembler code. sneaky but valid ๐
Relaxing must be turned on if linker stubs are needed โ see the section on EIND and linker stubs below. don't skip it ๐
-mstrict-Xโ use address registerXin a way proposed by the hardware. This means thatXis only used in indirect, post-increment or pre-decrement addressing. she stays in her lane ๐
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
extra instructions = extra vibe tax, ngl.
-mtiny-stackโ only change the lower 8 bits of the stack pointer. that's it. that's the whole option ๐-mfract-convert-truncateโ allow to use truncation instead of rounding towards zero for fractional fixed-point types.-nodevicelibโ don't link against AVR-LibC's device specific librarylib<mcu>.a. bye bestie ๐-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. you're on your own now, respectfully ๐
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. she's always watching ๐ฅ
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 โ read carefully bestie, this part is important ๐ซถ
- The compiler never sets
EIND. - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions or might readEINDdirectly in order to emulate an indirect call/jump by means of aRETinstruction. - The compiler assumes that
EINDnever changes during the startup code or during the application. In particular,EINDis not saved/restored in function or interrupt service routine prologue/epilogue. so like, don't be weird with it. - 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. trampoline but make it assembly ๐ญ
- 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. (rude, honestly ๐) - The default linker script is arranged for code with
EIND = 0. If code is supposed to work for a setup withEIND != 0, a custom linker script has to be used in order to place the sections whose name start with.trampolinesinto the segment whereEINDpoints to. - The startup code from libgcc never sets
EIND. Notice that startup code is a blend of code from libgcc and AVR-LibC. For the impact of AVR-LibC onEIND, see the AVR-LibC user manual (https://www.nongnu.org/avr-libc/user-manual/). - It is legitimate for user-specific startup code to set up
EINDearly, for example by means of initialization code located in section.init3. Such code runs prior to general startup code that initializes RAM and calls constructors, but after the bit of startup code from AVR-LibC that setsEINDto the segment where the vector table is located.
#include <avr/io.h>
static void
__attribute__((section(".init3"),naked,used,no_instrument_function))
init3_set_eind (void)
{
__asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
"out %i0,r24" :: "n" (&EIND) : "r24","memory");
}
The __trampolines_start symbol is defined in the linker script. fancy โจ
- Stubs are generated automatically by the linker if the following two conditions are met:
- <The address of a label is taken by means of the
gsmodifier> (short for generate stubs) like so:
- <The address of a label is taken by means of the
LDI r24, lo8(gs(<func>))
LDI r25, hi8(gs(<func>))
- <The final location of that label is in a code segment> outside the segment where the stubs are located.
- The compiler emits such
gsmodifiers for code labels in the following situations: - Taking address of a function or code label.
- Computed goto.
- If prologue-save function is used, see
-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
RAMPspecial function registers with zero. - If a AVR Named Address Spaces, named address space other than generic or
__flashis used, thenRAMPZis set as needed before the operation. - If the device supports RAM larger than 64 KiB and the compiler needs to change
RAMPZto accomplish an operation,RAMPZis reset to zero after the operation. - If the device comes with a specific
RAMPregister, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it. - RAM larger than 64 KiB is not supported by GCC for AVR targets. If you use inline assembler to read from locations outside the 16-bit address range and change one of the
RAMPregisters, you must reset it to zero after the access.
โ ๏ธ That last one is a real vibe-killer if you ignore it โ touch a RAMP register in inline asm and forget to zero it back out, and everything downstream is chaos ๐ญ
๐ 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=mcu option. Possible values are:
2, 25, 3, 31, 35, 4, 5, 51, 6
for mcu="avr2", "avr25", "avr3", "avr31", "avr35", "avr4", "avr5", "avr51", "avr6",
respectively and
100, 102, 103, 104, 105, 106, 107
for mcu="avrtiny", "avrxmega2", "avrxmega3", "avrxmega4", "avrxmega5", "avrxmega6", "avrxmega7", respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4. ๐
__AVR_Device__
Setting -mmcu=device defines this built-in macro which reflects the device's name. For example, -mmcu=atmega8 defines the built-in macro __AVR_ATmega8__, -mmcu=attiny261a defines __AVR_ATtiny261A__, etc.
The built-in macros' names follow the scheme __AVR_Device__ where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase. ๐ซถ
If device is not a device but only a core architecture like avr51, this macro is not defined.
__AVR_DEVICE_NAME__
Setting -mmcu=device defines this built-in macro to the device's name. For example, with -mmcu=atmega8 the macro is defined to "atmega8".
If device is not a device but only a core architecture like avr51, this macro is not defined.
__AVR_XMEGA__
The device / architecture belongs to the XMEGA family of devices. โจ
__AVR_HAVE_ADIW__
The device has the ADIW and SBIW instructions.
__AVR_HAVE_ELPM__
The device has the ELPM instruction.
__AVR_HAVE_ELPMX__
The device has the ELPM Rn,Z and ELPM Rn,Z+ instructions.
__AVR_HAVE_LPMX__
The device has the LPM Rn,Z and LPM Rn,Z+ instructions.
__AVR_HAVE_MOVW__
The device has the MOVW instruction to perform 16-bit register-register moves.
__AVR_HAVE_MUL__
The device has a hardware multiplier. ๐ช
__AVR_HAVE_JMP_CALL__
The device has the JMP and CALL instructions. This is the case for devices with more than 8 KiB of program memory.
__AVR_HAVE_EIJMP_EICALL__ / __AVR_3_BYTE_PC__
The device has the EIJMP and EICALL instructions. This is the case for devices with more than 128 KiB of program memory. This also means that the program counter (PC) is 3 bytes wide.
__AVR_2_BYTE_PC__
The program counter (PC) is 2 bytes wide. This is the case for devices with up to 128 KiB of program memory.
__AVR_HAVE_8BIT_SP__ / __AVR_HAVE_16BIT_SP__
The stack pointer (SP) register is treated as 8-bit respectively 16-bit register by the compiler. The definition of these macros is affected by -mtiny-stack.
__AVR_HAVE_SPH__ / __AVR_SP8__
The device has the SPH (high part of stack pointer) special function register or has an 8-bit stack pointer, respectively. The definition of these macros is affected by -mmcu= and in the cases of -mmcu=avr2 and -mmcu=avr25 also by -msp8.
__AVR_HAVE_RAMPD__ / __AVR_HAVE_RAMPX__ / __AVR_HAVE_RAMPY__ / __AVR_HAVE_RAMPZ__
The device has the RAMPD, RAMPX, RAMPY, RAMPZ special function register, respectively.
__NO_INTERRUPTS__
This macro reflects the -mno-interrupts command-line option.
__AVR_ERRATA_SKIP__ / __AVR_ERRATA_SKIP_JMP_CALL__
Some AVR devices (AT90S8515, ATmega103) must not skip 32-bit instructions because of a hardware erratum. Skip instructions are SBRS, SBRC, SBIS, SBIC and CPSE. The second macro is only defined if __AVR_HAVE_JMP_CALL__ is also set.
__AVR_ISA_RMW__
The device has Read-Modify-Write instructions (XCH, LAC, LAS and LAT).
__AVR_SFR_OFFSET__=offset
Instructions that can address I/O special function registers directly like IN, OUT, SBI, etc. may use a different address as if addressed by an instruction to access RAM like LD or STS. This offset depends on the device architecture and has to be subtracted from the RAM address in order to get the respective I/O address.
__AVR_SHORT_CALLS__
The -mshort-calls command line option is set.
__AVR_PM_BASE_ADDRESS__=addr
Some devices support reading from flash memory by means of LD* instructions. The flash memory is seen in the data address space at an offset of __AVR_PM_BASE_ADDRESS__. If this macro is not defined, this feature is not available. If defined, the address space is linear and there is no need to put .rodata into RAM. This is handled by the default linker description file, and is currently available for avrtiny and avrxmega3. Even more convenient, there is no need to use address spaces like __flash or features like attribute progmem and pgm_read_*. ๐
__WITH_AVRLIBC__
The compiler is configured to be used together with AVR-Libc. See the --with-avrlibc configure option.
__HAVE_DOUBLE_MULTILIB__
Defined if -mdouble= acts as a multilib option.
__HAVE_DOUBLE32__ / __HAVE_DOUBLE64__
Defined if the compiler supports 32-bit double resp. 64-bit double. The actual layout is specified by option -mdouble=.
__DEFAULT_DOUBLE__
The size in bits of double if -mdouble= is not set. To test the layout of double in a program, use the built-in macro __SIZEOF_DOUBLE__.
__HAVE_LONG_DOUBLE32__ / __HAVE_LONG_DOUBLE64__ / __HAVE_LONG_DOUBLE_MULTILIB__ / __DEFAULT_LONG_DOUBLE__
Same as above, but for long double instead of double.
__WITH_DOUBLE_COMPARISON__
Reflects the --with-double-comparison={tristate|bool|libf7} configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to 2 or 3.
__WITH_LIBF7_LIBGCC__ / __WITH_LIBF7_MATH__ / __WITH_LIBF7_MATH_SYMBOLS__
Reflects the --with-libf7={libgcc|math|math-symbols} configure option (https://gcc.gnu.org/install/configure.html#avr).
๐ฆ AVR Internal Options
The following options are used internally by the compiler and to communicate between device specs files and the compiler proper. You don't need to set these options by hand, in particular they are not optimization options. Using these options in the wrong way may lead to sub-optimal or wrong code. They are documented for completeness, and in order to get a better understanding of device specs (https://gcc.gnu.org/wiki/avr-gcc#spec-files) files.
-mn-flash=num โ Assume that the flash memory has a size of num times 64 KiB. This determines which__flashNaddress spaces are available.-mrmwโ Assume that the device supports the Read-Modify-Write instructionsXCH,LAC,LASandLAT.-mshort-callsโ Assume thatRJMPandRCALLcan target the whole program memory. This option is used for multilib generation and selection for the devices from architectureavrxmega3.-mskip-bugโ Generate code without skips (CPSE,SBRS,SBRC,SBIS,SBIC) over 32-bit instructions.-msp8โ Treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. This option is used by the compiler to select and build multilibs for architecturesavr2andavr25. These architectures mix devices with and withoutSPH.
๐ Real talk: these bad boys are compiler-internal plumbing. Hand-setting them is giving "I read half a wiki page and now nothing compiles" energy. Documented for completeness only, bestie ๐
๐ค Blackfin Options
(next part energy โ this is where the Blackfin era begins โจ)
-mcpu=cpu[-sirevision]โ bestie, this one tells GCC exactly which target Blackfin processor you're on. Right now cpu can be any of:bf512,bf514,bf516,bf518,bf522,bf523,bf524,bf525,bf526,bf527,bf531,bf532,bf533,bf534,bf536,bf537,bf538,bf539,bf542,bf544,bf547,bf548,bf549,bf542m,bf544m,bf547m,bf548m,bf549m,bf561,bf592. That's the whole roster, no cap ๐
The optional sirevision is literally the silicon revision of your target chip, and any workarounds available for that revision get switched on. If sirevision is none, zero workarounds โ none, nada. If sirevision is any, then all the workarounds for the targeted processor get enabled. The __SILICON_REVISION__ macro gets defined to two hex digits representing the major and minor numbers of the silicon revision. But if sirevision is none, then __SILICON_REVISION__ is not defined at all. And if sirevision is any, __SILICON_REVISION__ is defined to be 0xffff. If you just skip the optional sirevision entirely, GCC assumes the latest known silicon revision of the targeted Blackfin processor. Fingers crossed energy โจ
GCC also defines a preprocessor macro for whichever cpu you specified. For the bfin-elf toolchain, this option makes the hardware BSP that libgloss provides get linked in โ unless you passed -msim. ๐ซถ
Don't pass this option at all? Then bf532 is your default processor, periodt.
Heads up: support forbf561is incomplete ๐ญ forbf561, only the preprocessor macro gets defined. That's it. That's the whole feature.
-msimโ says your program is gonna run on the simulator, so the simulator BSP fromlibglossgets linked in. This only does anything for thebfin-elftoolchain. Also, some other options โ like-mid-shared-libraryand-mfdpicโ lowkey imply-msimon their own.-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. The way this slays: it skips the instructions that save, set up and restore frame pointers, and frees up one extra register in leaf functions. Free real estate ๐-mspecld-anomalyโ when enabled, the compiler makes sure the generated code doesn't contain speculative loads after jump instructions. Use this and__WORKAROUND_SPECULATIVE_LOADSgets defined.-mno-specld-anomalyโ don't generate the extra code that prevents speculative loads from happening.-mcsync-anomalyโ when enabled, the compiler makes sure the generated code doesn't haveCSYNCorSSYNCinstructions too soon after conditional branches. Use this and__WORKAROUND_SPECULATIVE_SYNCSgets defined.-mno-csync-anomalyโ don't generate extra code to preventCSYNCorSSYNCinstructions from showing up too soon after a conditional branch.-mlow64kโ when enabled, the compiler is free to take advantage of knowing that the entire program fits into the low 64k of memory. Tiny program privilege ๐ธ-mno-low64kโ assume the program is arbitrarily large. This is the default.-mstack-check-l1โ do stack checking using info that the uClinux kernel places into L1 scratchpad memory.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. This lets you do execute in place and shared libraries in an environment with no virtual memory management. It implies-fPIC, and with abfin-elftarget it also 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 this library or executable won't link against any other ID shared libraries. That lets the compiler use faster code for jumps and calls. Speedy queen โญ-mno-leaf-id-shared-libraryโ don't assume the code being compiled won't link against any ID shared libraries. You get slower code for jump and call insns, and that's the tradeoff.- *
-mshared-library-id=n* โ specifies the identification number of the ID-based shared library you're compiling. A value of0generates more compact code; any other value forces the allocation of that number to the current library, but it's no more space- or time-efficient than just omitting this option entirely. ๐ -msep-dataโ generate code that lets the data segment live in a different area of memory from the text segment. This enables execute in place in an environment without virtual memory management, by eliminating relocations against the text section.-mno-sep-dataโ generate code that assumes the data segment follows the text segment. This is the default.-mlong-calls,-mno-long-callsโ tells the compiler to do function calls by first loading the address of the function into a register, then doing a subroutine call on that register. You need this switch if the target function sits outside the 24-bit addressing range of the offset-based version of the subroutine call instruction. ๐
This feature is not enabled by default. Passing -mno-long-calls restores the default behavior. Note that these switches have zero effect on how the compiler generates code to handle function calls via function pointers โ those are a whole different vibe.
-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), all in the interest of performance. Living dangerously for speed ๐ฅ-minline-pltโ enable inlining of PLT entries in function calls to functions that aren't known to bind locally. Has no effect without-mfdpic.-mmulticoreโ build a standalone application for multicore Blackfin processors. This causes proper start files and link scripts that support multicore to be used, and defines the macro__BFIN_MULTICORE. It can only be used with-mcpu=bf561[-sirevision].
This option can be used together with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, you get the single-application/dual-core programming model โ and in that model, the main function of Core B should be named coreb_main.
If you don't use this option at all, the single-core application programming model is what you get.
-mcoreaโ build a standalone application for Core A of BF561 when you're using the one-application-per-core programming model. Proper start files and link scripts get used to support Core A, and the macro__BFIN_COREAis defined. This option can only be used in conjunction with-mmulticore.-mcorebโ build a standalone application for Core B of BF561 when you're using the one-application-per-core programming model. Proper start files and link scripts get used to support Core B, and the macro__BFIN_COREBis defined. When you use this option,coreb_mainshould be used instead ofmain. This option can only be used in conjunction with-mmulticore.-msdramโ build a standalone application for SDRAM. Proper start files and link scripts get used to put the application into SDRAM, and the macro__BFIN_SDRAMis defined. The loader should initialize SDRAM before loading the application.-micplbโ assume that ICPLBs are enabled at run time. This has an effect on certain anomaly workarounds. For Linux targets, the default is to assume ICPLBs are enabled; for standalone applications, the default is off.
๐ป C6X Options ๐ป
- *
-march=name* โ this specifies the name of the target architecture. GCC uses this name to figure out what kind of instructions it can emit when generating assembly code. Permissible names are:c62x,c64x,c64x+,c67x,c67x+,c674x. -mbig-endianโ generate code for a big-endian target.-mlittle-endianโ generate code for a little-endian target. This is the default.-msimโ choose startup files and linker script suitable for the simulator.-msdata=defaultโ put small global and static data in the.neardatasection, which is pointed to by registerB14. Put small uninitialized global and static data in the.bsssection, which sits adjacent to the.neardatasection. Put small read-only data into the.rodatasection. The corresponding sections used for large pieces of data are.fardata,.farand.const. Small data getting the VIP treatment ๐-msdata=allโ put all data, not just small objects, into the sections reserved for small data, and use addressing relative to theB14register to access them. Everything gets in, no bouncer.-msdata=noneโ make no use of the sections reserved for small data, and use absolute addresses to access all data. Put all initialized global and static data in the.fardatasection, all uninitialized data in the.farsection, and all constant data into the.constsection.
๐ฆ CRIS Options ๐ฆ
These options are defined specifically for the CRIS ports, iykyk.
- *
-march=architecture-type*, *-mcpu=architecture-type* โ generate code for the specified architecture. Your choices for architecture-type arev3,v8andv10, for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. 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* โ warn when the stack frame of a function exceeds n bytes. Keeping an eye on your stack's growth ๐ฑ -metrax4,-metrax100โ these two are synonyms for-march=v3and-march=v8respectively.-mmul-bug-workaround,-mno-mul-bug-workaroundโ work around a bug in themulsandmuluinstructions for CPU models where it applies. This option is disabled by default.-mpdebugโ enable CRIS-specific verbose debug-related information in the assembly code. This option also has the effect of turning off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file.-mcc-initโ don't use condition-code results from a previous instruction; always emit compare and test instructions before using condition codes. Baby steps, always verify ๐-mno-side-effectsโ don't 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โ okay so these bad boys arrange (and theno-versions eliminate the arranging of ๐ ) the alignment for the stack frame, individual data, and constants so everything lines up for the biggest single data access size your chosen CPU model can handle. Default? 32-bit alignment, periodt. Important vibe check tho: ABI details like structure layout are not affected by these options, so don't come for me if your structs don't move.-m32-bit,-m16-bit,-m8-bitโ basically the same energy as the stack-/data-/const-align options up above, except these arrange for the stack frame, writable data, and constants to all be 32-bit, 16-bit, or 8-bit aligned respectively. 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 get yeeted ๐ โ no return instructions, no return sequences generated in the code.
Use this one only together with your own eyeballs inspecting the compiled code, bestie. No warnings, no errors get generated even when call-saved registers must be saved or storage for local variables needs to be allocated. It'll just silently not do it. ๐
-melfโ legacy no-op option. It does literally nothing, she's just here for the nostalgia ๐.-simโ this one arranges to link with input-output functions from a simulator library. Code, initialized data, and zero-initialized data are all allocated consecutively.-sim2โ like-sim, but it passes linker options to locate initialized data at0x40000000and zero-initialized data at0x80000000.
๐ฆ C-SKY Options ๐ฆ
GCC supports these options when compiling for C-SKY V2 processors. Let's get into it ๐
-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. Yes that's a lot of them, she's an icon with many looks ๐-mbig-endian,-EB,-mlittle-endian,-ELโ select big- or little-endian code. The default is little-endian.-mfloat-abi=nameโ specifies which floating-point ABI to use. Permissible values are:soft,softfpandhard.
Specifying soft causes GCC to generate output containing library calls for floating-point operations. softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions.
The default depends on the specific target configuration. Also heads up ๐จ: the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. No mixing and matching, iykyk.
-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. 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.-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, it says coprocessor. That's what the page says, don't @ me ๐ซถ)-msecurityโ enable C-SKY security instructions; the default is off.-mtrustโ enable C-SKY trust instructions; the default is off.-mdsp,-medsp,-mvdspโ enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively. All of these options default to off.-mdiv,-mno-divโ generate divide instructions. Default is off.-msmart,-mno-smartโ generate code for Smart Mode, using only registers numbered0-7to allow use of 16-bit instructions. This option is ignored for CK801 where this is the required behavior, and it defaults to on for CK802. For other targets, the default is off.-mhigh-registers,-mno-high-registersโ generate code using the high registers numbered16-31. This option is not supported on CK801, CK802, or CK803, and is enabled by default for other processors.-manchor,-mno-anchorโ generate code using global anchor symbol addresses.-mpushpop,-mno-pushpopโ generate code using"push"and"pop"instructions. This option defaults to on.-mmultiple-stld,-mstm,-mno-multiple-stld,-mno-stmโ generate code using"stm"and"ldm"instructions. This option isn't supported on CK801 but is enabled by default on other processors.-mconstpool,-mno-constpoolโ create constant pools in the compiler instead of deferring it to the assembler. This option is the default and required for correct code generation on CK801 and CK802, and is optional on other processors.-mstack-size,-mno-stack-sizeโ emit".stack_size"directives for each function in the assembly output. This option defaults to off.-mccrt,-mno-ccrtโ generate code for the C-SKY compiler runtime instead of libgcc. This option defaults to off.-mbranch-cost=nโ set the branch costs to roughly"n"instructions. The default is1.-msched-prolog,-mno-sched-prologโ permit scheduling of function prologue and epilogue sequences.
Lowkey a warning: using this option can result in code that is not compliant with the C-SKY V2 ABI prologue requirements and that cannot be debugged or backtraced ๐ญ. It is disabled by default.
-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 does so by running the compiler or linker multiple times and joining the results together with lipo.
The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can be used to override this.
The Darwin tools vary in their behavior when presented with an ISA mismatch, and it's giving chaotic energy fr. 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. Sneaky but okay ๐
-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.-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โ tells everyone the earliest MacOS X your executable will run on is version. Cute typical values for version include12,10.12, and10.5.8. If the compiler was built to use the system's headers by default, then the default here is literally 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. Flexible queen behavior ๐-mkernelโ enable kernel development mode, aka main character energy for kernel devs ๐. This option 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. It's giving "I do everything" and honestly, it does.-mone-byte-boolโ overrides the defaults for"bool"so that"sizeof(bool)==1". By defaultsizeof(bool)is4when compiling for Darwin/PowerPC and1when compiling for Darwin/x86, so this option has no effect on x86. Ngl, x86 said "not my problem" ๐
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 (yes bestie, legacy support, we respect her ๐ธ).-all_loadโ loads all members of static archive libraries. Seeman ld(1)for more information. She's thorough, she's extra, she's iconic โจ-arch_errors_fatalโ cause the errors having to do with files that have the wrong architecture to be fatal. No mercy, no survivors, periodt ๐-bind_at_loadโ causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.-bundleโ produce a Mach-o bundle format file. Seeman ld(1)for more information.-bundle_loader executableโ this option specifies the executable that will load the build output file being linked. Seeman ld(1)for more information.-dynamiclibโ when passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand. Glow up from executable to library, we love a transformation arc ๐ฆ-force_cpusubtype_ALLโ this causes GCC's output file to have theALLsubtype, instead of one controlled by the-mcpuor-marchoption.
Okay so now we got a whole pile of options that are just passed straight through to the Darwin linker. The Darwin linker man page describes them in detail โ I'm just handing you the full guest list, every single name, no gatekeeping ๐ซถ:
-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
And yeah, before you come for me in the replies โ -sectobjectsymbols, -segs_read_only_addr and -segs_read_write_addr each show up twice in the list. That's literally what the page says, I'm not duplicating anything, I'm just being faithful ๐ 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. Retro tech era, but make it slay ๐
-mno-soft-float,-msoft-floatโ use (do not use) the hardware floating-point instructions for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. Unless they are replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines issue floating-point operations. If you are compiling for an Alpha without floating-point operations, you must ensure that the library is built so as not to call them.
Note that Alpha implementations without floating-point operations are required to have floating-point registers. Yeah, makes no sense, don't ask, that's just how she is ๐
-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. Important caveat bestie, don't skip that part โ ๏ธ
A typical use of this option is building a kernel that does not use, and hence need not save and restore, any floating-point registers.
-mieeeโ the Alpha architecture implements floating-point hardware optimized for maximum performance. It is mostly compliant with the IEEE floating-point standard. However, for full compliance, software assistance is required. This option generates code fully IEEE-compliant code except that the inexact-flag is not maintained (see below). If this option is turned on, the preprocessor macro_IEEE_FPis defined during compilation. The resulting code is less efficient but is able to correctly support denormalized numbers and exceptional IEEE values such as not-a-number and plus/minus infinity. Other Alpha compilers call this option-ieee_with_no_inexact.-mieee-with-inexactโ this is like-mieeeexcept the generated code also maintains the IEEE inexact-flag. Turning on this option causes the generated code to implement fully-compliant IEEE math. In addition to_IEEE_FP,_IEEE_FP_EXACTis defined as a preprocessor macro. On some Alpha implementations the resulting code may execute significantly slower than the code generated by default. Since there is very little code that depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this option-ieee_with_inexact. Speed vs. precision, the eternal struggle ๐ญ-mfp-trap-mode=trap-modeโ this option controls what floating-point related traps are enabled. Other Alpha compilers call this option-fptm trap-mode. The trap mode can be set to one of four values:nโ this is the default (normal) setting. The only traps that are enabled are the ones that cannot be disabled in software (e.g., division by zero trap).uโ in addition to the traps enabled byn, underflow traps are enabled as well.suโ likeu, but the instructions are marked to be safe for software completion (see Alpha architecture manual for details).suiโ likesu, but inexact traps are enabled as well.
-mfp-rounding-mode=rounding-modeโ selects the IEEE rounding mode. Other Alpha compilers call this option-fprm rounding-mode. The rounding-mode can be one of:nโ normal IEEE rounding mode. Floating-point numbers are rounded towards the nearest machine number or towards the even machine number in case of a tie.mโ round towards minus infinity.cโ chopped rounding mode. Floating-point numbers are rounded towards zero.dโ dynamic rounding mode. A field in the floating-point control register (fpcr, see Alpha architecture reference manual) controls the rounding mode in effect. The C library initializes this register for rounding towards plus infinity. Thus, unless your program modifies thefpcr,dcorresponds to round towards plus infinity.
-mtrap-precision=trap-precisionโ in the Alpha architecture, floating-point traps are imprecise. This means without software assistance it is impossible to recover from a floating trap and program execution normally needs to be terminated ๐. GCC can generate code that can assist operating system trap handlers in determining the exact location that caused a floating-point trap. Depending on the requirements of an application, different levels of precision can be selected:pโ program precision. This option is the default and means a trap handler can only identify which program caused a floating-point exception.fโ function precision. The trap handler can determine the function that caused a floating-point exception.iโ instruction precision. The trap handler can determine the exact instruction that caused a floating-point exception.
Other Alpha compilers provide the equivalent options called -scope_safe and -resumption_safe.
-mieee-conformantโ this option marks the generated code as IEEE conformant. You must not use this option unless you also specify-mtrap-precision=iand either-mfp-trap-mode=suor-mfp-trap-mode=sui. Its only effect is to emit the line.eflag 48in the function prologue of the generated assembly file. Tiny effect, big requirements, she's high maintenance and we stan ๐-mbuild-constantsโ normally GCC examines a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it cannot, it outputs the constant as a literal and generates code to load it from the data segment at run time.
Use this option to require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six).
You typically use this option to build a shared library dynamic loader. Itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment. It's giving self-made, self-relocating, self-obsessed ๐
-mbwx,-mno-bwx,-mcix,-mno-cix,-mfix,-mno-fix,-mmax,-mno-maxโ indicate whether GCC should generate code to use the optional BWX, CIX, FIX and MAX instruction sets. The default is to use the instruction sets supported by the CPU type specified via-mcpu=option or that of the CPU on which GCC was built if none is specified. Let the CPU decide, she knows herself best โจ-mfloat-vax,-mfloat-ieeeโ bestie, one of these makes your code use VAX F and G floating-point arithmetic instead of IEEE single and double precision, and the other one makes it not do that. Pick your fighter ๐-mexplicit-relocs,-mno-explicit-relocsโ okay so story time ๐ back in the day, older Alpha assemblers literally had no way to generate symbol relocations except through assembler macros, and those macros? They do not allow optimal instruction scheduling. Rude. But GNU binutils as of version2.12supports a shiny 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 assembler's capabilities when it is built and sets the default accordingly. iykyk ๐ซถ-msmall-data,-mlarge-dataโ when-mexplicit-relocsis in effect, static data is accessed via gp-relative relocations. With-msmall-data, objects 8 bytes long or smaller get parked in a small data area (the.sdataand.sbsssections) and are accessed via 16-bit relocations off of the$gpregister. The tradeoff? It limits the size of the small data area to64KB, but it lets the variables be directly accessed via a single instruction. slay โก
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. no cap, that's the rule ๐ค
When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.
-msmall-text,-mlarge-textโ with-msmall-text, the compiler assumes that the code of the entire program (or shared library) fits in4MB, and is thus reachable with a branch instruction. And when-msmall-datais used, the compiler can assume that all local symbols share the same$gpvalue, which means it can reduce the number of instructions required for a function call from4to1. efficiency icon ๐
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 do not specify a processor type, GCC defaults to the processor on which the compiler was built. ๐ ๏ธ
Supported values for cpu_type are:
ev4,ev45,21064โ Schedules as an EV4 and has no instruction set extensions.ev5,21164โ Schedules as an EV5 and has no instruction set extensions.ev56,21164aโ Schedules as an EV5 and supports the BWX extension.pca56,21164pc,21164PCโ Schedules as an EV5 and supports the BWX and MAX extensions. (three whole spellings, she's flexible ๐)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โ same energy but *only sets the instruction scheduling parameters for machine type *cpu_type. The instruction set is not changed. periodt.
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.
-mmemory-latency=timeโ sets the latency the scheduler should assume for typical memory references as seen by the application. Heads up: this number is **highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. ๐ญ
Valid options for time are:
numberโ A decimal number representing clock cycles.L1,L2,L3,mainโ The compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note thatL3is only valid for EV5. ๐
๐ง eBPF Options ๐ง
- *
-mframe-limit=bytes* โ this specifies the hard limit for frame sizes, in bytes. Currently, the value that can be specified should be less than or equal to32767. Defaults to whatever limit is imposed by the version of the Linux kernel targeted. โจ - *
-mkernel=version* โ 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. that's a whole lotta versions bestie ๐ซถ -mbig-endianโ Generate code for a big-endian target.-mlittle-endianโ Generate code for a little-endian target. This is the default. ๐ฃ-mjmpextโ Enable generation of extra conditional-branch instructions. Enabled for CPU v2 and above.-mjmp32โ Enable 32-bit jump instructions. Enabled for CPU v3 and above.-malu32โ Enable 32-bit ALU instructions. Enabled for CPU v3 and above.- *
-mcpu=version* โ specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default isv3.
Supported values for version are:
v1โ The first stable eBPF ISA with no special features or extensions.v2โ Supports the jump extensions, as in-mjmpext.v3โ All features ofv2, plus:- 32-bit jump operations, as in
-mjmp32 - 32-bit ALU operations, as in
-malu32
- 32-bit jump operations, as in
-mco-reโ Enable BPF Compile Once - Run Everywhere (CO-RE) support. Requires and is implied by-gbtf. ๐ฅ-mno-co-reโ Disable BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is enabled by default when generating BTF debug information for the BPF target.-mxbpfโ Generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture:- Save and restore callee-saved registers at function entry and exit, respectively. ๐
๐ธ FR30 Options ๐ธ
These options are defined specifically for the FR30 port. bespoke, we love to see it ๐
-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 a20-bitrange. โ ๏ธ careful bestie-mno-lsimโ Assume that runtime support has been provided and so there is no need to include the simulator library (libsim.a) on the linker command line.
๐ฆ FT32 Options ๐ฆ
These options are defined specifically for the FT32 port.
-msimโ Specifies that the program will be run on the simulator. This causes an alternate runtime startup and library to be linked. You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. ๐ซถ seriously, don't-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. go big or go home โจ-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 useicc0andfcc0.-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 a12-bitrange from the GOT base address; with-fPICor-fPIE, GOT offsets are computed with 32 bits. With abfin-elftarget, this option implies-msim. ๐ฎโ๐จ big brain stuff-minline-pltโ Enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without-mfdpic. It's enabled by default if optimizing for speed and compiling for shared libraries (i.e.,-fPICor-fpic), or when an optimization option such as-O3or above is present in the command line.-mTLSโ Assume a large TLS segment when generating thread-local code. (note the capital letters bestie, they matter ๐)-mtlsโ Do not assume a large TLS segment when generating thread-local code.-mgprel-roโ Enable the use ofGPRELrelocations 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 trades1instruction for4. With-fPICor-fPIE, it trades3instructions for4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it is not,-mno-gprel-rocan be used to disable it. math girlie behaviour ๐-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. like ever. ๐-mlinked-fpโ follows that EABI rule where you always get a frame pointer whenever a stack frame exists, no exceptions ๐ it's on by default, and honestly if you wanna break up with it,-mno-linked-fpis right there.-mlong-callsโ makes function calls use indirect addressing so you can call stuff outside the current compilation unit. basically it lets functions live anywhere in the 32-bit address space, wanderers welcome ๐-malign-labelsโ tries to line labels up all pretty on an 8-byte boundary by dropping NOPs into the previous packet. heads up tho: this literally only does anything when VLIW packing is enabled, and it does not make new packets, it just sprinkles NOPs into the ones you already have ๐-mlibrary-picโ generate position-independent EABI code. yes queen, PIC it up โจ-macc-4โ use only the first four media accumulator registers. rationing, honestly.-macc-8โ use all eight media accumulator registers. greedy girl summer ๐-mpackโ pack VLIW instructions.-mno-packโ do not pack VLIW instructions.-mno-eflagsโ don't mark ABI switches ine_flags.-mcond-moveโ enables conditional-move instructions (this is the default).
lowkey this switch is mostly for debugging the compiler and will probably get deleted in a future version ๐ don't get attached.
-mno-cond-moveโ disables conditional-move instructions.
same warning bestie: mainly for debugging the compiler, likely gone in a future version ๐ญ
-msccโ enables conditional set instructions (default).
again โ debugging the compiler, probably removed later ๐
-mno-sccโ disables conditional set instructions.
debugging-only vibes, likely to be removed in a future version.
-mcond-execโ enables conditional execution (default).
you already know: mainly for debugging the compiler, probably gone in a future version ๐
-mno-cond-execโ disables conditional execution.
compiler debugging switch, likely removed in a future version.
-mvliw-branchโ runs a pass that packs branches into VLIW instructions (default).
debugging switch, probably getting yeeted in a future version ๐ซถ
-mno-vliw-branchโ don't run the pass that packs branches into VLIW instructions.
debugging switch, likely removed in a future version.
-mmulti-cond-execโ enables optimization of"&&"and"||"in conditional execution (default).
debugging switch energy, probably gone in a future version โญ
-mno-multi-cond-execโ disables optimization of"&&"and"||"in conditional execution.
debugging switch, likely removed in a future version.
-mnested-cond-execโ enables nested conditional execution optimizations (default).
debugging switch, probably removed in a future version ๐
-mno-nested-cond-execโ disables nested conditional execution optimizations.
debugging switch, likely removed in a future version.
-moptimize-membarโ removes redundant"membar"instructions from the compiler-generated code. enabled by default, so it's already slaying for you ๐ฅ-mno-optimize-membarโ turns off that automatic removal of redundant"membar"instructions from the generated code.-mtomcat-statsโ makes gas print out tomcat statistics. numbers! stats! tomcat!! ๐ฑ- *
-mcpu=cpu* โ picks the processor type to generate code for. the possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple. choose wisely bestie ๐
๐ธ GNU/Linux Options ๐ธ
These -m options are defined for GNU/Linux targets:
-mglibcโ use the GNU C library. this is the default except on*-*-linux-*uclibc*,*-*-linux-*musl*and*-*-linux-*android*targets.-muclibcโ use the uClibc C library. default on*-*-linux-*uclibc*targets.-mmuslโ use the musl C library. default on*-*-linux-*musl*targets.-mbionicโ use the Bionic C library. default on*-*-linux-*android*targets.-mandroidโ compile code that's compatible with the Android platform, which is the default on*-*-linux-*android*targets.
When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, it makes the GCC driver pass Android-specific options to the linker. and finally, it causes the preprocessor macro "__ANDROID__" to be defined. one option, three jobs, main character energy ๐
-tno-android-ccโ disables the compilation effects of-mandroid, i.e., don't enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default.-tno-android-ldโ disables the linking effects of-mandroid, i.e., pass standard Linux linking options to the linker.
๐ H8/300 Options ๐
These -m options are defined for the H8/300 implementations:
-mrelaxโ shortens some address references at link time when it can; it uses the linker option-relax. chill vibes only.-mhโ generate code for the H8/300H.-msโ generate code for the H8S.-mnโ generate code for the H8S and H8/300H in normal mode. โ ๏ธ this switch must be used with either-mhor-ms, no solo runs.-ms2600โ generate code for the H8S/2600. โ ๏ธ this switch must be used with-ms.-mexrโ extended registers get stored on the stack before a function with monitor attribute executes. the default option is-mexr. this one's only valid for H8S targets ๐-mno-exrโ extended registers are not stored on the stack before a function with monitor attribute executes. the default option is-mno-exr. again, only valid for H8S targets.-mint32โ makes"int"data 32 bits by default. grow up king ๐ฑ-malign-300โ on the H8/300H and H8S, use the same alignment rules as the H8/300. the default for H8/300H and H8S is to align longs and floats on 4-byte boundaries;-malign-300makes them align on 2-byte boundaries instead. and for the record: this option has no effect on the H8/300. none. zero. nada ๐ฆ
๐ 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. you can peep/usr/lib/sched.modelson an HP-UX system to figure out the right architecture option for your machine ๐ code compiled for lower-numbered architectures runs on higher-numbered ones, but **not the other way around โ it's giving one-way street, 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. same thing, shorter nickname โจ-matomic-libcallsโ generate libcalls for atomic loads and stores when sync libcalls are disabled. enabled by default. it only affects the generation of atomic libcalls by the HPPA backend.
Both the sync and libatomic libcall implementations use locking. as a result, processor stores are not atomic with respect to other atomic operations. processor loads up to DImode are atomic with respect to other atomic operations, provided they're implemented as a single access.
The PA-RISC architecture doesn't support any atomic operations in hardware except for the "ldcw" instruction. so basically all atomic support is implemented using sync and atomic libcalls. sync libcall support lives in libgcc.a. atomic libcall support lives in libatomic.
This option generates "__atomic_exchange" calls for atomic stores. it also provides special handling for atomic DImode accesses on 32-bit targets. busy busy ๐
-mbig-switchโ does nothing. preserved for backward compatibility. it's literally just vibing ๐ญ-mcaller-copiesโ the caller copies function arguments passed by hidden reference. โ ๏ธ use this one with care, bestie โ 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 gives better compatibility with OpenMP. so, trade-offs ๐ซถ-mcoherent-ldcwโ useldcw/ldcdcoherent cache-control hint.-mdisable-fpregsโ disables floating-point registers. equivalent to"-msoft-float".-mdisable-indexingโ stops the compiler from using indexing address modes. this dodges some rather obscure problems when compiling MIG-generated code under MACH ๐-mfast-indirect-callsโ generates code that assumes calls never cross space boundaries. this lets GCC emit code that does faster indirect calls.
โ ๏ธ real talk: this option does not work in the presence of shared libraries or nested functions. like, at all. ๐
- *
-mfixed-range=register-range* โ generate code treating the given register range as fixed registers. a fixed register is one the register allocator can't use โ super handy when you're compiling kernel code ๐ a register range is specified as two registers separated by a dash. you can specify multiple register ranges separated by a comma. -mgasโ enable the use of assembler directives that only GAS understands.-mgnu-ldโ use options specific to GNUld. this passes-sharedtoldwhen building a shared library. it's the default when GCC is configured โ explicitly or implicitly โ with the GNU linker.
This option does not affect which ld gets called; it only changes what parameters are passed to that ld. which ld gets called is determined by the --with-ld configure option, GCC's program search path, and finally by the user's PATH. you can print the linker GCC uses with which gcc -print-prog-name=ld ๐
this option is only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*.
-mhp-ldโ use options specific to HPld. this passes-btoldwhen building a shared library, and passes+Accept TypeMismatchtoldon all links. it's the default when GCC is configured โ explicitly or implicitly โ with the HP linker.
Same deal as above: it does not affect which ld is called, it only changes what parameters get passed to that ld. the ld that's called is determined by the --with-ld configure option, GCC's program search path, and finally the user's PATH. and again, you can print the linker with which gcc -print-prog-name=ld ๐
also only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*.
-mlinker-optโ turns on the optimization pass in the HP-UX linker โจ. But bestie, listen: this makes symbolic debugging impossible ๐ญ, and it also trips a bug in the HP-UX 8 and HP-UX 9 linkers where they spit out bogus error messages while linking some programs. Rude of them, honestly.-mlong-callsโ generates code that uses long call sequences, so a call can always reach linker-generated stubs ๐ . By default, long calls are only generated when the distance from the call site to the beginning of the function or translation unit (whichever applies) exceeds a predefined limit set by the branch type being used. The limits for normal calls are7,600,000and240,000bytes โ respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at240,000bytes.
Distances are measured from the beginning of functions when you use the -ffunction-sections option, or when you use the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker.
Normally you do not want to use this, because it degrades performance ๐. But it can be useful in large applications, especially when partial linking is used to build the application.
What kind of long calls get used depends on what the assembler and linker can do, and on the type of code being generated. On systems that support long absolute calls, and long pic symbol-difference or pc-relative calls, the impact should be relatively small. However โ on 32-bit ELF systems in pic code, an indirect call is used, and it is quite long ๐.
-mlong-load-storeโ generates 3-instruction load and store sequences, which the HP-UX 10 linker sometimes requires. This is equivalent to the+koption to the HP compilers ๐ซถ.-mjump-in-delayโ ignored, kept around for compatibility purposes only. It's giving "still invited to the party but doesn't do anything" ๐.-mno-space-regsโ generates code that assumes the target has no space registers. This lets GCC generate faster indirect calls and use unscaled index address modes โก. Such code is suitable for level 0 PA systems and kernels.-morderedโ assume memory references are ordered and barriers are not needed ๐.-mportable-runtimeโ use the portable calling conventions proposed by HP for ELF systems.- *
-mschedule=cpu-type* โ schedule code according to the constraints for the machine typecpu-type. The choices forcpu-typeare700,7100,7100LC,7200,7300and8000. Check/usr/lib/sched.modelson an HP-UX system to figure out the proper scheduling option for your machine. The default scheduling is8000โจ. -msioโ generates the predefine_SIOfor server IO. The default is-mwsio, which generates the predefines__hp9000s700,__hp9000s700__and_WSIOfor workstation IO. These options are available under HP-UX and HI-UX ๐.-msoft-floatโ generates output containing library calls for floating point. Warning: the requisite libraries are not available for all HPPA targets ๐ญ. Normally the facilities of the machine's usual C compiler are used, but that can't be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation.
Heads up: -msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a โ the library that comes with GCC โ with -msoft-float for this to work ๐.
-msoft-multโ use software integer multiplication. This disables the use of thexmpyuinstruction ๐ .- *
-munix=unix-std* โ generates compiler predefines and selects a startfile for the specified UNIX standard. The choices forunix-stdare93,95and98.93is supported on all HP-UX versions.95is available on HP-UX 10.10 and later.98is available on HP-UX 11.11 and later. The default values are93for HP-UX 10.00,95for HP-UX 10.10 through to 11.00, and98for HP-UX 11.11 and later ๐ฆ.
-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, plus the startfile unix95.o. -munix=98 provides additional predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, plus the startfile unix98.o.
Big important note: this option changes the interfaces for various library routines ๐ณ. It also affects the operational behavior of the C library. So extreme care is needed when using this option, fr fr.
Library code intended to work with more than one UNIX standard must test, set and restore the variable __xpg4_extended_mask as appropriate. Most GNU software doesn't provide this capability ๐.
-nolibdldโ suppresses the generation of link options that searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later.-staticโ the HP-UX implementation ofsetlocalein libc has a dependency onlibdld.sl, and there isn't an archive version oflibdld.sl๐ญ. So when-staticis specified, special link options are needed to resolve this dependency.
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when -static is specified. This causes the resulting binary to be dynamic ๐ณ. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to stop the GCC driver from adding these link options.
-threadsโ adds 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. Buckle up bestie, there's a lot ๐.
-mbig-endianโ generate code for a big-endian target. This is the default for HP-UX.-mlittle-endianโ generate code for a little-endian target. This is the default for AIX5 and GNU/Linux.-mgnu-as,-mno-gnu-asโ generate (or don't) code for the GNU assembler. This is the default โจ.-mgnu-ld,-mno-gnu-ldโ generate (or don't) code for the GNU linker. This is the default โจ.-mno-picโ generate code that doesn't use a global pointer register. The result is not position independent code, and it violates the IA-64 ABI ๐ญ.-mvolatile-asm-stop,-mno-volatile-asm-stopโ generate (or don't) a stop bit immediately before and after volatile asm statements.-mregister-names,-mno-register-namesโ generate (or don't)in,loc, andoutregister names for the stacked registers. This may make assembler output more readable ๐.-mno-sdata,-msdataโ disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs ๐.-mconstant-gpโ generate code that uses a single constant global pointer value. Useful when compiling kernel code.-mauto-picโ generate code that is self-relocatable. This implies-mconstant-gp. Useful when compiling firmware code ๐ .-minline-float-divide-min-latencyโ generate code for inline divides of floating-point values using the minimum latency algorithm.-minline-float-divide-max-throughputโ generate code for inline divides of floating-point values using the maximum throughput algorithm.-mno-inline-float-divideโ do not generate inline code for divides of floating-point values.-minline-int-divide-min-latencyโ generate code for inline divides of integer values using the minimum latency algorithm.-minline-int-divide-max-throughputโ generate code for inline divides of integer values using the maximum throughput algorithm.-mno-inline-int-divideโ do not generate inline code for divides of integer values.-minline-sqrt-min-latencyโ 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.-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 it doesn't always do so ๐.- *
-mfixed-range=register-range* โ generate code treating the given register range as fixed registers. A fixed register is one 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โ turns speculative scheduling of the instructions that depend on the data speculative loads before reload on/off. This only actually does anything when-msched-br-data-specis enabled. Default setting: enabled. โจ-msched-ar-in-data-spec,-mno-sched-ar-in-data-specโ turns speculative scheduling of the instructions that depend on the data speculative loads after reload on/off. This is effective only with-msched-ar-data-specenabled. Default setting: enabled. ๐-msched-in-control-spec,-mno-sched-in-control-specโ turns speculative scheduling of the instructions that depend on the control speculative loads on/off. This is effective only with-msched-control-specenabled. Default setting: 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. Default setting: 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. Default setting: 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. Default setting: 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: ๐ง
-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. โกnone,0โ prevent the use of hardware floating-point instructions. ๐ซ
-msoft-floatโ force-mfpu=noneand prevents the use of floating-point registers for parameter passing. This option may change the target ABI. ๐ญ-msingle-floatโ force-mfpu=32and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI. ๐ญ-mdouble-floatโ force-mfpu=64and allow the use of 32/64-bit floating-point registers for parameter passing. This option may change the target ABI. ๐ญ-mbranch-cost=nโ set the cost of branches to roughly n instructions. ๐ฟ-mcheck-zero-division,-mno-check-zero-divisonโ trap (do not trap) on integer division by zero. The default is-mcheck-zero-divisionfor-O0or-Og, and-mno-check-zero-divisionfor other optimization levels. Note the spelling on the second option there:-mno-check-zero-divisonโ copy it exactly, bestie. ๐ซถ-mcond-move-int,-mno-cond-move-intโ conditional moves for integral data in general-purpose registers are enabled (disabled). The default is-mcond-move-int. ๐-mcond-move-float,-mno-cond-move-floatโ conditional moves for floating-point registers are enabled (disabled). The default is-mcond-move-float. ๐-mmemcpy,-mno-memcpyโ force (do not force) the use of"memcpy"for non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. Setting optimization level to-Osalso forces the use of"memcpy", but-mno-memcpymay override this behavior if explicitly specified, regardless of the order these options on the command line. ๐ฆ-mstrict-align,-mno-strict-alignโ avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. The default is-mno-strict-align. ๐-msmall-data-limit=numberโ put global and static data smaller than number bytes into a special section (on some targets). The default value is0. ๐-mmax-inline-memcpy-size=nโ inline all block moves (such as calls to"memcpy"or structure copies) less than or equal to n bytes. The default value of n is1024. ๐ฆ-mcmodel=code-modelโ set the code model to one of:tiny-static(Not implemented yet) ๐งtiny(Not implemented yet) ๐งnormalโ the text segment must be within 128MB addressing space. The data segment must be within 2GB addressing space. โmediumโ the text segment and data segment must be within 2GB addressing space. โlarge(Not implemented yet) ๐งextremeโ this mode does not limit the size of the code segment and data segment. The-mcmodel=extremeoption is incompatible with-fpltand-mno-explicit-relocs. ๐
The default code model is normal. ๐
-mexplicit-relocs,-mno-explicit-relocsโ use or do not use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit instruction scheduling but allow linker relaxation. The default value for the option is determined with the assembler capability detected during GCC build-time and the setting of-mrelax:-mexplicit-relocsif the assembler supports relocation operators but-mrelaxis not enabled,-mno-explicit-relocsotherwise. ๐ง-mdirect-extern-access,-mno-direct-extern-accessโ do not use or use GOT to access external symbols. The default is-mno-direct-extern-access: GOT is used for external symbols with default visibility, but not used for other external symbols. With-mdirect-extern-access, GOT is not used and all external symbols are PC-relatively addressed. It is only suitable for environments where no dynamic link is performed, like firmwares, OS kernels, executables linked with-staticor-static-pie.-mdirect-extern-accessis not compatible with-fPICor-fpic. ๐-mrelax,-mno-relaxโ take (do not take) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option is also passed to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support:-mrelaxif the assembler supports both the-mrelaxoption and the conditional branch relaxation (it's required โ otherwise the.aligndirectives and conditional branch instructions in the assembly code outputted by GCC may be rejected by the assembler because of a relocation overflow),-mno-relaxotherwise. ๐-mpass-mrelax-to-as,-mno-pass-mrelax-to-asโ bestie, these two control whether GCC passes โ or does not pass โ the-mrelaxor-mno-relaxoption to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption,-mno-pass-mrelax-to-asotherwise. This option is mostly useful for debugging, or interoperation with assemblers different from the build-time one.
๐ธ M32C Options ๐ธ
-mcpu=nameโ Select the CPU for which code is generated.namemay be one ofr8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series.-msimโ Specifies that the program will be run on the simulator. This causes an alternate runtime library to be linked in which supports, for example, file I/O. You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed.-memregs=numberโ Specifies the number of memory-based pseudo-registers GCC uses during code generation. These pseudo-registers are used like real registers, so there is a tradeoff between GCC's ability to fit the code into available registers, and the performance penalty of using memory instead of registers. Note that all modules in a program must be compiled with the same value for this option. Because of that, you must not use this option with GCC's default runtime libraries.
๐ฆ M32R/D Options ๐ฆ
These -m options are defined for Renesas M32R/D architectures:
-m32r2โ Generate code for the M32R/2.-m32rxโ Generate code for the M32R/X.-m32rโ Generate code for the M32R. This is the default.-mmodel=smallโ Assume all objects live in the lower 16MB of memory (so that their addresses can be loaded with theld24instruction), and assume all subroutines are reachable with theblinstruction. This is the default.
The addressability of a particular object can be set with the model attribute.
-mmodel=mediumโ Assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume all subroutines are reachable with theblinstruction.-mmodel=largeโ Assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume subroutines may not be reachable with theblinstruction (the compiler generates the much slowerseth/add3/jlinstruction sequence).-msdata=noneโ Disable use of the small data area. Variables are put into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default.
The small data area consists of sections .sdata and .sbss. Objects may be explicitly put in the small data area with the section attribute using one of these sections.
-msdata=sdataโ Put small global and static data in the small data area, but do not generate special code to reference them.-msdata=useโ Put small global and static data in the small data area, and generate special instructions to reference them.-G numโ Put global and static objects less than or equal tonumbytes into the small data or BSS sections instead of the normal data or BSS sections. The default value ofnumis 8. The-msdataoption must be set to one ofsdataorusefor this option to have any effect.
All modules should be compiled with the same -G num value. Compiling with different values of num may or may not work; if it doesn't the linker gives an error message โ incorrect code is not generated.
-mdebugโ Makes the M32R-specific code in the compiler display some statistics that might help in debugging programs.-malign-loopsโ Align all loops to a 32-byte boundary.-mno-align-loopsโ Do not enforce a 32-byte alignment for loops. This is the default.-missue-rate=numberโ Issuenumberinstructions per cycle.numbercan only be 1 or 2.-mbranch-cost=numberโnumbercan only be 1 or 2. If it is 1 then branches are preferred over conditional code, if it is 2, then the opposite applies.-mflush-trap=numberโ Specifies the trap number to use to flush the cache. The default is 12. Valid numbers are between 0 and 15 inclusive.-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 ofarchfor M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures are selected according to Freescale's ISA classification and the permissible values are:isaa,isaaplus,isabandisac.
GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture.
-mcpu=cpuโ Generate code for a specific M680x0 or ColdFire processor. The M680x0 cpus are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire cpus are given by the table below, which also classifies the CPUs into families:
Family โ -mcpu arguments
51โ51,51ac,51ag,51cn,51em,51je,51jf,51jg,51jm,51mm,51qe,51qm5206โ5202,5204,52065206eโ5206e5208โ5207,52085211aโ5210a,5211a5213โ5211,5212,52135216โ5214,521652235โ52230,52231,52232,52233,52234,522355225โ5224,522552259โ52252,52254,52255,52256,52258,522595235โ5232,5233,5234,5235,523x5249โ52495250โ52505271โ5270,52715272โ52725275โ5274,52755282โ5280,5281,5282,528x53017โ53011,53012,53013,53014,53015,53016,530175307โ53075329โ5327,5328,5329,532x5373โ5372,5373,537x5407โ54075475โ5470,5471,5472,5473,5474,5475,547x,5480,5481,5482,5483,5484,5485
-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected.
GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the table above.
-mtune=tuneโ Tune the code for a particular microarchitecture within the constraints set by-marchand-mcpu. The M680x0 microarchitectures are:68000,68010,68020,68030,68040,68060andcpu32. The ColdFire microarchitectures are:cfv1,cfv2,cfv3,cfv4andcfv4e.
You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively.
GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.
GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.
-m68000,-mc68000โ Generate output for a 68000. This is the default when the compiler is configured for 68000-based systems. It is equivalent to-march=68000.
Use this option for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356.
-m68010โ Generate output for a 68010. This is the default when the compiler is configured for 68010-based systems. It is equivalent to-march=68010.-m68020,-mc68020โ Generate output for a 68020. This is the default when the compiler is configured for 68020-based systems. It is equivalent to-march=68020.-m68030โ Generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It is equivalent to-march=68030.-m68040โ Generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It is equivalent to-march=68040.
This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option if your 68040 does not have code to emulate those instructions.
-m68060โ Generate output for a 68060. This is the default when the compiler is configured for 68060-based systems. It is equivalent to-march=68060.
This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use this option if your 68060 does not have code to emulate those instructions.
-mcpu32โ Generate output for a CPU32. This is the default when the compiler is configured for CPU32-based systems. It is equivalent to-march=cpu32.
Use this option for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360.
-m5200โ Generate output for a 520X ColdFire CPU. This is the default when the compiler is configured for 520X-based systems. It is equivalent to-mcpu=5206, and is now deprecated in favor of that option.
Use this option for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
-m5206eโ makes code for a 5206e ColdFire CPU. It's deprecated now bestie, use the equivalent-mcpu=5206einstead โจ-m528xโ code for a member of the ColdFire 528X family. Also deprecated, use the equivalent-mcpu=528x๐-m5307โ code for a ColdFire 5307 CPU. Deprecated, use the equivalent-mcpu=5307๐-m5407โ code for a ColdFire 5407 CPU. Deprecated, use the equivalent-mcpu=5407๐ธ-mcfv4eโ code for a ColdFire V4e family CPU (like the 547x/548x, iykyk). This one includes hardware floating-point instructions, fancy. It's equivalent to-mcpu=547x, and it's now deprecated in favor of that option ๐ฆ-m68020-40โ generates output for a 68040, but without using any of the new instructions. The result is code that runs relatively efficiently on either a 68020/68881, a 68030, or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040, no cap.
This option is equivalent to -march=68020 -mtune=68020-40 โญ
-m68020-60โ same energy but for a 68060: output for a 68060 without any of the new instructions, so it runs relatively efficiently on either a 68020/68881, a 68030, or a 68040. Again, the generated code does use the 68881 instructions that are emulated on the 68060.
This option is equivalent to -march=68020 -mtune=68020-60 โจ
-mhard-float,-m68881โ generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro__HAVE_68881__on M680x0 targets and__mcffpu__on ColdFire targets ๐-msoft-floatโ do not generate floating-point instructions; use library calls instead. This is the default for 68000, 68010, and 68832 targets. It's also the default for ColdFire devices that have no FPU ๐ซถ-mdiv,-mno-divโ generate (or don't generate) ColdFire hardware divide and remainder instructions. If-marchis used without-mcpu, the default is"on"for ColdFire architectures and"off"for M680x0 architectures. Otherwise the default comes from the target CPU (either the default CPU, or the one you named with-mcpu). For example, the default is"off"for-mcpu=5206and"on"for-mcpu=5206e๐ฅ
GCC defines the macro __mcfhwdiv__ when this option is enabled.
-mshortโ treats typeintas 16 bits wide, likeshort int. Also, parameters passed on the stack get aligned to a 16-bit boundary even on targets whose API mandates promotion to 32-bit ๐-mno-shortโ does not considerintto 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โ uses a different function-calling convention, where functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. It saves one instruction in the caller since there's no need to pop the arguments there. Iconic, honestly.
โ ๏ธ This calling convention is incompatible with the one normally used on Unix, so you can't use it if you need to call libraries compiled with the Unix compiler. Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. And it gets worse: seriously incorrect code results if you call a function with too many arguments. (Normally extra arguments are harmlessly ignored, but not here bestie ๐ญ)
The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.
The default is -mno-rtd ๐
-malign-int,-mno-align-intโ control whether GCC alignsint,long,long long,float,double, andlong doublevariables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory ๐
Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k ๐จ
Okay so next up is a paragraph just vibing here without its own option header, but the tea is real: 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โ generates 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โ generates code that assumes the data segment follows the text segment. This is the default ๐-mid-shared-libraryโ generates 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โ generates 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 isn't needed;-fPICsuffices, periodt.
GCC normally uses a single instruction to load values from the GOT. While that's relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
If that happens, recompile your code with -mxgot. It should then work with very large GOTs. But ngl, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol ๐ญ
Note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. If you have such a linker, you should only need -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do.
These options have no effect unless GCC is generating position-independent code ๐ฅ
-mlong-jump-table-offsetsโ use 32-bit offsets inswitchtables. The default is to use 16-bit offsets โญ
๐ง MCore Options ๐ง
These are the -m options defined for the Motorola M*Core processors ๐
-mhardlit,-mno-hardlitโ inline constants into the code stream if it can be done in two instructions or less โจ-mdiv,-mno-divโ use the divide instruction. (Enabled by default.) ๐-mrelax-immediate,-mno-relax-immediateโ allow arbitrary-sized immediates in bit operations ๐-mwide-bitfields,-mno-wide-bitfieldsโ always treat bit-fields asint-sized ๐-m4byte-functions,-mno-4byte-functionsโ force all functions to be aligned to a 4-byte boundary ๐ฆ-mcallgraph-data,-mno-callgraph-dataโ 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๐
๐ฆ 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 the 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 areexecutableโ the normal executable vibe (this is the default), and it uses the startup codecrt0.o. โจxmdstubโ for use with the Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent calledxmdstub. This one uses the 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.o, which does not contain a processor reset vector handler. So it's the move when you want control on a processor reset to go to the bootloader rather than the application. ๐ฆnovectorsโ for applications that don't need any of the MicroBlaze vectors. This option may be useful for applications running within a monitoring application. This model usescrt3.oas a startup file. ๐
Heads up bestie: option-xl-mode-app-modelis a deprecated alias for-mxl-mode-app-model. ๐ซถ
-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. This lets data be referenced by offset from the start of the text address instead of the GOT, since PC-relative addressing is not supported. ๐ธ
๐ MIPS Options ๐
-EBโ generate big-endian code.-ELโ generate little-endian code. This is the default formips*el-*-*configurations.-march=arch โ generate code that runs on arch, which can be the name of a generic MIPS ISA, or the name of a particular processor. ๐
The ISA names are: mips1, mips2, mips3, mips4, mips32, mips32r2, mips32r3, mips32r5, mips32r6, mips64, mips64r2, mips64r3, mips64r5 and mips64r6.
The processor names are: 4kc, 4km, 4kp, 4ksc, 4kec, 4kem, 4kep, 4ksd, 5kc, 5kf, 20kc, 24kc, 24kf2_1, 24kf1_1, 24kec, 24kef2_1, 24kef1_1, 34kc, 34kf2_1, 34kf1_1, 34kn, 74kc, 74kf2_1, 74kf1_1, 74kf3_2, 1004kc, 1004kf2_1, 1004kf1_1, i6400, i6500, interaptiv, loongson2e, loongson2f, loongson3a, gs464, gs464e, gs264e, m4k, m14k, m14kc, m14ke, m14kec, m5100, m5101, octeon, octeon+, octeon2, octeon3, orion, p5600, p6600, r2000, r3000, r3900, r4000, r4400, r4600, r4650, r4700, r5900, r6000, r8000, rm7000, rm9000, r10000, r12000, r14000, r16000, sb1, sr71000, vr4100, vr4111, vr4120, vr4130, vr4300, vr5000, vr5400, vr5500, xlr and xlp. ๐ญ that's a lot, i know.
The special value from-abi selects the most compatible architecture for the selected ABI (that is, mips1 for 32-bit ABIs and mips3 for 64-bit ABIs).
The native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
In processor names, a final 000 can be abbreviated as k (for example, -march=r2k). Prefixes are optional, and vr may be written r.
Names of the form nf2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. For compatibility reasons, nf is accepted as a synonym for nf2_1 while nx and nbfx are accepted as synonyms for nf1_1. ๐ง
GCC defines two macros based on the value of this option. The first is _MIPS_ARCH, which gives the name of target architecture, as a string. The second has the form _MIPS_ARCH_foo, where foo is the capitalized value of _MIPS_ARCH. For example, -march=r2000 sets _MIPS_ARCH to "r2000" and defines the macro _MIPS_ARCH_R2000. ๐
Note that the _MIPS_ARCH macro uses the processor names given above. In other words, it has the full prefix and does not abbreviate 000 as k. In the case of from-abi, the macro names the resolved architecture (either "mips1" or "mips3"). It names the default architecture when no -march option is given.
-mtune=arch โ optimize for arch. Among other things, this option controls the way instructions are scheduled, and the perceived cost of arithmetic operations. The list of arch values is the same as for-march. โญ
When this option is not used, GCC optimizes for the processor specified by -march. By using -march and -mtune together, it's possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family. literal bestie behavior, iykyk.
-mtune defines the macros _MIPS_TUNE and _MIPS_TUNE_foo, which work in the same way as the -march ones described above.
-mips1โ equivalent to-march=mips1.-mips2โ equivalent to-march=mips2.-mips3โ equivalent to-march=mips3.-mips4โ equivalent to-march=mips4.-mips32โ equivalent to-march=mips32.-mips32r3โ equivalent to-march=mips32r3.-mips32r5โ equivalent to-march=mips32r5.-mips32r6โ equivalent to-march=mips32r6.-mips64โ equivalent to-march=mips64.-mips64r2โ equivalent to-march=mips64r2.-mips64r3โ equivalent to-march=mips64r3.-mips64r5โ equivalent to-march=mips64r5.-mips64r6โ equivalent to-march=mips64r6.-mips16,-mno-mips16โ generate (do not generate) MIPS16 code. If GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE. ๐ฆ
MIPS16 code generation can also be controlled on a per-function basis by means of mips16 and nomips16 attributes.
-mflip-mips16โ generate MIPS16 code on alternating functions. This option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code. ๐ like please don't ship this k?-minterlink-compressed,-mno-interlink-compressedโ require (do not require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa.
For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed. โจ
-minterlink-mips16,-mno-interlink-mips16โ aliases of-minterlink-compressedand-mno-interlink-compressed. These options predate the microMIPS ASE and are retained for backwards compatibility. ๐-mabi=32,-mabi=o64,-mabi=n32,-mabi=64,-mabi=eabiโ generate code for the given ABI.
Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead. ๐ธ
For information about the O64 ABI, see <https://gcc.gnu.org/projects/mipso64-abi.html>.
GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. You can select this combination with -mabi=32 -mfp64. This ABI relies on the mthc1 and mfhc1 instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors.
The register assignments for arguments and return values remain the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved. ๐
Two 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. ๐
-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 -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. However, as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is selected by -mno-shared.
-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker. ate, no crumbs. โจ
-mshared is 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 -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.
-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. ๐ three whole instructions, the tragedy.
Note that some linkers can create multiple GOTs. If you have such a linker, you should only need to use -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do. ๐
๐ quick heads-up bestie: these options have no effect unless GCC is generating position independent code. Like, they literally do nothing otherwise. Periodt.
-mgp32โ assume general-purpose registers are 32 bits wide. that's the vibe.-mgp64โ assume general-purpose registers are 64 bits wide. big register energy โจ-mfp32โ assume floating-point registers are 32 bits wide.-mfp64โ assume floating-point registers are 64 bits wide.-mfpxxโ do not assume the width of floating-point registers at all. we simply don't know her ๐ฆ-mhard-floatโ use floating-point coprocessor instructions. hardware girlie behaviour ๐-msoft-floatโ do not use floating-point coprocessor instructions; implement floating-point calculations using library calls instead. software mode, no cap.-mno-floatโ same as-msoft-float, but it additionally asserts that the program being compiled does not perform any floating-point operations. currently only supported by some bare-metal MIPS configurations, where it may select a special set of libraries that lack all floating-point support (including, for example, the floating-point"printf"formats).
๐ญ okay genuine warning: if code compiled with -mno-float accidentally contains floating-point operations, it is likely to suffer a link-time or run-time failure. not a vibe. not at all.
-msingle-floatโ assume the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ assume the floating-point coprocessor supports double-precision operations. this is the default, so if you did nothing, congrats, this is you ๐-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 you're using the o32 FPXX ABI,-mno-odd-spregis set by default. the odd ones out, lowkey ๐ซถ
๐ธ the NaN lore (yes we're doing this)
-mabs=2008,-mabs=legacyโ these control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with the"abs.fmt"and"neg.fmt"machine instructions.
by default, or when -mabs=legacy is used, the legacy treatment is selected. in this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. a longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead โ unless the -ffinite-math-only option has also been specified.
the -mabs=2008 option selects the IEEE 754-2008 treatment. in this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. these instructions are therefore always used for the respective operations. iconic, honestly โจ
-mnan=2008,-mnan=legacyโ these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.
the -mnan=legacy option selects the legacy encoding. in this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.
the -mnan=2008 option selects the IEEE 754-2008 encoding. in this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0. literally the exact opposite, iykyk ๐
the default is -mnan=legacy unless GCC has been configured with --with-nan=2008.
-mllsc,-mno-llscโ use (or don't use)ll,sc, andsyncinstructions to implement atomic memory built-in functions. when neither option is specified, GCC uses the instructions if the target architecture supports them.
-mllsc is useful if the runtime environment can emulate the instructions, and -mno-llsc can be useful when compiling for nonstandard ISAs. you can make either option the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations; see the installation documentation for details ๐ง
-mdsp,-mno-dspโ use (do not use) revision 1 of the MIPS DSP ASE. this option defines the preprocessor macro"__mips_dsp". it also defines"__mips_dsp_rev"to1.-mdspr2,-mno-dspr2โ use (do not use) revision 2 of the MIPS DSP ASE. this option defines the preprocessor macros"__mips_dsp"and"__mips_dspr2". it also defines"__mips_dsp_rev"to2. glow-up from rev 1, we love to see it ๐-msmartmips,-mno-smartmipsโ use (do not use) the MIPS SmartMIPS ASE. she's smart and she's MIPS, main character energy ๐-mpaired-single,-mno-paired-singleโ use (do not use) paired-single floating-point instructions. this option requires hardware floating-point support to be enabled. no hardware floats, no paired-single, that's the rule ๐-mdmx,-mno-mdmxโ use (do not use) MIPS Digital Media Extension instructions. this option can only be used when generating 64-bit code and requires hardware floating-point support to be enabled. two conditions, bestie, both of them ๐-mips3d,-mno-mips3dโ use (do not use) the MIPS-3D ASE. the option-mips3dimplies-mpaired-single. it comes as a package deal ๐-mmicromips,-mno-micromipsโ generate (do not generate) microMIPS code. microMIPS code generation can also be controlled on a per-function basis by means of"micromips"and"nomicromips"attributes. tiny but fierce ๐ฆ
๐ฅ the ASE speedrun (all of these are "use / do not use" pairs)
-mmt,-mno-mtโ use (do not use) MT Multithreading instructions.-mmcu,-mno-mcuโ use (do not use) the MIPS MCU ASE instructions.-meva,-mno-evaโ use (do not use) the MIPS Enhanced Virtual Addressing instructions.-mvirt,-mno-virtโ use (do not use) the MIPS Virtualization (VZ) instructions.-mxpa,-mno-xpaโ use (do not use) the MIPS eXtended Physical Address (XPA) instructions.-mcrc,-mno-crcโ use (do not use) the MIPS Cyclic Redundancy Check (CRC) instructions.-mginv,-mno-ginvโ use (do not use) the MIPS Global INValidate (GINV) instructions. GINV, she is literally in the name ๐-mloongson-mmi,-mno-loongson-mmiโ use (do not use) the MIPS Loongson MultiMedia extensions Instructions (MMI).-mloongson-ext,-mno-loongson-extโ use (do not use) the MIPS Loongson EXTensions (EXT) instructions.-mloongson-ext2,-mno-loongson-ext2โ use (do not use) the MIPS Loongson EXTensions r2 (EXT2) instructions.
๐ sizes, symbols, and small data (the whole saga)
-mlong64โ force"long"types to be 64 bits wide. see-mlong32for an explanation of the default and the way that the pointer size is determined. check the next bullet bestie โฌ๏ธ-mlong32โ force"long","int", and pointer types to be 32 bits wide.
the default size of "int"s, "long"s and pointers depends on the ABI. all the supported ABIs use 32-bit "int"s. the n64 ABI uses 64-bit "long"s, as does the 64-bit EABI; the others use 32-bit "long"s. pointers are the same size as "long"s, or the same size as integer registers, whichever is smaller. the way that rule is worded, honestly ๐
-msym32,-mno-sym32โ assume (do not assume) that all symbols have 32-bit values, regardless of the selected ABI. this option is useful in combination with-mabi=64and-mno-abicallsbecause it allows GCC to generate shorter and faster references to symbolic addresses. short and fast, we stan โจ-G numโ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. GCC can then generate more efficient accesses to the data; see-mgpoptfor details. the default-Goption depends on the configuration. small data = happy data ๐-mlocal-sdata,-mno-local-sdataโ extend (do not extend) the-Gbehavior to local data too, such as to static variables in C.-mlocal-sdatais the default for all configurations.
if the linker complains that an application is using too much small data, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. you might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program. sharing is caring but the small data section is finite ๐ซถ
-mextern-sdata,-mno-extern-sdataโ assume (do not assume) that externally-defined data is in a small data section if the size of that data is within the-Glimit.-mextern-sdatais the default for all configurations.
if you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is no bigger than num bytes, you must make sure that Var is placed in a small data section. if Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a "section" attribute to Var's definition. if Var is common, you must link the application with a high-enough -G setting.
ngl the easiest way to satisfy these restrictions is to compile and link every module with the same-Goption. however, you may wish to build a library that supports several different small data limits. you can do this by compiling the library with the highest supported-Gsetting and additionally using-mno-extern-sdatato stop the library from making assumptions about externally-defined data. big brain move ๐ง โจ
-mgpopt,-mno-gpoptโ use (do not use) GP-relative accesses for symbols that are known to be in a small data section; see-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations.
-mno-gpopt is useful for cases where the $gp register might not hold the value of "_gp". for example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (in such situations, the boot monitor itself is usually compiled with -G0.) ๐ญ chaos.
-mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. it's giving chain reaction ๐
-membedded-data,-mno-embedded-dataโ allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. this gives slightly slower code than the default, but reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems. trade-offs, bestie, it's always trade-offs ๐ธ-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ put uninitialized"const"variables in the read-only data section. this option is only meaningful in conjunction with-membedded-data. otherwise it's just standing there, doing nothing ๐-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. go off, read whatever you want ๐
-mcode-readable=pcrelโ so MIPS16 PC-relative load instructions are allowed to touch executable sections, but like, every other instruction still can't. This one's a slay on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set โจ. Also lowkey useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM.-mcode-readable=noโ nope, instructions must not access executable sections, periodt. This vibe is useful on targets configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM ๐ .
-msplit-addresses,-mno-split-addressesโ enable (disable) use of the%hi()and%lo()assembler relocation operators. Honestly? This option has been superseded by-mexplicit-relocsbut it's retained for backwards compatibility, so it's giving legacy icon ๐.-mexplicit-relocs,-mno-explicit-relocsโ use (do not use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by-mno-explicit-relocs, is to use assembler macros instead.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators โ
.
-mcheck-zero-division,-mno-check-zero-divisionโ trap (do not trap) on integer division by zero. The default is-mcheck-zero-division.-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 is only supported on MIPS II and later. Also, some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE) ๐ญ. Use-mdivide-trapsto allow conditional traps on architectures that support them and-mdivide-breaksto force the use of breaks.
The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. Divide-by-zero checks can be completely disabled using -mno-check-zero-division.
-mload-store-pairs,-mno-load-store-pairsโ enable (disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding ๐ซถ. This option is enabled by default but only takes effect when the selected architecture is known to support bonding.-munaligned-access,-mno-unaligned-accessโ enable (disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So-mno-unaligned-accessmay be needed by kernel ๐.-mmemcpy,-mno-memcpyโ force (do not force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies โจ.-mlong-calls,-mno-long-callsโ disable (do not disable) use of thejalinstruction. Calling functions usingjalis more efficient but requires the caller and callee to be in the same 256 megabyte segment. This option has no effect on abicalls code. The default is-mno-long-calls.-mmad,-mno-madโ enable (disable) use of themad,maduandmulinstructions, as provided by the R4650 ISA ๐ฅ.-mimadd,-mno-imaddโ enable (disable) use of themaddandmsubinteger instructions. The default is-mimaddon architectures that supportmaddandmsubexcept for the 74k architecture where it was found to generate slower code ๐.-mfused-madd,-mno-fused-maddโ enable (disable) use of the floating-point multiply-accumulate instructions, when they are available. The default is-mfused-madd.
On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances ๐. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions.
-nocppโ tell the MIPS assembler to not run its preprocessor over user assembler files (with a.ssuffix) when assembling them.
-mfix-24k,-mno-fix-24kโ work around the 24K E48 (lost data on stores during refill) errata. The workarounds are implemented by the assembler rather than by GCC ๐ง.-mfix-r4000,-mno-fix-r4000โ work around certain R4000 CPU errata:- 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 2 "F1" and "F2" floating-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. If called, the function must take the same arguments as the common_flush_func, that is, the address of the memory range for which the cache is being flushed, the size of the memory range, and the number 3 (to flush both caches) ๐ธ. The default depends on the target GCC was configured for, but commonly is either_flush_funcor__cpu_flush.mbranch-cost=num โ sets the cost of branches to roughly num "simple" instructions ๐. Heads up though: this cost is only a heuristic and is not guaranteed to give you consistent results across releases. A zero cost redundantly selects the default, which is based on the-mtunesetting.-mbranch-likely,-mno-branch-likelyโ turn the use of Branch Likely instructions on or off, regardless of whatever the default is for the architecture you picked ๐. By default, Branch Likely instructions may be generated if your selected architecture supports them. The exception? MIPS32 and MIPS64 architectures and the processors that implement them โ for those, Branch Likely instructions are not generated by default, because MIPS32 and MIPS64 specifically deprecate their use ๐ซถ.-mcompact-branches=neverโ ensures compact branch instructions will never be generated ๐ซ.-mcompact-branches=optimalโ this is the default โจ. It causes 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 gets chosen if one is available.-mcompact-branches=alwaysโ ensures a compact branch instruction will be generated if it's available for MIPS Release 6 onwards. If a compact branch instruction is not available (or pre-R6), a delay slot form of the branch is used instead.
ok so a couple of caveats on these compact-branch flags, bestie, don't skip this ๐ โ these options control which form of branches will be generated. If -mcompact-branches=always is used for MIPS16/microMIPS targets, it will just be ignored right now. The behaviour for MIPS16/microMIPS may change in future, since they do have some compact branch instructions.
-mfp-exceptions,-mno-fp-exceptionsโ specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled. For instance, on the SB-1, if FP exceptions are disabled and we're emitting 64-bit code, then we can use both FP pipes โ otherwise we can only use one FP pipe ๐ญ.-mvr4130-align,-mno-vr4130-alignโ the VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned ๐ฏ. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel. It only has an effect when optimizing for the VR4130, and it normally makes code faster โ at the expense of making it bigger. It's enabled by default at optimization level-O3.-msynci,-mno-synciโ enable (disable) generation of"synci"instructions on architectures that support it ๐ธ. The"synci"instructions (if enabled) are generated when"__builtin___clear_cache"is compiled. This option defaults to-mno-synci, but the default can be overridden by configuring GCC with--with-synci.
๐จ real talk: when compiling code for single processor systems, it's generally safe to use "synci". BUT on many multi-core (SMP) systems it does not invalidate the instruction caches on all cores and may lead to undefined behavior. You've been warned ๐
.
-mrelax-pic-calls,-mno-relax-pic-callsโ try to turn PIC calls that are normally dispatched via register$25into direct calls ๐ฅ. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call.-mrelax-pic-callsis the default if GCC was configured to use an assembler and a linker that support the".reloc"assembly directive and-mexplicit-relocsis in effect. With-mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone โ no help from the compiler needed ๐ซก.-mmcount-ra-address,-mno-mcount-ra-addressโ emit (do not emit) code that allows"_mcount"to modify the calling function's return address. When enabled, this option extends the usual"_mcount"interface with a new ra-address parameter, which has type"intptr_t *"and is passed in register$12."_mcount"can then modify the return address by doing both of the following:- Returning the new address in register
$31. - Storing the new address in
"*ra-address", if ra-address is nonnull.
- Returning the new address in register
The default is -mno-mcount-ra-address.
-mframe-header-opt,-mno-frame-header-optโ enable (disable) frame header optimization in the o32 ABI ๐. When using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. When enabled, this optimization will suppress the allocation of the frame header if it can be determined that it's unused. This optimization is off by default at all optimization levels ๐.-mlxc1-sxc1,-mno-lxc1-sxc1โ when applicable, enable (disable) the generation of"lwxc1","swxc1","ldxc1","sdxc1"instructions. Enabled by default โจ.-mmadd4,-mno-madd4โ when applicable, enable (disable) the generation of 4-operand"madd.s","madd.d"and related instructions. Enabled by default ๐.
๐ง MMIX OPTIONS ๐ง
These options are defined for the MMIX, bestie:
-mlibfuncs,-mno-libfuncsโ specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size ๐ฆ.-mepsilon,-mno-epsilonโ generate floating-point comparison instructions that compare with respect to the"rE"epsilon register ๐.-mabi=mmixware,-mabi=gnuโ generate code that passes function parameters and return values that (in the called function) are seen as registers$0and up โ as opposed to the GNU ABI, which uses global registers$231and up ๐-mzero-extend,-mno-zero-extendโ when reading data from memory in sizes shorter than 64 bits, use (do not use) zero-extending load instructions by default, rather than sign-extending ones โญ.-mknuthdiv,-mno-knuthdivโ make the result of a division yielding a remainder have the same sign as the divisor. With the default,-mno-knuthdiv, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid โ the latter being almost exclusively used ๐.-mtoplevel-symbols,-mno-toplevel-symbolsโ prepend (do not prepend) a:to all global symbols, so the assembly code can be used with the"PREFIX"assembly directive ๐.-melfโ generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator ๐ .-mbranch-predict,-mno-branch-predictโ use (do not use) the probable-branch instructions, when static branch prediction indicates a probable branch ๐ฎ.-mbase-addresses,-mno-base-addressesโ generate (do not generate) code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register ๐ซถ. The register is used for one or more base address requests within the range0to255from the value held in the register. This generally leads to short and fast code, but the number of different data items that can be addressed is limited. Which means: a program that uses lots of static data may require-mno-base-addresses๐ญ.-msingle-exit,-mno-single-exitโ force (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 both"a0"and"d0"๐ฏ. Otherwise, the pointer is returned only in"a0", and attempts to call such functions without a prototype result in errors. Note that this option is on by default โ use-mno-return-pointer-on-d0to disable it.-mno-crt0โ do not link in the C run-time initialization object file ๐ซ.-mrelaxโ indicate to the linker that it should perform a relaxation optimization pass to shorten branches, calls and absolute memory addresses ๐. This option only has an effect when used on the command line for the final link step.
๐ญ heads up: this option makes symbolic debugging impossible. Like, fully. Plan accordingly.
-mliwโ allow the compiler to generate Long Instruction Word instructions if the target is the AM33 or later. This is the default โจ. This option defines the preprocessor macro"__LIW__".-mno-liwโ do not allow the compiler to generate Long Instruction Word instructions. This option defines the preprocessor macro"__NO_LIW__"๐ซ.-msetlbโ allow the compiler to generate theSETLBandLccinstructions if the target is the AM33 or later. This is the default ๐. This option defines the preprocessor macro"__SETLB__".-mno-setlbโ do not allow the compiler to generateSETLBorLccinstructions. This option defines the preprocessor macro"__NO_SETLB__"๐.
๐ฆ MOXIE OPTIONS ๐ฆ
-mebโ generate big-endian code. This is the default formoxie-*-*configurations ๐.-melโ generate little-endian code ๐ธ.-mmul.xโ generatemul.xandumul.xinstructions. This is the default formoxiebox-*-*configurations โญ.-mno-crt0โ do not link in the C run-time initialization object file ๐ซ.
๐ MSP430 OPTIONS ๐
These options are defined for the MSP430:
-masm-hexโ force assembly output to always use hex constants ๐ข. Normally such constants are signed decimals, but this option is available for testsuite and/or aesthetic purposes ๐ .-mmcu=โ bestie, this is the โpick your MCUโ knob ๐ . It makes a C preprocessor symbol from the MCU name: uppercase it, then slap__on the front and back. That symbol is whatmsp430.huses to pull in an MCU-specific extra header file.
The option also sets which ISA to use. If the MCU name is known to only support the 430 ISA, then 430 gets selected; otherwise itโs the 430X ISA. The generic MCU name msp430 can also be used to select the 430 ISA, and the generic msp430x MCU name selects the 430X ISA.
It also adds an MCU-specific linker script to the linker command line. The scriptโs name is the MCU name with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and causes the linker to search for a script called xxx.ld.
The ISA and hardware multiply support for the different MCUs are hard-coded into GCC. But an external devices.csv file can extend device support beyond whatโs hard-coded.
GCC searches for devices.csv in this precedence order โ first method wins over the second, and the second wins over the third:
- Include path specified with
-Iand-Lโdevices.csvis searched for in each of the directories specified by include paths and linker library search paths. - Path specified by the environment variable
MSP430_GCC_INCLUDE_DIRโ set the global environment variableMSP430_GCC_INCLUDE_DIRto the full path of the directory containingdevices.csv, and GCC will search that directory fordevices.csv. Ifdevices.csvis found, this directory is also 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 is also 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โ turns warnings on or off for conflicts between the MCU name from-mmcuand the ISA set by-mcpuand/or the hardware multiply support set by-mhwmult. It also toggles warnings about unrecognized MCU names. This option is on by default โจ.-mcpu=โ specifies the ISA to use. Accepted values aremsp430,msp430xandmsp430xv2. This option is deprecated ๐ซ โ use-mmcu=to select the ISA instead.-msimโ link to the simulator runtime libraries and linker script. Overrides any scripts that would be selected by-mmcu=.-mlargeโ use large-model addressing: 20-bit pointers, 20-bitsize_t.-msmallโ use small-model addressing: 16-bit pointers, 16-bitsize_t.-mrelaxโ passed to the assembler and linker, and lets the linker do certain optimizations that canโt happen until the final link. iconic linker behavior, no cap.mhwmult=โ describes the type of hardware multiply supported by the target. Accepted values arenonefor no hardware multiply,16bitfor the original 16-bit-only multiply supported by early MCUs,32bitfor the 16/32-bit multiply supported by later MCUs, andf5seriesfor the 16/32-bit multiply supported by F5-series MCUs. You can also give a value ofauto, which tells GCC to deduce hardware multiply support from the MCU name provided by-mmcu. 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.
Hardware multiplies are normally performed by calling a library routine. This saves space in the generated code. When compiling at -O3 or higher, however, the hardware multiplier is invoked inline โ bigger code, but faster code.
The hardware multiply routines disable interrupts while running and restore the previous interrupt state when they finish. That makes them safe to use inside interrupt handlers as well as in normal code ๐.
-minrtโ enable the use of a minimum runtime environment: no static initializers or constructors. This is intended for memory-constrained devices. The compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required.-mtiny-printfโ enable reduced-code-sizeprintfandputslibrary functions. The tiny implementations of these functions are not reentrant, so use them with caution in multi-threaded applications ๐ญ.
Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it is sent to write.
This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.
-mmax-inline-shift=โ takes an integer between0and64inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When this value needs to be exceeded, anmspabihelper function 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 is used instead.
-mcode-region=,-mdata-region=โ these 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.-msilicon-errata=โ passes on a request to the assembler to enable the fixes for the named silicon errata.-msilicon-errata-warn=โ passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied.-mwarn-devices-csv,-mno-warn-devices-csvโ warn ifdevices.csvis not found or 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 of2between4and512.-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.
-mctor-dtorโ enable constructor/destructor feature.-mrelaxโ guide linker to relax instructions.
๐ฆ Nios II Options ๐ฆ
These are the options defined for the Altera Nios II processor.
-G numโ put global and static objects less than or equal tonumbytes into the small data or BSS sections instead of the normal data or BSS sections. The default value ofnumis8.-mgpopt=option,-mgpopt,-mno-gpoptโ generate (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โ makes GCC generate GP-relative addresses for function pointers as well as data pointers. ๐ซถ Heads up though: if you use this, your entire text, data, and BSS segments have to fit inside 64K of memory, and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. That's the whole deal, no wiggle room.-mgpoptis literally the same thing as-mgpopt=local, and-mno-gpoptis the same thing as-mgpopt=none. โจ
The default is -mgpopt โ except when -fpic or -fPIC is specified to generate position-independent code. Also note that the Nios II ABI does not permit GP-relative accesses from shared libraries, so don't even try it bestie. ๐ซ
You may need to pass -mno-gpopt explicitly when you're building programs that include large amounts of small data, including large GOT data sections. Why? Because in that case the 16-bit offset for GP-relative addressing may just not be big enough to let you access the entire small data section. ๐ญ It's giving "too much stuff, not enough offset."
-mgprel-sec=regexpโ lets you name extra sections that can be accessed via GP-relative addressing. It's most useful when you pair it 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-Goption, and the sections you specify are in addition to the standard".sdata"and".sbss"small-data sections that-mgpoptalready recognizes.-mr0rel-sec=regexpโ names the sections that can be accessed via a 16-bit offset from"r0"โ that is, the low 32K or high 32K of the 32-bit address space. Most useful in conjunction with"section"attributes on variable declarations and a custom linker script, and the regexp here is a POSIX Extended Regular Expression too. ๐
In contrast to using GP-relative addressing for small data, zero-based addressing is never generated by default, and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory. So it's very much a "you build it, you name it" situation.
-mel,-mebโ generate little-endian (the default) or big-endian (experimental ๐) code, respectively.-march=archโ specifies the name of the target Nios II architecture. GCC uses this name to figure out what kind of instructions it's allowed to 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. Cute, right? ๐ฆ
-mbypass-cache,-mno-bypass-cacheโ force all load and store instructions to always bypass the cache by using I/O variants of the instructions. The default is not to bypass the cache.-mno-cache-volatile,-mcache-volatileโ volatile memory accesses 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โ don't use table-based fast divide for small numbers. The default is to use the fast divide at-O3and above. โก-mno-hw-mul,-mhw-mul,-mno-hw-mulx,-mhw-mulx,-mno-hw-div,-mhw-divโ enable or disable the compiler emitting the"mul","mulx"and"div"family of instructions. The default is to emit"mul"and not emit"div"and"mulx".-mbmx,-mno-bmx,-mcdx,-mno-cdxโ enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. Enabling these also requires-march=r2. Since these instructions are optional extensions to the R2 architecture, the default is not to emit them. ๐-mcustom-insn=N,-mno-custom-insnโ each-mcustom-insn=Noption turns on a custom instruction with encoding N when generating code that uses insn. For example,-mcustom-fadds=253generates custom instruction253for single-precision floating-point add operations instead of the default behavior of using a library call. ๐ฅ
The following values of insn are supported. Except as otherwise noted, floating-point operations are expected to be implemented with normal IEEE 754 semantics and correspond directly to the C operators or the equivalent GCC built-in functions.
Single-precision floating point: ๐
fadds,fsubs,fdivs,fmulsโ binary arithmetic operations.fnegsโ unary negation.fabssโ unary absolute value.fcmpeqs,fcmpges,fcmpgts,fcmples,fcmplts,fcmpnesโ comparison operations.fmins,fmaxsโ floating-point minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified.fsqrtsโ unary square root operation.fcoss,fsins,ftans,fatans,fexps,flogsโ floating-point trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified. ๐
Double-precision floating point: ๐
faddd,fsubd,fdivd,fmuldโ binary arithmetic operations.fnegdโ unary negation.fabsdโ unary absolute value.fcmpeqd,fcmpged,fcmpgtd,fcmpled,fcmpltd,fcmpnedโ comparison operations.fmind,fmaxdโ double-precision minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified.fsqrtdโ unary square root operation.fcosd,fsind,ftand,fatand,fexpd,flogdโ double-precision trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified.
Conversions: ๐
fextsdโ conversion from single precision to double precision.ftruncdsโ conversion from double precision to single precision.fixsi,fixsu,fixdi,fixduโ conversion from floating point to signed or unsigned integer types, with truncation towards zero.roundโ conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the__builtin_lroundffunction when-fno-math-errnois used.floatis,floatus,floatid,floatudโ conversion from signed or unsigned integer types to floating-point types.
In addition, all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. ๐ซก Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or the only operand of a unary operation) is given to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction that returns a double-precision result returns the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC automatically generates the necessary code sequences to write register X and/or read register Y when double-precision floating-point instructions are used.
fwrxโ write src1 into the least significant half of X and src2 into the most significant half of X.fwryโ write src1 into Y.frdxhi,frdxloโ read the most or least (respectively) significant half of X and store it in dest.frdyโ read the value of Y and store it into dest.
Not me letting you in on this: 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โ enables a predefined, named set of custom instruction encodings (see-mcustom-insnabove). Currently, the following sets are defined:-mcustom-fpu-cfg=60-1is equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
-mcustom-fpu-cfg=60-2is equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
-mcustom-fpu-cfg=72-3is equivalent to:
-mcustom-floatus=243 -mcustom-fixsi=244 -mcustom-floatis=245 -mcustom-fcmpgts=246 -mcustom-fcmples=249 -mcustom-fcmpeqs=250 -mcustom-fcmpnes=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
-mcustom-fpu-cfg=fph2is equivalent to:
-mcustom-fabss=224 -mcustom-fnegs=225 -mcustom-fcmpnes=226 -mcustom-fcmpeqs=227 -mcustom-fcmpges=228 -mcustom-fcmpgts=229 -mcustom-fcmples=230 -mcustom-fcmplts=231 -mcustom-fmaxs=232 -mcustom-fmins=233 -mcustom-round=248 -mcustom-fixsi=249 -mcustom-floatis=250 -mcustom-fsqrts=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255
Custom instruction assignments given by individual -mcustom-insn= options override those given by -mcustom-fpu-cfg=, regardless of the order of the options on the command line. Order does not save you here, bestie. ๐
You can also 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. And 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โ okay sosystemlibis the name of the library that hands you the low-level system calls your C library needs โ thinkreadandwritetype stuff ๐ . You'd typically use this to link against a library that a HAL BSP provides. ๐
๐ฆ Nvidia PTX Options ๐ฆ
These ones are defined for Nvidia PTX, bestie:
-m64โ lowkey ignored, but it's preserved for backward compatibility. Only the 64-bit ABI is supported, periodt.-march=architecture-stringโ generate code for the PTX ISA target architecture you name (likesm_35). The valid architecture strings aresm_30,sm_35,sm_53,sm_70,sm_75andsm_80. The default depends on how the compiler was configured โ peep--with-arch.
This option sets the value of the preprocessor macro __PTX_SM__; for instance, for sm_35 it has the value 350. โจ
-misa=architecture-stringโ literally just an alias of-march=. iykyk.-march-map=architecture-stringโ picks the closest available-march=value that isn't more capable than what you asked for. For instance, for-march-map=sm_50it selects-march=sm_35, and for-march-map=sm_53it selects-march=sm_53. ๐-mptx=version-stringโ generate code for the PTX ISA version you name (like7.0). The valid version strings include3.1,6.0,6.3, and7.0. Default PTX ISA version is6.0, unless a higher version is required for the PTX ISA target architecture you specified via-march=.
This option sets the values of the preprocessor macros __PTX_ISA_VERSION_MAJOR__ and __PTX_ISA_VERSION_MINOR__; for instance, for 3.1 those macros have the values 3 and 1 respectively. ๐ซถ
-mmainkernelโ link in code for a__mainkernel. This is for stand-alone execution instead of offloading execution.-moptimizeโ apply partitioned execution optimizations. This is the default whenever any level of optimization is selected.-msoft-stackโ generate code that does not use.localmemory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays oralloca), and when global memory is used for the underlying storage, it makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use-mgompinstead. ๐-muniform-simtโ switches to a code generation variant that lets you execute all the 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 the 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. The shared memory arrayint __nvptx_uni[]stores all-zeros or all-ones bitmasks for each warp, indicating the current mode (0outside of SIMD regions). Each thread can bitwise-and the bitmask at positiontid.ywith the current lane index to compute the master lane index. main character energy fr fr ๐ซ-mgompโ generate code for use in OpenMP offloading: enables the-msoft-stackand-muniform-simtoptions, and selects the corresponding multilib variant. ate. ๐ฅ
๐ธ OpenRISC Options ๐ธ
These options are defined for OpenRISC:
-mboard=nameโ configure a board-specific runtime. This gets passed to the linker for newlib board library linking. The default isor1ksim. ๐-mnewlibโ this option is ignored; it's for compatibility purposes only. It used to select linker and preprocessor options for use with newlib.-msoft-div,-mhard-divโ select software or hardware divide (l.div,l.divu) instructions. The default is hardware divide.-msoft-mul,-mhard-mulโ select software or hardware multiply (l.mul,l.muli) instructions. The default is hardware multiply.-msoft-float,-mhard-floatโ select software or hardware for floating point operations. The default is software.-mdouble-floatโ when-mhard-floatis selected, this enables generation of double-precision floating point instructions. By default functions from libgcc are used to perform double-precision floating point operations.-munordered-floatโ when-mhard-floatis selected, this enables generation of unordered floating point compare and set flag (lf.sfun*) instructions. By default functions from libgcc are used to perform unordered floating point compare and set flag operations.-mcmovโ enable generation of conditional move (l.cmov) instructions. By default the equivalent gets generated using set and branch.-mrorโ enable generation of rotate right (l.ror) instructions. By default functions from libgcc are used to perform rotate right operations.-mroriโ enable generation of rotate right with immediate (l.rori) instructions. By default functions from libgcc are used to perform rotate right with immediate operations.-msextโ enable generation of sign extension (l.ext*) instructions. By default memory loads are used to perform sign extension.-msfimmโ enable generation of compare and set flag with immediate (l.sf*i) instructions. By default extra instructions get generated to store the immediate to a register first.-mshftimmโ enable generation of shift with immediate (l.srai,l.srli,l.slli) instructions. By default extra instructions get generated to store the immediate to a register first.-mcmodel=smallโ generate OpenRISC code for the small model: the GOT is limited to 64k. This is the default model.-mcmodel=largeโ generate OpenRISC code for the large model: the GOT may grow up to 4G in size. ๐ญ
๐ PDP-11 Options ๐
These options are defined for the PDP-11:
-mfpuโ use hardware FPP floating point. This is the default. (FIS floating point on the PDP-11/40 is not supported.) Implies-m45.-msoft-floatโ do not use hardware floating point.-mac0โ return floating-point results in ac0 (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. ๐ง
โญ PowerPC Options โญ
These are listed under... yeah, that's all she wrote here. (not me staring at a whole entire empty section ๐)
๐ PRU Options ๐
These command-line options are defined for the PRU target:
-minrtโ link with a minimum runtime environment, with no support for static initializers and constructors. Using this option can significantly reduce the size of the final ELF binary. โ ๏ธ Beware: the compiler could still generate code with static initializers and constructors. It is up to the programmer to 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
NULLin 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 the 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 if you want a specific calling convention, bestie, specify one explicitly. The valid calling conventions are ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Some calling conventions are literally impossible to implement on some ISAs: for example, -march=rv32if -mabi=ilp32d is invalid because the ABI requires 64-bit values be passed in F registers, but F registers are only 32 bits wide. Thereโs also the ilp32e ABI that can only be used with the rv32e architecture. This ABI is not well specified at present, and is subject to change. ๐ซถ
-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 forISA-spec-stringare:2.2โ Produce code conforming to version 2.2.20190608โ Produce code conforming to version 20190608.20191213โ Produce code conforming to version 20191213.
The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version.
-march=ISA-stringโ Generate code for given RISC-V ISA (e.g.rv64im). ISA strings must be lower-case. Examples includerv64i,rv32g,rv32e, andrv32imaf.
When -march= is not specified, use the setting from -mcpu.
If both -march and -mcpu= are not specified, the default for this argument is system dependent, users who want a specific architecture extensions should specify one explicitly.
-mcpu=processor-stringโ Use architecture of and optimize the output for the given processor, specified by particular CPU name. Permissible values for this option are:sifive-e20,sifive-e21,sifive-e24,sifive-e31,sifive-e34,sifive-e76,sifive-s21,sifive-s51,sifive-s54,sifive-s76,sifive-u54, andsifive-u74. ๐-mtune=processor-stringโ Optimize the output for the given processor, specified by microarchitecture or particular CPU name. Permissible values for this option are:rocket,sifive-3-series,sifive-5-series,sifive-7-series,thead-c906,size, and all valid options for-mcpu=.
When -mtune= is not specified, use the setting from -mcpu, the default is rocket if both are not specified.
The size choice is not intended for use by end-users. This is used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but does not override the pipeline info. This helps reduce code size while still giving good performance.
-mpreferred-stack-boundary=numโ Attempt to keep the stack boundary aligned to a 2 raised tonumbyte boundary. If-mpreferred-stack-boundaryis not specified, the default is4(16 bytes or 128-bits).
Warning: If you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. ๐ญ
-msmall-data-limit=nโ Put global and static data smaller thannbytes into a special section (on some targets).-msave-restore,-mno-save-restoreโ Do or donโt use smaller but slower prologue and epilogue code that uses library function calls. The default is to use fast inline prologues and epilogues.-minline-atomics,-mno-inline-atomicsโ Do or donโt use smaller but slower subword atomic emulation code that useslibatomicfunction calls. The default is to use fast inline subword atomics that do not requirelibatomic.-mshorten-memrefs,-mno-shorten-memrefsโ Do or do not attempt to make more use of compressed load/store instructions by replacing a load/store of โbase register + large offsetโ with a new load/store of โnew base + small offsetโ. If the new base gets stored in a compressed register, then the new load/store can be compressed. Currently targets 32-bit integer load/stores only.-mstrict-align,-mno-strict-alignโ Do not or do generate unaligned memory accesses. The default is set depending on whether the processor we are optimizing for supports fast unaligned access or not.-mcmodel=medlowโ Generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses-2 GiBand+2 GiB. Programs can be statically or dynamically linked. This is the default code model.-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.
Heads up: 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.
-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. (Yes, that second spelling is exactly how the manual has it.)-mrelax,-mno-relaxโ Take advantage of linker relaxations to reduce the number of instructions required to materialize symbol addresses. The default is to take advantage of linker relaxations.-mriscv-attribute,-mno-riscv-attributeโ Emit (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32.-mcsr-check,-mno-csr-checkโ Enables or disables the CSR checking.-malign-data=typeโ Control how GCC aligns variables and constants of array, structure, or union types. Supported values fortypearexlenwhich uses x register width as the alignment value, andnaturalwhich 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 atguard. Supported locations areglobalfor a global canary ortlsfor per-thread canary in the TLS block.
With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel.
๐ธ RL78 Options ๐ธ
-msimโ Links in additional target libraries to support operation within a simulator.-mmul=none,-mmul=g10,-mmul=g13,-mmul=g14,-mmul=rl78โ Specifies the type of hardware multiplication and division support to be used. The simplest isnone, which uses software for both multiplication and division. 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=none option on the command line. Thus specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral and specifying -mcpu=g10 disables the use of hardware multiplications altogether.
Note, although the RL78/G14 core is the default target, specifying -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain since it also enables G14 hardware multiply support. If these options are not specified on the command line then software multiplication routines will be used even though the code targets the RL78 core. This is for backwards compatibility with older toolchains which did not have hardware multiply and divide support.
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.-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โ tells the compiler that interrupt handler functions should keep the MDUC registers safe ๐พ. This is only actually needed if normal code might touch the MDUC registers โ like, say, because it's doing multiplication and division ops ๐. The default is to ignore the MDUC registers, because that makes interrupt handlers faster (and we love a speedy handler, no cap โจ). You also have to pass the target option-mg13for this to work at all, since the feature only exists on the G13 target (S2 core). And heads up: the MDUC registers only get saved if the interrupt handler actually does a multiplication or division operation, or if it calls another function. Yeah, it's giving "conditional queen" ๐ .
๐ธ IBM RS/6000 and PowerPC Options ๐ธ
These -m options are defined for the IBM RS/6000 and PowerPC, bestie ๐ซถ:
-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're using ๐. The default value of these options is determined when configuring GCC. Specifying-mcpu=cpu_typeoverrides the specification of these options. And real talk: we recommend you use the-mcpu=cpu_typeoption rather than the ones listed above, iykyk ๐
Specifying -mpowerpc-gpopt lets GCC use the optional PowerPC architecture instructions in the General Purpose group, including floating-point square root ๐. Specifying -mpowerpc-gfxopt lets GCC use the optional PowerPC architecture instructions in the Graphics group, including floating-point select โจ.
The -mmfcrf option allows GCC to generate the move from condition register field instruction implemented on the POWER4 processor and other processors that support the PowerPC V2.01 architecture ๐. The -mpopcntb option allows GCC to generate the popcount and double-precision FP reciprocal estimate instruction implemented on the POWER5 processor and other processors that support the PowerPC V2.02 architecture ๐ซ. The -mpopcntd option allows GCC to generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture ๐ฅ. The -mfprnd option allows GCC to generate the FP round to integer instructions implemented on the POWER5+ processor and other processors that support the PowerPC V2.03 architecture ๐ธ. The -mcmpb option allows GCC to generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture ๐. The -mhard-dfp option allows GCC to generate the decimal floating-point instructions implemented on some POWER processors ๐.
The -mpowerpc64 option allows GCC to generate the additional 64-bit instructions that are found in the full PowerPC64 architecture, and to treat GPRs as 64-bit, doubleword quantities ๐. GCC defaults to -mno-powerpc64.
-mcpu=cpu_typeโ sets the architecture type, register usage, and instruction scheduling parameters for machine type cpu_type ๐ ๏ธ. Supported values for cpu_type are401,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๐. That's a lot of CPUs, and honestly? Slay, we love a comprehensive list ๐ .
-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endian), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes ๐.
Specifying native as cpu type detects and selects the architecture option that corresponds to the host processor of the system performing the compilation ๐. Heads up though: -mcpu=native has no effect if GCC does not recognize the processor ๐ญ.
The other options specify a specific processor. Code generated under those options runs best on that processor, and may not run at all on others โ ๏ธ โ so don't be out here assuming portability, bestie.
The -mcpu options automatically enable or disable the following options:
-maltivec -mfprnd -mhard-float -mmfcrf -mmultiple -mpopcntb
-mpopcntd -mpowerpc64 -mpowerpc-gpopt -mpowerpc-gfxopt -mmulhw
-mdlmzb -mmfpgpr -mvsx -mcrypto -mhtm -mpower8-fusion
-mpower8-vector -mquad-memory -mquad-memory-atomic -mfloat128
-mfloat128-hardware -mprefixed -mpcrel -mmma -mrop-protect
The particular options set for any particular CPU varies between compiler versions, depending on what setting seems to produce optimal code for that CPU ๐; it doesn't necessarily reflect the actual hardware's capabilities. So if you wish to set an individual option to a particular value, you may specify it after the -mcpu option, like -mcpu=970 -mno-altivec โจ.
On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option at present, because AIX does not have full support for these options ๐. You may still enable or disable them individually if you're sure it'll work in your environment โ your call, main character ๐ซถ.
-mtune=cpu_typeโ sets the instruction scheduling parameters for machine type cpu_type, but does not set the architecture type or register usage, the way-mcpu=cpu_typedoes ๐ซ. The same values for cpu_type are used for-mtuneas for-mcpu. If both are specified, the code generated uses the architecture and registers set by-mcpu, but the scheduling parameters set by-mtune๐.-mcmodel=smallโ generate PowerPC64 code for the small model: the TOC is limited to 64k ๐ฃ.-mcmodel=mediumโ generate PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size ๐ธ. This is the default for 64-bit Linux, bestie ๐-mcmodel=largeโ generate PowerPC64 code for the large model: the TOC may be up to 4G in size. Other data and code is only limited by the 64-bit address space ๐ โ absolute unit energy.-maltivec,-mno-altivecโ generate code that uses (does not use) AltiVec instructions, and also enable the use of built-in functions that allow more direct access to the AltiVec instruction set ๐. You may also need to set-mabi=altivecto adjust the current ABI with AltiVec ABI enhancements ๐ ๏ธ.
When -maltivec is used, the element order for AltiVec intrinsics such as vec_splat, vec_extract, and vec_insert match array element order corresponding to the endianness of the target ๐. That is, element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform ๐. Left vs right, it matters, okay??
-mvrsave,-mno-vrsaveโ generate VRSAVE instructions when generating AltiVec code ๐พ.-msecure-pltโ generate code that allowsldandld.soto build executables and shared libraries with non-executable.pltand.gotsections ๐. This is a PowerPC 32-bit SYSV ABI option โจ.-mbss-pltโ generate code that uses a BSS.pltsection thatld.sofills in, and requires.pltand.gotsections that are both writable and executable ๐ฌ. This is a PowerPC 32-bit SYSV ABI option.
Okay so that second one is giving "writable and executable at the same time," which is lowkey the vibe security people have nightmares about ๐. Just so you know what you're signing up for, bestie.
-msplit-patch-nopsโ when adding NOPs for a patchable area via the-fpatchable-function-entryoption, emit the "before" NOPs in front of the global entry point and the "after" NOPs after the local entry point ๐ฏ. This makes the sequence of NOPs not consecutive when a global entry point is generated. Without this option the NOPs are emitted directly before and after the local entry point, making them consecutive but moving global and local entry point further apart ๐. If only a single entry point is generated, this option has no effect โ it literally does nothing, no thoughts head empty ๐ธ.-misel,-mno-iselโ this switch enables or disables the generation of ISEL instructions โก.-mvsx,-mno-vsxโ generate code that uses (does not use) vector/scalar (VSX) instructions, and also enable the use of built-in functions that allow more direct access to the VSX instruction set ๐ฆ.-mcrypto,-mno-cryptoโ enable the use (disable) of the built-in functions that allow direct access to the cryptographic instructions that were added in version 2.07 of the PowerPC ISA ๐.-mhtm,-mno-htmโ enable (disable) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions that were added in version 2.07 of the PowerPC ISA ๐ง .-mpower8-fusion,-mno-power8-fusionโ generate code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors ๐ฅ. (Yes, the manpage literally says "does not keeps" โ we're keeping it, character for character, because that's iconic in its own way ๐ญ.)-mpower8-vector,-mno-power8-vectorโ generate code that uses (does not use) the vector and scalar instructions that were added in version 2.07 of the PowerPC ISA ๐. Also enable 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 ๐ซ. The-mquad-memoryoption requires use of 64-bit mode โ ๏ธ โ no 32-bit shenanigans allowed.-mquad-memory-atomic,-mno-quad-memory-atomicโ generate code that uses (does not use) the atomic quad word memory instructions โ๏ธ. The-mquad-memory-atomicoption requires use of 64-bit mode too ๐-mfloat128,-mno-float128โ enable/disable the__float128keyword for IEEE 128-bit floating point, and use either software emulation for IEEE 128-bit floating point or hardware instructions ๐งฎ.
The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support ๐. And the IEEE 128-bit floating point is only supported on Linux ๐ง.
The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on other systems ๐.
If you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions โก. Otherwise, if you do not specify to generate ISA 3.0 instructions, or you are targeting a 32-bit big endian system, IEEE 128-bit floating point will be done with software emulation ๐ข โ slower vibes, but it still works, bestie ๐ซถ.
-mfloat128-hardware,-mno-float128-hardwareโ turns on/off using ISA 3.0 hardware instructions to support the__float128data type โจ. The default for-mfloat128-hardwareis enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems ๐.-m32,-m64โ generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux) ๐. The 32-bit environment setsint,longand pointer to 32 bits and generates code that runs on any PowerPC variant. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits, and generates code for PowerPC64, as for-mpowerpc64.-mfull-toc,-mno-fp-in-toc,-mno-sum-in-toc,-mminimal-tocโ these modify generation of the TOC (Table Of Contents), which is created for every executable file ๐. The-mfull-tocoption is selected by default. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also places floating-point constants in the TOC. However, only 16,384 entries are available in the TOC ๐ญ.
If you receive a linker error message that saying you have overflowed the available TOC space, you can reduce the amount of TOC space used with the -mno-fp-in-toc and -mno-sum-in-toc options. -mno-fp-in-toc 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 causes GCC to produce very slightly slower and larger code at the expense of conserving TOC space ๐
.
If you still run out of space in the TOC even when you specify both of 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 extremely little TOC space. You may wish to use this option only on files that contain less frequently-executed code ๐ซถ.
-maix64,-maix32โ enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bit"long"type, and the infrastructure needed to support them ๐ฅ. Specifying-maix64implies-mpowerpc64, while-maix32disables the 64-bit ABI and implies-mno-powerpc64. GCC defaults to-maix32.-mxl-compat,-mno-xl-compatโ produce code that conforms more closely to IBM XL compiler semantics when using AIX-compatible ABI ๐ธ. Pass floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. Do not assume that most significant double in 128-bit long double value is properly rounded when comparing values and converting to double. Use XL symbol names for long double support routines.
The AIX calling convention was extended but not initially documented to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared. IBM XL compilers access floating-point arguments that do not fit in the RSA from the stack when a subroutine is compiled without optimization. Because always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not enabled by default and only is necessary when calling subroutines compiled by IBM XL compilers without optimization ๐.
-mpeโ support IBM RS/6000 SP Parallel Environment (PE) ๐ฆ. Link an application written to use message passing with special startup code to enable the application to run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the-specs=option to specify the appropriate directory location. The Parallel Environment does not support threads, so the-mpeoption and the-pthreadoption are incompatible ๐.-malign-natural,-malign-powerโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux, the option-malign-naturaloverrides the ABI-defined alignment of larger types, such as floating-point doubles, on their natural size-based boundary โจ. The option-malign-powerinstructs GCC to follow the ABI-specified alignment rules. GCC defaults to the standard alignment defined in the ABI.
On 64-bit Darwin, natural alignment is the default, and -malign-power is not supported ๐.
-msoft-float,-mhard-floatโ generate code that does not use (uses) the floating-point register set ๐. Software floating-point emulation is provided if you use the-msoft-floatoption, and pass the option to GCC when linking.-mmultiple,-mno-multipleโ generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions ๐ . These instructions are generated by default on POWER systems, and not generated on PowerPC systems. Do not use-mmultipleon little-endian PowerPC systems, since those instructions do not work when the processor is in little-endian mode. The exceptions are PPC740 and PPC750 which permit these instructions in little-endian mode.-mupdate,-mno-updateโ generate code that uses (does not use) the load or store instructions that update the base register to the address of the calculated memory location ๐ฅ. These instructions are generated by default. If you use-mno-update, there is a small window between the time that the stack pointer is updated and the address of the previous frame is stored, which means code that walks the stack frame across interrupts or signals may get corrupted data ๐ญ.-mavoid-indexed-addresses,-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, such as when stepping through large arrays that cross a 16M boundary. This option is enabled by default when targeting Power6 and disabled otherwise.-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions ๐. These instructions are generated by default if hardware floating point is used. The machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off.-mmulhw,-mno-mulhwโ generate code that uses (does not use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors ๐ฆ. These instructions are generated by default when targeting those processors.-mdlmzb,-mno-dlmzbโ generate code that uses (does not use) the string-searchdlmzbinstruction on the IBM 405, 440, 464 and 476 processors ๐ธ. This instruction is generated by default when targeting those processors.-mno-bit-align,-mbit-alignโ on System V.4 and embedded PowerPC systems do not (do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field ๐.
For example, by default a structure containing nothing but 8 unsigned bit-fields of length 1 is aligned to a 4-byte boundary and has a size of 4 bytes. By using -mno-bit-align, the structure is aligned to a 1-byte boundary and is 1 byte in size.
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems do not (do) assume that unaligned memory references are handled by the system โจ.-mrelocatable,-mno-relocatableโ generate code that allows (does not allow) a static executable to be relocated to a different address at run time ๐ฅ. A simple embedded PowerPC system loader should relocate the entire contents of.got2and 4-byte locations listed in the.fixupsection, a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with-mrelocatableor-mrelocatable-lib.-mrelocatablecode aligns the stack to an 8-byte boundary.-mrelocatable-lib,-mno-relocatable-libโ like-mrelocatable,-mrelocatable-libgenerates a.fixupsection to allow static executables to be relocated at run time, but-mrelocatable-libdoes not use the smaller stack alignment of-mrelocatable๐. Objects compiled with-mrelocatable-libmay be linked with objects compiled with any combination of the-mrelocatableoptions.-mno-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 ๐. The-mlittle-endianoption is the same as-mlittle.-mbig,-mbig-endianโ on System V.4 and embedded PowerPC systems compile code for the processor in big-endian mode ๐. The-mbig-endianoption is the same as-mbig.-mdynamic-no-picโ on Darwin and Mac OS X systems, compile code so that it is not relocatable, but that its external references are relocatable ๐. The resulting code is suitable for applications, but not shared libraries.-msingle-pic-baseโ treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function ๐ซถ. The runtime system is responsible for initializing this register with an appropriate value before execution begins.-mprioritize-restricted-insns=priorityโ this option controls the priority that is assigned to dispatch-slot restricted instructions during the second scheduling pass ๐ฅ. The argumentprioritytakes the value0,1, or2to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions.-msched-costly-dep=dependence_typeโ this option controls which dependences are considered costly by the target during instruction scheduling ๐. The argumentdependence_typetakes 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 whose latency is greater than or equal to number counts as costly. that's the whole vibe check ๐-minsert-sched-nops=schemeโ controls which NOP insertion scheme gets used during the second scheduling pass, bestie. scheme takes one of these:noโ don't insert NOPs. none. zero. bye ๐padโ pad with NOPs any dispatch group that has vacant issue slots, following the scheduler's grouping. filling the empty seats fr fr ๐ซถregroup_exactโ insert NOPs to force costly dependent insns into separate groups, and insert exactly as many NOPs as needed to force an insn into a new group, per the estimated processor grouping.numberโ insert NOPs to force costly dependent insns into separate groups, inserting number NOPs to force an insn into a new group. you pick the count, you own the count โจ
-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. vintage behavior, iconic honestly ๐-mcall-sysv-eabi,-mcall-eabiโ specify both-mcall-sysvand-meabioptions. two-for-one deal ๐-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. we love a Linux moment ๐-mcall-freebsdโ on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system.-mcall-netbsdโ on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system.-mcall-openbsdโ on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system.-mtraceback=traceback_typeโ select the type of traceback table. valid values for traceback_type arefull,part, andno. three choices, no notes ๐ฆ-maix-struct-returnโ return all structures in memory (as specified by the AIX ABI). all of them. in memory. periodt.-msvr4-struct-returnโ return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI). tiny structs get the register treatment โจ
-mabi=abi-typeโ extend the current ABI with a particular extension, or remove such extension. valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default. that's the roster, memorize it ๐-mabi=ibmlongdoubleโ change the current ABI to use IBM extended-precisionlong double. this is not likely to work if your system defaults to using IEEE extended-precisionlong double๐ญ and if you change thelong doubletype from IEEE extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. requires-mlong-double-128to be enabled. so many hoops but okay ๐-mabi=ieeelongdoubleโ change the current ABI to use IEEE extended-precisionlong double. this is not likely to work if your system defaults to using IBM extended-precisionlong double๐ and if you change thelong doubletype from IBM extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. requires-mlong-double-128to be enabled. mirror image, same drama ๐ช-mabi=elfv1โ change the current ABI to use the ELFv1 ABI. this is the default ABI for big-endian PowerPC 64-bit Linux. overriding the default ABI requires special system support and is likely to fail in spectacular ways. spectacular!! we love a warning that has main character energy ๐ฅ-mabi=elfv2โ change the current ABI to use the ELFv2 ABI. this is the default ABI for little-endian PowerPC 64-bit Linux. overriding the default ABI requires special system support and is likely to fail in spectacular ways. same chaos, different endianness ๐-mgnu-attribute,-mno-gnu-attributeโ emit.gnu_attributeassembly directives to set tag/value pairs in a.gnu.attributessection that specify ABI variations in function parameters or return values.-mprototype,-mno-prototypeโ on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped. otherwise, the compiler must insert an instruction before every non-prototyped call to set or clear bit 6 of the condition code register (CR) to indicate whether floating-point values are passed in the floating-point registers in case the function takes variable arguments. with-mprototype, only calls to prototyped variable argument functions set or clear the bit. bit 6 ofCRreally said "it's giving bookkeeping" ๐ญ-msimโ on embedded PowerPC systems, assume that the startup module is calledsim-crt0.oand that the standard C libraries arelibsim.aandlibc.a. this is the default forpowerpc-*-eabisimconfigurations. slay ๐ซถ-mmvmeโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibmvme.aandlibc.a.-madsโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.a.-myellowknifeโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a. yellowknife is such a name ngl ๐-mvxworksโ on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system.-membโ on embedded PowerPC systems, set thePPC_EMBbit in the ELF flags header to indicate that eabi extended relocations are used.-meabi,-mno-eabiโ on System V.4 and embedded PowerPC systems, do (do not) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications. selecting-meabimeans that the stack is aligned to an 8-byte boundary, a function__eabiis called frommainto set up the EABI environment, and the-msdataoption can use bothr2andr13to point to two separate small data areas. selecting-mno-eabimeans that the stack is aligned to a 16-byte boundary, no EABI initialization function is called frommain, and the-msdataoption only usesr13to point to a single small data area. the-meabioption is on by default if you configured GCC using one of thepowerpc*-*-eabi*options. two data areas vs one, choose your fighter โญ-msdata=eabiโ on System V.4 and embedded PowerPC systems, put small initializedconstglobal and static data in the.sdata2section, which is pointed to by registerr2. put small initialized non-constglobal and static data in the.sdatasection, which is pointed to by registerr13. put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. the-msdata=eabioption is incompatible with the-mrelocatableoption ๐จ the-msdata=eabioption also sets the-memboption. package deal ๐-msdata=sysvโ on System V.4 and embedded PowerPC systems, put small global and static data in the.sdatasection, which is pointed to by registerr13. put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. the-msdata=sysvoption is incompatible with the-mrelocatableoption ๐จ-msdata=default,-msdataโ on System V.4 and embedded PowerPC systems, if-meabiis used, compile code the same as-msdata=eabi, otherwise compile code the same as-msdata=sysv. it reads the room and adapts, lowkey iconic ๐ธ-msdata=dataโ on System V.4 and embedded PowerPC systems, put small global data in the.sdatasection. put small uninitialized global data in the.sbsssection. do not use registerr13to address small data however ๐ โโ๏ธ this is the default behavior unless other-msdataoptions are used.-msdata=none,-mno-sdataโ on embedded PowerPC systems, put all initialized global and static data in the.datasection, and all uninitialized data in the.bsssection. back to basics bestie ๐-mreadonly-in-sdataโ put read-only objects in the.sdatasection as well. this is the default. yes, read-only, yes, still in there, yes, it's fine ๐-mblock-move-inline-limit=numโ inline all block moves (such as calls tomemcpyor structure copies) 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. respect the floor ๐ง-mblock-compare-inline-limit=numโ generate non-looping inline code for all block compares (such as calls tomemcmpor structure compares) 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. zero means no inline, not even the loop version, no cap ๐-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 is not constant, at most num bytes will be compared beforememcmpis called to compare the remainder of the block. the default value is target-specific. looping era ๐ช๏ธ-mstring-compare-inline-limit=numโ compare at most num string bytes with inline code. if the difference or end of string is not found at the end of the inline compare a call tostrcmporstrncmpwill take care of the rest of the comparison. the default is 64 bytes. the handoff is so clean โจ-G numโ 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-G numswitch is also passed to the linker. all modules should be compiled with the same-G numvalue. consistency is the moment, don't mix values ๐ฅ-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, do (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 that 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). broad assumption, extra cost, iconic honestly ๐ธ
some linkers are capable of detecting out-of-range calls and generating glue code on the fly. on these 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. future feature loadingโฆ โณ
Okay so picking up right here: 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 tells the compiler to emit 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.
-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 indlopen'dshared 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.-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together.-mtls-markers,-mno-tls-markersโ Mark (do not mark) calls to__tls_get_addrwith a relocation specifying the function argument. The relocation allows the linker to reliably associate function call with argument setup instructions for TLS optimization, which in turn allows GCC to better schedule the sequence.-mrecip,-mno-recipโ This option enables use of the reciprocal estimate and reciprocal square root estimate instructions with additional Newton-Raphson steps to increase precision instead of doing a divide or square root and divide for floating-point arguments. You should use the-ffast-mathoption when using-mrecip(or at least-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math). Note that while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of1.0equals0.99999994) for reciprocal square roots.-mrecip=optโ This option controls which reciprocal estimate instructions may be used. opt is a comma-separated list of options, which may be preceded by a!to invert the option:allโ Enable all estimate instructions.defaultโ Enable the default instructions, equivalent to-mrecip.noneโ Disable all estimate instructions, equivalent to-mno-recip.divโ Enable the 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.
-mrecip-precision,-mno-recip-precisionโ Assume (do not assume) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. Selecting-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precision. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they do not 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 specifies 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 forpower7. 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. The-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. The-mno-save-toc-indirectoption is 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.
The -mno-compat-align-parm option is the default.
-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offset,-mstack-protector-guard-symbol=symbolโ Generate stack protection code using canary at guard. Supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default with GNU libc version2.4or later).
With 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.--param rs6000-vect-unroll-limit=โ The vectorizer will check with target information to determine whether it would be beneficial to unroll the main vectorized loop and by how much. This parameter sets the upper bound of how much the vectorizer will unroll the main loop. The default value is four.
๐ธ RX Options ๐ธ
These command-line options are defined for RX targets:
-m64bit-doubles,-m32bit-doublesโ Make thedoubledata type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles. Note RX floating-point hardware only works on 32-bit values, which is why the default is-m32bit-doubles.-fpu,-nofpuโ Enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series.
Floating-point instructions are only generated for 32-bit floating-point values, however, so the FPU hardware is not used for doubles if the -m64bit-doubles option is used.
๐ heads up bestie: if the-fpuoption is on, then-funsafe-math-optimizationsgets switched on automatically too. Why? Because the RX FPU instructions are literally unsafe themselves. No cap. ๐
-mcpu=nameโ picks which type of RX CPU you're targeting. rn there are three supported: the generic RX600 and RX200 series hardware, plus the specific RX610 CPU. Default is RX600.
The only difference between RX600 and RX610 is that RX610 doesn't support the MVTIPL instruction. That's it, that's the whole tea. ๐ต
The RX200 series has no hardware floating-point unit, so -nofpu is enabled by default when you pick this type.
-mbig-endian-data,-mlittle-endian-dataโ stores data (but not code!! just data) in big-endian format. Default is-mlittle-endian-data, i.e. data goes in little-endian format. ๐-msmall-data-limit=Nโ sets the max size in bytes of global and static variables that can go into the small data area. Using the small data area can give you smaller and faster code, but the area's size is limited and it's on you, the programmer, to make sure it doesn't overflow. Also, when the small data area is used, one of RX's registers (usuallyr13) gets reserved to point at this area, so the compiler can't use it anymore. That could mean slower and/or bigger code if variables end up pushed onto the stack instead of chilling in that register. ๐ญ
Note: common variables (the ones that haven't been initialized) and constants don't go into the small data area, because they get assigned to other sections in the output executable.
Default value is zero, which disables this whole feature. Note: it's not enabled by default with higher optimization levels (-O2 etc) because reserving a register can be potentially detrimental. It's up to the programmer to experiment and discover whether this feature actually benefits their program. See the -mpid option's description for how the actual register holding the small data area pointer gets chosen. ๐
-msim,-mno-simโ use the simulator runtime. Default is to use the libgloss board-specific runtime.-mas100-syntax,-mno-as100-syntaxโ when generating assembler output, use a syntax compatible with Renesas's AS100 assembler. The GAS assembler can handle this syntax too, but it has some restrictions, so it's not generated by default. ๐-mmax-constant-size=Nโ sets the maximum size, in bytes, of a constant that can be used as an operand in an RX instruction. Even though the RX instruction set does allow constants up to 4 bytes long in instructions, a longer value means a longer instruction. So sometimes it's beneficial to restrict the size of constants used in instructions โ constants that are too big get placed into a constant pool instead and referenced via register indirection.
The value N can be between 0 and 4. A value of 0 (the default) or 4 means constants of any size are allowed. โจ
-mrelaxโ enables linker relaxation. Linker relaxation is where the linker tries to shrink your program by finding shorter versions of various instructions. Disabled by default. ๐ฆ-mint-register=Nโ specifies how many registers to reserve for fast interrupt handler functions. N can be between 0 and 4. A value of 1 means registerr13is reserved for the exclusive use of fast interrupt handlers. A value of 2 reservesr13andr12. A value of 3 reservesr13,r12andr11, and a value of 4 reservesr13throughr10. A value of 0, the default, reserves nothing. ๐ซ-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 โ for example because it does 64-bit multiplications. Default is to ignore the accumulator, since that makes the interrupt handlers faster. ๐ฅ-mpid,-mno-pidโ enables generation of position independent data. When it's on, any access to constant data happens via an offset from a base address held in a register. That lets the location of constant data be figured out at run time without needing the executable to be relocated โ a big win for embedded apps with tight memory constraints. Data that can be modified is not affected by this option. ๐
Note: this feature reserves a register, usually r13, for the constant data base address. That can make code slower and/or bigger, especially in complicated functions.
The actual register chosen to hold the constant data base address depends on whether -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register r13 and going downwards, registers get allocated first to satisfy -mint-register, then -mpid, and finally -msmall-data-limit. So it's totally possible for the small data area register to be r8 if both -mint-register=4 and -mpid are specified on the command line. ๐คฏ
By default this feature is off. You can restore the default with the -mno-pid command-line option.
-mno-warn-multiple-fast-interrupts,-mwarn-multiple-fast-interruptsโ stops GCC from throwing a warning if it finds more than one fast interrupt handler while compiling a file. Default is to warn for each extra fast interrupt handler it finds, because RX only supports one such interrupt. ๐-mallow-string-insns,-mno-allow-string-insnsโ enables or disables use of the string manipulation instructionsSMOVF,SCMPU,SMOVB,SMOVU,SUNTIL,SWHILE, and also theRMPAinstruction. 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.) ๐
Default is to allow these instructions, but GCC can't reliably detect every circumstance where a string instruction might be used to access an I/O register, so their use can't be disabled automatically. Instead it relies on the programmer to use -mno-allow-string-insns if their program touches I/O space.
When the instructions are enabled, GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__; otherwise it defines __RX_DISALLOW_STRING_INSNS__. ๐
-mjsr,-mno-jsrโ use only (or not only)JSRinstructions to access functions. You can use this when code size exceeds the range ofBSRinstructions. Note that-mno-jsrdoes not mean "don't useJSR" โ it means any type of branch may be used. ๐
โ ๏ธ Note: the generic GCC command-line option-ffixed-reghas special significance to the RX port when it's used with theinterruptfunction attribute. That attribute marks a function meant to process fast interrupts. GCC makes sure it only uses registersr10,r11,r12and/orr13โ 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. Bestie, these are giving mainframe main character energy. ๐
-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 do the floating-point operations. When-mhard-floatis specified, the compiler generates IEEE floating-point instructions. This is 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 do the 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 thelong doubletype. A size of 64 bits makeslong doubleequivalent todouble. This is the default. ๐-mbackchain,-mno-backchainโ store (or don't store) the address of the caller's frame as a backchain pointer into the callee's stack frame. A backchain may be needed so you can debug with 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 goes into the topmost word of the 96/160 byte register save area. ๐
In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain; but using the backchain for debugging usually requires the whole binary be built with -mbackchain. Note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. 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. 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, letting you use the available stack space more efficiently. 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. ๐ฆ
Okay so, continuing the S/390 and zSeries saga โ as long as the stack frame backchain isn't being used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. ๐ซถ But heads up: 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 โ and that code is not call-compatible with code compiled with -mpacked-stack. Also, 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 that uses 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 doesn't have this limitation.-m64,-m31โ when-m31is specified, generate code compliant to the GNU/Linux for S/390 ABI. When-m64is specified, generate code compliant to the GNU/Linux for zSeries ABI. This lets GCC in particular generate 64-bit instructions. For the s390 targets, the default is-m31, while the s390x targets default to-m64.-mzarch,-mesaโ when-mzarchis specified, generate code using the instructions available on z/Architecture. When-mesais specified, generate code using the instructions available on ESA/390. Note that-mesais not possible with-m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is-mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is-mzarch.-mhtm,-mno-htmโ the-mhtmoption enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions.-mhtmis enabled by default when using-march=zEC12.-mvx,-mno-vxโ when-mvxis specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context, a GAS.gnu_attributecommand will be added to mark the resulting binary with the ABI used.-mvxis enabled by default when using-march=z13.-mzvector,-mno-zvectorโ the-mzvectoroption enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support forvectorto be used as a keyword to define vector type variables and arguments.vectoris only available when GNU extensions are enabled. It will not be expanded when requesting strict standard compliance, e.g. with-std=c99. In addition to the GCC low-level builtins,-mzvectorenables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. In order to make use of these builtins, the header filevecintrin.hneeds to be included.-mzvectoris disabled by default.-mmvcle,-mno-mvcleโ generate (or do not generate) code using the"mvcle"instruction to perform block moves. When-mno-mvcleis specified, use a"mvc"loop instead. This is the default unless optimizing for size.-mdebug,-mno-debugโ print (or do not print) additional debug information when compiling. The default is to not print debug information.- *
-march=cpu-type* โ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. Possible values for cpu-type arez900/arch5,z990/arch6,z9-109,z9-ec/arch7,z10/arch8,z196/arch9,zEC12,z13/arch11,z14/arch12,z15/arch13,z16/arch14, andnative.
The default is -march=z900.
Specifying native as cpu type can be used to select the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
- *
-mtune=cpu-type* โ tune to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions. The list of cpu-type values is the same as for-march. The default is the value used for-march. -mtpf-trace,-mno-tpf-traceโ generate code that adds (does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS.-mtpf-trace-skip,-mno-tpf-trace-skipโ generate code that changes (does not change) the default branch targets enabled by-mtpf-traceto point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying-mtpf-trace.-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used.- *
-mwarn-framesize=framesize* โ emit a warning if the current function exceeds the given frame size. Because this is a compile-time check, it doesn't need to be a real problem when the program runs. It'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 calls"alloca"or uses dynamically-sized arrays. This is generally a bad idea with a limited stack size.- *
-mstack-guard=stack-guard*,-mstack-size=stack-size โ if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows downward ๐). If the stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to 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 function label is prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label,2 * post-halfwordsbytes are appended, using the largest NOP like instructions the architecture allows (maximum 1000000).
If both arguments are zero, hotpatching is disabled.
This option can be overridden for individual functions with the "hotpatch" attribute.
๐ธ SH Options ๐ธ
These -m options are defined for the SH implementations, bestie โ there's a lot of them, so buckle up ๐
-m1โ generate code for the SH1.-m2โ generate code for the SH2.-m2eโ generate code for the SH2e.-m2a-nofpuโ generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.-m2a-single-onlyโ generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.-m2a-singleโ generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.-m2aโ generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.-m3โ generate code for the SH3.-m3eโ generate code for the SH3e.-m4-nofpuโ generate code for the SH4 without a floating-point unit.-m4-single-onlyโ generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.-m4-singleโ generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.-m4โ generate code for the SH4.-m4-100โ generate code for SH4-100.-m4-100-nofpuโ generate code for SH4-100 in such a way that the floating-point unit is not used.-m4-100-singleโ generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.-m4-100-single-onlyโ generate code for SH4-100 in such a way that no double-precision floating-point operations are used.-m4-200โ generate code for SH4-200.-m4-200-nofpuโ generate code for SH4-200 in such a way that the floating-point unit is not used.-m4-200-singleโ generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.-m4-200-single-onlyโ generate code for SH4-200 in such a way that no double-precision floating-point operations are used.-m4-300โ generate code for SH4-300.-m4-300-nofpuโ generate code for SH4-300 in such a way that the floating-point unit is not used.-m4-300-singleโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-300-single-onlyโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-340โ generate code for SH4-340 (no MMU, no FPU).-m4-500โ generate code for SH4-500 (no FPU). Passes-isa=sh4-nofputo the assembler.-m4a-nofpuโ generate code for the SH4al-dsp, or for a SH4a in such a way that the floating-point unit is not used.-m4a-single-onlyโ generate code for the SH4a, in such a way that no double-precision floating-point operations are used.-m4a-singleโ generate code for the SH4a assuming the floating-point unit is in single-precision mode by default.-m4aโ generate code for the SH4a.-m4alโ lowkey the same as-m4a-nofpu, except it sneaks-dspthrough to the assembler for you. And nope, GCC isn't out here generating any DSP instructions at the moment, bestie, it's just passing the flag along. ๐-mbโ compile your code for the processor in big-endian mode. big endian rights โจ-mlโ compile your code for the processor in little-endian mode. tiny endian energy ๐-mdalignโ align doubles at 64-bit boundaries. โ ๏ธ heads up though: this literally changes the calling conventions, so some functions from the standard C library will not work unless you recompile it first with-mdalign. not a drill, recompile your libc first fr fr ๐ญ-mrelaxโ shorten some address references at link time when it's possible; it does this by using the linker option-relax. cuter links, same vibes ๐ฆ-mbigtableโ use 32-bit offsets inswitchtables. the default is 16-bit offsets, so this is you choosing the bigger ~~purse~~ table.-mbitopsโ enable the use of bit manipulation instructions on SH2A. bit-flipping era ๐ฅ-mfmovdโ enable the use of the instructionfmovd. and please go check-mdalignfor the alignment constraints, because alignment drama is real. ๐-mrenesasโ comply with the calling conventions defined by Renesas. respect the house rules ๐-mno-renesasโ comply with the calling conventions defined for GCC before the Renesas conventions were even a thing. this option is the default for all targets of the SH toolchain, so it's giving main character energy by being the standard. ๐-mnomacsaveโ mark theMACregister as call-clobbered, even if-mrenesasis given.MACsaid "don't save me" and we're respecting it. ๐-mieee,-mno-ieeeโ control the IEEE compliance of floating-point comparisons, which affects how we handle the cases where the result of a comparison is unordered. by default-mieeeis implicitly enabled. ๐ but if-ffinite-math-onlyis enabled, then-mno-ieeeis implicitly set, which gives you faster floating-point greater-equal and less-equal comparisons. and both of those implicit settings can be overridden by just specifying either-mieeeor-mno-ieeeyourself. you're in charge, bestie. โจ-minline-ic_invalidateโ inline code to invalidate instruction cache entries after setting up nested function trampolines. this option has no effect if-musermodeis in effect and the selected code generation option (e.g.-m4) does not allow the use of theicbiinstruction. if the selected code generation option doesn't allowicbiand-musermodeis not in effect, then the inlined code manipulates the instruction cache address array directly with an associative write. and that's a whole situation, because it 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. ๐ญ the TLB said "we're done here." ๐-misizeโ dump instruction size and location in the assembly code. little receipts for every instruction, iykyk ๐งพ-mpadstructโ okay so this option is deprecated. it pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. deprecated means move on, bestie, it's not coming back. ๐ฉ-matomic-model=modelโ sets the model of atomic operations and additional parameters as a comma separated list. for the details on the atomic built-in functions, go 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. these generated atomic sequences require additional support from the interrupt/exception handling code of the system, and they're 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 they're only suitable for single-core systems. when using this model, thegbr-offset=parameter has to be specified as well. no skipping it. ๐ซถ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 it's 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 it's suitable for multi-core systems. since the hardware instructions support only 32 bit atomic variables, access to 8 or 16 bit variables is emulated with 32 bit accesses. code compiled with this option is also compatible with other software atomic model interrupt/exception handling systems if executed on an SH4A system. additional support from the interrupt/exception handling code of the system is not required for this model. โจgbr-offset=โ this parameter specifies the offset in bytes of the variable in the thread control block structure that should be used by the generated atomic sequences when thesoft-tcbmodel has been selected. for other models this parameter is ignored. the specified value must be an integer multiple of four and in the range 0-1020. rules are rules ๐strictโ this parameter prevents mixed usage of multiple atomic models, even if they are compatible, and makes the compiler generate atomic sequences of the specified model only. no blending, no mixing, one model only. periodt. ๐
-mtasโ generate thetas.bopcode for__atomic_test_and_set. โ ๏ธ but notice: depending on the particular hardware and software configuration, this can degrade overall performance due to the operand cache line flushes that are implied by thetas.binstruction. and on multi-core SH4A processors thetas.binstruction must be used with caution since it can result in data corruption for certain cache configurations. data corruption is not the vibe, be careful out there ๐ญ๐-mprefergotโ when generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table. GOT > PLT for this one specific situation, and that's that. ๐ฆ-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*. and if the target is SH1* or SH2*,-musermodehas no effect, since there is no user mode. there's just nothing to switch to, bestie. ๐ซ-multcost=numberโ set the cost to assume for a multiply insn. one number, one multiply, one cost. โญ-mdiv=strategyโ set the division strategy to be used for integer division operations.strategycan be one of:call-div1โ calls a library function that uses the single-step division instructiondiv1to perform the operation. division by zero calculates an unspecified result and does not trap. this is the default except for SH4, SH2A and SHcompact.call-fpโ calls a library function that performs the operation in double precision floating point. division by zero causes a floating-point exception. this is the default for SHcompact with FPU. specifying this for targets that do not have a double precision FPU defaults tocall-div1. ๐call-tableโ calls a library function that uses a lookup table for small divisors and thediv1instruction with case distinction for larger divisors. division by zero calculates an unspecified result and does not trap. this is the default for SH4. specifying this for targets that do not have dynamic shift instructions defaults tocall-div1.
when a division strategy has not been specified, the default strategy is selected based on the current target. for SH2A the default strategy is to use the divs and divu instructions instead of library function calls. no library, just vibes and instructions. ๐ฅ
-maccumulate-outgoing-argsโ reserve space once for outgoing arguments in the function prologue rather than around each call. generally beneficial for performance and size. it's also needed for unwinding to avoid changing the stack frame around conditional code. efficiency icon ๐-mdivsi3_libfunc=nameโ set the name of the library function used for 32-bit signed division toname. this only affects the name used in the call division strategies, and the compiler still expects the same sets of input/output/clobbered registers as if this option were not present. so rename all you want, the register contract stays. ๐-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. hands off those registers, allocator. โ-mbranch-cost=numโ assumenumto be the cost for a branch instruction. higher numbers make the compiler try to generate more branch-free code if possible. if not specified, the value is selected depending on the processor type that is being compiled for. pick a number, any number (but pick it deliberately) โญ-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, and 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. bugs are not the moment, but the workaround is ๐ญ-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. ๐ข and here's the 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 old flags are still hanging around like a loyal bestie ๐ซถ-mfsca,-mno-fscaโ lets you green-light (or hard no) the compiler emitting the"fsca"instruction for sine and cosine approximations โจ heads up tho:-mfscaonly works with-funsafe-math-optimizations, they're a package deal. It's on by default when you're generating code for SH4A. And-mno-fscakills the sine/cosine approximations even if-funsafe-math-optimizationsis literally right there in effect ๐ซถ-mfsrra,-mno-fsrraโ same vibe but for the"fsrra"instruction, aka reciprocal square root approximations ๐ the catch:-mfsrrahas to be used in combination with-funsafe-math-optimizationsand-ffinite-math-only. Enabled by default when generating code for SH4A.-mno-fsrradisables reciprocal square root approximations even if-funsafe-math-optimizationsand-ffinite-math-onlyare both in effect, no cap.-mpretend-cmoveโ prefers zero-displacement conditional branches for conditional move instruction patterns ๐ฆ and yeah, this can result in faster code on the SH4 processor. slay.-mfdpicโ generate code using the FDPIC ABI ๐
๐ธ Solaris 2 Options ๐ธ
These -m options are supported on Solaris 2:
-mclear-hwcapโ-mclear-hwcaptells the compiler to remove the hardware capabilities generated by the Solaris assembler ๐ this is only necessary when object files use ISA extensions not supported by the current machine, but check at runtime whether or not to use them.-mimpure-textโ-mimpure-text, used in addition to-shared, tells the compiler to not pass-z textto the linker when linking a shared object. Using this option, you can link position-dependent code into a shared object.
-mimpure-text suppresses the "relocations remain against allocatable but non-writable sections" linker error message. However, the necessary relocations trigger copy-on-write, and the shared object is not actually shared across processes ๐ญ instead of using -mimpure-text, you should compile all source code with -fpic or -fPIC. fr fr, listen to the manpage on this one.
These switches are supported in addition to the above on Solaris 2:
-pthreadsโ this is a synonym for-pthread๐
โญ SPARC Options โญ
These -m options are supported on the SPARC:
-mno-app-regs,-mapp-regsโ specify-mapp-regsto generate output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications ๐ like the global register 1, each global register 2 through 4 is then treated as an allocable register that is clobbered by function calls. This is the default.
To be fully SVR4 ABI-compliant at the cost of some performance loss, specify -mno-app-regs. You should compile libraries and system software with this option ๐ซก
-mflat,-mno-flatโ with-mflat, the compiler does not generate save/restore instructions and uses a"flat"or single register window model ๐ this model is compatible with the regular register window model. The local registers and the input registers (0--5) are still treated as"call-saved"registers and are saved on the stack as needed.
With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode ๐
-mfpu,-mhard-floatโ generate output containing floating-point instructions. This is the default โจ-mno-fpu,-msoft-floatโ generate output containing library calls for floating point.
โ ๏ธ Warning: the requisite libraries are not available for all SPARC targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. The embedded targetssparc-*-aoutandsparclite-*-*do provide software floating-point support.
-msoft-float changes the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option ๐ญ in particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float in order for this to work. all of it. no half-measures.
-mhard-quad-floatโ generate output containing quad-word (long double) floating-point instructions ๐ฅ-msoft-quad-floatโ generate output containing library calls for quad-word (long double) floating-point instructions. The functions called are those specified in the SPARC ABI. This is the default.
As of this writing, there are no SPARC implementations that have hardware support for the quad-word floating-point instructions ๐ they all invoke a trap handler for one of these instructions, and then the trap handler emulates the effect of the instruction. Because of the trap handler overhead, this is much slower than calling the ABI library routines. Thus the -msoft-quad-float option is the default. makes sense, honestly.
-mno-unaligned-doubles,-munaligned-doublesโ assume that doubles have 8-byte alignment. This is the default ๐
With -munaligned-doubles, GCC assumes that doubles have 8-byte alignment only if they are contained in another type, or if they have an absolute address. Otherwise, it assumes they have 4-byte alignment. Specifying this option avoids some rare compatibility problems with code generated by other compilers. It is not the default because it results in a performance loss, especially for floating-point code ๐
-muser-mode,-mno-user-modeโ do not generate code that can only run in supervisor mode. This is relevant only for the"casa"instruction emitted for the LEON3 processor. This is the default ๐ฆ-mfaster-structs,-mno-faster-structsโ with-mfaster-structs, the compiler assumes that structures should have 8-byte alignment โจ this enables the use of pairs of"ldd"and"std"instructions for copies in structure assignment, in place of twice as many"ld"and"st"pairs. However, the use of this changed alignment directly violates the SPARC ABI ๐ฌ thus, it's intended only for use on targets where the developer acknowledges that their resulting code is not directly in line with the rules of the ABI. you've been warned, bestie.-mstd-struct-return,-mno-std-struct-returnโ with-mstd-struct-return, the compiler generates checking code in functions returning structures or unions to detect size mismatches between the two sides of function calls, as per the 32-bit ABI ๐
The default is -mno-std-struct-return. This option has no effect in 64-bit mode.
-mlra,-mno-lraโ enable Local Register Allocation. This is the default for SPARC since GCC 7 so-mno-lraneeds to be passed to get old Reload ๐ vintage behavior unlocked, i guess.-mcpu=cpu_type โ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type arev7,cypress,v8,supersparc,hypersparc,leon,leon3,leon3v7,leon5,sparclite,f930,f934,sparclite86x,sparclet,tsc701,v9,ultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7andm8๐
Native Solaris and GNU/Linux toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor ๐
Default instruction scheduling parameters are used for values that select an architecture and not an implementation. These are v7, v8, sparclite, sparclet, v9.
Here is a list of each supported architecture and their supported implementations ๐
v7โcypress,leon3v7v8โsupersparc,hypersparc,leon,leon3,leon5sparcliteโf930,f934,sparclite86xsparcletโtsc701v9โultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7,m8
By default (unless configured otherwise), GCC generates code for the V7 variant of the SPARC architecture ๐ with -mcpu=cypress, the compiler additionally optimizes it for the Cypress CY7C602 chip, as used in the SPARCStation/SPARCServer 3xx series. This is also appropriate for the older SPARCStation 1, 2, IPX etc.
With -mcpu=v8, GCC generates code for the V8 variant of the SPARC architecture. The only difference from V7 code is that the compiler emits the integer multiply and integer divide instructions which exist in SPARC-V8 but not in SPARC-V7 โจ with -mcpu=supersparc, the compiler additionally optimizes it for the SuperSPARC chip, as used in the SPARCStation 10, 1000 and 2000 series.
With -mcpu=sparclite, GCC generates code for the SPARClite variant of the SPARC architecture. This adds the integer multiply, integer divide step and scan ("ffs") instructions which exist in SPARClite but not in SPARC-V7 ๐ฅ with -mcpu=f930, the compiler additionally optimizes it for the Fujitsu MB86930 chip, which is the original SPARClite, with no FPU. With -mcpu=f934, the compiler additionally optimizes it for the Fujitsu MB86934 chip, which is the more recent SPARClite with FPU.
With -mcpu=sparclet, GCC generates code for the SPARClet variant of the SPARC architecture. This adds the integer multiply, multiply/accumulate, integer divide step and scan ("ffs") instructions which exist in SPARClet but not in SPARC-V7 ๐
with -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip.
With -mcpu=v9, GCC generates code for the V9 variant of the SPARC architecture. This adds 64-bit integer and floating-point move instructions, 3 additional floating-point condition code registers and conditional move instructions ๐ with -mcpu=ultrasparc, the compiler additionally optimizes it for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, the compiler additionally optimizes it for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, the compiler additionally optimizes it for Sun UltraSPARC T1 chips. With -mcpu=niagara2, the compiler additionally optimizes it for Sun UltraSPARC T2 chips. With -mcpu=niagara3, the compiler additionally optimizes it for Sun UltraSPARC T3 chips. With -mcpu=niagara4, the compiler additionally optimizes it for Sun UltraSPARC T4 chips. With -mcpu=niagara7, the compiler additionally optimizes it for Oracle SPARC M7 chips. With -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips ๐
-mtune=cpu_typeโ okay so this one tunes how instructions get scheduled for cpu_type, but it does not touch the instruction set or register set like-mcpu=cpu_typedoes. Same value list as-mcpu=cpu_type, but ngl only the ones that pick an actual CPU implementation are useful, and those are:cypress,supersparc,hypersparc,leon,leon3,leon3v7,leon5,f930,f934,sparclite86x,tsc701,ultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7andm8. With native Solaris and GNU/Linux toolchains you can also usenative. ๐-mv8plus,-mno-v8plusโ with-mv8plus, GCC spits out code for the SPARC-V8+ ABI. The glow-up vs. the V8 ABI? Global and out registers are considered 64 bits wide. Default-on for Solaris in 32-bit mode for all SPARC-V9 processors, periodt. โจ-mvis,-mno-visโ-mvislets GCC generate code that takes advantage of the UltraSPARC Visual Instruction Set extensions. Default is-mno-vis(soz, off by default bestie).-mvis2,-mno-vis2โ-mvis2= version 2.0 of the UltraSPARC Visual Instruction Set extensions, slay. Default is-mvis2when you're targeting a cpu that supports these instructions, like UltraSPARC-III and later. Setting-mvis2also sets-mvis. ๐ซถ-mvis3,-mno-vis3โ-mvis3= version 3.0 of the UltraSPARC Visual Instruction Set extensions. Default is-mvis3when the cpu supports them, like niagara-3 and later. Setting-mvis3also sets-mvis2and-mvis. ๐ฅ-mvis4,-mno-vis4โ-mvis4= version 4.0 of the UltraSPARC Visual Instruction Set extensions. Default is-mvis4when the cpu supports them, like niagara-7 and later. Setting-mvis4also sets-mvis3,-mvis2and-mvis. ๐-mvis4b,-mno-vis4bโ-mvis4b= version 4.0 of the UltraSPARC Visual Instruction Set extensions plus the extra VIS instructions introduced in the Oracle SPARC Architecture 2017. Default is-mvis4bwhen the cpu supports them, like m8 and later. Setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvis. ๐-mcbcond,-mno-cbcondโ with-mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. Default is-mcbcondwhen targeting a CPU that supports them, like Niagara-4 and later. ๐-mfmaf,-mno-fmafโ with-mfmaf, GCC generates code that takes advantage of the UltraSPARC Fused Multiply-Add Floating-point instructions. Default is-mfmafwhen targeting a CPU that supports them, like Niagara-3 and later. ๐-mfsmuld,-mno-fsmuldโ with-mfsmuld, GCC generates code that takes advantage of the Floating-point Multiply Single to Double (FsMULd) instruction. Default is-mfsmuldwhen targeting a CPU supporting architecture versions V8 or V9 with FPU โ but not-mcpu=leon. ๐-mpopc,-mno-popcโ with-mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. Default is-mpopcwhen targeting a CPU that supports it, like Niagara-2 and later. โญ-msubxc,-mno-subxcโ with-msubxc, GCC generates code that takes advantage of the UltraSPARC Subtract-Extended-with-Carry instruction. Default is-msubxcwhen targeting a CPU that supports it, like Niagara-7 and later. ๐-mfix-at697fโ turns on the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). ๐-mfix-ut699โ turns on the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.-mfix-ut700โ turns on the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ turns on the documented workaround for the back-to-back store errata of the GR712RC processor. ๐ฆ
So these -m options are supported in addition to all the ones above on SPARC-V9 processors in 64-bit environments, iykyk:
-m32,-m64โ generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. ๐ธ-mcmodel=whichโ set the code model to one of:medlowโ the Medium/Low code model: 64-bit addresses, programs must be linked in the low 32 bits of memory. Programs can be statically or dynamically linked.medmidโ the Medium/Middle code model: 64-bit addresses, programs must be linked in the low 44 bits of memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.medanyโ the Medium/Anywhere code model: 64-bit addresses, programs may be linked anywhere in memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.embmedanyโ the Medium/Anywhere code model for embedded systems: 64-bit addresses, the text and data segments must be less than 2GB in size, both starting anywhere in memory (determined at link time). The global register%g4points to the base of the data segment. Programs are statically linked and PIC is not supported. ๐
-mmemory-model=mem-modelโ set the memory model in force on the processor to one of:defaultโ the default memory model for the processor and operating system.rmoโ Relaxed Memory Orderpsoโ Partial Store Ordertsoโ Total Store Orderscโ Sequential Consistency
These memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's PSTATE.MM field. ๐
-mstack-bias,-mno-stack-biasโ with-mstack-bias, GCC assumes the stack pointer (and frame pointer if present) are offset by-2047, which must be added back when making stack frame references. This is the default in 64-bit mode. Otherwise, assume no such offset is present. โจ
๐ Options for System V ๐
These extra options are available on System V Release 4 for compatibility with other compilers on those systems, bestie:
-Gโ create a shared object. It is recommended that-symbolicor-sharedbe used instead (so like, lowkey deprecated vibes).-Qyโ identify the versions of each tool used by the compiler, in a.identassembler directive in the output.-Qnโ refrain from adding.identdirectives to the output file (this is the default).-YP,dirsโ search the directories dirs, and no others, for libraries specified with-l.-Ym,dirโ look in the directory dir to find the M4 preprocessor. The assembler uses this option. ๐
๐ฆ V850 Options ๐ฆ
These -m options are defined for V850 implementations, no cap:
-mlong-calls,-mno-long-callsโ treat all calls as being far away (near). If calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer. ๐ฅ-mno-ep,-mepโ do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into theepregister, and use the shortersldandsstinstructions. The-mepoption is on by default if you optimize. ๐-mno-prolog-function,-mprolog-functionโ do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. The external functions are slower, but use less code space if more than one function saves the same number of registers. The-mprolog-functionoption is on by default if you optimize. ๐ซถ-mspaceโ try to make the code as small as possible. At present, this just turns on the-mepand-mprolog-functionoptions. ๐-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, it's giving copy-paste energy, but that's literally what the docs say ๐)-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. ๐ธ
Heads up bestie: if neither-mv850nor-mv850enor-mv850e1nor-mv850e2nor-mv850e2v3nor-mv850e3v5are defined, then a default target processor is chosen and the relevant__v850*__preprocessor constant is defined. And the preprocessor constants__v850and__v851__are always defined, regardless of which processor variant is the target. ๐
-mdisable-callt,-mno-disable-calltโ this option suppresses generation of theCALLTinstruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture. ๐
This one's on by default when the RH850 ABI is in use (peep -mrh850-abi), and off by default when the GCC ABI is in use. And if CALLT instructions are being generated, the C preprocessor symbol __V850_CALLT__ gets defined. ๐
-mrelax,-mno-relaxโ passes on (or doesn't pass on) the-mrelaxcommand-line option to the assembler.-mlong-jumps,-mno-long-jumpsโ disables (or re-enables) generation of PC-relative jump instructions.-msoft-float,-mhard-floatโ disables (or re-enables) generation of hardware floating point instructions. Only significant when the target architecture is V850E2V3 or higher. If hardware floating point instructions are being generated then the C preprocessor symbol__FPU_OK__is defined, otherwise__NO_FPU__is defined. ๐ซถ-mloopโ enables the use of the e3v5LOOPinstruction. Not enabled by default when the e3v5 architecture is selected, because its use is still experimental. ๐-mrh850-abi,-mghsโ enables support for the RH850 version of the V850 ABI. This is the default. With this version of the ABI, these rules apply:- Integer sized structures and unions are returned via a memory pointer rather than a register.
- Large structures and unions (more than 8 bytes in size) are passed by value.
- Functions are aligned to 16-bit boundaries.
- The
-m8byte-aligncommand-line option is supported. - The
-mdisable-calltcommand-line option is enabled by default. The-mno-disable-calltcommand-line option is not supported. When this version of the ABI is enabled, the C preprocessor symbol__V850_RH850_ABI__is defined.
-mgcc-abiโ enables support for the old GCC version of the V850 ABI. With this version, these rules apply:- Integer sized structures and unions are returned in register
r10. - Large structures and unions (more than 8 bytes in size) are passed by reference.
- Functions are aligned to 32-bit boundaries, unless optimizing for size.
- The
-m8byte-aligncommand-line option is not supported. - The
-mdisable-calltcommand-line option is supported but not enabled by default. When this version of the ABI is enabled, the C preprocessor symbol__V850_GCC_ABI__is defined.
- Integer sized structures and unions are returned in register
-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. Only use this if the assembler/linker complain about out of range branches within a switch table. ๐-mapp-regsโ this one makes r2 and r5 get used in the code the compiler generates. This setting is the default.-mno-app-regsโ this one makes r2 and r5 be treated as fixed registers.
๐ VAX Options ๐
These -m options are defined for the VAX:
-munixโ do not output certain jump instructions (aobleqand so on) that the Unix assembler for the VAX cannot handle across long ranges.-mgnuโ do output those jump instructions, on the assumption that the GNU assembler is being used.-mgโ output code for G-format floating-point numbers instead of D-format.-mlra,-mno-lraโ enable Local Register Allocation. This is still experimental for the VAX, so by default the compiler uses standard reload. ๐ง
๐ฆ Visium Options ๐ฆ
-mdebugโ a program that does 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 does file I/O and is destined to run on the simulator should be linked with this 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.
Bestie, listen:-msoft-floatchanges 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 compilelibgcc.a(the library that comes with GCC) with-msoft-floatfor this to work. No cap. ๐จ
- *
-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.mcmis a synonym ofgr5, 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. 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-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 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. That last 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're 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. Buckle up, bestie, there's a lot of them. ๐
-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 lets GCC 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โ 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 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, and the instruction set support is: MMX, SSE, SSE2, SSE3, FXSR. Vintage, but she still serves ๐
๐ธ core2
Intel Core 2 CPU, 64-bit extensions, bringing MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF, FXSR instruction set support. The CPU that raised a whole generation of nerds, honestly ๐ซถ
๐ฆ nehalem, corei7
Both names, same girl โจ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support. That's MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR โ iconic.
๐ westmere
Intel Westmere CPU with 64-bit extensions and MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL instruction set support. She said "add PCLMUL" and honestly? slay.
๐ sandybridge, corei7-avx
Two aliases, one vibe ๐ Intel Sandy Bridge CPU with 64-bit extensions and MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL instruction set support. AVX walked in and everything changed, periodt.
โญ 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 โ so: MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C. Bestie she is stacked ๐ง
๐ฅ haswell, core-avx2
Intel Haswell CPU with 64-bit extensions, and the full support list is 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. AVX2 debut, we were all gagged ๐ญ
๐ 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, PREFETCHW instruction set support. Yes, MOVBE shows up twice in there โ that's what the list says, don't come for me ๐
๐ซ 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, SGX instruction set support. Main character energy, lowkey the default for a whole era โญ
๐ฆ skylake-avx512
Intel Skylake Server CPU with 64-bit extensions, and the list just keeps going bestie: MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD instruction set support. The AVX-512 era begins ๐โจ
๐ธ 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, AVX512VNNI instruction set support. Basically Skylake-AVX512 but with AVX512VNNI, and we love an upgrade ๐
๐ cannonlake
Intel Cannon Lake Server CPU with 64-bit extensions, supporting 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. New friends: PKU, AVX512VBMI, AVX512IFMA, SHA ๐ซถ
๐ cooperlake
Intel Cooper Lake CPU with 64-bit extensions and 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, AVX512BF16 instruction set support. AVX512BF16 said hi ๐ฅ
๐ง icelake-client
Intel Ice Lake Client CPU with 64-bit extensions, supporting 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. That list is a whole personality and I respect it ๐ญ
๐ธ 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, CLWB. Server edition, extra toppings, no notes ๐
๐ tigerlake
Intel Tiger Lake CPU with 64-bit extensions and 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, KEYLOCKER instruction set support. Yes AVX512VP2INTERSECT is a real name, I didn't make it up ๐
โญ 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, AVX512VPOPCNTDQ instruction set support. Note she's the desktop one, no SGX here ๐ซถ
๐ alderlake, raptorlake, meteorlake
Three names, one CPU family ๐ Intel Alder Lake/Raptor Lake/Meteor Lake CPU with 64-bit extensions and 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, AVX-VNNI instruction set support. Hybrid era, ate and left no crumbs.
๐ sapphirerapids, emeraldrapids
Both aliases, same giant flex โจ Intel Sapphire Rapids/Emerald Rapids CPU with 64-bit extensions, supporting MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16, AVX512BF16. AMX has entered the chat ๐
๐ง graniterapids
Intel Granite Rapids CPU with 64-bit extensions: MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16, AVX512BF16, AMX-FP16, PREFETCHI instruction set support. AMX-FP16 and PREFETCHI are the new girls ๐
๐ฆ graniterapids-d
Intel Granite Rapids D CPU with 64-bit extensions, and yes there's one more at the end: MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512FP16, AVX512BF16, AMX-FP16, PREFETCHI, AMX-COMPLEX instruction set support. AMX-COMPLEX really said "and one more thing" ๐ญ
๐ bonnell, atom
Intel Bonnell CPU with 64-bit extensions, keeping it cute and small with MOVBE, MMX, SSE, SSE2, SSE3, SSSE3 instruction set support. Netbook legend, lowkey iconic ๐
๐ธ silvermont, slm
Intel Silvermont CPU with 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND instruction set support. Tiny chip, big try ๐ซถ
โญ 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, FSGSBASE instruction set support. Look at her go, she's got XSAVE now ๐
๐ goldmont-plus
Intel Goldmont Plus CPU with 64-bit extensions, supporting 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. The "plus" is PTWRITE, RDPID and SGX, and she earned them โจ
๐ฅ 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, WAITPKG instruction set support. The low-power one with the longest list, honestly rude of her ๐
sierraforestโ Intel Sierra Forest CPU, and she's got 64-bit extensions plus an entire buffet of instruction set support:MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PREFETCHW,PCLMUL,RDRND,XSAVE,XSAVEC,XSAVES,XSAVEOPT,FSGSBASE,PTWRITE,RDPID,SGX,GFNI-SSE,CLWB,MOVDIRI,MOVDIR64B,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKL,AVX-VNNI,AVXIFMA,AVXVNNIINT8,AVXNECONVERT,CMPCCXADD,ENQCMDandUINTR. like. that's the whole list bestie, no crumbs left ๐grandridgeโ Intel Grand Ridge CPU, 64-bit extensions, and honestly the exact same flex as above:MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PREFETCHW,PCLMUL,RDRND,XSAVE,XSAVEC,XSAVES,XSAVEOPT,FSGSBASE,PTWRITE,RDPID,SGX,GFNI-SSE,CLWB,MOVDIRI,MOVDIR64B,CLDEMOTE,WAITPKG,ADCX,AVX,AVX2,BMI,BMI2,F16C,FMA,LZCNT,PCONFIG,PKU,VAES,VPCLMULQDQ,SERIALIZE,HRESET,KL,WIDEKL,AVX-VNNI,AVXIFMA,AVXVNNIINT8,AVXNECONVERT,CMPCCXADD,ENQCMDandUINTRinstruction set support. twin energy fr ๐ซถknlโ Intel Knights Landing CPU. 64-bit extensions and:MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,AVX,XSAVE,PCLMUL,FSGSBASE,RDRND,F16C,AVX2,BMI,BMI2,LZCNT,FMA,MOVBE,HLE,RDSEED,ADCX,PREFETCHW,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1instruction set support. (yesMOVBEshows up twice in the list, don't @ me, that's literally what it says ๐ญ)knmโ Intel Knights Mill CPU. 64-bit extensions plus:MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,CX16,SAHF,FXSR,AVX,XSAVE,PCLMUL,FSGSBASE,RDRND,F16C,AVX2,BMI,BMI2,LZCNT,FMA,MOVBE,HLE,RDSEED,ADCX,PREFETCHW,AVX512PF,AVX512ER,AVX512F,AVX512CDandPREFETCHWT1,AVX5124VNNIW,AVX5124FMAPSandAVX512VPOPCNTDQinstruction set support. she's got extras โจk6โ AMD K6 CPU, MMX instruction set support. vintage but cute ๐k6-2,k6-3โ improved versions of the AMD K6 CPU withMMXand3DNow!instruction set support. glow-up szn ๐ธathlon,athlon-tbirdโ AMD Athlon CPU, rockingMMX,3dNOW!, enhanced3DNow!andSSEprefetch instructions support.athlon-4,athlon-xp,athlon-mpโ improved AMD Athlon CPU withMMX,3DNow!, enhanced3DNow!and the fullSSEinstruction set support. the way she ate ๐k8,opteron,athlon64,athlon-fxโ processors built on the AMD K8 core with x86-64 instruction set support, and that includes the AMD Opteron, Athlon 64, and Athlon 64 FX processors. (bestie, this supersetsMMX,SSE,SSE2,3DNow!, enhanced3DNow!and 64-bit instruction set extensions.) ๐k8-sse3,opteron-sse3,athlon64-sse3โ improved versions of AMD K8 cores, now withSSE3instruction set support. upgrade era ๐ฆamdfam10,barcelonaโ CPUs based on AMD Family 10h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSE4A,3DNow!, enhanced3DNow!,ABMand 64-bit instruction set extensions.)bdver1โ CPUs based on AMD Family 15h cores with x86-64 instruction set support. (This supersetsFMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver2โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,AVX2,XOP,LWP,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)znver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT, and 64-bit instruction set extensions.) ๐งznver2โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD, and 64-bit instruction set extensions.)znver3โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES, and 64-bit instruction set extensions.)znver4โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNIand 64-bit instruction set extensions.) the AVX512 arc, iconic ๐ฅznver5โ AMD Family 1ah core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,CLWB,F16C,FMA,FSGSBASE,AVX,AVX2,ADCX,RDSEED,MWAITX,SHA,CLZERO,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABM,XSAVEC,XSAVES,CLFLUSHOPT,POPCNT,RDPID,WBNOINVD,PKU,VPCLMULQDQ,VAES,AVX512F,AVX512DQ,AVX512IFMA,AVX512CD,AVX512BW,AVX512VL,AVX512BF16,AVX512VBMI,AVX512VBMI2,AVX512VNNI,AVX512BITALG,AVX512VPOPCNTDQ,GFNI,AVXVNNI,MOVDIRI,MOVDIR64B,AVX512VP2INTERSECT,PREFETCHIand 64-bit instruction set extensions.) newest gen, main character energy ๐btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSSE3,SSE4A,CX16,ABMand 64-bit instruction set extensions.)btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This one includesMOVBE,F16C,BMI,AVX,PCLMUL,AES,SSE4.2,SSE4.1,CX16,ABM,SSE4A,SSSE3,SSE3,SSE2,SSE,MMXand 64-bit instruction set extensions. (note: "includes" this time, not "supersets" โ read the room ๐)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.)
ok the "no scheduling is implemented for this chip" note is lowkey doing a lot of heavy lifting in this VIA section โ it's a real caveat, not a vibe, so don't expect fancy instruction scheduling for any of these ๐ฅฒ
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.) two cores, zero scheduling, we love consistency ๐nano-x4โ VIA Nano Quad Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.)lujiazuiโ ZHAOXIN lujiazui CPU with x86-64,MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,AES,PCLMUL,RDRND,XSAVE,XSAVEOPT,FSGSBASE,CX16,ABM,BMI,BMI2,FXSR,RDSEEDinstruction set support. While the CPUs do supportAVXandF16C, these aren't enabled by-march=lujiazuifor performance reasons. ๐ (yes bestie, they exist and they're deliberately gated โ that's the note, don't come for me)geodeโ AMD Geode embedded processor withMMXand3DNow!instruction set support. tiny legend ๐-mtune=cpu-typeโ tunes literally everything applicable about the generated code to cpu-type, except the ABI and the set of available instructions ๐ . So like, picking a specific cpu-type schedules things appropriately for that particular chip, but the compiler does not generate any code that can't run on the default machine type unless you also use a-march=cpu-typeoption. Example bestie: 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 ๐.
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 ๐.
-mcpu=cpu-typeโ a deprecated synonym for-mtune๐. Like, it still works but it's giving "old news", yk? Use-mtuneinstead, bestie ๐.-mfpmath=unitโ generate floating-point arithmetic for selected unit unit ๐ . The choices for unit are:387โ use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise ๐ง. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See-ffloat-storefor more detailed description โญ.
This is the default choice for non-Darwin x86-32 targets ๐.
sseโ use scalar floating-point instructions present in the SSE instruction set ๐ธ. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using 387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too ๐.
For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option effective. For the x86-64 compiler, these extensions are enabled by default ๐ซถ.
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 ๐ญ. (Yeah, that's the tradeoff, bestie.)
This is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled โจ.
sse,387/sse+387/bothโ attempt to utilize both instruction sets at once ๐ฅ. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE the execution resources too. Use this option with care, as it is still experimental, because the GCC register allocator does not model separate functional units well, resulting in unstable performance ๐. No cap, it's giving "handle with care" energy.
-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 โจ. Iconic little optimization, ngl.
"stdcall"โ slaps the stdcall calling sequence onto one specific function (function attribute energy). And if you're feeling rebellious, you can override-mrtdby hitting it with the"cdecl"attribute instead.
โ ๏ธ Warning: this calling convention does not vibe with the one normally used on Unix, so you literally cannot use it if you need to call libraries compiled with the Unix compiler. Like, at all. No cap.
Also โ and this is important, bestie โ you must provide function prototypes for all functions that take a variable number of arguments (yes, that includes "printf"), otherwise GCC generates straight-up incorrect code for calls to those functions. ๐
And on top of that? You get seriously incorrect code if you call a function with too many arguments. (Normally extra arguments are harmlessly ignored, so yeah, this is the one case where it bites.)
-mregparm=numโ controls how many registers get used to pass integer arguments. Default is zero registers passed, and you can push it to at most 3 registers. Want to control this for one specific function instead? Use the"regparm"function attribute.
โ ๏ธ Warning: if you use this switch and num is nonzero, then every single module has to be built with the same value โ libraries included. That means system libraries and startup modules too, no exceptions. ๐ซถ
-msseregparmโ uses SSE register passing conventions forfloatanddoublearguments and return values. Fine-tune it per-function with the"sseregparm"function attribute.
โ ๏ธ Warning: same deal โ use this switch and all modules must be built with the same value, libraries and all. System libraries and startup modules included. ๐
-mvect8-ret-in-memโ returns 8-byte vectors in memory instead of in MMX registers. This is the default on VxWorks so it matches the ABI of the Sun Studio compilers up to version 12. Only reach for this option if you genuinely need to stay compatible with existing code produced by those previous compiler versions or older versions of GCC. Legacy-compat obligations only, iykyk.-mpc32,-mpc64,-mpc80โ sets 80387 floating-point precision to 32, 64 or 80 bits respectively. The details, because they matter:-mpc32rounds the significands of floating-point operation results to 24 bits (single precision).-mpc64rounds them to 53 bits (double precision).-mpc80rounds them to 64 bits (extended double precision) โ and that's the default.
When you use this option, floating-point operations in higher precisions are not available to the programmer unless you set the FPU control word explicitly. โจ
Setting rounding to less than the default 80 bits can speed some programs up by 2% or more ๐ฅ โ but heads up: some mathematical libraries assume that extended-precision (80-bit) floating-point operations are enabled by default. Routines in those libraries could suffer significant loss of accuracy when this option sets precision below extended precision, typically through the so-called "catastrophic cancellation". So yeah, know what you're doing.
-mdaz-ftzโ the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register control floating-point calculations. SSE and AVX instructions, including scalar and vector instructions, can benefit from enabling the FTZ and DAZ flags when-mdaz-ftzis specified. Don't set the FTZ/DAZ flags when-mno-daz-ftzor-sharedis specified โ oh, and-mdaz-ftzwill set FTZ/DAZ flags even with-shared. Yeah, we said both. That's the whole bit. ๐ญ-mstackrealignโ realigns the stack at entry. On the x86,-mstackrealigngenerates an alternate prologue and epilogue that realigns the run-time stack whenever it's necessary. This is how you mix legacy code that keeps 4-byte stack alignment together with modern code that keeps 16-byte stack alignment for SSE compatibility. Also peep the"force_align_arg_pointer"attribute โ that one works per-function. ๐ง-mpreferred-stack-boundary=numโ tries to keep the stack boundary aligned to a 2 raised to num byte boundary. If-mpreferred-stack-boundaryisn't specified, the default is4(16 bytes, a.k.a. 128 bits).
โ ๏ธ Warning: when generating code for the x86-64 architecture with SSE extensions disabled, you can use-mpreferred-stack-boundary=3to keep the stack boundary aligned to an 8 byte boundary. Since the x86-64 ABI requires 16 byte stack alignment, this is ABI incompatible and only meant for controlled environments where stack space is an important limitation. This option leads to wrong code when functions compiled with 16 byte stack alignment (like functions from a standard library) are called with a misaligned stack โ and in that case, SSE instructions may lead to misaligned memory access traps. Also, variable arguments are handled incorrectly for 16 byte aligned objects (including x87long doubleand__int128), which gives you wrong results. You must build all modules with-mpreferred-stack-boundary=3, libraries included โ system libraries and startup modules too. ๐
-mincoming-stack-boundary=numโ assumes the incoming stack is aligned to a 2 raised to num byte boundary. If-mincoming-stack-boundaryisn't specified, the one specified by-mpreferred-stack-boundaryis used.
On Pentium and Pentium Pro, "double" and "long double" values should be aligned to an 8-byte boundary (see -malign-double) or they suffer significant run time performance penalties. On Pentium III, the Streaming SIMD Extension (SSE) data type "__m128" may not work properly if it isn't 16-byte aligned.
To make sure these values are properly aligned on the stack, the stack boundary has to be at least as aligned as anything stored on the stack requires. And every function must be generated so it keeps the stack aligned. So calling a function compiled with a higher preferred stack boundary from a function compiled with a lower preferred stack boundary most likely misaligns the stack. Recommendation: libraries that use callbacks should always just use the default setting. ๐
This extra alignment does eat extra stack space and generally increases code size. Code that's sensitive to stack space usage โ embedded systems and operating system kernels, we're looking at you โ may want to reduce the preferred alignment to -mpreferred-stack-boundary=2.
- Here's the big one, the extended-instruction-set buffet ๐ โ each of these switches enables use of instructions in the corresponding set:
-mmmx
-msse
-msse2
-msse3
-mssse3
-msse4
-msse4a
-msse4.1
-msse4.2
-mavx
-mavx2
-mavx512f
-mavx512pf
-mavx512er
-mavx512cd
-mavx512vl
-mavx512bw
-mavx512dq
-mavx512ifma
-mavx512vbmi
-msha
-maes
-mpclmul
-mclflushopt
-mclwb
-mfsgsbase
-mptwrite
-mrdrnd
-mf16c
-mfma
-mpconfig
-mwbnoinvd
-mfma4
-mprfchw
-mrdpid
-mprefetchwt1
-mrdseed
-msgx
-mxop
-mlwp
-m3dnow
-m3dnowa
-mpopcnt
-mabm
-madx
-mbmi
-mbmi2
-mlzcnt
-mfxsr
-mxsave
-mxsaveopt
-mxsavec
-mxsaves
-mrtm
-mhle
-mtbm
-mmwaitx
-mclzero
-mpku
-mavx512vbmi2
-mavx512bf16
-mavx512fp16
-mgfni
-mvaes
-mwaitpkg
-mvpclmulqdq
-mavx512bitalg
-mmovdiri
-mmovdir64b
-menqcmd
-muintr
-mtsxldtrk
-mavx512vpopcntdq
-mavx512vp2intersect
-mavx5124fmaps
-mavx512vnni
-mavxvnni
-mavx5124vnniw
-mcldemote
-mserialize
-mamx-tile
-mamx-int8
-mamx-bf16
-mhreset
-mkl
-mwidekl
-mavxifma
-mavxvnniint8
-mavxneconvert
-mcmpccxadd
-mamx-fp16
-mprefetchi
-mraoint
-mamx-complex
So what do these actually turn on? The MMX, SSE, SSE2, SSE3, SSSE3, SSE4, SSE4A, SSE4.1, SSE4.2, AVX, AVX2, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX512VL, AVX512BW, AVX512DQ, AVX512IFMA, AVX512VBMI, SHA, AES, PCLMUL, CLFLUSHOPT, CLWB, FSGSBASE, PTWRITE, RDRND, F16C, FMA, PCONFIG, WBNOINVD, FMA4, PREFETCHW, RDPID, PREFETCHWT1, RDSEED, SGX, XOP, LWP, 3DNow!, enhanced 3DNow!, POPCNT, ABM, ADX, BMI, BMI2, LZCNT, FXSR, XSAVE, XSAVEOPT, XSAVEC, XSAVES, RTM, HLE, TBM, MWAITX, CLZERO, PKU, AVX512VBMI2, GFNI, VAES, WAITPKG, VPCLMULQDQ, AVX512BITALG, MOVDIRI, MOVDIR64B, AVX512BF16, ENQCMD, AVX512VPOPCNTDQ, AVX5124FMAPS, AVX512VNNI, AVX5124VNNIW, SERIALIZE, UINTR, HRESET, AMXTILE, AMXINT8, AMXBF16, KL, WIDEKL, AVXVNNI, AVX512-FP16, AVXIFMA, AVXVNNIINT8, AVXNECONVERT, CMPCCXADD, AMX-FP16, PREFETCHI, RAOINT, AMX-COMPLEX or CLDEMOTE extended instruction sets. Each one has a matching -mno- option to turn the instruction use back off. โจ
These extensions are also available as built-in functions โ see x86 Built-in Functions for the full rundown of which functions these switches enable and disable.
Want SSE/SSE2 instructions generated automatically from floating-point code (instead of 387 instructions)? That's -mfpmath=sse, bestie.
Fun fact: GCC depresses SSEx instructions when -mavx is used. Instead it generates new AVX instructions, or AVX equivalence for all SSEx instructions, whenever they're needed. ๐
These options let GCC use these extended instructions in generated code even without -mfpmath=sse. Applications that do run-time CPU detection have to compile separate files for each supported architecture, using the appropriate flags โ and in particular, the file containing the CPU detection code should be compiled without these options. Important detail, don't skip it. ๐ธ
-mdump-tune-featuresโ tells GCC to dump the names of the x86 performance tuning features and their default settings. Those names are exactly what you plug into-mtune-ctrl=feature-list. ๐ฆ-mtune-ctrl=feature-listโ fine-grain control over 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 isn't preceded with^; if it is preceded by^, it's turned off.
โ ๏ธ Heads up: -mtune-ctrl=feature-list is intended to be used by GCC developers. Using it may lead you into code paths that aren't covered by testing, and it can potentially result in compiler ICEs or runtime errors. You've been warned. ๐ญ
-mno-defaultโ instructs GCC to turn off all tunable features. See also-mtune-ctrl=feature-listand-mdump-tune-features. ๐-mcldโ tells GCC to drop acldinstruction into the prologue of any function that uses string instructions ๐งต String instructions check the DF flag to pick autoincrement vs. autodecrement mode, and the ABI says DF is cleared on function entry โ but some operating systems are out here violating that spec and not clearing DF in their exception dispatchers ๐ค so the exception handler can get invoked with DF set, and then your string instructions go in the wrong direction. This option can be on by default for 32-bit x86 targets if GCC was configured with--enable-cld. In that case you can suppress thecldinstructions with-mno-cld.-mvzeroupperโ makes GCC emit avzeroupperinstruction before control flow transfers out of the function, which minimizes the AVX-to-SSE transition penalty ๐จ and also removes unnecessaryzeroupperintrinsics.-mprefer-avx128โ tells the auto-vectorizer to use 128-bit AVX instructions instead of 256-bit ones ๐ฏ- *
-mprefer-vector-width=opt* โ tells GCC to use opt-bit vector width in instructions instead of whatever the default is on the selected platform. The values are:noneโ no extra limitations applied to GCC beyond the ones defined by the selected platform.128โ prefer 128-bit vector width for instructions.256โ prefer 256-bit vector width for instructions.512โ prefer 512-bit vector width for instructions.
- *
-mmove-max=bits* โ sets the maximum number of bits that can be efficiently moved from memory to memory to bits. Valid values for bits are128,256and512. - *
-mstore-max=bits* โ sets the maximum number of bits that can be efficiently stored to memory to bits. Valid values for bits are128,256and512. -mcx16โ lets GCC generateCMPXCHG16Binstructions in 64-bit code so compare-and-exchange operations work on 16-byte-aligned 128-bit objects ๐ which is super useful for atomically updating data structures bigger than one machine word. The compiler uses this instruction to implement__syncBuiltins. But bestie, heads up: for__atomicBuiltins operating on 128-bit integers, a library call is always used.-msahfโ enables generation ofSAHFinstructions in 64-bit code. Early Intel Pentium 4 CPUs with Intel 64 support, before the Pentium 4 G1 step showed up in December 2005, were missing theLAHFandSAHFinstructions that AMD64 supports ๐ those are load and store instructions, respectively, for certain status flags. In 64-bit mode, theSAHFinstruction is used to optimize thefmod,dremandremainderbuilt-in functions; see Other Builtins for the deets.-mmovbeโ enables use of themovbeinstruction to implement__builtin_bswap32and__builtin_bswap64๐-mshstkโ the-mshstkoption enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET) ๐ก๏ธ-mcrc32โ enables the built-in functions__builtin_ia32_crc32qi,__builtin_ia32_crc32hi,__builtin_ia32_crc32siand__builtin_ia32_crc32dito generate thecrc32machine instruction.-mmwaitโ enables the built-in functions__builtin_ia32_monitorand__builtin_ia32_mwaitto generate themonitorandmwaitmachine instructions ๐ด-mrecipโ enables use ofRCPSSandRSQRTSSinstructions (plus their vectorized variantsRCPPSandRSQRTPS) with an extra Newton-Raphson step to bump up precision, instead ofDIVSSandSQRTSS(and their vectorized variants) for single-precision floating-point arguments โจ These instructions are only generated when-funsafe-math-optimizationsis enabled together with-ffinite-math-onlyand-fno-trapping-math. Note that while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can go down by up to 2 ulp (i.e. the inverse of 1.0 equals0.99999994).
Note that GCC already implements 1.0f/sqrtf(x) in terms of RSQRTSS (or RSQRTPS) with -ffast-math (or the option combo above), and doesn't need -mrecip.
Also note that GCC emits the above sequence with an additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the option combo above), and doesn't need -mrecip.
- *
-mrecip=opt* โ controls which reciprocal estimate instructions may be used ๐๏ธ opt is a comma-separated list of options, and any of them may be preceded by a!to invert it:allโ enable all estimate instructions.defaultโ enable the default instructions, equivalent to-mrecip.noneโ disable all estimate instructions, equivalent to-mno-recip.divโ enable the approximation for scalar division.vec-divโ enable the approximation for vectorized division.sqrtโ enable the approximation for scalar square root.vec-sqrtโ enable the approximation for vectorized square root.
So, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations except for square root ๐
-mveclibabi=type โ specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values for type aresvmlfor the Intel short vector math library andacmlfor the AMD math core library. To use this option, **both-ftree-vectorizeand-funsafe-math-optimizationshave to be enabled, and an SVML- or ACML-ABI-compatible library must be specified at link time ๐
GCC currently emits calls to vmldExp2, vmldLn2, vmldLog102, vmldPow2, vmldTanh2, vmldTan2, vmldAtan2, vmldAtanh2, vmldCbrt2, vmldSinh2, vmldSin2, vmldAsinh2, vmldAsin2, vmldCosh2, vmldCos2, vmldAcosh2, vmldAcos2, vmlsExp4, vmlsLn4, vmlsLog104, vmlsPow4, vmlsTanh4, vmlsTan4, vmlsAtan4, vmlsAtanh4, vmlsCbrt4, vmlsSinh4, vmlsSin4, vmlsAsinh4, vmlsAsin4, vmlsCosh4, vmlsCos4, vmlsAcosh4 and vmlsAcos4 for the corresponding function type when -mveclibabi=svml is used, and __vrd2_sin, __vrd2_cos, __vrd2_exp, __vrd2_log, __vrd2_log2, __vrd2_log10, __vrs4_sinf, __vrs4_cosf, __vrs4_expf, __vrs4_logf, __vrs4_log2f, __vrs4_log10f and __vrs4_powf for the corresponding function type when -mveclibabi=acml is used.
- *
-mabi=name* โ generates code for the specified calling convention. Permissible values aresysvfor the ABI used on GNU/Linux and other systems, andmsfor the Microsoft ABI. The default is the Microsoft ABI when targeting Microsoft Windows, and the SysV ABI on all other systems ๐ฅ๏ธ You can control this behavior for specific functions using the function attributesms_abiandsysv_abi. -mforce-indirect-callโ forces all calls to functions to be indirect. This is useful when using Intel Processor Trace, where it generates more precise timing information for function calls โฑ๏ธ-mmanual-endbrโ inserts the ENDBR instruction at function entry only via thecf_checkfunction attribute. Useful with the-fcf-protection=branchoption to control ENDBR insertion at the function entry ๐-mcet-switchโ by default, CET instrumentation is turned off on switch statements that use a jump table, and indirect branch track is disabled. Since jump tables live in read-only memory, this doesn't result in a direct loss of hardening ๐ง but if the jump table index is attacker-controlled, the indirect jump may not be constrained by CET. This option turns on CET instrumentation to enable indirect branch track for switch statements with jump tables, which makes the jump targets reachable via any indirect jumps.-mcall-ms2sysv-xloguesโ because 64-bit ABIs differ, any Microsoft ABI function that calls a System V ABI function has to consider RSI, RDI and XMM6-15 as clobbered ๐ฉ By default, the code for saving and restoring these registers is emitted inline, which makes for pretty lengthy prologues and epilogues. Using-mcall-ms2sysv-xloguesemits prologues and epilogues that use stubs in the static portion oflibgccto do those saves and restores, reducing function size at the cost of a few extra instructions.- *
-mtls-dialect=type* โ generates code to access thread-local storage using thegnuorgnu2conventions.gnuis the conservative default;gnu2is more efficient, but it may add compile- and run-time requirements that can't be satisfied on all systems โ ๏ธ -mpush-args,-mno-push-argsโ use PUSH operations to store outgoing parameters. This method is shorter and usually just as fast as the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance, thanks to 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 isn't equal to2. The drawback? A notable increase in code size ๐ฌ This switch implies-mno-push-args.-mthreadsโ supports thread-safe exception handling on MinGW ๐งต Programs that rely on thread-safe exception handling must compile and link all code with the-mthreadsoption. When compiling,-mthreadsdefines-D_MT; when linking, it links in a special thread helper library-lmingwthrdwhich cleans up per-thread exception-handling data.-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 GCC normally does ๐ Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via a function call or as data in a file), it may be necessary to access either format.
This option is enabled by default for Microsoft Windows targets. You can also control it locally with variable or type attributes โ peep x86 Variable Attributes and x86 Type Attributes for the deets. ๐ซถ
The Microsoft structure layout algorithm is honestly pretty simple, except for the bit-field packing part (that's where things get spicy). The padding and alignment of struct members, and whether a bit-field is allowed to straddle a storage-unit boundary, are determined by these rules:
- Structure members are stored sequentially in the order in which they are declared: the first member gets the lowest memory address and the last member gets the highest. ๐
- Every data object has an alignment requirement. For all data except structures, unions, and arrays, that alignment requirement is either the size of the object or the current packing size (specified with either the
"aligned"attribute or the"pack"pragma) โ whichever is less. For structures, unions, and arrays, the alignment requirement is the largest alignment requirement of its members. Every object is allocated an offset so that:
offset % alignment_requirement == 0
- Adjacent bit-fields get packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size and if the next bit-field fits into the current allocation unit without crossing the boundary imposed by the common alignment requirements of the bit-fields. โจ
Now, MSVC interprets zero-length bit-fields like this:
- If a zero-length bit-field is inserted between two bit-fields that are normally coalesced, the bit-fields are not coalesced. ๐ค
For example:
struct
{
unsigned long bf_1 : 12;
unsigned long : 0;
unsigned long bf_2 : 12;
} t1;
The size of "t1" is 8 bytes with the zero-length bit-field. If the zero-length bit-field were removed, "t1"'s size would be 4 bytes.
- If a zero-length bit-field is inserted after a bit-field,
"foo", and the alignment of the zero-length bit-field is greater than the member that follows it,"bar", then"bar"is aligned as the type of the zero-length bit-field. ๐
For example:
struct
{
char foo : 4;
short : 0;
char bar;
} t2;
struct
{
char foo : 4;
short : 0;
double bar;
} t3;
For "t2", "bar" is placed at offset 2, rather than offset 1. Accordingly, the size of "t2" is 4. For "t3", the zero-length bit-field does not affect the alignment of "bar" or, as a result, the size of the structure.
Taking this into account, it 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 a whole. For example,
"t2"has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short. - Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
{
char foo : 6;
long : 0;
} t4;
Here, "t4" takes up 4 bytes.
- Zero-length bit-fields following non-bit-field members are ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
Here, "t5" takes up 2 bytes.
-mno-align-stringopsโ 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, so it's just out here guessing. ๐ญ-minline-all-stringopsโ by default GCC inlines string operations only when the destination is known to be aligned to at least a 4-byte boundary. This option enables more inlining and increases code size, but may improve performance of code that depends on fast"memcpy"and"memset"for short lengths. It also enables inline expansion of"strlen"for all pointer alignments. ๐ฅ-minline-stringops-dynamicallyโ for string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks. Bestie does a vibe check at runtime, iconic behavior honestly.-mstringop-strategy=algโ override the internal decision heuristic for the particular algorithm to use for inlining string operations. The allowed values for alg are:rep_byterep_4byterep_8byte
Expand using i386 "rep" prefix of the specified size.
byte_looploopunrolled_loop
Expand into an inline loop.
libcall
Always use a library call.
-mmemcpy-strategy=strategyโ override the internal decision heuristic to decide if"__builtin_memcpy"should be inlined and what inline algorithm to use when the expected size of the copy operation is known. strategy is a comma-separated list ofalg:max_size:dest_aligntriplets. alg is specified in-mstringop-strategy, max_size specifies the max byte size with which inline algorithm alg is allowed. For the last triplet, the max_size must be-1. The max_size of the triplets in the list must be specified in increasing order. The minimal byte size for alg is 0 for the first triplet and"max_size + 1"of the preceding range. ๐-mmemset-strategy=strategyโ the option is similar to-mmemcpy-strategy=except that it is to control"__builtin_memset"expansion.-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. This avoids the instructions to save, set up, and restore frame pointers and makes an extra register available in leaf functions. The option-fomit-leaf-frame-pointerremoves the frame pointer for leaf functions, which might make debugging harder. ๐-mtls-direct-seg-refs,-mno-tls-direct-seg-refsโ controls whether TLS variables may be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer must be added. Whether or not this is valid depends on the operating system, and whether it maps the segment to cover the entire TLS area.
For systems that use the GNU C Library, the default is on.
-msse2avx,-mno-sse2avxโ specify that the assembler should encode SSE instructions with VEX prefix. The option-mavxturns this on by default. โจ-mfentry,-mno-fentryโ if profiling is active (-pg), put the profiling counter call before the prologue. Note: on x86 architectures the attribute"ms_hook_prologue"isn't possible at the moment for-mfentryand-pg. ๐-mrecord-mcount,-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection that contains pointers to each profiling call. This is useful for automatically patching and out calls.-mnop-mcount,-mno-nop-mcountโ if profiling is active (-pg), generate the calls to the profiling functions as NOPs. This is useful when they should be patched in later dynamically. This is likely only useful together with-mrecord-mcount. ๐ง-minstrument-return=typeโ instrument function exit in-pg-mfentryinstrumented functions with a call to the specified function. This only instruments true returns ending withret, but not sibling calls ending withjump. Valid *type*s arenoneto not instrument,callto generate a call to__return__, ornop5to generate a 5 byte nop.-mrecord-return,-mno-record-returnโ generate a__return_locsection pointing to all return instrumentation code.-mfentry-name=nameโ set name of__fentry__symbol called at function entry for-pg-mfentryfunctions.-mfentry-section=nameโ set name of section 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 RAX register when there are no variable arguments passed in vector registers.
Warning: since the RAX register is used to avoid unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or jump to a random location. ๐ญ GCC 4.4 or newer don't have those issues, regardless of the RAX register value.
-m8bit-idiv,-mno-8bit-idivโ on some processors, like Intel Atom, 8-bit unsigned integer divide is much faster than 32-bit/64-bit integer divide. This option generates a run-time check. If both dividend and divisor are within range of 0 to 255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. โก-mavx256-split-unaligned-load,-mavx256-split-unaligned-storeโ split 32-byte AVX unaligned load and store.-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offsetโ generate stack protection code using canary at guard. Supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default). This option has effect only when-fstack-protectoror-fstack-protector-allis specified. ๐ก๏ธ
With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which segment register (%fs or %gs) 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.
-mgeneral-regs-onlyโ generate code that uses only the general-purpose registers. This prevents the compiler from using floating-point, vector, mask and bound registers. No fancy registers for you, only the basics. ๐-mrelax-cmpxchg-loopโ okay so when GCC has to spit out a compare-and-swap loop for__syncBuiltins and__atomicBuiltins and there's no native instruction to do it in one go, this flag makes it optimize for the highly contended case ๐ it issues an atomic load before theCMPXCHGinstruction, and uses thePAUSEinstruction to save CPU power when restarting the loop. very "be polite to the other threads" of it, we love to see it ๐ซถ-mindirect-branch=choiceโ converts indirect calls and jumps according to choice. here's the menu, bestie:- the default is
keep, which keeps indirect call and jump unmodified (iconic "if it ain't broke" energy โจ) thunkconverts indirect call and jump to call and return thunkthunk-inlineconverts indirect call and jump to inlined call and return thunkthunk-externconverts indirect call and jump to external call and return thunk provided in a separate object file
- the default is
you can control this behavior for a specific function by using the function attribute indirect_branch ๐
note that-mcmodel=largeis incompatible with-mindirect-branch=thunkand-mindirect-branch=thunk-externsince the thunk function may not be reachable in the large code model. literally cannot be reached, it's giving lost in the address space ๐ญ
note that-mindirect-branch=thunk-externis compatible with-fcf-protection=branchsince the external thunk can be made to enable control-flow check. slay, they coexist ๐
-mfunction-return=choiceโ same deal but for function returns, converted according to choice:- the default is
keep, which keeps function return unmodified thunkconverts function return to call and return thunkthunk-inlineconverts function return to inlined call and return thunkthunk-externconverts function return to external call and return thunk provided in a separate object file
- the default is
you can control this behavior for a specific function by using the function attribute function_return ๐ธ
note that-mindirect-return=thunk-externis compatible with-fcf-protection=branchsince the external thunk can be made to enable control-flow check.
note that-mcmodel=largeis incompatible with-mfunction-return=thunkand-mfunction-return=thunk-externsince the thunk function may not be reachable in the large code model. same problem as above, the thunk is just too far away ๐ฅฒ
-mindirect-branch-registerโ forces indirect call and jump via register. simple as that, no notes ๐-mharden-sls=choiceโ generates code to mitigate against straight line speculation (SLS) with choice. the options:- default is
none, which disables all SLS hardening returnenables SLS hardening for function returnsindirect-jmpenables SLS hardening for indirect jumpsallenables all SLS hardening
- default is
pick your fighter โญ
-mindirect-branch-cs-prefixโ adds a CS prefix tocallandjmpto indirect thunk with branch target in r8-r15 registers so that the call and jmp instruction length is 6 bytes to allow them to be replaced withlfence; call *%r8-r15orlfence; jmp *%r8-r15at run-time. tiny byte-level glow-up, we respect it ๐ง
these -m switches are supported in addition to the above on x86-64 processors in 64-bit environments.
-m32,-m64,-mx32,-m16,-miamcuโ generate code for a 16-bit, 32-bit or 64-bit environment. the full tea โ:-m32setsint,long, and pointer types to 32 bits, and generates code that runs in 32-bit mode.-m64setsintto 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. (Darwin main character behaviour, honestly ๐)-mx32setsint,long, and pointer types to 32 bits, and generates code for the x86-64 architecture.-m16is the same as-m32, except for that it outputs the.code16gccassembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode.-miamcugenerates code which conforms to Intel MCU psABI. it requires the-m32option to be turned on. no-m32, no deal ๐ฅ
-mno-red-zoneโ do not use a so-called "red zone" for x86-64 code. ok so 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. ๐ซ very "not in my house" of the compiler-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. yes has to, it's mandatory bestie ๐-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. it's giving "there are levels to this" ๐-mcmodel=largeโ generate code for the large model. this model makes no assumptions about addresses and sizes of sections. zero assumptions, pure chaos, we love a free spirit ๐ฆ-maddress-mode=longโ generate code for long address mode. this is only supported for 64-bit and x32 environments. it is the default address mode for 64-bit environments โญ-maddress-mode=shortโ generate code for short address mode. this is only supported for 32-bit and x32 environments. it is the default address mode for 32-bit and x32 environments ๐-mneeded,-mno-neededโ emitGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for Linux target to indicate the micro-architecture ISA level required to execute the binary. a little note-to-self baked into the binary ๐ซถ-mno-direct-extern-accessโ without-fpicnor-fPIC, always use the GOT pointer to access external symbols. with-fpicor-fPIC, treat access to protected symbols as local symbols. the default is-mdirect-extern-access.
Warning: shared libraries compiled with-mno-direct-extern-accessand executable compiled with-mdirect-extern-accessmay not be binary compatible if protected symbols are used in shared libraries and executable. ๐ญ this is a real one, do not ignore the warning, it will not be cute
-munroll-only-small-loopsโ controls conservative small loop unrolling. it's default enabled by O2, and unrolls loop with less than 4 insns by 1 time. explicit-f[no-]unroll-[all-]loopswould disable this flag to avoid any unintended unrolling behavior that user does not want. the way that GCC respects your boundaries ๐๐-mlam=choiceโ LAM (linear-address masking) allows special bits in the pointer to be used for metadata. the default isnone. withu48, pointer bits in positions 62:48 can be used for metadata; withu57, pointer bits in positions 62:57 can be used for metadata. so many bits, so much metadata โจ
๐ช x86 Windows Options
these additional options are available for Microsoft Windows targets:
-mconsoleโ specifies that a console application is to be generated, by instructing the linker to set the PE header subsystem type required for console applications. this option is available for Cygwin and MinGW targets and is enabled by default on those targets ๐-mdllโ available for Cygwin and MinGW targets. it specifies that a DLL---a dynamic link library---is to be generated, enabling the selection of the required runtime startup object and entry point ๐-mnop-fun-dllimportโ available for Cygwin and MinGW targets. it specifies that thedllimportattribute should be ignored. "pretend you didn't see it" energy ๐-mthreadsโ available for MinGW targets. it specifies that MinGW-specific thread support is to be used ๐งต-municodeโ available for MinGW-w64 targets. it causes theUNICODEpreprocessor macro to be predefined, and chooses Unicode-capable runtime startup code. yes bestie, we're going Unicode ๐-mwin32โ available for Cygwin and MinGW targets. it specifies that the typical Microsoft Windows predefined macros are to be set in the pre-processor, but does not influence the choice of runtime library/startup code. macros only, no commitment ๐-mwindowsโ available for Cygwin and MinGW targets. it specifies that a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately ๐ชโจ-fno-set-stack-executableโ available for MinGW targets. it specifies that the executable flag for the stack used by nested functions isn't set. this is necessary for binaries running in kernel mode of Microsoft Windows, as there the User32 API, which is used to set executable privileges, isn't available. no User32, no problem ๐ธ-fwritable-relocated-rdataโ available for MinGW and Cygwin targets. it specifies that relocated-data in read-only section is put into the.datasection. this is a necessary for older runtimes not supporting modification of.rdatasections for pseudo-relocation. shoutout to the old runtimes ๐ซก-mpe-aligned-commonsโ available for Cygwin and MinGW targets. it specifies that the GNU extension to the PE file format that permits the correct alignment of COMMON variables should be used when generating code. it is enabled by default if GCC detects that the target assembler found during configuration supports the feature ๐
see also under x86 Options for standard options.
โก Xstormy16 Options
these options are defined for Xstormy16:
-msimโ choose startup files and linker script suitable for the simulator. that's it, that's the whole option, and honestly? clean, minimal, iconic ๐
๐ช๏ธ Xtensa Options
these options are supported for Xtensa targets:
-mconst16,-mno-const16โ enable or disable use ofCONST16instructions for loading constant values. theCONST16instruction is currently not a standard option from Tensilica. when enabled,CONST16instructions are always used in place of the standardL32Rinstructions. the use ofCONST16is enabled by default only if theL32Rinstruction is not available. always in place of, not sometimes, always โ worth knowing fr fr ๐ฅ-mfused-madd,-mno-fused-maddโ turns fused multiply/add and multiply/subtract instructions on or off for the floating-point option. ๐ Heads up: this does nothing if the floating-point option isn't also enabled, so don't come crying to me. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and the add/subtract. That's lowkey desirable in some cases where you need strictly IEEE 754-compliant results: the fused multiply add/subtract instructions don't round the intermediate result, so you get results with more bits of precision than the IEEE standard specifies. ๐ญ Disabling them also guarantees your program's output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. no cap.-mserialize-volatile,-mno-serialize-volatileโ when this is enabled, GCC insertsMEMWinstructions beforevolatilememory references to guarantee sequential consistency. โจ The default is-mserialize-volatile. Use-mno-serialize-volatileto omit theMEMWinstructions. that's it, that's the whole vibe.-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 stay winning.-mtext-section-literals,-mno-text-section-literalsโ these 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 lets the literal pool live in a data RAM/ROM, and it also lets the linker 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 so they stay 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โ also about literal pool treatment, bestie, don't get them twisted. 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. The compiler does not produce explicit.literaldirectives and loads literals into registers withMOVIinstructions instead ofL32R, so the assembler can do relaxation and place literals as necessary. This option lets the assembler create several literal pools per function and assemble very big functions โ which may not be possible with-mtext-section-literals. ๐ฅ-mtarget-align,-mno-target-alignโ when enabled, GCC tells the assembler to automatically align instructions to reduce branch penalties, at the expense of some code density. The assembler tries to widen density instructions to align branch targets and the instructions following call instructions. ๐ฆ If there aren't enough preceding safe density instructions to align a target, no widening happens โ no forcing, no drama. The default is-mtarget-align. These options do not affect the treatment of auto-aligned instructions likeLOOP, which the assembler always aligns, either by widening density instructions or by inserting NOP instructions. ๐-mlongcalls,-mno-longcallsโ when enabled, GCC tells the assembler to translate direct calls into 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 happens for calls to functions in other source files. Specifically, the assembler translates a directCALLinstruction into anL32Rfollowed by aCALLXinstruction. ๐ The default is-mno-longcalls. Use this in programs where the call target can potentially be out of range. Lowkey important detail: 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. ๐ Also note the assembler uses an indirect call for every cross-file call, not just those that really are out of range. ๐-mabi=nameโ generate code for the specified ABI. Permissible values arecall0andwindowed. The default ABI is chosen by the Xtensa core configuration. โจ-mabi=call0โ when enabled, function parameters are passed in registersa2througha7, registersa12througha15are caller-saved, and registera15may be used as a frame pointer. ๐ When this version of the ABI is enabled the C preprocessor symbol__XTENSA_CALL0_ABI__is defined.-mabi=windowedโ when enabled, function parameters are passed in registersa10througha15, and the called function rotates the register window by 8 registers on entry so its arguments are found in registersa2througha7. Registera7may be used as a frame pointer. The register window is rotated 8 registers back upon return. ๐ซ When this version of the ABI is enabled the C preprocessor symbol__XTENSA_WINDOWED_ABI__is defined.-mextra-l32r-costs=nโ specify an extra cost of instruction RAM/ROM access forL32Rinstructions, in clock cycles. โฑ๏ธ When optimizing for speed, this affects whether a constant gets loaded from the literal pool usingL32Ror synthesized from a small one with a couple of arithmetic instructions. The default value is0. iykyk.
๐ฆ zSeries Options ๐ฆ
These are listed under
๐ธ ENVIRONMENT ๐ธ
Okay bestie, this section is all about the env vars that lowkey run the whole show behind the scenes. Some of them work by handing GCC directories or prefixes to go dig around in when it's hunting for files. Others are vibes-only: they configure how the compilation environment behaves.
Heads up: you can also just tell GCC where to look with options like-B,-Iand-L. Those win over the environment variables, and the environment variables in turn win over whatever GCC's configuration says. Priority chain, periodt.
๐
LANG, LC_CTYPE, LC_MESSAGES, LC_ALL
These four control how GCC uses localization info, which is the whole reason it can roll with different national conventions. GCC peeks at the LC_CTYPE and LC_MESSAGES locale categories if it was configured to do so. You can set those categories to literally any value your install supports. A classic value is en_GB.UTF-8 โ English, United Kingdom, encoded in UTF-8. Slay.
LC_CTYPEโ this one specifies character classification. GCC uses it to figure out the character boundaries in a string, which you genuinely need for some multibyte encodings that contain quote and escape characters that would otherwise get read as "string ends here" or "escape time." ๐ญLC_MESSAGESโ this one picks the language for diagnostic messages. (Yes, your errors can be multilingual. Iconic.)LC_ALLโ if it's set, it overrides bothLC_CTYPEandLC_MESSAGES. If it's not set, those two default to the value ofLANG. And if none of these are set at all? GCC defaults to traditional C English behavior. Very "we tried nothing and we're all out of ideas," but make it valid.
๐ซถ TMPDIR
If TMPDIR is set, it names the directory used for temporary files. GCC needs temp files to hold the output of one compilation stage while it feeds it into the next stage โ like, the preprocessor's output becomes the input to the compiler proper. Pipeline realness. โจ
๐ GCC_COMPARE_DEBUG
Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. Go read that option's docs for the deets โ she's got lore.
๐ GCC_EXEC_PREFIX
If GCC_EXEC_PREFIX is set, it gives a prefix to stick onto the names of the subprograms the compiler executes. Note: no slash gets added when the prefix is combined with a subprogram name โ but you're absolutely free to specify a prefix that already ends in a slash if that's your vibe.
If GCC_EXEC_PREFIX isn't set, GCC tries to work out a sensible prefix from the pathname it was invoked with. And if it can't find the subprogram using your specified prefix, it goes looking in the usual places instead. Fallback queen. ๐
The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/, where prefix is the prefix of the installed compiler. In many cases prefix is the value of "prefix" from when you ran the configure script.
Other prefixes given with -B take precedence over this one.
This prefix is also used for finding files like crt0.o that get used for linking. And plot twist โ it's used in a genuinely unusual way when 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 swapping that beginning for the specified prefix to produce an alternate directory name. So with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. And if a standard directory begins with the configured prefix, then that prefix value gets replaced by GCC_EXEC_PREFIX when looking for header files. Messy? Yes. Documented? Also yes. ๐ญ
๐ฆ COMPILER_PATH
The value of COMPILER_PATH is a colon-separated list of directories, much like PATH. GCC tries those directories when searching for subprograms โ but only if it couldn't find them using GCC_EXEC_PREFIX. Backup plan energy.
๐ LIBRARY_PATH
The value of LIBRARY_PATH is also a colon-separated list of directories, much like PATH. When GCC is configured as a native compiler, it tries those directories when searching for special linker files, if it can't find them via GCC_EXEC_PREFIX. Linking with GCC also uses these directories when searching for ordinary libraries for the -l option โ but directories given with -L come first. No cutting the line, bestie.
๐ LANG (yes, again โ she does double duty)
This variable passes locale info to the compiler. One way that info gets used: determining the character set for parsing character literals, string literals and comments in C and C++. When the compiler is configured to allow multibyte characters, these LANG values are recognized:
C-JISโ recognize JIS characters.C-SJISโ recognize SJIS characters.C-EUCJPโ recognize EUCJP characters.
If LANG isn't defined, or it has some other value, then the compiler uses "mblen" and "mbtowc" as defined by the default locale to recognize and translate multibyte characters. Default behavior, we love her.
โญ GCC_EXTRA_DIAGNOSTIC_OUTPUT
If GCC_EXTRA_DIAGNOSTIC_OUTPUT is set to one of the values below, then extra text gets emitted to stderr whenever fix-it hints are emitted. But watch out: -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable. Options stay winning. ๐
fixits-v1โ emit parseable fix-it hints, equivalent to-fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.fixits-v2โ same asfixits-v1, but columns are expressed as display columns, as per-fdiagnostics-column-unit=display.
Some additional environment variables affect the behavior of the preprocessor. Yes, there's more. Buckle up. ๐ง
๐ 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, where the preprocessor goes looking for header files. That special character, "PATH_SEPARATOR", is target-dependent and decided at GCC build time. For Microsoft Windows-based targets it's a semicolon, and for almost literally every other target it's a colon.
CPATHโ a list of directories searched as if given with-I, but after any paths from-Ioptions on the command line. This one is used no matter which language is being preprocessed.- The remaining three apply only when preprocessing the particular language they name. Each specifies a list of directories searched as if given with
-isystem, but after any paths from-isystemoptions on the command line.
In all of these variables, an empty element tells the compiler to search its current working directory. Empty elements can show up at the beginning or the end of a path. For instance, if CPATH is ":/special/include", that hits exactly the same as -I. -I/special/include. Sneaky but valid. ๐
๐ธ DEPENDENCIES_OUTPUT
If this variable is set, its value specifies how to output dependencies for Make based on the non-system header files the compiler processed. System header files get ignored in the dependency output. Not invited to the party.
The value of DEPENDENCIES_OUTPUT can be just a file name โ in which case the Make rules get written to that file, with the target name guessed from the source file name. Or the value can be in the form file target, in which case the rules get written to file using target as the target name.
In other words, this env var is equivalent to combining the options -MM and -MF, plus an optional -MT switch if you're feeling extra. ๐
๐ SUNPRO_DEPENDENCIES
Same as DEPENDENCIES_OUTPUT (see above), except system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted. Different flavor, same family.
๐ฅ SOURCE_DATE_EPOCH
If this variable is set, its value specifies a UNIX timestamp to use in place of the current date and time in the "__DATE__" and "__TIME__" macros โ so the embedded timestamps become reproducible. Reproducible builds girlies, this one's for you. โจ
The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (leap seconds excluded) since 01 Jan 1970 00:00:00, represented in ASCII. Identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command.
The value should be a known timestamp, like the last modification time of the source or the package, and it should be set by the build process. Don't just make one up, bestie. ๐ญ
๐ BUGS ๐
For instructions on how to report bugs, go look at <https://bugs.opensuse.org/>. They're waiting for your findings.
๐ง FOOTNOTES ๐ง
- On some systems,
gcc -sharedneeds to build supplementary stub code for constructors to actually work. On multi-libbed systems,gcc -sharedmust select the correct support libraries to link against. Failing to supply the correct flags may lead to subtle defects โ and supplying them when they aren't necessary is innocuous (harmless, no drama). Also,-sharedsuppresses the addition of startup code that alters the floating-point environment, as done with-ffast-math,-Ofastor-funsafe-math-optimizationson some targets. Noted, logged, memorized. ๐
๐ฆ SEE ALSO ๐ฆ
gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1) โ and the Info entries for gcc, cpp, as, ld, binutils and gdb. The whole friend group. ๐ซถ
๐ AUTHOR ๐
See the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for the contributors to GCC. Every single one of them. Main characters, all of them.
๐ COPYRIGHT ๐
Copyright (c) 1988-2023 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page.
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.
And that's the whole page, bestie โ we made it to the end of all 122 parts! ๐ This one's gcc-13, dated 2026-09-10, and honestly she ate. Go forth and compile something iconic. ๐
โจ
๐ฆ where this page comes from
- opensuse-leap 16.0: gcc13 13.5.0+git10516-160000.1.1 ยท GPL-3.0-or-later
- opensuse-leap 16.0: gcc13 13.5.0+git10516-160000.1.1 ยท GPL-3.0-or-later
- opensuse-leap 16.0: gcc13 13.5.0+git10516-160000.1.1 ยท GPL-3.0-or-later
- opensuse-leap 16.0: gcc13 13.5.0+git10516-160000.1.1 ยท GPL-3.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms