• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2013 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import("//build/buildflag_header.gni")
6import("//build/config/android/config.gni")
7import("//build/config/c++/c++.gni")
8import("//build/config/chrome_build.gni")
9import("//build/config/chromeos/args.gni")
10import("//build/config/chromeos/ui_mode.gni")
11import("//build/config/clang/clang.gni")
12import("//build/config/compiler/compiler.gni")
13import("//build/config/coverage/coverage.gni")
14import("//build/config/dcheck_always_on.gni")
15import("//build/config/gclient_args.gni")
16import("//build/config/host_byteorder.gni")
17import("//build/config/pch.gni")
18import("//build/config/rust.gni")
19import("//build/config/ui.gni")
20import("//build/config/unwind.gni")
21import("//build/toolchain/cc_wrapper.gni")
22import("//build/toolchain/cros/cros_config.gni")
23import("//build/toolchain/rbe.gni")
24import("//build/toolchain/toolchain.gni")
25import("//build_overrides/build.gni")
26
27if (current_cpu == "arm" || current_cpu == "arm64") {
28  import("//build/config/arm.gni")
29}
30if (current_cpu == "mipsel" || current_cpu == "mips64el" ||
31    current_cpu == "mips" || current_cpu == "mips64") {
32  import("//build/config/mips.gni")
33}
34if (is_mac) {
35  import("//build/config/apple/symbols.gni")
36}
37if (is_ios) {
38  import("//build/config/ios/ios_sdk.gni")
39}
40if (is_nacl) {
41  # To keep NaCl variables out of builds that don't include NaCl, all
42  # variables defined in nacl/config.gni referenced here should be protected by
43  # is_nacl conditions.
44  import("//build/config/nacl/config.gni")
45}
46
47lld_path = ""
48if (!is_clang) {
49  declare_args() {
50    # This allows overriding the location of lld.
51    lld_path = rebase_path("$clang_base_path/bin", root_build_dir)
52  }
53} else {
54  # clang looks for lld next to it, no need for -B.
55  lld_path = ""
56}
57
58declare_args() {
59  # Normally, Android builds are lightly optimized, even for debug builds, to
60  # keep binary size down. Setting this flag to true disables such optimization
61  android_full_debug = false
62
63  # Compile in such a way as to make it possible for the profiler to unwind full
64  # stack frames. Setting this flag has a large effect on the performance of the
65  # generated code than just setting profiling, but gives the profiler more
66  # information to analyze.
67  # Requires profiling to be set to true.
68  enable_full_stack_frames_for_profiling = false
69
70  # Enable fatal linker warnings. Building Chromium with certain versions
71  # of binutils can cause linker warning.
72  fatal_linker_warnings = true
73
74  # Build with C++ RTTI enabled. Chromium builds without RTTI by default,
75  # but some sanitizers are known to require it, like CFI diagnostics
76  # and UBsan variants.
77  use_rtti = use_cfi_diag || is_ubsan_vptr || is_ubsan_security
78
79  # AFDO (Automatic Feedback Directed Optimizer) is a form of profile-guided
80  # optimization that GCC supports. It used by ChromeOS in their official
81  # builds. To use it, set auto_profile_path to the path to a file containing
82  # the needed gcov profiling data.
83  auto_profile_path = ""
84
85  # Optimize for coverage guided fuzzing (balance between speed and number of
86  # branches)
87  optimize_for_fuzzing = false
88
89  # Path to an AFDO profile to use while building with clang, if any. Empty
90  # implies none.
91  clang_sample_profile_path = ""
92
93  # Some configurations have default sample profiles. If this is true and
94  # clang_sample_profile_path is empty, we'll fall back to the default.
95  #
96  # We currently only have default profiles for Chromium in-tree, so we disable
97  # this by default for all downstream projects, since these profiles are likely
98  # nonsensical for said projects.
99  clang_use_default_sample_profile =
100      chrome_pgo_phase == 0 && build_with_chromium && is_official_build &&
101      (is_android || chromeos_is_browser_only)
102
103  # This configuration is used to select a default profile in Chrome OS based on
104  # the microarchitectures we are using. This is only used if
105  # clang_use_default_sample_profile is true and clang_sample_profile_path is
106  # empty.
107  chromeos_afdo_platform = "atom"
108
109  # Emit debug information for profiling wile building with clang.
110  # Only enable this for ChromeOS official builds for AFDO.
111  clang_emit_debug_info_for_profiling = is_chromeos_device && is_official_build
112
113  # Turn this on to have the compiler output extra timing information.
114  compiler_timing = false
115
116  # Turn this on to use ghash feature of lld for faster debug link on Windows.
117  # http://blog.llvm.org/2018/01/improving-link-time-on-windows-with.html
118  use_ghash = true
119
120  # Whether to enable ThinLTO optimizations. Turning ThinLTO optimizations on
121  # can substantially increase link time and binary size, but they generally
122  # also make binaries a fair bit faster.
123  #
124  # TODO(gbiv): We disable optimizations by default on most platforms because
125  # the space overhead is too great. We should use some mixture of profiles and
126  # optimization settings to better tune the size increase.
127  thin_lto_enable_optimizations =
128      (is_chromeos || is_android || is_win || is_linux || is_mac ||
129       (is_ios && use_lld)) && is_official_build
130
131  # Whether to enable thin lto incremental builds.
132  # See: https://clang.llvm.org/docs/ThinLTO.html#incremental
133  # The cache can lead to non-determinism: https://crbug.com/1486045
134  thin_lto_enable_cache = true
135
136  # Initialize all local variables with a pattern. This flag will fill
137  # uninitialized floating-point types (and 32-bit pointers) with 0xFF and the
138  # rest with 0xAA. This makes behavior of uninitialized memory bugs consistent,
139  # recognizable in the debugger, and crashes on memory accesses through
140  # uninitialized pointers.
141  #
142  # Flag discussion: https://crbug.com/977230
143  #
144  # TODO(crbug.com/40721698): This regresses binary size by ~1MB on Android and
145  # needs to be evaluated before enabling it there as well.
146  init_stack_vars = !(is_android && is_official_build)
147
148  # Zero init has favorable performance/size tradeoffs for Chrome OS
149  # but was not evaluated for other platforms.
150  init_stack_vars_zero = is_chromeos
151
152  # This argument is to control whether enabling text section splitting in the
153  # final binary. When enabled, the separated text sections with prefix
154  # '.text.hot', '.text.unlikely', '.text.startup' and '.text.exit' will not be
155  # merged to '.text' section. This allows us to identify the hot code section
156  # ('.text.hot') in the binary, which allows our data collection pipelines to
157  # more easily identify code that we assume to be hot/cold that doesn't turn
158  # out to be such in the field.
159  use_text_section_splitting = is_chromeos
160
161  # Enable DWARF v5.
162  use_dwarf5 = false
163
164  # Override this to put full paths to PDBs in Windows PE files. This helps
165  # windbg and Windows Performance Analyzer with finding the PDBs in some local-
166  # build scenarios. This is never needed for bots or official builds. Because
167  # this puts the output directory in the DLLs/EXEs it breaks build determinism.
168  # Bugs have been reported to the windbg/WPA teams and this workaround will be
169  # removed when they are fixed.
170  use_full_pdb_paths = false
171
172  # Enable -H, which prints the include tree during compilation.
173  # For use by tools/clang/scripts/analyze_includes.py
174  show_includes = false
175
176  # Enable Profi algorithm. Profi can infer block and edge counts.
177  # https://clang.llvm.org/docs/UsersManual.html#using-sampling-profilers
178  # TODO(crbug.com/1375958i:) Possibly enable this for Android too.
179  use_profi = is_chromeos
180
181  # If true, linker crashes will be rerun with `--reproduce` which causes
182  # a reproducer file to be saved.
183  save_reproducers_on_lld_crash = false
184
185  # Enable ShadowCallStack for compiled binaries. SCS stores a pointer to a
186  # shadow call stack in register x18. Hence, x18 must not be used by the OS
187  # or libraries. We assume that to be the case for high end Android
188  # configurations. For more details see
189  # https://clang.llvm.org/docs/ShadowCallStack.html
190  enable_shadow_call_stack = false
191
192  # Use DWARF simple template names, with the following exceptions:
193  #
194  # * Windows is not supported as it doesn't use DWARF.
195  # * Apple platforms (e.g. MacOS, iPhone, iPad) aren't supported because xcode
196  #   lldb doesn't have the needed changes yet.
197  # TODO(crbug.com/40244196): Remove if the upstream default ever changes.
198  #
199  # This greatly reduces the size of debug builds, at the cost of
200  # debugging information which is required by some specialized
201  # debugging tools.
202  simple_template_names = is_clang && !is_nacl && !is_win && !is_apple
203}
204
205declare_args() {
206  # Set to true to use icf, Identical Code Folding.
207  use_icf = (is_posix || is_fuchsia) && !is_debug && !using_sanitizer &&
208            !use_clang_coverage && current_os != "zos" &&
209            !(is_android && use_order_profiling) && use_lld
210}
211
212if (is_android) {
213  # Set the path to use orderfile for linking Chrome
214  # Note that this is for using only one orderfile for linking
215  # the Chrome binary/library.
216  declare_args() {
217    chrome_orderfile_path = ""
218
219    if (defined(default_chrome_orderfile)) {
220      # Allow downstream tools to set orderfile path with
221      # another variable.
222      chrome_orderfile_path = default_chrome_orderfile
223    }
224  }
225}
226
227declare_args() {
228  # Turn off the --call-graph-profile-sort flag for lld by default. Enable
229  # selectively for targets where it's beneficial.
230  enable_call_graph_profile_sort =
231      chrome_pgo_phase == 2 ||
232      (is_chromeos &&
233       (clang_use_default_sample_profile || clang_sample_profile_path != ""))
234}
235
236assert(!(llvm_force_head_revision && use_remoteexec && host_os != "linux"),
237       "rbe with locally built clang only works on linux")
238
239# default_include_dirs ---------------------------------------------------------
240#
241# This is a separate config so that third_party code (which would not use the
242# source root and might have conflicting versions of some headers) can remove
243# this and specify their own include paths.
244config("default_include_dirs") {
245  include_dirs = [
246    "//",
247    root_gen_dir,
248  ]
249}
250
251# Compiler instrumentation can introduce dependencies in DSOs to symbols in
252# the executable they are loaded into, so they are unresolved at link-time.
253config("no_unresolved_symbols") {
254  if (!using_sanitizer &&
255      (is_linux || is_chromeos || is_android || is_fuchsia)) {
256    ldflags = [
257      "-Wl,-z,defs",
258      "-Wl,--as-needed",
259    ]
260  }
261}
262
263# compiler ---------------------------------------------------------------------
264#
265# Base compiler configuration.
266#
267# See also "runtime_library" below for related stuff and a discussion about
268# where stuff should go. Put warning related stuff in the "warnings" config.
269
270config("compiler") {
271  asmflags = []
272  cflags = []
273  cflags_c = []
274  cflags_cc = []
275  cflags_objc = []
276  cflags_objcc = []
277  rustflags = []
278  ldflags = []
279  defines = []
280  configs = []
281  rustflags = []
282
283  # System-specific flags. If your compiler flags apply to one of the
284  # categories here, add it to the associated file to keep this shared config
285  # smaller.
286  if (is_win) {
287    configs += [ "//build/config/win:compiler" ]
288  } else if (is_android) {
289    configs += [ "//build/config/android:compiler" ]
290  } else if (is_linux || is_chromeos) {
291    configs += [ "//build/config/linux:compiler" ]
292  } else if (is_nacl) {
293    configs += [ "//build/config/nacl:compiler" ]
294  } else if (is_mac) {
295    configs += [ "//build/config/mac:compiler" ]
296  } else if (is_ios) {
297    configs += [ "//build/config/ios:compiler" ]
298  } else if (is_fuchsia) {
299    configs += [ "//build/config/fuchsia:compiler" ]
300  } else if (current_os == "aix") {
301    configs += [ "//build/config/aix:compiler" ]
302  } else if (current_os == "zos") {
303    configs += [ "//build/config/zos:compiler" ]
304  }
305
306  configs += [
307    # See the definitions below.
308    ":clang_revision",
309    ":rustc_revision",
310    ":compiler_cpu_abi",
311    ":compiler_codegen",
312    ":compiler_deterministic",
313  ]
314
315  # Here we enable -fno-delete-null-pointer-checks, which makes various nullptr
316  # operations (e.g. dereferencing) into defined behavior. This avoids deletion
317  # of some security-critical code: see https://crbug.com/1139129.
318  # The older NaCl toolchain does not support the flag. And, we still want UBSan
319  # to catch undefined behavior related to nullptrs, so do not add this flag if
320  # UBSan is enabled. GCC seems to have some bugs compiling constexpr code when
321  # this is defined, so only enable it if using_clang.
322  # See: https://gcc.gnu.org/PR97913
323  # TODO(mpdenton): remove is_clang once GCC bug is fixed.
324  if ((!is_nacl || is_nacl_saigo) && !is_ubsan && is_clang) {
325    cflags += [ "-fno-delete-null-pointer-checks" ]
326  }
327
328  # Don't emit the GCC version ident directives, they just end up in the
329  # .comment section or debug info taking up binary size, and makes comparing
330  # .o files built with different compiler versions harder.
331  if (!is_win || is_clang) {
332    cflags += [ "-fno-ident" ]
333  }
334
335  # In general, Windows is totally different, but all the other builds share
336  # some common compiler and linker configuration.
337  if (!is_win) {
338    # Common POSIX compiler flags setup.
339    # --------------------------------
340    cflags += [ "-fno-strict-aliasing" ]  # See http://crbug.com/32204
341
342    # Stack protection. ShadowCallStack and Stack protector address the same
343    # problems. Therefore, we only enable one or the other. Clang advertises SCS as
344    # a stronger alternative to StackProtector, so we give SCS precedence over SP.
345    if (enable_shadow_call_stack) {
346      # On Aarch64, SCS requires the x18 register to be unused because it will hold
347      # a pointer to the shadow stack. For Android we know that Clang doesn't use
348      # x18 by default. On other OSs adding "-ffixed-x18" might be required.
349      assert(is_android)
350
351      scs_parameters = [
352        "-fsanitize=shadow-call-stack",
353        "-fno-stack-protector",
354      ]
355      cflags += scs_parameters
356      ldflags += scs_parameters
357    } else {
358      if (is_apple) {
359        # The strong variant of the stack protector significantly increases
360        # binary size, so only enable it in debug mode.
361        if (is_debug) {
362          cflags += [ "-fstack-protector-strong" ]
363        } else {
364          cflags += [ "-fstack-protector" ]
365        }
366      } else if ((is_posix && !is_chromeos && !is_nacl) || is_fuchsia) {
367        if (current_os != "aix") {
368          # Not available on aix.
369          cflags += [ "-fstack-protector" ]
370        }
371      }
372    }
373
374    if (use_lld) {
375      ldflags += [ "-fuse-ld=lld" ]
376      if (lld_path != "") {
377        ldflags += [ "-B$lld_path" ]
378      }
379    }
380
381    # Linker warnings.
382    if (fatal_linker_warnings && !is_apple && current_os != "aix" &&
383        current_os != "zos") {
384      ldflags += [ "-Wl,--fatal-warnings" ]
385    }
386    if (fatal_linker_warnings && is_apple) {
387      ldflags += [ "-Wl,-fatal_warnings" ]
388    }
389  }
390
391  if (is_clang && is_debug) {
392    # Allow comparing the address of references and 'this' against 0
393    # in debug builds. Technically, these can never be null in
394    # well-defined C/C++ and Clang can optimize such checks away in
395    # release builds, but they may be used in asserts in debug builds.
396    cflags_cc += [
397      "-Wno-undefined-bool-conversion",
398      "-Wno-tautological-undefined-compare",
399    ]
400  }
401
402  # Non-Apple Posix and Fuchsia compiler flags setup.
403  # -----------------------------------
404  if ((is_posix && !is_apple) || is_fuchsia) {
405    if (enable_profiling) {
406      if (!is_debug) {
407        cflags += [ "-g" ]
408
409        if (enable_full_stack_frames_for_profiling) {
410          cflags += [
411            "-fno-inline",
412            "-fno-optimize-sibling-calls",
413          ]
414        }
415      }
416    }
417
418    # Explicitly pass --build-id to ld. Compilers used to always pass this
419    # implicitly but don't any more (in particular clang when built without
420    # ENABLE_LINKER_BUILD_ID=ON).
421    if (is_official_build) {
422      # The sha1 build id has lower risk of collision but is more expensive to
423      # compute, so only use it in the official build to avoid slowing down
424      # links.
425      ldflags += [ "-Wl,--build-id=sha1" ]
426    } else if (current_os != "aix" && current_os != "zos") {
427      ldflags += [ "-Wl,--build-id" ]
428    }
429
430    if (!is_android) {
431      defines += [
432        # _FILE_OFFSET_BITS=64 should not be set on Android in order to maintain
433        # the behavior of the Android NDK from earlier versions.
434        # See https://android-developers.googleblog.com/2017/09/introducing-android-native-development.html
435        "_FILE_OFFSET_BITS=64",
436        "_LARGEFILE_SOURCE",
437        "_LARGEFILE64_SOURCE",
438      ]
439    }
440
441    if (!is_nacl) {
442      if (exclude_unwind_tables) {
443        cflags += [
444          "-fno-unwind-tables",
445          "-fno-asynchronous-unwind-tables",
446        ]
447        rustflags += [ "-Cforce-unwind-tables=no" ]
448        defines += [ "NO_UNWIND_TABLES" ]
449      } else {
450        cflags += [ "-funwind-tables" ]
451        rustflags += [ "-Cforce-unwind-tables=yes" ]
452      }
453    }
454  }
455
456  # Apple compiler flags setup.
457  # ---------------------------------
458  if (is_apple) {
459    # On Intel, clang emits both Apple's "compact unwind" information and
460    # DWARF eh_frame unwind information by default, for compatibility reasons.
461    # This flag limits emission of eh_frame information to functions
462    # whose unwind information can't be expressed in the compact unwind format
463    # (which in practice means almost everything gets only compact unwind
464    # entries). This reduces object file size a bit and makes linking a bit
465    # faster.
466    # On arm64, this is already the default behavior.
467    if (current_cpu == "x64") {
468      asmflags += [ "-femit-dwarf-unwind=no-compact-unwind" ]
469      cflags += [ "-femit-dwarf-unwind=no-compact-unwind" ]
470    }
471
472    # dsymutil is not available in the system, on bots, for rustc to call. Our
473    # linker_driver.py script runs dsymutil itself, which is set to be the
474    # linker for Rust targets as well.
475    rustflags += [ "-Csplit-debuginfo=unpacked" ]
476  }
477
478  # Linux/Android/Fuchsia common flags setup.
479  # ---------------------------------
480  if (is_linux || is_chromeos || is_android || is_fuchsia) {
481    asmflags += [ "-fPIC" ]
482    cflags += [ "-fPIC" ]
483    ldflags += [ "-fPIC" ]
484    rustflags += [ "-Crelocation-model=pic" ]
485
486    if (!is_clang) {
487      # Use pipes for communicating between sub-processes. Faster.
488      # (This flag doesn't do anything with Clang.)
489      cflags += [ "-pipe" ]
490    }
491
492    ldflags += [
493      "-Wl,-z,noexecstack",
494      "-Wl,-z,relro",
495    ]
496
497    if (!is_component_build) {
498      ldflags += [ "-Wl,-z,now" ]
499    }
500  }
501
502  # Linux-specific compiler flags setup.
503  # ------------------------------------
504  if (use_icf && (!is_apple || use_lld)) {
505    ldflags += [ "-Wl,--icf=all" ]
506  }
507
508  if (is_linux || is_chromeos) {
509    cflags += [ "-pthread" ]
510    # Do not use the -pthread ldflag here since it becomes a no-op
511    # when using -nodefaultlibs, which would cause an unused argument
512    # error.  "-lpthread" is added in //build/config:default_libs.
513  }
514
515  # Clang-specific compiler flags setup.
516  # ------------------------------------
517  if (is_clang) {
518    cflags += [ "-fcolor-diagnostics" ]
519
520    # Enable -fmerge-all-constants. This used to be the default in clang
521    # for over a decade. It makes clang non-conforming, but is fairly safe
522    # in practice and saves some binary size. We might want to consider
523    # disabling this (https://bugs.llvm.org/show_bug.cgi?id=18538#c13),
524    # but for now it looks like our build might rely on it
525    # (https://crbug.com/829795).
526    cflags += [ "-fmerge-all-constants" ]
527
528    # TODO(crbug.com/345541122): investigate the fuchsia binary size increase.
529    if (is_win) {
530      cflags += [ "/Zc:sizedDealloc-" ]
531    } else {
532      cflags += [ "-fno-sized-deallocation" ]
533    }
534  }
535
536  if (use_lld) {
537    # TODO(thakis): Make the driver pass --color-diagnostics to the linker
538    # if -fcolor-diagnostics is passed to it, and pass -fcolor-diagnostics
539    # in ldflags instead.
540    if (is_win) {
541      # On Windows, we call the linker directly, instead of calling it through
542      # the driver.
543      ldflags += [ "--color-diagnostics" ]
544    } else {
545      ldflags += [ "-Wl,--color-diagnostics" ]
546    }
547  }
548
549  # Enable text section splitting only on linux when using lld for now. Other
550  # platforms can be added later if needed.
551  if ((is_linux || is_chromeos) && use_lld && use_text_section_splitting) {
552    ldflags += [ "-Wl,-z,keep-text-section-prefix" ]
553  }
554
555  if (is_clang && !is_nacl && current_os != "zos") {
556    cflags += [ "-fcrash-diagnostics-dir=" + clang_diagnostic_dir ]
557    if (save_reproducers_on_lld_crash && use_lld) {
558      ldflags += [
559        "-fcrash-diagnostics=all",
560        "-fcrash-diagnostics-dir=" + clang_diagnostic_dir,
561      ]
562    }
563
564    # TODO(hans): Remove this once Clang generates better optimized debug info
565    # by default. https://crbug.com/765793
566    cflags += [
567      "-mllvm",
568      "-instcombine-lower-dbg-declare=0",
569    ]
570    if (!is_debug && use_thin_lto && is_a_target_toolchain) {
571      if (is_win) {
572        ldflags += [ "-mllvm:-instcombine-lower-dbg-declare=0" ]
573      } else {
574        ldflags += [ "-Wl,-mllvm,-instcombine-lower-dbg-declare=0" ]
575      }
576    }
577
578    # TODO(crbug.com/40283598): This causes binary size growth and potentially
579    # other problems.
580    # TODO(crbug.com/40284925): This isn't supported by Cronet's mainline llvm version.
581    if (default_toolchain != "//build/toolchain/cros:target" &&
582        !llvm_android_mainline) {
583      cflags += [
584        "-mllvm",
585        "-split-threshold-for-reg-with-hint=0",
586      ]
587      if (use_thin_lto && is_a_target_toolchain) {
588        if (is_win) {
589          ldflags += [ "-mllvm:-split-threshold-for-reg-with-hint=0" ]
590        } else {
591          ldflags += [ "-Wl,-mllvm,-split-threshold-for-reg-with-hint=0" ]
592        }
593      }
594    }
595
596    # TODO(crbug.com/40192287): Investigate why/if this should be needed.
597    if (is_win) {
598      cflags += [ "/clang:-ffp-contract=off" ]
599    } else {
600      cflags += [ "-ffp-contract=off" ]
601    }
602  }
603
604  # C11/C++11 compiler flags setup.
605  # ---------------------------
606  if (is_linux || is_chromeos || is_android || (is_nacl && is_clang) ||
607      current_os == "aix") {
608    if (is_clang) {
609      standard_prefix = "c"
610
611      # Since we build with -std=c* and not -std=gnu*, _GNU_SOURCE will not be
612      # defined by the compiler.  However, lots of code relies on the
613      # non-standard features that _GNU_SOURCE enables, so define it manually.
614      defines += [ "_GNU_SOURCE" ]
615
616      if (is_nacl) {
617        # Undefine __STRICT_ANSI__ to get non-standard features which would
618        # otherwise not be enabled by NaCl's sysroots.
619        cflags += [ "-U__STRICT_ANSI__" ]
620      }
621    } else {
622      # Gcc does not support ##__VA_ARGS__ when in standards-conforming mode,
623      # but we use this feature in several places in Chromium.
624      # TODO(thomasanderson): Replace usages of ##__VA_ARGS__ with the
625      # standard-compliant __VA_OPT__ added by C++20, and switch the gcc build
626      # to -std=c*.
627      standard_prefix = "gnu"
628    }
629
630    cflags_c += [ "-std=${standard_prefix}11" ]
631    if (is_nacl && !is_nacl_saigo) {
632      # This is for the pnacl_newlib toolchain. It's only used to build
633      # a few independent ppapi test files that don't pull in any other
634      # dependencies.
635      cflags_cc += [ "-std=${standard_prefix}++14" ]
636      if (is_clang) {
637        cflags_cc += [ "-fno-trigraphs" ]
638      }
639    } else if (is_clang) {
640      if (defined(use_cxx17) && use_cxx17) {
641        cflags_cc += [ "-std=${standard_prefix}++17" ]
642      } else {
643        cflags_cc += [ "-std=${standard_prefix}++20" ]
644      }
645    } else {
646      # The gcc bots are currently using GCC 9, which is not new enough to
647      # support "c++20"/"gnu++20".
648      cflags_cc += [ "-std=${standard_prefix}++2a" ]
649    }
650  } else if (is_win) {
651    cflags_c += [ "/std:c11" ]
652    if (defined(use_cxx17) && use_cxx17) {
653      cflags_cc += [ "/std:c++17" ]
654    } else {
655      cflags_cc += [ "/std:c++20" ]
656    }
657    if (!is_clang) {
658      # Required for the __cplusplus macro definition to match the C++ version
659      # on MSVC. clang-cl defines it by default and doesn't need this flag.
660      # See: https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus
661      cflags_cc += [ "/Zc:__cplusplus" ]
662    }
663  } else if (!is_nacl) {
664    # TODO(mcgrathr) - the NaCl GCC toolchain doesn't support either
665    # gnu11/gnu++11 or c11/c++11; we technically don't need this toolchain any
666    # more, but there are still a few buildbots using it, so until those are
667    # turned off we need the !is_nacl clause and the (is_nacl && is_clang)
668    # clause, above.
669    cflags_c += [ "-std=c11" ]
670
671    if (defined(use_cxx17) && use_cxx17) {
672      cflags_cc += [ "-std=c++17" ]
673    } else {
674      cflags_cc += [ "-std=c++20" ]
675    }
676  }
677
678  if (is_clang && current_os != "zos") {
679    # C++17 removes trigraph support, but clang still warns that it ignores
680    # them when seeing them.  Don't.
681    cflags_cc += [ "-Wno-trigraphs" ]
682  }
683
684  if (use_relative_vtables_abi) {
685    cflags_cc += [ "-fexperimental-relative-c++-abi-vtables" ]
686    ldflags += [ "-fexperimental-relative-c++-abi-vtables" ]
687  }
688
689  # Add flags for link-time optimization. These flags enable
690  # optimizations/transformations that require whole-program visibility at link
691  # time, so they need to be applied to all translation units, and we may end up
692  # with miscompiles if only part of the program is compiled with LTO flags. For
693  # that reason, we cannot allow targets to enable or disable these flags, for
694  # example by disabling the optimize configuration.
695  # TODO(pcc): Make this conditional on is_official_build rather than on gn
696  # flags for specific features.
697  #
698  # High-end Android: While Full LTO provides a small performance improvement
699  # (according to Speedometer), it also results in an unacceptable increase in
700  # build time. Thin LTO appears to provide the best build time-optimization
701  # tradeoff. As of April 2024, Full LTO:
702  #   - Increases build time by ~1:30 hours, to ~2:40 hours (from ~1:10 hours
703  #     with Thin LTO) on Chromium builders.
704  #   - Increases Speedometer 2.1 score by 1.1% [0].
705  #   - Increases Speedometer 3.0 score by 1.2% [1].
706  # ... over Thin LTO.
707  #
708  # [0]: https://pinpoint-dot-chromeperf.appspot.com/job/15efb0313e0000
709  # [1]: https://pinpoint-dot-chromeperf.appspot.com/job/157f0b42be0000
710  if (!is_debug && use_thin_lto && is_a_target_toolchain) {
711    assert(use_lld, "LTO is only supported with lld")
712
713    cflags += [
714      "-flto=thin",
715      "-fsplit-lto-unit",
716    ]
717
718    if (thin_lto_enable_cache) {
719      # Limit the size of the ThinLTO cache to the lesser of 10% of
720      # available disk space, 40GB and 100000 files.
721      cache_policy =
722          "cache_size=10%:cache_size_bytes=40g:cache_size_files=100000"
723      cache_dir = rebase_path("$root_out_dir/thinlto-cache", root_build_dir)
724      if (is_win) {
725        ldflags += [
726          "/lldltocache:$cache_dir",
727          "/lldltocachepolicy:$cache_policy",
728        ]
729      } else {
730        if (is_apple) {
731          ldflags += [ "-Wl,-cache_path_lto,$cache_dir" ]
732        } else {
733          ldflags += [ "-Wl,--thinlto-cache-dir=$cache_dir" ]
734        }
735        ldflags += [ "-Wl,--thinlto-cache-policy=$cache_policy" ]
736      }
737    }
738
739    # An import limit of 30 has better performance (per speedometer) and lower
740    # binary size than the default setting of 100.
741    # TODO(gbiv): We ideally shouldn't need to specify this; ThinLTO
742    # should be able to better manage binary size increases on its own.
743    #
744    # For high-end Android, 30 seems to be the right trade-off between performance
745    # and binary size, at least based on Speedometer. For example, increasing
746    # `import_instr_limit`to 50 improves Speedometer 2.1 score by 0.7% [0], while
747    # Speedometer 3.0 score remains roughly the same (-0.1%) [1]. The binary size
748    # increases by about 2MB [2] (or 1.1%: the arm64 native code size in M124 is
749    # 178MB).
750    # [0]: https://pinpoint-dot-chromeperf.appspot.com/job/16984a18be0000
751    # [1]: https://pinpoint-dot-chromeperf.appspot.com/job/11984a18be0000
752    # [2]: https://ci.chromium.org/ui/p/chromium/builders/try/android-binary-size/1848442
753    import_instr_limit = 30
754
755    if (is_win) {
756      ldflags += [
757        "/opt:lldltojobs=all",
758        "-mllvm:-import-instr-limit=$import_instr_limit",
759        "-mllvm:-disable-auto-upgrade-debug-info",
760      ]
761    } else {
762      ldflags += [ "-flto=thin" ]
763
764      # Enabling ThinLTO on Chrome OS too, in an effort to reduce the memory
765      # usage in crbug.com/1038040. Note this will increase build time in
766      # Chrome OS.
767
768      # In ThinLTO builds, we run at most one link process at a time,
769      # and let it use all cores.
770      # TODO(thakis): Check if '=0' (that is, number of cores, instead
771      # of "all" which means number of hardware threads) is faster.
772      ldflags += [ "-Wl,--thinlto-jobs=all" ]
773
774      if (is_chromeos) {
775        # ARM was originally set lower than x86 to keep the size
776        # bloat of ThinLTO to <10%, but that's potentially no longer true.
777        # FIXME(inglorion): maybe tune these?
778        # TODO(b/271459198): Revert limit on amd64 to 30 when fixed.
779        import_instr_limit = 20
780      } else if (is_android && (optimize_for_size || use_order_profiling)) {
781        # Reduce inlining for the orderfile instrumented build to mitigate
782        # crbug.com/330761384.
783        # TODO(crbug.com/40219076): Investigate if we can get the > 6% perf win
784        # of import_instr_limit 30 with a binary size hit smaller than ~2 MiB.
785        import_instr_limit = 5
786      }
787
788      ldflags += [ "-Wl,-mllvm,-import-instr-limit=$import_instr_limit" ]
789
790      if (is_apple) {
791        ldflags += [ "-Wcrl,object_path_lto" ]
792      }
793
794      # We only use one version of LLVM within a build so there's no need to
795      # upgrade debug info, which can be expensive since it runs the verifier.
796      ldflags += [ "-Wl,-mllvm,-disable-auto-upgrade-debug-info" ]
797    }
798
799    if (!optimize_for_size) {
800      # Ideally the compiler would handle this automatically with PGO (see
801      # comments at https://crrev.com/c/5440500).
802      cflags += [
803        "-mllvm",
804        "-inlinehint-threshold=360",
805      ]
806      if (is_win) {
807        ldflags += [ "-mllvm:-inlinehint-threshold=360" ]
808      } else {
809        ldflags += [ "-Wl,-mllvm,-inlinehint-threshold=360" ]
810      }
811    }
812
813    # TODO(crbug.com/40182783): investigate why this isn't effective on
814    # arm32.
815    if (!is_android || current_cpu == "arm64") {
816      cflags += [ "-fwhole-program-vtables" ]
817
818      if (toolchain_supports_rust_thin_lto) {
819        # whole-program-vtables implies -fsplit-lto-unit, and Rust needs to match
820        # behaviour. Rust needs to know the linker will be doing LTO in this case
821        # or it rejects the Zsplit-lto-unit flag.
822        rustflags += [
823          "-Zsplit-lto-unit",
824          "-Clinker-plugin-lto=yes",
825        ]
826      } else {
827        # Don't include bitcode if it won't be used.
828        rustflags += [ "-Cembed-bitcode=no" ]
829      }
830
831      if (!is_win) {
832        ldflags += [ "-fwhole-program-vtables" ]
833      }
834    }
835
836    # This flag causes LTO to create an .ARM.attributes section with the correct
837    # architecture. This is necessary because LLD will refuse to link a program
838    # unless the architecture revision in .ARM.attributes is sufficiently new.
839    # TODO(pcc): The contents of .ARM.attributes should be based on the
840    # -march flag passed at compile time (see llvm.org/pr36291).
841    if (current_cpu == "arm") {
842      ldflags += [ "-march=$arm_arch" ]
843    }
844  }
845
846  if (compiler_timing) {
847    if (is_clang && !is_nacl) {
848      cflags += [ "-ftime-trace" ]
849      if (use_lld && is_mac) {
850        ldflags += [ "-Wl,--time-trace" ]
851      }
852    } else if (is_win) {
853      cflags += [
854        # "Documented" here:
855        # http://aras-p.info/blog/2017/10/23/Best-unknown-MSVC-flag-d2cgsummary/
856        "/d2cgsummary",
857      ]
858    }
859  }
860
861  # Pass flag to LLD so Android builds can allow debuggerd to properly symbolize
862  # stack crashes (http://crbug.com/919499).
863  if (use_lld && is_android) {
864    ldflags += [ "-Wl,--no-rosegment" ]
865  }
866
867  # TODO(crbug.com/40242425): Cleanup undefined symbol errors caught by
868  # --no-undefined-version.
869  if (use_lld && !is_win && !is_mac && !is_ios) {
870    ldflags += [ "-Wl,--undefined-version" ]
871  }
872
873  if (use_lld && is_apple) {
874    ldflags += [ "-Wl,--strict-auto-link" ]
875  }
876
877  # LLD does call-graph-sorted binary layout by default when profile data is
878  # present. On Android this increases binary size due to more thinks for long
879  # jumps. Turn it off by default and enable selectively for targets where it's
880  # beneficial.
881  if (use_lld && !enable_call_graph_profile_sort) {
882    if (is_win) {
883      ldflags += [ "/call-graph-profile-sort:no" ]
884    } else {
885      ldflags += [ "-Wl,--no-call-graph-profile-sort" ]
886    }
887  }
888
889  if (is_clang && !is_nacl && show_includes) {
890    if (is_win) {
891      cflags += [
892        "/clang:-H",
893        "/clang:-fshow-skipped-includes",
894      ]
895    } else {
896      cflags += [
897        "-H",
898        "-fshow-skipped-includes",
899      ]
900    }
901  }
902
903  # This flag enforces that member pointer base types are complete. It helps
904  # prevent us from running into problems in the Microsoft C++ ABI (see
905  # https://crbug.com/847724).
906  if (is_clang && !is_nacl && target_os != "chromeos" &&
907      (is_win || use_custom_libcxx)) {
908    cflags += [ "-fcomplete-member-pointers" ]
909  }
910
911  # Use DWARF simple template names.
912  if (simple_template_names) {
913    cflags_cc += [ "-gsimple-template-names" ]
914  }
915
916  # MLGO specific flags. These flags enable an ML-based inliner trained on
917  # Chrome on Android (arm32) with ThinLTO enabled, optimizing for size.
918  # The "release" ML model is embedded into clang as part of its build.
919  # Currently, the ML inliner is only enabled when targeting Android due to:
920  # a) Android is where size matters the most.
921  # b) MLGO presently has the limitation of only being able to embed one model
922  #    at a time; It is unclear if the embedded model is beneficial for
923  #    non-Android targets.
924  # MLGO is only officially supported on linux.
925  if (use_ml_inliner && is_a_target_toolchain) {
926    assert(
927        is_android && host_os == "linux",
928        "MLGO is currently only supported for targeting Android on a linux host")
929    if (use_thin_lto) {
930      ldflags += [ "-Wl,-mllvm,-enable-ml-inliner=release" ]
931    }
932  }
933
934  if (clang_embed_bitcode) {
935    assert(!use_thin_lto,
936           "clang_embed_bitcode is only supported in non-ThinLTO builds")
937    cflags += [
938      "-Xclang",
939      "-fembed-bitcode=all",
940    ]
941  }
942
943  if (lld_emit_indexes_and_imports) {
944    assert(use_thin_lto,
945           "lld_emit_indexes_and_imports is only supported with ThinLTO builds")
946    ldflags += [
947      "-Wl,--save-temps=import",
948      "-Wl,--thinlto-emit-index-files",
949    ]
950  }
951
952  # Pass the same C/C++ flags to the objective C/C++ compiler.
953  cflags_objc += cflags_c
954  cflags_objcc += cflags_cc
955
956  # Assign any flags set for the C compiler to asmflags so that they are sent
957  # to the assembler. The Windows assembler takes different types of flags
958  # so only do so for posix platforms.
959  if (is_posix || is_fuchsia) {
960    asmflags += cflags
961    asmflags += cflags_c
962  }
963
964  if (is_chromeos_device && !is_nacl) {
965    # On ChromeOS devices, we want to ensure we're using Chrome's allocator
966    # symbols for all C++ new/delete operator overloads. PartitionAlloc
967    # and other local allocators should always take precedence over system or
968    # preloaded allocators. These are the mangled symbol names.
969    # See b/280115910 for details.
970    ldflags += [
971      "-Wl,--export-dynamic-symbol=_ZdaPv,-u,_ZdaPv",
972      "-Wl,--export-dynamic-symbol=_ZdaPvRKSt9nothrow_t,-u,_ZdaPvRKSt9nothrow_t",
973      "-Wl,--export-dynamic-symbol=_ZdlPv,-u,_ZdlPv",
974      "-Wl,--export-dynamic-symbol=_ZdlPvm,-u,_ZdlPvm",
975      "-Wl,--export-dynamic-symbol=_ZdlPvRKSt9nothrow_t,-u,_ZdlPvRKSt9nothrow_t",
976      "-Wl,--export-dynamic-symbol=_Znam,-u,_Znam",
977      "-Wl,--export-dynamic-symbol=_ZnamRKSt9nothrow_t,-u,_ZnamRKSt9nothrow_t",
978      "-Wl,--export-dynamic-symbol=_Znwm,-u,_Znwm",
979      "-Wl,--export-dynamic-symbol=_ZnwmRKSt9nothrow_t,-u,_ZnwmRKSt9nothrow_t",
980      "-Wl,--export-dynamic-symbol=_ZdaPvmSt11align_val_t,-u,_ZdaPvmSt11align_val_t",
981      "-Wl,--export-dynamic-symbol=_ZdaPvSt11align_val_t,-u,_ZdaPvSt11align_val_t",
982      "-Wl,--export-dynamic-symbol=_ZdaPvSt11align_val_tRKSt9nothrow_t,-u,_ZdaPvSt11align_val_tRKSt9nothrow_t",
983      "-Wl,--export-dynamic-symbol=_ZdlPvmSt11align_val_t,-u,_ZdlPvmSt11align_val_t",
984      "-Wl,--export-dynamic-symbol=_ZdlPvSt11align_val_t,-u,_ZdlPvSt11align_val_t",
985      "-Wl,--export-dynamic-symbol=_ZdlPvSt11align_val_tRKSt9nothrow_t,-u,_ZdlPvSt11align_val_tRKSt9nothrow_t",
986      "-Wl,--export-dynamic-symbol=_ZnamSt11align_val_t,-u,_ZnamSt11align_val_t",
987      "-Wl,--export-dynamic-symbol=_ZnamSt11align_val_tRKSt9nothrow_t,-u,_ZnamSt11align_val_tRKSt9nothrow_t",
988      "-Wl,--export-dynamic-symbol=_ZnwmSt11align_val_t,-u,_ZnwmSt11align_val_t",
989      "-Wl,--export-dynamic-symbol=_ZnwmSt11align_val_tRKSt9nothrow_t,-u,_ZnwmSt11align_val_tRKSt9nothrow_t",
990    ]
991  }
992
993  # Rust compiler flags setup.
994  # ---------------------------
995  rustflags += [
996    # Overflow checks are optional in Rust, but even if switched
997    # off they do not cause undefined behavior (the overflowing
998    # behavior is defined). Because containers are bounds-checked
999    # in safe Rust, they also can't provoke buffer overflows.
1000    # As such these checks may be less important in Rust than C++.
1001    # But in (simplistic) testing they have negligible performance
1002    # overhead, and this helps to provide consistent behavior
1003    # between different configurations, so we'll keep them on until
1004    # we discover a reason to turn them off.
1005    "-Coverflow-checks=on",
1006
1007    # By default Rust passes `-nodefaultlibs` to the linker, however this
1008    # conflicts with our `--unwind=none` flag for Android dylibs, as the latter
1009    # is then unused and produces a warning/error. So this removes the
1010    # `-nodefaultlibs` from the linker invocation from Rust, which would be used
1011    # to compile dylibs on Android, such as for constructing unit test APKs.
1012    "-Cdefault-linker-libraries",
1013
1014    # To make Rust .d files compatible with ninja
1015    "-Zdep-info-omit-d-target",
1016
1017    # If a macro panics during compilation, show which macro and where it is
1018    # defined.
1019    "-Zmacro-backtrace",
1020
1021    # For deterministic builds, keep the local machine's current working
1022    # directory from appearing in build outputs.
1023    "-Zremap-cwd-prefix=.",
1024  ]
1025
1026  if (!is_win || force_rustc_color_output) {
1027    # Colorize error output. The analogous flag is passed for clang. This must
1028    # be platform-gated since rustc will unconditionally output ANSI escape
1029    # sequences, ignoring the platform, when stderr is not a terminal.
1030    rustflags += [ "--color=always" ]
1031  }
1032  if (rust_abi_target != "") {
1033    rustflags += [ "--target=$rust_abi_target" ]
1034  }
1035  if (!use_thin_lto || !toolchain_supports_rust_thin_lto) {
1036    # Don't include bitcode if it won't be used.
1037    rustflags += [ "-Cembed-bitcode=no" ]
1038
1039    # Disable "automatic" ThinLTO between codegen units. The weak symbol
1040    # resolution across units can have surprising effects on linking, see
1041    # crbug.com/324126269 and github.com/rust-lang/rust/issues/120842.
1042    rustflags += [ "-Clto=no" ]
1043  }
1044  if (is_official_build) {
1045    rustflags += [ "-Ccodegen-units=1" ]
1046  }
1047  if (!rust_prebuilt_stdlib) {
1048    # When building against the Chromium Rust stdlib (which we compile) always
1049    # abort instead of unwinding when panic occurs. In official builds, panics
1050    # abort immediately (this is configured in the stdlib) to keep binary size
1051    # down. So we unconditionally match behaviour in unofficial too.
1052    rustflags += [
1053      "-Cpanic=abort",
1054      "-Zpanic_abort_tests",
1055    ]
1056  }
1057
1058  # Normally, this would be defined in the `runtime_library` config but NaCl
1059  # saigo libc++ does not use the custom hermetic libc++. Unfortunately, there
1060  # isn't really a better config to add this define for the define to
1061  # consistently apply in both Chromium and non-Chromium code *and* non-NaCl
1062  # and NaCl code.
1063  #
1064  # TODO(crbug.com/40511454): Move this back to the `runtime_library`
1065  # config when NaCl is removed.
1066  if (use_safe_libcxx) {
1067    # TODO(crbug.com/40275904): Switch saigo to hardened mode once
1068    # it's rolled in.
1069    if (is_nacl_saigo) {
1070      defines += [ "_LIBCPP_ENABLE_ASSERTIONS=1" ]
1071    } else {
1072      defines += [ "_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE" ]
1073    }
1074  } else {
1075    defines += [ "_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_NONE" ]
1076  }
1077
1078  # Enable libstdc++ hardening lightweight assertions. Those have a low
1079  # performance penalty but are considered a bare minimum for security.
1080  if (use_safe_libstdcxx) {
1081    defines += [ "_GLIBCXX_ASSERTIONS=1" ]
1082  }
1083
1084  # 64-bit Android sometimes defines __ARM_NEON but not __ARM_NEON__.
1085  # 32-bit Android builds and macOS, however, define __ARM_NEON__,
1086  # and code typically checks for this.
1087  #
1088  # Reduce confusion by making the __ARM_NEON__ #define always available,
1089  # as NEON is a mandatory part of ARMv8 anyway.
1090  if (current_cpu == "arm64") {
1091    defines += [ "__ARM_NEON__=1" ]
1092  }
1093}
1094
1095# The BUILDCONFIG file sets this config on targets by default, which means when
1096# building with ThinLTO, no optimization is performed in the link step.
1097config("thinlto_optimize_default") {
1098  if (!is_debug && use_thin_lto && is_a_target_toolchain) {
1099    lto_opt_level = 0
1100
1101    if (is_win) {
1102      ldflags = [ "/opt:lldlto=" + lto_opt_level ]
1103    } else {
1104      ldflags = [ "-Wl,--lto-O" + lto_opt_level ]
1105    }
1106
1107    if (toolchain_supports_rust_thin_lto) {
1108      # We always point Rust to a linker that performs LTO, so we don't want Rust
1109      # to preemptively do so during compilation too or they conflict. But we do
1110      # want Rust to generate LTO metadata in order for the linker to do its job.
1111      rustflags = [ "-Clinker-plugin-lto=yes" ]
1112    } else {
1113      # Don't include bitcode if it won't be used.
1114      rustflags = [ "-Cembed-bitcode=no" ]
1115    }
1116  }
1117}
1118
1119# Use this to enable optimization in the ThinLTO link step for select targets
1120# when thin_lto_enable_optimizations is set by doing:
1121#
1122#   configs -= [ "//build/config/compiler:thinlto_optimize_default" ]
1123#   configs += [ "//build/config/compiler:thinlto_optimize_max" ]
1124#
1125# Since it makes linking significantly slower and more resource intensive, only
1126# use it on important targets such as the main browser executable or dll.
1127config("thinlto_optimize_max") {
1128  if (!is_debug && use_thin_lto && is_a_target_toolchain) {
1129    if (thin_lto_enable_optimizations) {
1130      lto_opt_level = 2
1131    } else {
1132      lto_opt_level = 0
1133    }
1134
1135    if (is_win) {
1136      ldflags = [ "/opt:lldlto=" + lto_opt_level ]
1137    } else {
1138      ldflags = [ "-Wl,--lto-O" + lto_opt_level ]
1139    }
1140
1141    if (toolchain_supports_rust_thin_lto) {
1142      # We always point Rust to a linker that performs LTO, so we don't want Rust
1143      # to preemptively do so during compilation too or they conflict. But we do
1144      # want Rust to generate LTO metadata in order for the linker to do its job.
1145      rustflags = [ "-Clinker-plugin-lto=yes" ]
1146    } else {
1147      # Don't include bitcode if it won't be used.
1148      rustflags = [ "-Cembed-bitcode=no" ]
1149    }
1150  }
1151}
1152
1153# This provides the basic options to select the target CPU and ABI.
1154# It is factored out of "compiler" so that special cases can use this
1155# without using everything that "compiler" brings in.  Options that
1156# tweak code generation for a particular CPU do not belong here!
1157# See "compiler_codegen", below.
1158config("compiler_cpu_abi") {
1159  cflags = []
1160  ldflags = []
1161  defines = []
1162
1163  configs = []
1164  if (is_chromeos) {
1165    configs += [ "//build/config/chromeos:compiler_cpu_abi" ]
1166  }
1167
1168  if ((is_posix && !is_apple) || is_fuchsia) {
1169    # CPU architecture. We may or may not be doing a cross compile now, so for
1170    # simplicity we always explicitly set the architecture.
1171    if (current_cpu == "x64") {
1172      cflags += [
1173        "-m64",
1174        "-msse3",
1175      ]
1176
1177      # Minimum SIMD support for devices running lacros.
1178      # See https://crbug.com/1475858
1179      if (is_chromeos_lacros) {
1180        cflags += [
1181          "-mssse3",
1182          "-msse4",
1183          "-msse4.1",
1184          "-msse4.2",
1185        ]
1186      }
1187      ldflags += [ "-m64" ]
1188    } else if (current_cpu == "x86") {
1189      cflags += [ "-m32" ]
1190      ldflags += [ "-m32" ]
1191      if (!is_nacl) {
1192        cflags += [
1193          "-mfpmath=sse",
1194          "-msse3",
1195        ]
1196      }
1197    } else if (current_cpu == "arm") {
1198      if (is_clang && !is_android && !is_nacl &&
1199          !(is_chromeos_lacros && is_chromeos_device)) {
1200        cflags += [ "--target=arm-linux-gnueabihf" ]
1201        ldflags += [ "--target=arm-linux-gnueabihf" ]
1202      }
1203      if (!is_nacl) {
1204        cflags += [
1205          "-march=$arm_arch",
1206          "-mfloat-abi=$arm_float_abi",
1207        ]
1208      }
1209      if (arm_tune != "") {
1210        cflags += [ "-mtune=$arm_tune" ]
1211      }
1212    } else if (current_cpu == "arm64") {
1213      if (is_clang && !is_android && !is_nacl && !is_fuchsia &&
1214          !(is_chromeos_lacros && is_chromeos_device)) {
1215        cflags += [ "--target=aarch64-linux-gnu" ]
1216        ldflags += [ "--target=aarch64-linux-gnu" ]
1217      }
1218    } else if (current_cpu == "mipsel" && !is_nacl) {
1219      ldflags += [ "-Wl,--hash-style=sysv" ]
1220      if (custom_toolchain == "") {
1221        if (is_clang) {
1222          if (is_android) {
1223            cflags += [ "--target=mipsel-linux-android" ]
1224            ldflags += [ "--target=mipsel-linux-android" ]
1225          } else {
1226            cflags += [ "--target=mipsel-linux-gnu" ]
1227            ldflags += [ "--target=mipsel-linux-gnu" ]
1228          }
1229        } else {
1230          cflags += [ "-EL" ]
1231          ldflags += [ "-EL" ]
1232        }
1233      }
1234
1235      if (mips_arch_variant == "r6") {
1236        cflags += [ "-mno-odd-spreg" ]
1237        ldflags += [ "-mips32r6" ]
1238        if (is_clang) {
1239          cflags += [
1240            "-march=mipsel",
1241            "-mcpu=mips32r6",
1242          ]
1243        } else {
1244          cflags += [
1245            "-mips32r6",
1246            "-Wa,-mips32r6",
1247          ]
1248          if (is_android) {
1249            ldflags += [ "-Wl,-melf32ltsmip" ]
1250          }
1251        }
1252        if (mips_use_msa == true) {
1253          cflags += [
1254            "-mmsa",
1255            "-mfp64",
1256          ]
1257        }
1258      } else if (mips_arch_variant == "r2") {
1259        ldflags += [ "-mips32r2" ]
1260        if (is_clang) {
1261          cflags += [
1262            "-march=mipsel",
1263            "-mcpu=mips32r2",
1264          ]
1265        } else {
1266          cflags += [
1267            "-mips32r2",
1268            "-Wa,-mips32r2",
1269          ]
1270          if (mips_float_abi == "hard" && mips_fpu_mode != "") {
1271            cflags += [ "-m$mips_fpu_mode" ]
1272          }
1273        }
1274      } else if (mips_arch_variant == "r1") {
1275        ldflags += [ "-mips32" ]
1276        if (is_clang) {
1277          cflags += [
1278            "-march=mipsel",
1279            "-mcpu=mips32",
1280          ]
1281        } else {
1282          cflags += [
1283            "-mips32",
1284            "-Wa,-mips32",
1285          ]
1286        }
1287      } else if (mips_arch_variant == "loongson3") {
1288        defines += [ "_MIPS_ARCH_LOONGSON" ]
1289        cflags += [
1290          "-march=loongson3a",
1291          "-mno-branch-likely",
1292          "-Wa,-march=loongson3a",
1293        ]
1294      }
1295
1296      if (mips_dsp_rev == 1) {
1297        cflags += [ "-mdsp" ]
1298      } else if (mips_dsp_rev == 2) {
1299        cflags += [ "-mdspr2" ]
1300      }
1301
1302      cflags += [ "-m${mips_float_abi}-float" ]
1303    } else if (current_cpu == "mips" && !is_nacl) {
1304      ldflags += [ "-Wl,--hash-style=sysv" ]
1305      if (custom_toolchain == "") {
1306        if (is_clang) {
1307          cflags += [ "--target=mips-linux-gnu" ]
1308          ldflags += [ "--target=mips-linux-gnu" ]
1309        } else {
1310          cflags += [ "-EB" ]
1311          ldflags += [ "-EB" ]
1312        }
1313      }
1314
1315      if (mips_arch_variant == "r6") {
1316        cflags += [
1317          "-mips32r6",
1318          "-Wa,-mips32r6",
1319        ]
1320        if (mips_use_msa == true) {
1321          cflags += [
1322            "-mmsa",
1323            "-mfp64",
1324          ]
1325        }
1326      } else if (mips_arch_variant == "r2") {
1327        cflags += [
1328          "-mips32r2",
1329          "-Wa,-mips32r2",
1330        ]
1331        if (mips_float_abi == "hard" && mips_fpu_mode != "") {
1332          cflags += [ "-m$mips_fpu_mode" ]
1333        }
1334      } else if (mips_arch_variant == "r1") {
1335        cflags += [
1336          "-mips32",
1337          "-Wa,-mips32",
1338        ]
1339      }
1340
1341      if (mips_dsp_rev == 1) {
1342        cflags += [ "-mdsp" ]
1343      } else if (mips_dsp_rev == 2) {
1344        cflags += [ "-mdspr2" ]
1345      }
1346
1347      cflags += [ "-m${mips_float_abi}-float" ]
1348    } else if (current_cpu == "mips64el") {
1349      cflags += [ "-D__SANE_USERSPACE_TYPES__" ]
1350      ldflags += [ "-Wl,--hash-style=sysv" ]
1351      if (custom_toolchain == "") {
1352        if (is_clang) {
1353          if (is_android) {
1354            cflags += [ "--target=mips64el-linux-android" ]
1355            ldflags += [ "--target=mips64el-linux-android" ]
1356          } else {
1357            cflags += [ "--target=mips64el-linux-gnuabi64" ]
1358            ldflags += [ "--target=mips64el-linux-gnuabi64" ]
1359          }
1360        } else {
1361          cflags += [
1362            "-EL",
1363            "-mabi=64",
1364          ]
1365          ldflags += [
1366            "-EL",
1367            "-mabi=64",
1368          ]
1369        }
1370      }
1371
1372      if (mips_arch_variant == "r6") {
1373        if (is_clang) {
1374          cflags += [
1375            "-march=mips64el",
1376            "-mcpu=mips64r6",
1377          ]
1378        } else {
1379          cflags += [
1380            "-mips64r6",
1381            "-Wa,-mips64r6",
1382          ]
1383          ldflags += [ "-mips64r6" ]
1384        }
1385        if (mips_use_msa == true) {
1386          cflags += [
1387            "-mmsa",
1388            "-mfp64",
1389          ]
1390        }
1391      } else if (mips_arch_variant == "r2") {
1392        ldflags += [ "-mips64r2" ]
1393        if (is_clang) {
1394          cflags += [
1395            "-march=mips64el",
1396            "-mcpu=mips64r2",
1397          ]
1398        } else {
1399          cflags += [
1400            "-mips64r2",
1401            "-Wa,-mips64r2",
1402          ]
1403        }
1404      } else if (mips_arch_variant == "loongson3") {
1405        defines += [ "_MIPS_ARCH_LOONGSON" ]
1406        cflags += [
1407          "-march=loongson3a",
1408          "-mno-branch-likely",
1409          "-Wa,-march=loongson3a",
1410        ]
1411      }
1412    } else if (current_cpu == "mips64") {
1413      ldflags += [ "-Wl,--hash-style=sysv" ]
1414      if (custom_toolchain == "") {
1415        if (is_clang) {
1416          cflags += [ "--target=mips64-linux-gnuabi64" ]
1417          ldflags += [ "--target=mips64-linux-gnuabi64" ]
1418        } else {
1419          cflags += [
1420            "-EB",
1421            "-mabi=64",
1422          ]
1423          ldflags += [
1424            "-EB",
1425            "-mabi=64",
1426          ]
1427        }
1428      }
1429
1430      if (mips_arch_variant == "r6") {
1431        cflags += [
1432          "-mips64r6",
1433          "-Wa,-mips64r6",
1434        ]
1435        ldflags += [ "-mips64r6" ]
1436
1437        if (mips_use_msa == true) {
1438          cflags += [
1439            "-mmsa",
1440            "-mfp64",
1441          ]
1442        }
1443      } else if (mips_arch_variant == "r2") {
1444        cflags += [
1445          "-mips64r2",
1446          "-Wa,-mips64r2",
1447        ]
1448        ldflags += [ "-mips64r2" ]
1449      }
1450    } else if (current_cpu == "ppc64") {
1451      if (current_os == "aix") {
1452        cflags += [ "-maix64" ]
1453        ldflags += [ "-maix64" ]
1454      } else {
1455        cflags += [ "-m64" ]
1456        ldflags += [ "-m64" ]
1457      }
1458    } else if (current_cpu == "riscv64") {
1459      if (is_clang && !is_android) {
1460        cflags += [ "--target=riscv64-linux-gnu" ]
1461        ldflags += [ "--target=riscv64-linux-gnu" ]
1462      }
1463      cflags += [ "-mabi=lp64d" ]
1464    } else if (current_cpu == "loong64") {
1465      if (is_clang) {
1466        cflags += [ "--target=loongarch64-linux-gnu" ]
1467        ldflags += [ "--target=loongarch64-linux-gnu" ]
1468      }
1469      cflags += [
1470        "-mabi=lp64d",
1471        "-mcmodel=medium",
1472      ]
1473    } else if (current_cpu == "s390x") {
1474      cflags += [ "-m64" ]
1475      ldflags += [ "-m64" ]
1476    }
1477  }
1478
1479  asmflags = cflags
1480}
1481
1482# This provides options to tweak code generation that are necessary
1483# for particular Chromium code or for working around particular
1484# compiler bugs (or the combination of the two).
1485config("compiler_codegen") {
1486  configs = []
1487  cflags = []
1488  ldflags = []
1489
1490  if (is_nacl) {
1491    configs += [ "//build/config/nacl:compiler_codegen" ]
1492  }
1493
1494  if (current_cpu == "arm64" && !is_win && is_clang) {
1495    # Disable outlining everywhere on arm64 except Win. For more information see
1496    # crbug.com/931297 for Android and crbug.com/1410297 for iOS.
1497    # TODO(crbug.com/40890229): Enable this on Windows if possible.
1498    cflags += [ "-mno-outline" ]
1499
1500    # This can be removed once https://bugs.llvm.org/show_bug.cgi?id=40348
1501    # has been resolved, and -mno-outline is obeyed by the linker during
1502    # ThinLTO.
1503    ldflags += [ "-Wl,-mllvm,-enable-machine-outliner=never" ]
1504  }
1505
1506  asmflags = cflags
1507}
1508
1509# This provides options that make the build deterministic, so that the same
1510# revision produces the same output, independent of the name of the build
1511# directory and of the computer the build is done on.
1512# The relative path from build dir to source dir makes it into the build
1513# outputs, so it's recommended that you use a build dir two levels deep
1514# (e.g. "out/Release") so that you get the same "../.." path as all the bots
1515# in your build outputs.
1516config("compiler_deterministic") {
1517  cflags = []
1518  ldflags = []
1519  swiftflags = []
1520
1521  # Eliminate build metadata (__DATE__, __TIME__ and __TIMESTAMP__) for
1522  # deterministic build.  See https://crbug.com/314403
1523  if (!is_official_build) {
1524    if (is_win && !is_clang) {
1525      cflags += [
1526        "/wd4117",  # Trying to define or undefine a predefined macro.
1527        "/D__DATE__=",
1528        "/D__TIME__=",
1529        "/D__TIMESTAMP__=",
1530      ]
1531    } else {
1532      cflags += [
1533        "-Wno-builtin-macro-redefined",
1534        "-D__DATE__=",
1535        "-D__TIME__=",
1536        "-D__TIMESTAMP__=",
1537      ]
1538    }
1539  }
1540
1541  # Makes builds independent of absolute file path.
1542  if (is_clang && strip_absolute_paths_from_debug_symbols) {
1543    # If debug option is given, clang includes $cwd in debug info by default.
1544    # For such build, this flag generates reproducible obj files even we use
1545    # different build directory like "out/feature_a" and "out/feature_b" if
1546    # we build same files with same compile flag.
1547    # Other paths are already given in relative, no need to normalize them.
1548    if (is_nacl) {
1549      # TODO(https://crbug.com/1231236): Use -ffile-compilation-dir= here.
1550      cflags += [
1551        "-Xclang",
1552        "-fdebug-compilation-dir",
1553        "-Xclang",
1554        ".",
1555      ]
1556    } else {
1557      # -ffile-compilation-dir is an alias for both -fdebug-compilation-dir=
1558      # and -fcoverage-compilation-dir=.
1559      cflags += [ "-ffile-compilation-dir=." ]
1560      swiftflags += [ "-file-compilation-dir=." ]
1561    }
1562    if (!is_win) {
1563      # We don't use clang -cc1as on Windows (yet? https://crbug.com/762167)
1564      asmflags = [ "-Wa,-fdebug-compilation-dir,." ]
1565    }
1566
1567    if (is_win && use_lld) {
1568      if (symbol_level == 2 || (is_clang && using_sanitizer)) {
1569        # Absolutize source file paths for PDB. Pass the real build directory
1570        # if the pdb contains source-level debug information and if linker
1571        # reproducibility is not critical.
1572        ldflags += [ "/PDBSourcePath:" + rebase_path(root_build_dir) ]
1573      } else {
1574        # Use a fake fixed base directory for paths in the pdb to make the pdb
1575        # output fully deterministic and independent of the build directory.
1576        ldflags += [ "/PDBSourcePath:o:\fake\prefix" ]
1577      }
1578    }
1579  }
1580
1581  # Tells the compiler not to use absolute paths when passing the default
1582  # paths to the tools it invokes. We don't want this because we don't
1583  # really need it and it can mess up the RBE cache entries.
1584  if (is_clang && (!is_nacl || is_nacl_saigo)) {
1585    cflags += [ "-no-canonical-prefixes" ]
1586
1587    # Same for links: Let the compiler driver invoke the linker
1588    # with a relative path and pass relative paths to built-in
1589    # libraries. Not needed on Windows because we call the linker
1590    # directly there, not through the compiler driver.
1591    # We don't link on RBE, so this change is just for cleaner
1592    # internal linker invocations, for people who work on the build.
1593    if (!is_win) {
1594      ldflags += [ "-no-canonical-prefixes" ]
1595    }
1596  }
1597}
1598
1599config("clang_revision") {
1600  if (is_clang && clang_base_path == default_clang_base_path) {
1601    update_args = [
1602      "--print-revision",
1603      "--verify-version=$clang_version",
1604    ]
1605    if (llvm_force_head_revision) {
1606      update_args += [ "--llvm-force-head-revision" ]
1607    }
1608    clang_revision = exec_script("//tools/clang/scripts/update.py",
1609                                 update_args,
1610                                 "trim string")
1611
1612    # This is here so that all files get recompiled after a clang roll and
1613    # when turning clang on or off. (defines are passed via the command line,
1614    # and build system rebuild things when their commandline changes). Nothing
1615    # should ever read this define.
1616    defines = [ "CR_CLANG_REVISION=\"$clang_revision\"" ]
1617  }
1618}
1619
1620config("rustc_revision") {
1621  if (rustc_revision != "") {
1622    # Similar to the above config, this is here so that all files get recompiled
1623    # after a rustc roll. Nothing should ever read this cfg. This will not be
1624    # set if a custom toolchain is used.
1625    rustflags = [
1626      "--cfg",
1627      "cr_rustc_revision=\"$rustc_revision\"",
1628    ]
1629  }
1630}
1631
1632config("compiler_arm_fpu") {
1633  if (current_cpu == "arm" && !is_ios && !is_nacl) {
1634    cflags = [ "-mfpu=$arm_fpu" ]
1635    if (!arm_use_thumb) {
1636      cflags += [ "-marm" ]
1637    }
1638    asmflags = cflags
1639  }
1640}
1641
1642config("compiler_arm_thumb") {
1643  if (current_cpu == "arm" && arm_use_thumb && is_posix &&
1644      !(is_apple || is_nacl)) {
1645    cflags = [ "-mthumb" ]
1646  }
1647}
1648
1649config("compiler_arm") {
1650  if (current_cpu == "arm" && is_chromeos) {
1651    # arm is normally the default mode for clang, but on chromeos a wrapper
1652    # is used to pass -mthumb, and therefor change the default.
1653    cflags = [ "-marm" ]
1654  }
1655}
1656
1657# runtime_library -------------------------------------------------------------
1658#
1659# Sets the runtime library and associated options.
1660#
1661# How do you determine what should go in here vs. "compiler" above? Consider if
1662# a target might choose to use a different runtime library (ignore for a moment
1663# if this is possible or reasonable on your system). If such a target would want
1664# to change or remove your option, put it in the runtime_library config. If a
1665# target wants the option regardless, put it in the compiler config.
1666
1667config("runtime_library") {
1668  configs = []
1669
1670  # The order of this config is important: it must appear before
1671  # android:runtime_library.  This is to ensure libc++ appears before
1672  # libandroid_support in the -isystem include order.  Otherwise, there will be
1673  # build errors related to symbols declared in math.h.
1674  if (use_custom_libcxx) {
1675    configs += [ "//build/config/c++:runtime_library" ]
1676  }
1677
1678  # Rust and C++ both provide intrinsics for LLVM to call for math operations. We
1679  # want to use the C++ intrinsics, not the ones in the Rust compiler_builtins
1680  # library. The Rust symbols are marked as weak, so that they can be replaced by
1681  # the C++ symbols. This config ensures the C++ symbols exist and are strong in
1682  # order to cause that replacement to occur by explicitly linking in clang's
1683  # compiler-rt library.
1684  if (is_clang && toolchain_has_rust) {
1685    configs += [ "//build/config/clang:compiler_builtins" ]
1686  }
1687
1688  # TODO(crbug.com/40570904): Come up with a better name for is POSIX + Fuchsia
1689  # configuration.
1690  if (is_posix || is_fuchsia) {
1691    configs += [ "//build/config/posix:runtime_library" ]
1692
1693    if (use_custom_libunwind) {
1694      # Instead of using an unwind lib from the toolchain,
1695      # buildtools/third_party/libunwind will be built and used directly.
1696      ldflags = [ "--unwindlib=none" ]
1697    }
1698  }
1699
1700  # System-specific flags. If your compiler flags apply to one of the
1701  # categories here, add it to the associated file to keep this shared config
1702  # smaller.
1703  if (is_win) {
1704    configs += [ "//build/config/win:runtime_library" ]
1705  } else if (is_linux || is_chromeos) {
1706    configs += [ "//build/config/linux:runtime_library" ]
1707    if (is_chromeos) {
1708      configs += [ "//build/config/chromeos:runtime_library" ]
1709    }
1710  } else if (is_ios) {
1711    configs += [ "//build/config/ios:runtime_library" ]
1712  } else if (is_mac) {
1713    configs += [ "//build/config/mac:runtime_library" ]
1714  } else if (is_android) {
1715    configs += [ "//build/config/android:runtime_library" ]
1716  }
1717
1718  if (is_component_build) {
1719    defines = [ "COMPONENT_BUILD" ]
1720  }
1721}
1722
1723# treat_warnings_as_errors ----------------------------------------------------
1724#
1725# Adding this config causes the compiler to treat warnings as fatal errors.
1726# This is used as a subconfig of both chromium_code and no_chromium_code, and
1727# is broken out separately so nocompile tests can force-enable this setting
1728# independently of the default warning flags.
1729config("treat_warnings_as_errors") {
1730  if (is_win) {
1731    cflags = [ "/WX" ]
1732  } else {
1733    cflags = [ "-Werror" ]
1734
1735    # The compiler driver can sometimes (rarely) emit warnings before calling
1736    # the actual linker.  Make sure these warnings are treated as errors as
1737    # well.
1738    ldflags = [ "-Werror" ]
1739  }
1740
1741  # Turn rustc warnings into the "deny" lint level, which produce compiler
1742  # errors. The equivalent of -Werror for clang/gcc.
1743  #
1744  # Note we apply the actual lint flags in config("compiler"). All warnings
1745  # are suppressed in third-party crates.
1746  rustflags = [ "-Dwarnings" ]
1747
1748  # TODO(https://crbug.com/326247202): Fix unused imports and remove this flag.
1749  rustflags += [ "-Aunused-imports" ]
1750}
1751
1752# default_warnings ------------------------------------------------------------
1753#
1754# Collects all warning flags that are used by default.  This is used as a
1755# subconfig of both chromium_code and no_chromium_code.  This way these
1756# flags are guaranteed to appear on the compile command line after -Wall.
1757config("default_warnings") {
1758  cflags = []
1759  cflags_c = []
1760  cflags_cc = []
1761  ldflags = []
1762  configs = []
1763
1764  if (is_win) {
1765    if (fatal_linker_warnings) {
1766      arflags = [ "/WX" ]
1767      ldflags = [ "/WX" ]
1768    }
1769    defines = [
1770      # Without this, Windows headers warn that functions like wcsnicmp
1771      # should be spelled _wcsnicmp. But all other platforms keep spelling
1772      # it wcsnicmp, making this warning unhelpful. We don't want it.
1773      "_CRT_NONSTDC_NO_WARNINGS",
1774
1775      # TODO(thakis): winsock wants us to use getaddrinfo instead of
1776      # gethostbyname. Fires mostly in non-Chromium code. We probably
1777      # want to remove this define eventually.
1778      "_WINSOCK_DEPRECATED_NO_WARNINGS",
1779    ]
1780    if (!is_clang) {
1781      # TODO(thakis): Remove this once
1782      # https://swiftshader-review.googlesource.com/c/SwiftShader/+/57968 has
1783      # rolled into angle.
1784      cflags += [ "/wd4244" ]
1785    }
1786  } else {
1787    if ((is_apple || is_android) && !is_nacl) {
1788      # Warns if a method is used whose availability is newer than the
1789      # deployment target.
1790      cflags += [ "-Wunguarded-availability" ]
1791    }
1792
1793    if (is_ios) {
1794      # When compiling Objective-C, warns if a selector named via @selector has
1795      # not been defined in any visible interface.
1796      cflags += [ "-Wundeclared-selector" ]
1797
1798      # Blink builds use a higher deployment target than non-Blink builds, so
1799      # suppress deprecation warnings in these builds.
1800      if (use_blink) {
1801        cflags += [ "-Wno-deprecated-declarations" ]
1802      }
1803    }
1804
1805    # Suppress warnings about ABI changes on ARM (Clang doesn't give this
1806    # warning).
1807    if (current_cpu == "arm" && !is_clang) {
1808      cflags += [ "-Wno-psabi" ]
1809    }
1810
1811    if (!is_clang) {
1812      cflags_cc += [
1813        # See comment for -Wno-c++11-narrowing.
1814        "-Wno-narrowing",
1815      ]
1816
1817      # -Wno-class-memaccess warns about hash table and vector in blink.
1818      # But the violation is intentional.
1819      if (!is_nacl) {
1820        cflags_cc += [ "-Wno-class-memaccess" ]
1821      }
1822
1823      # -Wunused-local-typedefs is broken in gcc,
1824      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63872
1825      cflags += [ "-Wno-unused-local-typedefs" ]
1826
1827      # Don't warn about "maybe" uninitialized. Clang doesn't include this
1828      # in -Wall but gcc does, and it gives false positives.
1829      cflags += [ "-Wno-maybe-uninitialized" ]
1830      cflags += [ "-Wno-deprecated-declarations" ]
1831
1832      # -Wcomment gives too many false positives in the case a
1833      # backslash ended comment line is followed by a new line of
1834      # comments
1835      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61638
1836      cflags += [ "-Wno-comments" ]
1837
1838      # -Wpacked-not-aligned complains all generated mojom-shared-internal.h
1839      # files.
1840      cflags += [ "-Wno-packed-not-aligned" ]
1841    }
1842  }
1843
1844  # Common Clang and GCC warning setup.
1845  if (!is_win || is_clang) {
1846    cflags += [
1847      # Disables.
1848      "-Wno-missing-field-initializers",  # "struct foo f = {0};"
1849      "-Wno-unused-parameter",  # Unused function parameters.
1850    ]
1851
1852    if (!is_nacl || is_nacl_saigo) {
1853      cflags += [
1854        # An ABI compat warning we don't care about, https://crbug.com/1102157
1855        # TODO(thakis): Push this to the (few) targets that need it,
1856        # instead of having a global flag.
1857        "-Wno-psabi",
1858      ]
1859    }
1860  }
1861
1862  if (is_clang) {
1863    cflags += [
1864      "-Wloop-analysis",
1865
1866      # TODO(thakis): This used to be implied by -Wno-unused-function,
1867      # which we no longer use. Check if it makes sense to remove
1868      # this as well. http://crbug.com/316352
1869      "-Wno-unneeded-internal-declaration",
1870    ]
1871
1872    if (!is_nacl || is_nacl_saigo) {
1873      if (is_win) {
1874        # TODO(thakis): https://crbug.com/617318
1875        # Currently RBE can not handle case sensitiveness for windows well.
1876        cflags += [ "-Wno-nonportable-include-path" ]
1877      }
1878
1879      if (is_fuchsia) {
1880        cflags_cc += [
1881          # TODO(crbug.com/42050603): fix and reenable
1882          "-Wno-missing-field-initializers",
1883
1884          # TODO(https://crbug.com/324953188): fix and reenable
1885          "-Wno-extra-qualification",
1886        ]
1887      }
1888
1889      cflags += [
1890        # TODO(crbug.com/330524456): -Wcast-function-type is under -Wextra now.
1891        "-Wno-cast-function-type",
1892
1893        # Ignore warnings about MSVC optimization pragmas.
1894        # TODO(thakis): Only for no_chromium_code? http://crbug.com/912662
1895        "-Wno-ignored-pragma-optimize",
1896
1897        # TODO(crbug.com/40231599) Evaluate and possibly enable.
1898        "-Wno-deprecated-builtins",
1899
1900        # TODO(crbug.com/40234766) Evaluate and possibly enable.
1901        "-Wno-bitfield-constant-conversion",
1902
1903        # TODO(crbug.com/40255410) Evaluate and possibly enable.
1904        "-Wno-deprecated-this-capture",
1905
1906        # TODO(crbug.com/40285259): Fix and re-enable.
1907        "-Wno-invalid-offsetof",
1908
1909        # TODO(crbug.com/40286317): Evaluate and possibly enable.
1910        "-Wno-vla-extension",
1911
1912        # TODO(crbug.com/40284799): Fix and re-enable.
1913        "-Wno-thread-safety-reference-return",
1914      ]
1915
1916      cflags_cc += [
1917        # TODO(crbug.com/328490295): Fix and re-enable for C flags.
1918        "-Wenum-compare-conditional",
1919      ]
1920
1921      if (!is_nacl) {
1922        cflags_cc += [
1923          # TODO(crbug.com/41486292): Fix and re-enable.
1924          "-Wno-c++11-narrowing-const-reference",
1925        ]
1926
1927        if (llvm_force_head_revision) {
1928          # TODO(crbug.com/344680447): Fix and re-enable.
1929          cflags_cc += [ "-Wno-missing-template-arg-list-after-template-kw" ]
1930        }
1931      }
1932    }
1933
1934    # Some builders, such as Cronet, use a different version of Clang than
1935    # Chromium. This can cause minor errors when compiling Chromium changes. We
1936    # want to avoid these errors.
1937    if (llvm_android_mainline) {
1938      cflags += [
1939        "-Wno-error=unknown-warning-option",
1940        "-Wno-error=unused-command-line-argument",
1941        "-Wno-error=unknown-pragmas",
1942      ]
1943    }
1944  }
1945
1946  # Rust warnings
1947
1948  # Require `unsafe` blocks even in `unsafe` fns. This is intended to become
1949  # an error by default eventually; see
1950  # https://github.com/rust-lang/rust/issues/71668
1951  rustflags = [ "-Dunsafe_op_in_unsafe_fn" ]
1952}
1953
1954# prevent_unsafe_narrowing ----------------------------------------------------
1955#
1956# Warnings that prevent narrowing or comparisons of integer types that are
1957# likely to cause out-of-bound read/writes or Undefined Behaviour. In
1958# particular, size_t is used for memory sizes, allocation, indexing, and
1959# offsets. Using other integer types along with size_t produces risk of
1960# memory-safety bugs and thus security exploits.
1961#
1962# In order to prevent these bugs, allocation sizes were historically limited to
1963# sizes that can be represented within 31 bits of information, allowing `int` to
1964# be safely misused instead of `size_t` (https://crbug.com/169327). In order to
1965# support increasing the allocation limit we require strictly adherence to
1966# using the correct types, avoiding lossy conversions, and preventing overflow.
1967# To do so, enable this config and fix errors by converting types to be
1968# `size_t`, which is both large enough and unsigned, when dealing with memory
1969# sizes, allocations, indices, or offsets.In cases where type conversion is not
1970# possible or is superfluous, use base::strict_cast<> or base::checked_cast<>
1971# to convert to size_t as needed.
1972# See also: https://docs.google.com/document/d/1CTbQ-5cQjnjU8aCOtLiA7G6P0i5C6HpSDNlSNq6nl5E
1973#
1974# To enable in a GN target, use:
1975#   configs += [ "//build/config/compiler:prevent_unsafe_narrowing" ]
1976
1977config("prevent_unsafe_narrowing") {
1978  if (is_clang) {
1979    cflags = [
1980      "-Wshorten-64-to-32",
1981      "-Wimplicit-int-conversion",
1982      "-Wsign-compare",
1983      "-Wsign-conversion",
1984    ]
1985    if (!is_nacl) {
1986      cflags += [
1987        # Avoid bugs of the form `if (size_t i = size; i >= 0; --i)` while
1988        # fixing types to be sign-correct.
1989        "-Wtautological-unsigned-zero-compare",
1990      ]
1991    }
1992  }
1993}
1994
1995# chromium_code ---------------------------------------------------------------
1996#
1997# Toggles between higher and lower warnings for code that is (or isn't)
1998# part of Chromium.
1999
2000config("chromium_code") {
2001  if (is_win) {
2002    if (is_clang) {
2003      cflags = [ "/W4" ]  # Warning level 4.
2004
2005      # Opt in to additional [[nodiscard]] on standard library methods.
2006      defines = [ "_HAS_NODISCARD" ]
2007    }
2008  } else {
2009    cflags = [ "-Wall" ]
2010    if (is_clang) {
2011      # Enable extra warnings for chromium_code when we control the compiler.
2012      cflags += [ "-Wextra" ]
2013    }
2014
2015    # In Chromium code, we define __STDC_foo_MACROS in order to get the
2016    # C99 macros on Mac and Linux.
2017    defines = [
2018      "__STDC_CONSTANT_MACROS",
2019      "__STDC_FORMAT_MACROS",
2020    ]
2021
2022    if (!is_debug && !using_sanitizer && current_cpu != "s390x" &&
2023        current_cpu != "s390" && current_cpu != "ppc64" &&
2024        current_cpu != "mips" && current_cpu != "mips64" &&
2025        current_cpu != "riscv64" && current_cpu != "loong64") {
2026      # Non-chromium code is not guaranteed to compile cleanly with
2027      # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are
2028      # disabled, so only do that for Release build.
2029      fortify_level = "2"
2030
2031      # ChromeOS's toolchain supports a high-quality _FORTIFY_SOURCE=3
2032      # implementation with a few custom glibc patches. Use that if it's
2033      # available.
2034      if (is_chromeos_device && !lacros_use_chromium_toolchain) {
2035        fortify_level = "3"
2036      }
2037      defines += [ "_FORTIFY_SOURCE=" + fortify_level ]
2038    }
2039
2040    if (is_apple) {
2041      cflags_objc = [ "-Wimplicit-retain-self" ]
2042      cflags_objcc = [ "-Wimplicit-retain-self" ]
2043    }
2044
2045    if (is_mac) {
2046      cflags_objc += [ "-Wobjc-missing-property-synthesis" ]
2047      cflags_objcc += [ "-Wobjc-missing-property-synthesis" ]
2048    }
2049  }
2050
2051  if (is_clang) {
2052    cflags += [
2053      # Warn on missing break statements at the end of switch cases.
2054      # For intentional fallthrough, use [[fallthrough]].
2055      "-Wimplicit-fallthrough",
2056
2057      # Warn on unnecessary extra semicolons outside of function definitions.
2058      "-Wextra-semi",
2059
2060      # Warn on unreachable code, including unreachable breaks and returns.
2061      # See https://crbug.com/346399#c148 for suppression strategies.
2062      "-Wunreachable-code-aggressive",
2063    ]
2064
2065    # Thread safety analysis is broken under nacl: https://crbug.com/982423.
2066    if (!is_nacl || is_nacl_saigo) {
2067      cflags += [
2068        # Thread safety analysis. See base/thread_annotations.h and
2069        # https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
2070        "-Wthread-safety",
2071      ]
2072    }
2073  }
2074
2075  configs = [
2076    ":default_warnings",
2077    ":noshadowing",
2078  ]
2079  if (treat_warnings_as_errors) {
2080    configs += [ ":treat_warnings_as_errors" ]
2081  }
2082}
2083
2084config("no_chromium_code") {
2085  cflags = []
2086  cflags_cc = []
2087  defines = []
2088
2089  if (is_win) {
2090    if (is_clang) {
2091      cflags += [ "/W3" ]  # Warning level 3.
2092    }
2093    cflags += [
2094      "/wd4800",  # Disable warning when forcing value to bool.
2095      "/wd4267",  # TODO(jschuh): size_t to int.
2096    ]
2097  } else {
2098    if (is_clang && !is_nacl) {
2099      # TODO(thakis): Remove !is_nacl once
2100      # https://codereview.webrtc.org/1552863002/ made its way into chromium.
2101      cflags += [ "-Wall" ]
2102    }
2103  }
2104
2105  if (is_clang) {
2106    cflags += [
2107      # Lots of third-party libraries have unused variables. Instead of
2108      # suppressing them individually, we just blanket suppress them here.
2109      "-Wno-unused-variable",
2110
2111      # Similarly, we're not going to fix all the C++11 narrowing issues in
2112      # third-party libraries.
2113      "-Wno-c++11-narrowing",
2114    ]
2115    if (!is_nacl) {
2116      cflags += [
2117        # Disabled for similar reasons as -Wunused-variable.
2118        "-Wno-unused-but-set-variable",
2119
2120        # TODO(crbug.com/40762742): Clean up and enable.
2121        "-Wno-misleading-indentation",
2122      ]
2123    }
2124  }
2125
2126  # Suppress all warnings in third party, as Cargo does:
2127  # https://doc.rust-lang.org/rustc/lints/levels.html#capping-lints
2128  rustflags = [ "--cap-lints=allow" ]
2129
2130  configs = [ ":default_warnings" ]
2131
2132  # GCC may emit unsuppressible warnings so only apply this config when
2133  # building with clang. crbug.com/589724
2134  if (treat_warnings_as_errors && is_clang) {
2135    configs += [ ":treat_warnings_as_errors" ]
2136  }
2137}
2138
2139# noshadowing -----------------------------------------------------------------
2140#
2141# Allows turning -Wshadow on.
2142
2143config("noshadowing") {
2144  # This flag has to be disabled for nacl because the nacl compiler is too
2145  # strict about shadowing.
2146  if (is_clang && (!is_nacl || is_nacl_saigo)) {
2147    cflags = [ "-Wshadow" ]
2148  }
2149}
2150
2151# rtti ------------------------------------------------------------------------
2152#
2153# Allows turning Run-Time Type Identification on or off.
2154
2155config("rtti") {
2156  if (is_win) {
2157    cflags_cc = [ "/GR" ]
2158  } else {
2159    cflags_cc = [ "-frtti" ]
2160  }
2161}
2162
2163config("no_rtti") {
2164  # Some sanitizer configs may require RTTI to be left enabled globally
2165  if (!use_rtti) {
2166    if (is_win) {
2167      cflags_cc = [ "/GR-" ]
2168    } else {
2169      cflags_cc = [ "-fno-rtti" ]
2170      cflags_objcc = cflags_cc
2171    }
2172  }
2173}
2174
2175# export_dynamic ---------------------------------------------------------------
2176#
2177# Ensures all exported symbols are added to the dynamic symbol table.  This is
2178# necessary to expose Chrome's custom operator new() and operator delete() (and
2179# other memory-related symbols) to libraries.  Otherwise, they might
2180# (de)allocate memory on a different heap, which would spell trouble if pointers
2181# to heap-allocated memory are passed over shared library boundaries.
2182config("export_dynamic") {
2183  # TODO(crbug.com/40118868): Revisit after target_os flip is completed.
2184  if (is_linux || is_chromeos_lacros || export_libcxxabi_from_executables) {
2185    ldflags = [ "-rdynamic" ]
2186  }
2187}
2188
2189# thin_archive -----------------------------------------------------------------
2190#
2191# Enables thin archives on posix, and on windows when the lld linker is used.
2192# Regular archives directly include the object files used to generate it.
2193# Thin archives merely reference the object files.
2194# This makes building them faster since it requires less disk IO, but is
2195# inappropriate if you wish to redistribute your static library.
2196# This config is added to the global config, so thin archives should already be
2197# enabled.  If you want to make a distributable static library, you need to do 2
2198# things:
2199# 1. Set complete_static_lib so that all dependencies of the library make it
2200#    into the library. See `gn help complete_static_lib` for details.
2201# 2. Remove the thin_archive config, so that the .a file actually contains all
2202#    .o files, instead of just references to .o files in the build directoy
2203config("thin_archive") {
2204  # The macOS and iOS default linker ld64 does not support reading thin
2205  # archives.
2206  if ((is_posix && !is_nacl && (!is_apple || use_lld)) || is_fuchsia) {
2207    arflags = [ "-T" ]
2208  } else if (is_win && use_lld) {
2209    arflags = [ "/llvmlibthin" ]
2210  }
2211}
2212
2213# exceptions -------------------------------------------------------------------
2214#
2215# Allows turning Exceptions on or off.
2216# Note: exceptions are disallowed in Google code.
2217
2218config("exceptions") {
2219  if (is_win) {
2220    # Enables exceptions in the STL.
2221    if (!use_custom_libcxx) {
2222      defines = [ "_HAS_EXCEPTIONS=1" ]
2223    }
2224    cflags_cc = [ "/EHsc" ]
2225  } else {
2226    cflags_cc = [ "-fexceptions" ]
2227    cflags_objcc = cflags_cc
2228  }
2229}
2230
2231config("no_exceptions") {
2232  if (is_win) {
2233    # Disables exceptions in the STL.
2234    # libc++ uses the __has_feature macro to control whether to use exceptions,
2235    # so defining this macro is unnecessary. Defining _HAS_EXCEPTIONS to 0 also
2236    # breaks libc++ because it depends on MSVC headers that only provide certain
2237    # declarations if _HAS_EXCEPTIONS is 1. Those MSVC headers do not use
2238    # exceptions, despite being conditional on _HAS_EXCEPTIONS.
2239    if (!use_custom_libcxx) {
2240      defines = [ "_HAS_EXCEPTIONS=0" ]
2241    }
2242  } else {
2243    cflags_cc = [ "-fno-exceptions" ]
2244    cflags_objcc = cflags_cc
2245  }
2246}
2247
2248# Warnings ---------------------------------------------------------------------
2249
2250# Generate a warning for code that might emit a static initializer.
2251# See: //docs/static_initializers.md
2252# See: https://groups.google.com/a/chromium.org/d/topic/chromium-dev/B9Q5KTD7iCo/discussion
2253config("wglobal_constructors") {
2254  if (is_clang) {
2255    cflags = [ "-Wglobal-constructors" ]
2256  }
2257}
2258
2259# This will generate warnings when using Clang if code generates exit-time
2260# destructors, which will slow down closing the program.
2261# TODO(thakis): Make this a blocklist instead, http://crbug.com/101600
2262config("wexit_time_destructors") {
2263  if (is_clang) {
2264    cflags = [ "-Wexit-time-destructors" ]
2265  }
2266}
2267
2268# Some code presumes that pointers to structures/objects are compatible
2269# regardless of whether what they point to is already known to be valid.
2270# gcc 4.9 and earlier had no way of suppressing this warning without
2271# suppressing the rest of them.  Here we centralize the identification of
2272# the gcc 4.9 toolchains.
2273config("no_incompatible_pointer_warnings") {
2274  cflags = []
2275  if (is_clang) {
2276    cflags += [ "-Wno-incompatible-pointer-types" ]
2277  } else if (current_cpu == "mipsel" || current_cpu == "mips64el") {
2278    cflags += [ "-w" ]
2279  } else if (is_chromeos_ash && current_cpu == "arm") {
2280    cflags += [ "-w" ]
2281  }
2282}
2283
2284# Optimization -----------------------------------------------------------------
2285#
2286# The BUILDCONFIG file sets the "default_optimization" config on targets by
2287# default. It will be equivalent to either "optimize" (release) or
2288# "no_optimize" (debug) optimization configs.
2289#
2290# You can override the optimization level on a per-target basis by removing the
2291# default config and then adding the named one you want:
2292#
2293#   configs -= [ "//build/config/compiler:default_optimization" ]
2294#   configs += [ "//build/config/compiler:optimize_max" ]
2295
2296# Shared settings for both "optimize" and "optimize_max" configs.
2297# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
2298if (is_win) {
2299  common_optimize_on_cflags = [
2300    "/Oy-",  # Disable omitting frame pointers, must be after /O2.
2301    "/Zc:inline",  # Remove unreferenced COMDAT (faster links).
2302  ]
2303  if (!is_asan) {
2304    common_optimize_on_cflags += [
2305      # Put data in separate COMDATs. This allows the linker
2306      # to put bit-identical constants at the same address even if
2307      # they're unrelated constants, which saves binary size.
2308      # This optimization can't be used when ASan is enabled because
2309      # it is not compatible with the ASan ODR checker.
2310      "/Gw",
2311    ]
2312  }
2313  common_optimize_on_ldflags = []
2314
2315  # /OPT:ICF is not desirable in Debug builds, since code-folding can result in
2316  # misleading symbols in stack traces.
2317  if (!is_debug && !is_component_build) {
2318    common_optimize_on_ldflags += [ "/OPT:ICF" ]  # Redundant COMDAT folding.
2319  }
2320
2321  if (is_official_build) {
2322    common_optimize_on_ldflags += [ "/OPT:REF" ]  # Remove unreferenced data.
2323    # TODO(thakis): Add LTO/PGO clang flags eventually, https://crbug.com/598772
2324  }
2325
2326  if (is_clang) {
2327    # See below.
2328    common_optimize_on_cflags += [ "/clang:-fno-math-errno" ]
2329  }
2330} else {
2331  common_optimize_on_cflags = []
2332  common_optimize_on_ldflags = []
2333
2334  if (is_android) {
2335    # TODO(jdduke) Re-enable on mips after resolving linking
2336    # issues with libc++ (crbug.com/456380).
2337    if (current_cpu != "mipsel" && current_cpu != "mips64el") {
2338      common_optimize_on_ldflags += [
2339        # Warn in case of text relocations.
2340        "-Wl,--warn-shared-textrel",
2341      ]
2342    }
2343  }
2344
2345  if (is_apple) {
2346    common_optimize_on_ldflags += [ "-Wl,-dead_strip" ]
2347
2348    if (is_official_build) {
2349      common_optimize_on_ldflags += [
2350        "-Wl,-no_data_in_code_info",
2351        "-Wl,-no_function_starts",
2352      ]
2353    }
2354  } else if (current_os != "aix" && current_os != "zos") {
2355    # Non-Mac Posix flags.
2356    # Aix does not support these.
2357
2358    common_optimize_on_cflags += [
2359      # Put data and code in their own sections, so that unused symbols
2360      # can be removed at link time with --gc-sections.
2361      "-fdata-sections",
2362      "-ffunction-sections",
2363    ]
2364    if ((!is_nacl || is_nacl_saigo) && is_clang) {
2365      # We don't care about unique section names, this makes object files a bit
2366      # smaller.
2367      common_optimize_on_cflags += [ "-fno-unique-section-names" ]
2368    }
2369
2370    if (is_official_build) {
2371      common_optimize_on_ldflags += [
2372        # Specifically tell the linker to perform optimizations.
2373        # See http://lwn.net/Articles/192624/.
2374        # -O2 enables string tail merge optimization in lld.
2375        "-Wl,-O2",
2376      ]
2377    }
2378
2379    common_optimize_on_ldflags += [ "-Wl,--gc-sections" ]
2380  }
2381
2382  # We cannot rely on errno being set after math functions,
2383  # especially since glibc does not set it. Thus, use -fno-math-errno
2384  # so that the compiler knows it can inline math functions.
2385  # Note that this is different from -ffast-math (even though -ffast-math
2386  # implies -fno-math-errno), which also allows a number of unsafe
2387  # optimizations.
2388  common_optimize_on_cflags += [ "-fno-math-errno" ]
2389}
2390
2391config("default_stack_frames") {
2392  if (!is_win) {
2393    if (enable_frame_pointers) {
2394      cflags = [ "-fno-omit-frame-pointer" ]
2395
2396      # Omit frame pointers for leaf functions on x86, otherwise building libyuv
2397      # gives clang's register allocator issues, see llvm.org/PR15798 /
2398      # crbug.com/233709
2399      if (is_clang && current_cpu == "x86" && !is_apple) {
2400        cflags += [ "-momit-leaf-frame-pointer" ]
2401      }
2402    } else {
2403      cflags = [ "-fomit-frame-pointer" ]
2404    }
2405  }
2406  # On Windows, the flag to enable framepointers "/Oy-" must always come after
2407  # the optimization flag [e.g. "/O2"]. The optimization flag is set by one of
2408  # the "optimize" configs, see rest of this file. The ordering that cflags are
2409  # applied is well-defined by the GN spec, and there is no way to ensure that
2410  # cflags set by "default_stack_frames" is applied after those set by an
2411  # "optimize" config. Similarly, there is no way to propagate state from this
2412  # config into the "optimize" config. We always apply the "/Oy-" config in the
2413  # definition for common_optimize_on_cflags definition, even though this may
2414  # not be correct.
2415}
2416
2417# Default "optimization on" config.
2418#
2419# High-end Android: As of April 2024, `-O2` appears to be a good default,
2420# particularly since a selection of "hot" targets are already using `-O3`.
2421# Enabling `-O3` for all targets does not change performance much (according
2422# to Speedometer), but regresses binary size. Using `-O3` as the default:
2423#   - Decreases Speedometer 2.1 score by 0.2% [0].
2424#   - Increases Speedometer 3.0 score by 0.1% [1].
2425#   - Increases binary size by 1.47MB [2] (or 0.8%: the arm64 native code size
2426#     in M124 is 178MB).
2427# ... over `-O2`.
2428#
2429# [0]: https://pinpoint-dot-chromeperf.appspot.com/job/147634a8be0000
2430# [1]: https://pinpoint-dot-chromeperf.appspot.com/job/132bc772be0000
2431# [2]: https://crrev.com/c/5447532
2432config("optimize") {
2433  if (is_win) {
2434    cflags = [ "/O2" ] + common_optimize_on_cflags
2435
2436    # The `-O3` for clang turns on extra optimizations compared to the standard
2437    # `-O2`. But for rust, `-Copt-level=3` is the default and is thus reliable
2438    # to use.
2439    rustflags = [ "-Copt-level=3" ]
2440  } else if (optimize_for_size || is_chromeos) {
2441    # Favor size over speed.
2442    # -Os in clang is more of a size-conscious -O2 than "size at any cost"
2443    # (AKA -Oz).
2444
2445    if (is_fuchsia) {
2446      cflags = [ "-Oz" ] + common_optimize_on_cflags
2447    } else {
2448      cflags = [ "-Os" ] + common_optimize_on_cflags
2449    }
2450
2451    if (is_clang && use_ml_inliner && is_a_target_toolchain && !is_chromeos) {
2452      cflags += [
2453        "-mllvm",
2454        "-enable-ml-inliner=release",
2455      ]
2456    }
2457
2458    # Similar to clang, we optimize with `-Copt-level=s` to keep loop
2459    # vectorization while otherwise optimizing for size.
2460    rustflags = [ "-Copt-level=s" ]
2461  } else {
2462    cflags = [ "-O2" ] + common_optimize_on_cflags
2463
2464    # The `-O3` for clang turns on extra optimizations compared to the standard
2465    # `-O2`. But for rust, `-Copt-level=3` is the default and is thus reliable
2466    # to use.
2467    rustflags = [ "-Copt-level=3" ]
2468  }
2469  ldflags = common_optimize_on_ldflags
2470}
2471
2472# Turn off optimizations.
2473config("no_optimize") {
2474  if (is_win) {
2475    cflags = [
2476      "/Od",  # Disable optimization.
2477      "/Ob0",  # Disable all inlining (on by default).
2478      "/GF",  # Enable string pooling (off by default).
2479    ]
2480
2481    if (target_cpu == "arm64") {
2482      # Disable omitting frame pointers for no_optimize build because stack
2483      # traces on Windows ARM64 rely on it.
2484      cflags += [ "/Oy-" ]
2485    }
2486  } else if (is_android && !android_full_debug) {
2487    # On Android we kind of optimize some things that don't affect debugging
2488    # much even when optimization is disabled to get the binary size down.
2489    if (is_clang) {
2490      cflags = [ "-Oz" ] + common_optimize_on_cflags
2491    } else {
2492      cflags = [ "-Os" ] + common_optimize_on_cflags
2493    }
2494
2495    if (!is_component_build) {
2496      # Required for library partitions. Without this all symbols just end up
2497      # in the base partition.
2498      ldflags = [ "-Wl,--gc-sections" ]
2499    }
2500  } else if (is_fuchsia) {
2501    # On Fuchsia, we optimize for size here to reduce the size of debug build
2502    # packages so they can be run in a KVM. See crbug.com/910243 for details.
2503    cflags = [ "-Og" ]
2504  } else {
2505    cflags = [ "-O0" ]
2506    ldflags = []
2507  }
2508}
2509
2510# Turns up the optimization level. Used to explicitly enable -O2 instead of
2511# -Os for select targets on platforms that use optimize_for_size. No-op
2512# elsewhere.
2513config("optimize_max") {
2514  if (is_nacl && is_nacl_irt) {
2515    # The NaCl IRT is a special case and always wants its own config.
2516    # Various components do:
2517    #   if (!is_debug) {
2518    #     configs -= [ "//build/config/compiler:default_optimization" ]
2519    #     configs += [ "//build/config/compiler:optimize_max" ]
2520    #   }
2521    # So this config has to have the selection logic just like
2522    # "default_optimization", below.
2523    configs = [ "//build/config/nacl:irt_optimize" ]
2524  } else {
2525    ldflags = common_optimize_on_ldflags
2526    if (is_win) {
2527      # Favor speed over size, /O2 must be before the common flags.
2528      # /O2 implies /Ot, /Oi, and /GF.
2529      cflags = [ "/O2" ] + common_optimize_on_cflags
2530    } else if (optimize_for_fuzzing) {
2531      cflags = [ "-O1" ] + common_optimize_on_cflags
2532    } else {
2533      cflags = [ "-O2" ] + common_optimize_on_cflags
2534    }
2535    rustflags = [ "-Copt-level=3" ]
2536  }
2537}
2538
2539# This config can be used to override the default settings for per-component
2540# and whole-program optimization, optimizing the particular target for speed
2541# instead of code size. This config is exactly the same as "optimize_max"
2542# except that we use -O3 instead of -O2 on non-IRT platforms.
2543#
2544# TODO(crbug.com/41259697) - rework how all of these configs are related
2545# so that we don't need this disclaimer.
2546config("optimize_speed") {
2547  if (is_nacl && is_nacl_irt) {
2548    # The NaCl IRT is a special case and always wants its own config.
2549    # Various components do:
2550    #   if (!is_debug) {
2551    #     configs -= [ "//build/config/compiler:default_optimization" ]
2552    #     configs += [ "//build/config/compiler:optimize_max" ]
2553    #   }
2554    # So this config has to have the selection logic just like
2555    # "default_optimization", below.
2556    configs = [ "//build/config/nacl:irt_optimize" ]
2557  } else {
2558    ldflags = common_optimize_on_ldflags
2559    if (is_win) {
2560      # Favor speed over size, /O2 must be before the common flags.
2561      # /O2 implies /Ot, /Oi, and /GF.
2562      cflags = [ "/O2" ] + common_optimize_on_cflags
2563      if (is_clang) {
2564        cflags += [ "/clang:-O3" ]
2565      }
2566    } else if (optimize_for_fuzzing) {
2567      cflags = [ "-O1" ] + common_optimize_on_cflags
2568    } else {
2569      cflags = [ "-O3" ] + common_optimize_on_cflags
2570    }
2571    rustflags = [ "-Copt-level=3" ]
2572  }
2573}
2574
2575config("optimize_fuzzing") {
2576  cflags = [ "-O1" ] + common_optimize_on_cflags
2577  rustflags = [ "-Copt-level=1" ]
2578  ldflags = common_optimize_on_ldflags
2579  visibility = [ ":default_optimization" ]
2580}
2581
2582# The default optimization applied to all targets. This will be equivalent to
2583# either "optimize" or "no_optimize", depending on the build flags.
2584config("default_optimization") {
2585  if (is_nacl && is_nacl_irt) {
2586    # The NaCl IRT is a special case and always wants its own config.
2587    # It gets optimized the same way regardless of the type of build.
2588    configs = [ "//build/config/nacl:irt_optimize" ]
2589  } else if (is_debug) {
2590    configs = [ ":no_optimize" ]
2591  } else if (optimize_for_fuzzing) {
2592    assert(!is_win, "Fuzzing optimize level not supported on Windows")
2593
2594    # Coverage build is quite slow. Using "optimize_for_fuzzing" makes it even
2595    # slower as it uses "-O1" instead of "-O3". Prevent that from happening.
2596    assert(!use_clang_coverage,
2597           "optimize_for_fuzzing=true should not be used with " +
2598               "use_clang_coverage=true.")
2599    configs = [ ":optimize_fuzzing" ]
2600  } else {
2601    configs = [ ":optimize" ]
2602  }
2603}
2604
2605_clang_sample_profile = ""
2606if (is_clang && is_a_target_toolchain) {
2607  if (clang_sample_profile_path != "") {
2608    _clang_sample_profile = clang_sample_profile_path
2609  } else if (clang_use_default_sample_profile) {
2610    assert(build_with_chromium,
2611           "Our default profiles currently only apply to Chromium")
2612    assert(is_android || is_chromeos || is_castos,
2613           "The current platform has no default profile")
2614    if (is_android || is_castos) {
2615      _clang_sample_profile = "//chrome/android/profiles/afdo.prof"
2616    } else {
2617      assert(
2618          chromeos_afdo_platform == "atom" ||
2619              chromeos_afdo_platform == "bigcore" ||
2620              chromeos_afdo_platform == "arm" ||
2621              chromeos_afdo_platform == "arm-exp",
2622          "Only 'atom', 'bigcore', 'arm' and 'arm-exp' are valid ChromeOS profiles.")
2623      _clang_sample_profile =
2624          "//chromeos/profiles/${chromeos_afdo_platform}.afdo.prof"
2625    }
2626  }
2627}
2628
2629# Clang offers a way to assert that AFDO profiles are accurate, which causes it
2630# to optimize functions not represented in a profile more aggressively for size.
2631# This config can be toggled in cases where shaving off binary size hurts
2632# performance too much.
2633config("afdo_optimize_size") {
2634  if (_clang_sample_profile != "" && sample_profile_is_accurate) {
2635    cflags = [ "-fprofile-sample-accurate" ]
2636  }
2637}
2638
2639# GCC and clang support a form of profile-guided optimization called AFDO.
2640# There are some targeted places that AFDO regresses, so we provide a separate
2641# config to allow AFDO to be disabled per-target.
2642config("afdo") {
2643  if (is_clang) {
2644    cflags = []
2645    if (clang_emit_debug_info_for_profiling) {
2646      # Add the following flags to generate debug info for profiling.
2647      cflags += [ "-gline-tables-only" ]
2648      if (!is_nacl) {
2649        cflags += [ "-fdebug-info-for-profiling" ]
2650      }
2651    }
2652    if (_clang_sample_profile != "") {
2653      assert(chrome_pgo_phase == 0, "AFDO can't be used in PGO builds")
2654      rebased_clang_sample_profile =
2655          rebase_path(_clang_sample_profile, root_build_dir)
2656      cflags += [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
2657      if (use_profi) {
2658        cflags += [ "-fsample-profile-use-profi" ]
2659      }
2660
2661      # crbug.com/1459429: ARM builds see failures due to -Wbackend-plugin.
2662      # These seem to be false positives - the complaints are about functions
2663      # marked with `__nodebug__` not having associated debuginfo. In the case
2664      # where this was observed, the `__nodebug__` function was also marked
2665      # `__always_inline__` and had no branches, so AFDO info is likely useless
2666      # there.
2667      cflags += [ "-Wno-backend-plugin" ]
2668      inputs = [ _clang_sample_profile ]
2669    }
2670  } else if (auto_profile_path != "" && is_a_target_toolchain) {
2671    cflags = [ "-fauto-profile=${auto_profile_path}" ]
2672    inputs = [ auto_profile_path ]
2673  }
2674}
2675
2676# Symbols ----------------------------------------------------------------------
2677
2678# The BUILDCONFIG file sets the "default_symbols" config on targets by
2679# default. It will be equivalent to one the three specific symbol levels.
2680#
2681# You can override the symbol level on a per-target basis by removing the
2682# default config and then adding the named one you want:
2683#
2684#   configs -= [ "//build/config/compiler:default_symbols" ]
2685#   configs += [ "//build/config/compiler:symbols" ]
2686
2687# A helper config that all configs passing /DEBUG to the linker should
2688# include as sub-config.
2689config("win_pdbaltpath") {
2690  visibility = [
2691    ":minimal_symbols",
2692    ":symbols",
2693  ]
2694
2695  # /DEBUG causes the linker to generate a pdb file, and to write the absolute
2696  # path to it in the executable file it generates.  This flag turns that
2697  # absolute path into just the basename of the pdb file, which helps with
2698  # build reproducibility. Debuggers look for pdb files next to executables,
2699  # so there's minimal downside to always using this. However, post-mortem
2700  # debugging of Chromium crash dumps and ETW tracing can be complicated by this
2701  # switch so an option to omit it is important.
2702  if (!use_full_pdb_paths) {
2703    ldflags = [ "/pdbaltpath:%_PDB%" ]
2704  }
2705}
2706
2707# Full symbols.
2708config("symbols") {
2709  rustflags = []
2710  if (is_win) {
2711    if (is_clang) {
2712      cflags = [
2713        # Debug information in the .obj files.
2714        "/Z7",
2715
2716        # Disable putting the compiler command line into the debug info to
2717        # prevent some types of non-determinism.
2718        "-gno-codeview-command-line",
2719      ]
2720    } else {
2721      cflags = [ "/Zi" ]  # Produce PDB file, no edit and continue.
2722    }
2723
2724    if (is_clang && use_lld && use_ghash) {
2725      cflags += [ "-gcodeview-ghash" ]
2726      ldflags = [ "/DEBUG:GHASH" ]
2727    } else {
2728      ldflags = [ "/DEBUG" ]
2729    }
2730
2731    # All configs using /DEBUG should include this:
2732    configs = [ ":win_pdbaltpath" ]
2733  } else {
2734    cflags = []
2735    if (is_mac && enable_dsyms) {
2736      # If generating dSYMs, specify -fno-standalone-debug. This was
2737      # originally specified for https://crbug.com/479841 because dsymutil
2738      # could not handle a 4GB dSYM file. But dsymutil from Xcodes prior to
2739      # version 7 also produces debug data that is incompatible with Breakpad
2740      # dump_syms, so this is still required (https://crbug.com/622406).
2741      cflags += [ "-fno-standalone-debug" ]
2742    }
2743
2744    # On aix -gdwarf causes linker failures due to thread_local variables.
2745    if (!is_nacl && current_os != "aix") {
2746      if (use_dwarf5) {
2747        cflags += [ "-gdwarf-5" ]
2748        rustflags += [ "-Zdwarf-version=5" ]
2749      } else {
2750        # Recent clang versions default to DWARF5 on Linux, and Android is about
2751        # to switch. TODO: Adopt that in controlled way. For now, keep DWARF4.
2752        # Apple platforms still default to 4 in clang, so they don't need the
2753        # cflags.
2754        if (!is_apple) {
2755          cflags += [ "-gdwarf-4" ]
2756        }
2757
2758        # On Apple, rustc defaults to DWARF2 so it needs to be told how to
2759        # match clang.
2760        rustflags += [ "-Zdwarf-version=4" ]
2761      }
2762    }
2763
2764    # The gcc-based nacl compilers don't support -fdebug-compilation-dir (see
2765    # elsewhere in this file), so they can't have build-dir-independent output.
2766    # Moreover pnacl does not support newer flags such as -fdebug-prefix-map
2767    # Disable symbols for nacl object files to get deterministic,
2768    # build-directory-independent output.
2769    # Keeping -g2 for saigo as it's the only toolchain whose artifacts that are
2770    # part of chromium release (other nacl toolchains are used only for tests).
2771    if ((!is_nacl || is_nacl_saigo) && current_os != "zos") {
2772      cflags += [ "-g2" ]
2773    }
2774
2775    if (!is_nacl && is_clang && !is_tsan && !is_asan) {
2776      # gcc generates dwarf-aranges by default on -g1 and -g2. On clang it has
2777      # to be manually enabled.
2778      #
2779      # It is skipped in tsan and asan because enabling it causes some
2780      # formatting changes in the output which would require fixing bunches
2781      # of expectation regexps.
2782      cflags += [ "-gdwarf-aranges" ]
2783    }
2784
2785    if (is_apple) {
2786      swiftflags = [ "-g" ]
2787    }
2788
2789    if (use_debug_fission) {
2790      cflags += [ "-gsplit-dwarf" ]
2791    }
2792    asmflags = cflags
2793    ldflags = []
2794
2795    # Split debug info with all thinlto builds except nacl and apple.
2796    # thinlto requires -gsplit-dwarf in ldflags.
2797    if (use_debug_fission && use_thin_lto && !is_nacl && !is_apple) {
2798      ldflags += [ "-gsplit-dwarf" ]
2799    }
2800
2801    # TODO(thakis): Figure out if there's a way to make this go for 32-bit,
2802    # currently we get "warning:
2803    # obj/native_client/src/trusted/service_runtime/sel_asm/nacl_switch_32.o:
2804    # DWARF info may be corrupt; offsets in a range list entry are in different
2805    # sections" there.  Maybe just a bug in nacl_switch_32.S.
2806    _enable_gdb_index =
2807        symbol_level == 2 && !is_apple && !is_nacl && current_cpu != "x86" &&
2808        current_os != "zos" && use_lld &&
2809        # Disable on non-fission 32-bit Android because it pushes
2810        # libcomponents_unittests over the 4gb size limit.
2811        !(is_android && !use_debug_fission && current_cpu != "x64" &&
2812          current_cpu != "arm64")
2813    if (_enable_gdb_index) {
2814      if (is_clang) {
2815        # This flag enables the GNU-format pubnames and pubtypes sections,
2816        # which lld needs in order to generate a correct GDB index.
2817        # TODO(pcc): Try to make lld understand non-GNU-format pubnames
2818        # sections (llvm.org/PR34820).
2819        cflags += [ "-ggnu-pubnames" ]
2820      }
2821      ldflags += [ "-Wl,--gdb-index" ]
2822    }
2823  }
2824
2825  configs = []
2826
2827  # Compress debug on 32-bit ARM to stay under 4GB file size limit.
2828  # https://b/243982712, https://crbug.com/1354616, https://crbug.com/334073642
2829  if (symbol_level == 2 && !use_debug_fission && !is_nacl &&
2830      (is_chromeos_device || is_android) &&
2831      (current_cpu == "arm" || current_cpu == "x86")) {
2832    configs += [ "//build/config:compress_debug_sections" ]
2833  }
2834
2835  if (is_clang && (!is_nacl || is_nacl_saigo) && current_os != "zos") {
2836    if (is_apple) {
2837      # TODO(crbug.com/40117949): Investigate missing debug info on mac.
2838      # Make sure we don't use constructor homing on mac.
2839      cflags += [
2840        "-Xclang",
2841        "-debug-info-kind=limited",
2842      ]
2843    } else {
2844      # Use constructor homing for debug info. This option reduces debug info
2845      # by emitting class type info only when constructors are emitted.
2846      cflags += [
2847        "-Xclang",
2848        "-fuse-ctor-homing",
2849      ]
2850    }
2851  }
2852  rustflags += [ "-g" ]
2853}
2854
2855# Minimal symbols.
2856# This config guarantees to hold symbol for stack trace which are shown to user
2857# when crash happens in unittests running on buildbot.
2858config("minimal_symbols") {
2859  rustflags = []
2860  if (is_win) {
2861    # Functions, files, and line tables only.
2862    cflags = []
2863
2864    if (is_clang) {
2865      cflags += [
2866        # Disable putting the compiler command line into the debug info to
2867        # prevent some types of non-determinism.
2868        "-gno-codeview-command-line",
2869      ]
2870    }
2871    if (is_clang && use_lld && use_ghash) {
2872      cflags += [ "-gcodeview-ghash" ]
2873      ldflags = [ "/DEBUG:GHASH" ]
2874    } else {
2875      ldflags = [ "/DEBUG" ]
2876    }
2877
2878    # All configs using /DEBUG should include this:
2879    configs = [ ":win_pdbaltpath" ]
2880
2881    # Enable line tables for clang. MSVC doesn't have an equivalent option.
2882    if (is_clang) {
2883      # -gline-tables-only is the same as -g1, but clang-cl only exposes the
2884      # former.
2885      cflags += [ "-gline-tables-only" ]
2886    }
2887  } else {
2888    cflags = []
2889    if (is_mac && !use_dwarf5) {
2890      # clang defaults to DWARF2 on macOS unless mac_deployment_target is
2891      # at least 10.11.
2892      # TODO(thakis): Remove this once mac_deployment_target is 10.11.
2893      cflags += [ "-gdwarf-4" ]
2894      rustflags += [ "-Zdwarf-version=4" ]
2895    } else if (!use_dwarf5 && !is_nacl && current_os != "aix") {
2896      # On aix -gdwarf causes linker failures due to thread_local variables.
2897      # Recent clang versions default to DWARF5 on Linux, and Android is about
2898      # to switch. TODO: Adopt that in controlled way.
2899      cflags += [ "-gdwarf-4" ]
2900      rustflags += [ "-Zdwarf-version=4" ]
2901    }
2902
2903    if (use_dwarf5 && !is_nacl) {
2904      cflags += [ "-gdwarf-5" ]
2905      rustflags += [ "-Zdwarf-version=5" ]
2906    }
2907
2908    # The gcc-based nacl compilers don't support -fdebug-compilation-dir (see
2909    # elsewhere in this file), so they can't have build-dir-independent output.
2910    # Moreover pnacl does not support newer flags such as -fdebug-prefix-map
2911    # Disable symbols for nacl object files to get deterministic,
2912    # build-directory-independent output.
2913    # Keeping -g1 for saigo as it's the only toolchain whose artifacts that are
2914    # part of chromium release (other nacl toolchains are used only for tests).
2915    if (!is_nacl || is_nacl_saigo) {
2916      cflags += [ "-g1" ]
2917    }
2918
2919    if (!is_nacl && is_clang && !is_tsan && !is_asan) {
2920      # See comment for -gdwarf-aranges in config("symbols").
2921      cflags += [ "-gdwarf-aranges" ]
2922    }
2923
2924    ldflags = []
2925    if (is_android && is_clang) {
2926      # Android defaults to symbol_level=1 builds, but clang, unlike gcc,
2927      # doesn't emit DW_AT_linkage_name in -g1 builds.
2928      # -fdebug-info-for-profiling enables that (and a bunch of other things we
2929      # don't need), so that we get qualified names in stacks.
2930      # TODO(thakis): Consider making clang emit DW_AT_linkage_name in -g1 mode;
2931      #               failing that consider doing this on non-Android too.
2932      cflags += [ "-fdebug-info-for-profiling" ]
2933    }
2934
2935    asmflags = cflags
2936  }
2937  rustflags += [ "-Cdebuginfo=1" ]
2938}
2939
2940# This configuration contains function names only. That is, the compiler is
2941# told to not generate debug information and the linker then just puts function
2942# names in the final debug information.
2943config("no_symbols") {
2944  if (is_win) {
2945    ldflags = [ "/DEBUG" ]
2946
2947    # All configs using /DEBUG should include this:
2948    configs = [ ":win_pdbaltpath" ]
2949  } else {
2950    cflags = [ "-g0" ]
2951    asmflags = cflags
2952  }
2953}
2954
2955# Default symbols.
2956config("default_symbols") {
2957  if (symbol_level == 0) {
2958    configs = [ ":no_symbols" ]
2959  } else if (symbol_level == 1) {
2960    configs = [ ":minimal_symbols" ]
2961  } else if (symbol_level == 2) {
2962    configs = [ ":symbols" ]
2963  } else {
2964    assert(false)
2965  }
2966
2967  # This config is removed by base unittests apk.
2968  if (is_android && is_clang && strip_debug_info) {
2969    configs += [ ":strip_debug" ]
2970  }
2971}
2972
2973config("strip_debug") {
2974  if (!defined(ldflags)) {
2975    ldflags = []
2976  }
2977  ldflags += [ "-Wl,--strip-debug" ]
2978}
2979
2980if (is_apple) {
2981  # On macOS and iOS, this enables support for ARC (automatic reference
2982  # counting). See http://clang.llvm.org/docs/AutomaticReferenceCounting.html.
2983  #
2984  # -fobjc-arc enables ARC overall.
2985  #
2986  # ARC does not add exception handlers to pure Objective-C code, but does add
2987  # them to Objective-C++ code with the rationale that C++ pervasively adds them
2988  # in for exception safety. However, exceptions are banned in Chromium code for
2989  # C++ and exceptions in Objective-C code are intended to be fatal, so
2990  # -fno-objc-arc-exceptions is specified to disable these unwanted exception
2991  # handlers.
2992  config("enable_arc") {
2993    common_flags = [
2994      "-fobjc-arc",
2995      "-fno-objc-arc-exceptions",
2996    ]
2997    cflags_objc = common_flags
2998    cflags_objcc = common_flags
2999  }
3000}
3001
3002if (is_android) {
3003  # Use orderfile for linking Chrome on Android.
3004  # This config enables using an orderfile for linking in LLD.
3005  config("chrome_orderfile_config") {
3006    # Don't try to use an orderfile with call graph sorting, except on Android,
3007    # where we care about memory used by code, so we still want to mandate
3008    # ordering.
3009    if (chrome_orderfile_path != "") {
3010      assert(use_lld)
3011      _rebased_orderfile = rebase_path(chrome_orderfile_path, root_build_dir)
3012      ldflags = [
3013        "-Wl,--symbol-ordering-file",
3014        "-Wl,$_rebased_orderfile",
3015        "-Wl,--no-warn-symbol-ordering",
3016      ]
3017      inputs = [ chrome_orderfile_path ]
3018    }
3019  }
3020}
3021
3022# Initialize all variables on the stack if needed.
3023config("default_init_stack_vars") {
3024  cflags = []
3025  if (init_stack_vars && is_clang && !is_nacl && !using_sanitizer) {
3026    if (init_stack_vars_zero) {
3027      cflags += [ "-ftrivial-auto-var-init=zero" ]
3028    } else {
3029      cflags += [ "-ftrivial-auto-var-init=pattern" ]
3030    }
3031  }
3032}
3033
3034buildflag_header("compiler_buildflags") {
3035  header = "compiler_buildflags.h"
3036
3037  flags = [
3038    "CLANG_PGO=$chrome_pgo_phase",
3039    "SYMBOL_LEVEL=$symbol_level",
3040  ]
3041}
3042
3043config("cet_shadow_stack") {
3044  if (enable_cet_shadow_stack && is_win) {
3045    assert(target_cpu == "x64")
3046    ldflags = [ "/CETCOMPAT" ]
3047  }
3048}
3049