• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium Authors. All rights reserved.
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/config/c++/c++.gni")
6import("//build/config/clang/clang.gni")
7import("//build/config/compiler/compiler.gni")
8import("//build/config/coverage/coverage.gni")
9import("//build/config/sanitizers/sanitizers.gni")
10import("//build/toolchain/cc_wrapper.gni")
11import("//build/toolchain/toolchain.gni")
12
13import("//build/misc/overrides/build.gni")
14
15if (current_cpu == "arm" || current_cpu == "arm64") {
16  import("//build/config/arm.gni")
17}
18if (is_android) {
19  import("//build_plugins/config/aosp/config.gni")
20}
21if (is_ohos) {
22  import("//build/config/ohos/config.gni")
23}
24if (is_mac) {
25  import("//build/config/mac/symbols.gni")
26}
27
28declare_args() {
29  # Default to warnings as errors for default workflow, where we catch
30  # warnings with known toolchains. Allow overriding this e.g. for Chromium
31  # builds on Linux that could use a different version of the compiler.
32  # With GCC, warnings in no-Chromium code are always not treated as errors.
33  treat_warnings_as_errors = true
34
35  # Whether to use the binary binutils checked into third_party/binutils.
36  # These are not multi-arch so cannot be used except on x86 and x86-64 (the
37  # only two architectures that are currently checked in). Turn this off when
38  # you are using a custom toolchain and need to control -B in cflags.
39  linux_use_bundled_binutils =
40      linux_use_bundled_binutils_override && is_linux &&
41      (current_cpu == "x64" || current_cpu == "x86")
42  binutils_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
43                              root_build_dir)
44
45  # Compile in such a way as to make it possible for the profiler to unwind full
46  # stack frames. Setting this flag has a large effect on the performance of the
47  # generated code than just setting profiling, but gives the profiler more
48  # information to analyze.
49  # Requires profiling to be set to true.
50  enable_full_stack_frames_for_profiling = false
51
52  # When we are going to use gold we need to find it.
53  # This is initialized below, after use_gold might have been overridden.
54  gold_path = false
55
56  if (is_win) {
57    # Whether the VS xtree header has been patched to disable warning 4702. If
58    # it has, then we don't need to disable 4702 (unreachable code warning).
59    # The patch is preapplied to the internal toolchain and hence all bots.
60    msvs_xtree_patched = false
61  }
62
63  # Enable fatal linker warnings. Building Chromium with certain versions
64  # of binutils can cause linker warning.
65  # See: https://bugs.chromium.org/p/chromium/issues/detail?id=457359
66  fatal_linker_warnings = true
67
68  # Build with C++ RTTI enabled. Chromium builds without RTTI by default,
69  # but some sanitizers are known to require it, like CFI diagnostics
70  # and UBsan variants.
71  use_rtti = use_cfi_diag || is_ubsan_vptr || is_ubsan_security
72
73  # AFDO (Automatic Feedback Directed Optimizer) is a form of profile-guided
74  # optimization that GCC supports. It used by ChromeOS in their official
75  # builds. To use it, set auto_profile_path to the path to a file containing
76  # the needed gcov profiling data.
77  auto_profile_path = ""
78
79  # Optimize symbol files for maximizing goma cache hit rate. This is on by
80  # default when goma is enabled on Linux and Windows.
81  # But setting this to true may make it harder to debug binaries on Linux.
82  # See below reference for detail.
83  strip_absolute_paths_from_debug_symbols = false
84
85  # Allow projects that wish to stay on C++11 to override Chromium's default.
86  use_cxx11 = false
87
88  # Path to an AFDO profile to use while building with clang, if any. Empty
89  # implies none.
90  clang_sample_profile_path = ""
91
92  # Some configurations have default sample profiles. If this is true and
93  # clang_sample_profile_path is empty, we'll fall back to the default.
94  #
95  # We currently only have default profiles for Chromium in-tree, so we disable
96  # this by default for all downstream projects, since these profiles are likely
97  # nonsensical for said projects.
98  clang_use_default_sample_profile =
99      is_official_build && (is_ohos || is_android || is_desktop_linux)
100
101  # Turn this on to have the compiler output extra timing information.
102  compiler_timing = false
103
104  # Set to true to pass --no-rosegment to lld. This is a workaround
105  # for a KI issue in Valgrind,
106  # https://bugs.kde.org/show_bug.cgi?id=384727
107  ro_segment_workaround_for_valgrind = false
108
109  # Turn this on to use ghash feature of lld for faster debug link on Windows.
110  # http://blog.llvm.org/2018/01/improving-link-time-on-windows-with.html
111  use_ghash = false
112
113  # Whether to enable ThinLTO optimizations. Turning ThinLTO optimizations on
114  # can substantially increase link time and binary size, but they generally
115  # also make binaries a fair bit faster.
116  thin_lto_enable_optimizations = is_chromeos
117
118  # By default only the binaries in official builds get build IDs.
119  force_local_build_id = true
120}
121
122declare_args() {
123  use_cxx11_on_ohos = use_cxx11
124}
125
126declare_args() {
127  # Set to true to use icf, Identical Code Folding.
128  #
129  # icf=all is broken in older golds, see
130  # https://sourceware.org/bugzilla/show_bug.cgi?id=17704
131  # See also https://crbug.com/663886
132  # `linux_use_bundled_binutils` is to avoid breaking Linux destroys which may
133  # still have a buggy gold.
134  # chromeos binutils has been patched with the fix, so always use icf there.
135  # The bug only affects x86 and x64, so we can still use ICF when targeting
136  # other architectures.
137  #
138  # lld doesn't have the bug.
139  use_icf = is_posix && !using_sanitizer && !use_clang_coverage &&
140            !((is_ohos || is_android) && use_order_profiling) &&
141            (use_lld ||
142             (use_gold &&
143              ((!(is_ohos || is_android) && linux_use_bundled_binutils) ||
144               is_chromeos || !(current_cpu == "x86" || current_cpu == "x64"))))
145}
146
147# Apply the default logic for these values if they were not set explicitly.
148if (gold_path == false) {
149  if (use_gold) {
150    gold_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
151                            root_build_dir)
152  } else {
153    gold_path = ""
154  }
155}
156
157if (use_debug_fission == "default") {
158  use_debug_fission = is_debug && !(is_ohos || is_android) && !is_win &&
159                      (use_gold || use_lld) && cc_wrapper == ""
160}
161
162# default_include_dirs ---------------------------------------------------------
163#
164# This is a separate config so that third_party code (which would not use the
165# source root and might have conflicting versions of some headers) can remove
166# this and specify their own include paths.
167config("default_include_dirs") {
168  include_dirs = [
169    "${root_out_dir}/override/third_party",
170    "//",
171    root_gen_dir,
172  ]
173}
174
175# compiler ---------------------------------------------------------------------
176#
177# Base compiler configuration.
178#
179# See also "runtime_library" below for related stuff and a discussion about
180# where stuff should go. Put warning related stuff in the "warnings" config.
181
182config("compiler") {
183  asmflags = []
184  cflags = []
185  cflags_c = []
186  cflags_cc = []
187  cflags_objc = []
188  cflags_objcc = []
189  ldflags = []
190  defines = []
191  configs = []
192  inputs = []
193
194  # System-specific flags. If your compiler flags apply to one of the
195  # categories here, add it to the associated file to keep this shared config
196  # smaller.
197  if (is_win) {
198    configs += [ "//build/config/win:compiler" ]
199  } else if (is_ohos) {
200    configs += [ "//build/config/ohos:compiler" ]
201  } else if (is_linux) {
202    configs += [ "//build/config/linux:compiler" ]
203  } else if (is_nacl) {
204    configs += [ "//build/config/nacl:compiler" ]
205  } else if (is_mac) {
206    configs += [ "//build/config/mac:compiler" ]
207  } else if (current_os == "aix") {
208    configs += [ "//build/config/aix:compiler" ]
209  } else if (is_mingw) {
210    configs += [ "//build/config/mingw:compiler" ]
211  } else if (is_android) {
212    configs += [ "//build_plugins/config/aosp:compiler" ]
213  } else if (is_ios) {
214    configs += [ "//build_plugins/config/ios:compiler" ]
215  }
216
217  configs += [
218    # See the definitions below.
219    ":compiler_cpu_abi",
220    ":compiler_codegen",
221  ]
222
223  if (is_ohos && is_standard_system && is_clang &&
224      (target_cpu == "arm" || target_cpu == "arm64")) {
225    ldflags += [ "-Wl,--pack-dyn-relocs=android+relr" ]
226  }
227
228  # In general, Windows is totally different, but all the other builds share
229  # some common GCC configuration.
230  if (!is_win) {
231    # Common POSIX compiler flags setup.
232    # --------------------------------
233    cflags += [ "-fno-strict-aliasing" ]  # See http://crbug.com/32204
234
235    configs += [ "//build/config/security:stack_protector_config" ]
236
237    # Linker warnings.
238    if (fatal_linker_warnings && !(is_chromeos && current_cpu == "arm") &&
239        !(is_ohos && use_order_profiling) && !is_mac && current_os != "aix" &&
240        !is_mingw && !is_ios) {
241      ldflags += [ "-Wl,--fatal-warnings" ]
242    }
243  } else {
244    cflags += [
245      # Assume UTF-8 by default to avoid code page dependencies.
246      "/utf-8",
247    ]
248    if (is_clang) {
249      # Don't look for includes in %INCLUDE%.
250      cflags += [ "/X" ]
251    }
252  }
253
254  # Eliminate build metadata (__DATE__, __TIME__ and __TIMESTAMP__) for
255  # deterministic build.  See https://crbug.com/314403
256  if (!is_official_build) {
257    if (is_win && !is_clang) {
258      cflags += [
259        "/wd4117",  # Trying to define or undefine a predefined macro.
260        "/D__DATE__=",
261        "/D__TIME__=",
262        "/D__TIMESTAMP__=",
263      ]
264    } else {
265      cflags += [
266        "-Wno-builtin-macro-redefined",
267        "-D__DATE__=",
268        "-D__TIME__=",
269        "-D__TIMESTAMP__=",
270      ]
271    }
272  }
273
274  if (is_clang && is_debug) {
275    # Allow comparing the address of references and 'this' against 0
276    # in debug builds. Technically, these can never be null in
277    # well-defined C/C++ and Clang can optimize such checks away in
278    # release builds, but they may be used in asserts in debug builds.
279    cflags_cc += [
280      "-Wno-undefined-bool-conversion",
281      "-Wno-tautological-undefined-compare",
282    ]
283  }
284
285  if (is_posix && !is_mac) {
286    if (enable_profiling) {
287      if (!is_debug) {
288        cflags += [ "-g" ]
289
290        if (enable_full_stack_frames_for_profiling) {
291          cflags += [
292            "-fno-inline",
293            "-fno-optimize-sibling-calls",
294          ]
295        }
296      }
297    }
298
299    if (!is_mingw && !is_ios && (is_official_build || force_local_build_id)) {
300      # Explicitly pass --build-id to ld. Compilers used to always pass this
301      # implicitly but don't any more (in particular clang when built without
302      # ENABLE_LINKER_BUILD_ID=ON). The crash infrastructure does need a build
303      # id, so explicitly enable it in official builds. It's not needed in
304      # unofficial builds and computing it does slow down the link, so go with
305      # faster links in unofficial builds.
306      ldflags += [ "-Wl,--build-id=md5" ]
307    }
308
309    if (!is_ohos && !is_ohos) {
310      defines += [
311        "_FILE_OFFSET_BITS=64",
312        "_LARGEFILE_SOURCE",
313        "_LARGEFILE64_SOURCE",
314      ]
315    }
316
317    if (!is_nacl) {
318      cflags += [ "-funwind-tables" ]
319    }
320  }
321
322  if (is_linux || is_android || is_ohos) {
323    if (use_pic) {
324      configs += [ "//build/config/security:pic_config" ]
325    }
326
327    if (!is_clang) {
328      # Use pipes for communicating between sub-processes. Faster.
329      # (This flag doesn't do anything with Clang.)
330      cflags += [ "-pipe" ]
331    }
332
333    configs += [ "//build/config/security:-Wl-z_config" ]
334
335    # Compiler instrumentation can introduce dependencies in DSOs to symbols in
336    # the executable they are loaded into, so they are unresolved at link-time.
337    if (is_ohos || (!using_sanitizer && !is_safestack)) {
338      ldflags += [
339        "-Wl,-z,defs",
340        "-Wl,--as-needed",
341      ]
342    }
343
344    # Change default thread stack size to 2MB for asan.
345    if (is_ohos && using_sanitizer) {
346      ldflags += [ "-Wl,-z,stack-size=2097152" ]
347    }
348  }
349
350  # Linux-specific compiler flags setup.
351  # ------------------------------------
352  if (is_android && is_clang) {
353    _rebased_aosp_toolchain_root =
354        rebase_path(aosp_toolchain_root, root_build_dir)
355
356    # Let clang find the linker in the NDK.
357    ldflags += [ "--gcc-toolchain=$_rebased_aosp_toolchain_root" ]
358  }
359
360  if ((is_posix && use_lld) || (target_os == "chromeos" && is_android) ||
361      (is_ohos && use_lld)) {
362    # NOTE: Some Chrome OS builds globally disable LLD, but they also build some
363    # targets against ohos toolchains which should use LLD. Therefore we
364    # explicitly select LLD in these cases.
365    ldflags += [ "-fuse-ld=lld" ]
366    if (current_cpu == "arm64") {
367      # Reduce the page size from 65536 in order to reduce binary size slightly
368      # by shrinking the alignment gap between segments. This also causes all
369      # segments to be mapped adjacently, which breakpad relies on.
370      ldflags += [ "-Wl,-z,max-page-size=4096" ]
371    }
372  } else if (use_gold) {
373    ldflags += [ "-fuse-ld=gold" ]
374    if (!(is_ohos || is_android)) {
375      # On ohos, this isn't needed.  gcc in the NDK knows to look next to
376      # it with -fuse-ld=gold, and clang gets a --gcc-toolchain flag passed
377      # above.
378      ldflags += [ "-B$gold_path" ]
379
380      if (linux_use_bundled_binutils) {
381        ldflags += [
382          # Experimentation found that using four linking threads
383          # saved ~20% of link time.
384          # Only apply this to the target linker, since the host
385          # linker might not be gold, but isn't used much anyway.
386          "-Wl,--threads",
387          "-Wl,--thread-count=4",
388        ]
389      }
390    }
391  } else if (linux_use_bundled_binutils) {
392    # Gold is the default linker for the bundled binutils so we explicitly
393    # enable the bfd linker when use_gold is not set.
394    ldflags += [ "-fuse-ld=bfd" ]
395  }
396
397  if (use_icf) {
398    ldflags += [ "-Wl,--icf=all" ]
399  }
400
401  if (linux_use_bundled_binutils) {
402    cflags += [ "-B$binutils_path" ]
403  }
404
405  if (is_linux) {
406    cflags += [ "-pthread" ]
407    # Do not use the -pthread ldflag here since it becomes a no-op
408    # when using -nodefaultlibs, which would cause an unused argument
409    # error.  "-lpthread" is added in //build/config:default_libs.
410  }
411
412  # Clang-specific compiler flags setup.
413  # ------------------------------------
414  if (is_clang) {
415    cflags += [ "-fcolor-diagnostics" ]
416
417    # Enable -fmerge-all-constants. This used to be the default in clang
418    # for over a decade. It makes clang non-conforming, but is fairly safe
419    # in practice and saves some binary size. We might want to consider
420    # disabling this (https://bugs.llvm.org/show_bug.cgi?id=18538#c13),
421    # but for now it looks like our build might rely on it
422    # (https://crbug.com/829795).
423    cflags += [ "-fmerge-all-constants" ]
424  }
425
426  if (use_lld) {
427    if (is_win) {
428      # On Windows, we call the linker directly, instead of calling it through
429      # the driver.
430      ldflags += [ "--color-diagnostics" ]
431    } else {
432      ldflags += [ "-Wl,--color-diagnostics" ]
433    }
434  }
435
436  if (is_clang && !is_nacl && !use_xcode_clang) {
437    cflags += [
438      "-Xclang",
439      "-mllvm",
440      "-Xclang",
441      "-instcombine-lower-dbg-declare=0",
442    ]
443  }
444
445  # Print absolute paths in diagnostics. There is no precedent for doing this
446  # on Linux/Mac (GCC doesn't support it), but MSVC does this with /FC and
447  # Windows developers rely on it (crbug.com/636109) so only do this on Windows.
448  if (msvc_use_absolute_paths && is_clang && is_win) {
449    cflags += [ "-fdiagnostics-absolute-paths" ]
450  }
451
452  # Makes builds independent of absolute file path.
453  # Currently disabled for nacl since its toolchain lacks this flag (too old).
454  if (symbol_level != 0 && is_clang && !is_nacl && !is_mac &&
455      strip_absolute_paths_from_debug_symbols) {
456    # If debug option is given, clang includes $cwd in debug info by default.
457    # For such build, this flag generates reproducible obj files even we use
458    # different build directory like "out/feature_a" and "out/feature_b" if
459    # we build same files with same compile flag.
460    # Other paths are already given in relative, no need to normalize them.
461    cflags += [
462      "-Xclang",
463      "-fdebug-compilation-dir",
464      "-Xclang",
465      ".",
466    ]
467
468    if (is_win && use_lld) {
469      if (symbol_level == 2 || (is_clang && using_sanitizer)) {
470        # Absolutize source file path for PDB. Pass the real build directory
471        # if the pdb contains source-level debug information.
472        ldflags += [ "/PDBSourcePath:" + rebase_path(root_build_dir) ]
473      } else {
474        # On Windows, (non-sanitizier) symbol_level 1 builds don't contain
475        # debug information in obj files; the linker just creates enough
476        # debug info at link time to produce symbolized stacks (without line
477        # numbers). In that case, there's no downside in using a fake fixed
478        # base directory for paths in the pdb. This makes the pdb output
479        # fully deterministic and independent of the build directory.
480        assert(symbol_level == 1 && !(is_clang && using_sanitizer))
481        ldflags += [ "/PDBSourcePath:o:\fake\prefix" ]
482      }
483    }
484  }
485
486  # Tells the compiler not to use absolute paths when passing the default
487  # paths to the tools it invokes. We don't want this because we don't
488  # really need it and it can mess up the goma cache entries.
489  if (is_clang && !is_nacl) {
490    cflags += [ "-no-canonical-prefixes" ]
491  }
492
493  # C11/C++11 compiler flags setup.
494  # ---------------------------
495  if (is_linux || is_ohos || is_android || (is_nacl && is_clang) ||
496      current_os == "aix") {
497    if (target_os == "ohos") {
498      cxx11_override = use_cxx11_on_ohos
499    } else {
500      cxx11_override = use_cxx11
501    }
502
503    if (is_clang) {
504      standard_prefix = "c"
505
506      # Since we build with -std=c* and not -std=gnu*, _GNU_SOURCE will not be
507      # defined by the compiler.  However, lots of code relies on the
508      # non-standard features that _GNU_SOURCE enables, so define it manually.
509      defines += [ "_GNU_SOURCE" ]
510
511      if (is_nacl) {
512        # Undefine __STRICT_ANSI__ to get non-standard features which would
513        # otherwise not be enabled by NaCl's sysroots.
514        cflags += [ "-U__STRICT_ANSI__" ]
515      }
516    } else {
517      # Gcc does not support ##__VA_ARGS__ when in standards-conforming mode,
518      # but we use this feature in several places in Chromium.
519      standard_prefix = "gnu"
520    }
521
522    #   cflags_c += [ "-std=${standard_prefix}11" ]
523    if (cxx11_override) {
524      # Override Chromium's default for projects that wish to stay on C++11.
525      cflags_cc += [ "-std=${standard_prefix}++11" ]
526    } else {
527      cflags_cc += [ "-std=${standard_prefix}++17" ]
528    }
529  } else if (!is_win && !is_nacl && !is_mingw) {
530    if (target_os == "ohos") {
531      cxx11_override = use_cxx11_on_ohos
532    } else {
533      cxx11_override = use_cxx11
534    }
535
536    if (cxx11_override) {
537      cflags_cc += [ "-std=c++11" ]
538    } else {
539      cflags_cc += [ "-std=c++17" ]
540    }
541  }
542
543  if (is_mac) {
544    # The system libc++ on Mac doesn't have aligned allocation in C++17.
545    defines += [ "_LIBCPP_HAS_NO_ALIGNED_ALLOCATION" ]
546    cflags_cc += [ "-stdlib=libc++" ]
547    ldflags += [ "-stdlib=libc++" ]
548  }
549
550  # Add flags for link-time optimization. These flags enable
551  # optimizations/transformations that require whole-program visibility at link
552  # time, so they need to be applied to all translation units, and we may end up
553  # with miscompiles if only part of the program is compiled with LTO flags. For
554  # that reason, we cannot allow targets to enable or disable these flags, for
555  # example by disabling the optimize configuration.
556  if (!is_debug && use_thin_lto &&
557      (current_toolchain == default_toolchain ||
558       ((is_ohos || is_android) && defined(ohoa_secondary_abi_toolchain) &&
559        current_toolchain == ohos_secondary_abi_toolchain))) {
560    assert(use_lld || target_os == "chromeos",
561           "gold plugin only supported with ChromeOS")
562
563    cflags += [ "-flto=thin" ]
564
565    if (thin_lto_enable_optimizations) {
566      lto_opt_level = 2
567    } else {
568      lto_opt_level = 0
569    }
570
571    if (is_win) {
572      # This is a straight translation of the non-Windows flags below,
573      # except we do not use the ThinLTO cache, which leaks temporary
574      # files on Windows (https://crbug.com/871962).
575      ldflags += [
576        "/opt:lldlto=" + lto_opt_level,
577        "/opt:lldltojobs=8",
578      ]
579    } else {
580      ldflags += [ "-flto=thin" ]
581
582      # Limit the parallelism to avoid too aggressive competition between
583      # linker jobs. This is still suboptimal to a potential dynamic
584      # resource allocation scheme, but should be good enough.
585      if (use_lld) {
586        # Limit the size of the ThinLTO cache to the lesser of 10% of available disk
587        # space, 10GB and 100000 files.
588        cache_policy =
589            "cache_size=10%:cache_size_bytes=10g:cache_size_files=100000"
590        ldflags += [
591          "-Wl,--thinlto-jobs=8",
592          "-Wl,--thinlto-cache-dir=" +
593              rebase_path("$root_out_dir/thinlto-cache", root_build_dir),
594          "-Wl,--thinlto-cache-policy,$cache_policy",
595        ]
596      } else {
597        ldflags += [ "-Wl,-plugin-opt,jobs=8" ]
598      }
599
600      if (use_lld) {
601        ldflags += [ "-Wl,--lto-O" + lto_opt_level ]
602        if (thin_lto_enable_optimizations) {
603          if (is_ohos || is_android) {
604            ldflags += [
605              "-Wl,-mllvm",
606              "-Wl,-import-instr-limit=5",
607            ]
608          }
609        }
610      } else {
611        not_needed([ "lto_opt_level" ])
612      }
613    }
614
615    if (!(is_ohos || is_android)) {
616      cflags += [ "-fwhole-program-vtables" ]
617      if (!is_win) {
618        ldflags += [ "-fwhole-program-vtables" ]
619      }
620    }
621
622    # Work-around for http://openradar.appspot.com/20356002
623    if (is_mac) {
624      ldflags += [ "-Wl,-all_load" ]
625    }
626
627    # This flag causes LTO to create an .ARM.attributes section with the correct
628    # architecture. This is necessary because LLD will refuse to link a program
629    # unless the architecture revision in .ARM.attributes is sufficiently new.
630    if (current_cpu == "arm") {
631      ldflags += [ "-march=$arm_arch" ]
632    }
633  }
634
635  if (compiler_timing) {
636    if (is_clang) {
637      if (is_win) {
638        cflags += [ "-Xclang" ]
639      }
640      cflags += [ "-ftime-report" ]
641    } else if (is_win) {
642      cflags += [
643        # "Documented" here:
644        # http://aras-p.info/blog/2017/10/23/Best-unknown-MSVC-flag-d2cgsummary/
645        "/d2cgsummary",
646      ]
647    }
648  }
649
650  # Pass flag to LLD to work around issue in Valgrind related to
651  # location of debug symbols.
652  if (use_lld && ro_segment_workaround_for_valgrind) {
653    ldflags += [ "-Wl,--no-rosegment" ]
654  }
655
656  # This flag enforces that member pointer base types are complete. It helps
657  # prevent us from running into problems in the Microsoft C++ ABI (see
658  # https://crbug.com/847724).
659  if (is_clang && !is_nacl && target_os != "chromeos" && !use_xcode_clang &&
660      (is_win || use_custom_libcxx)) {
661    cflags += [ "-fcomplete-member-pointers" ]
662  }
663
664  # Pass the same C/C++ flags to the objective C/C++ compiler.
665  cflags_objc += cflags_c
666  cflags_objcc += cflags_cc
667
668  # Assign any flags set for the C compiler to asmflags so that they are sent
669  # to the assembler. The Windows assembler takes different types of flags
670  # so only do so for posix platforms.
671  if (is_posix) {
672    asmflags += cflags
673    asmflags += cflags_c
674  }
675}
676
677# This provides the basic options to select the target CPU and ABI.
678# It is factored out of "compiler" so that special cases can use this
679# without using everything that "compiler" brings in.  Options that
680# tweak code generation for a particular CPU do not belong here!
681# See "compiler_codegen", below.
682config("compiler_cpu_abi") {
683  cflags = []
684  ldflags = []
685  defines = []
686
687  if (is_posix && !is_mac && !is_ios) {
688    # CPU architecture. We may or may not be doing a cross compile now, so for
689    # simplicity we always explicitly set the architecture.
690    if (current_cpu == "x64") {
691      cflags += [
692        "-m64",
693        "-march=x86-64",
694      ]
695      ldflags += [ "-m64" ]
696    } else if (current_cpu == "x86") {
697      cflags += [ "-m32" ]
698      ldflags += [ "-m32" ]
699      if (!is_nacl) {
700        cflags += [
701          "-msse2",
702          "-mfpmath=sse",
703          "-mmmx",
704        ]
705      }
706    } else if (current_cpu == "arm") {
707      if (is_clang && !is_android && !is_ohos && !is_nacl) {
708        cflags += [ "--target=arm-linux-gnueabihf" ]
709        ldflags += [ "--target=arm-linux-gnueabihf" ]
710      }
711      if (!is_nacl) {
712        cflags += [
713          "-march=$arm_arch",
714          "-mfloat-abi=$arm_float_abi",
715        ]
716      }
717      if (arm_tune != "") {
718        cflags += [ "-mtune=$arm_tune" ]
719      }
720    } else if (current_cpu == "arm64") {
721      if (is_clang && !is_android && !is_ohos && !is_nacl) {
722        cflags += [ "--target=aarch64-linux-gnu" ]
723        ldflags += [ "--target=aarch64-linux-gnu" ]
724      }
725      if (is_clang && (is_android || is_ohos)) {
726        ldflags += [ "-Wl,--hash-style=gnu" ]
727      }
728      if (!is_android) {
729        cflags += [
730          "-march=$arm_arch",
731          "-mfloat-abi=$arm_float_abi",
732          "-mfpu=$arm_fpu",
733        ]
734      }
735      ldflags += [ "-march=$arm_arch" ]
736    }
737  }
738
739  asmflags = cflags
740  if (current_cpu == "arm64") {
741    asmflags += [ "-march=armv8.2-a+dotprod+fp16" ]
742  }
743}
744
745# This provides options to tweak code generation that are necessary
746# for particular Chromium code or for working around particular
747# compiler bugs (or the combination of the two).
748config("compiler_codegen") {
749  configs = []
750  cflags = []
751
752  if (is_nacl) {
753    configs += [ "//build/config/nacl:compiler_codegen" ]
754  } else if (is_posix && !is_mac) {
755    if (current_cpu == "x86") {
756      if (is_clang) {
757        cflags += [ "-momit-leaf-frame-pointer" ]
758      }
759    } else if (current_cpu == "arm") {
760      if ((is_ohos || is_android) && !is_clang) {
761        # Clang doesn't support these flags.
762        cflags += [
763          "-fno-tree-sra",
764          "-fno-caller-saves",
765        ]
766      }
767    }
768  }
769
770  asmflags = cflags
771}
772
773config("compiler_arm_fpu") {
774  if (current_cpu == "arm" && !is_nacl) {
775    cflags = [ "-mfpu=$arm_fpu" ]
776    asmflags = cflags
777  }
778}
779
780config("compiler_arm_thumb") {
781  if (current_cpu == "arm" && arm_use_thumb && is_posix &&
782      !(is_mac || is_nacl)) {
783    cflags = [ "-mthumb" ]
784    if ((is_ohos || is_android) && !is_clang) {
785      # Clang doesn't support this option.
786      cflags += [ "-mthumb-interwork" ]
787    }
788  }
789}
790
791config("compiler_arm") {
792  if (current_cpu == "arm" && is_chromeos) {
793    # arm is normally the default mode for clang, but on chromeos a wrapper
794    # is used to pass -mthumb, and therefore change the default.
795    cflags = [ "-marm" ]
796  }
797}
798
799# runtime_library -------------------------------------------------------------
800#
801# Sets the runtime library and associated options.
802#
803# How do you determine what should go in here vs. "compiler" above? Consider if
804# a target might choose to use a different runtime library (ignore for a moment
805# if this is possible or reasonable on your system). If such a target would want
806# to change or remove your option, put it in the runtime_library config. If a
807# target wants the option regardless, put it in the compiler config.
808
809config("runtime_library") {
810  defines = []
811  configs = []
812
813  # The order of this config is important: it must appear before
814  # ohos:runtime_library.
815  if (is_posix) {
816    configs += [ "//build/config/posix:runtime_library" ]
817  }
818
819  # System-specific flags. If your compiler flags apply to one of the
820  # categories here, add it to the associated file to keep this shared config
821  # smaller.
822  if (is_win) {
823    configs += [ "//build/config/win:runtime_library" ]
824  } else if (is_linux) {
825    configs += [ "//build/config/linux:runtime_library" ]
826  } else if (is_mac) {
827    configs += [ "//build/config/mac:runtime_library" ]
828  } else if (is_ohos) {
829    configs += [ "//build/config/ohos:runtime_library" ]
830  } else if (is_android) {
831    configs += [ "//build_plugins/config/aosp:runtime_library" ]
832  } else if (is_ios) {
833    configs += [ "//build_plugins/config/ios:runtime_library" ]
834  }
835
836  if (is_component_build) {
837    defines += [ "COMPONENT_BUILD" ]
838  }
839}
840
841# default_warnings ------------------------------------------------------------
842#
843# Collects all warning flags that are used by default.  This is used as a
844# subconfig of both chromium_code and no_chromium_code.  This way these
845# flags are guaranteed to appear on the compile command line after -Wall.
846config("default_warnings") {
847  cflags = []
848  cflags_cc = []
849  ldflags = []
850
851  if (is_mac && !is_nacl) {
852    # When compiling Objective-C, warns if a method is used whose
853    # availability is newer than the deployment target.
854    cflags += [ "-Wunguarded-availability" ]
855  }
856
857  # Suppress warnings about ABI changes on ARM (Clang doesn't give this
858  # warning).
859  if (current_cpu == "arm" && !is_clang) {
860    cflags += [ "-Wno-psabi" ]
861  }
862
863  if (!is_clang) {
864    cflags_cc += [
865      # See comment for -Wno-c++11-narrowing.
866      "-Wno-narrowing",
867    ]
868
869    # -Wunused-local-typedefs is broken in gcc,
870    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63872
871    cflags += [ "-Wno-unused-local-typedefs" ]
872
873    # Don't warn about "maybe" uninitialized. Clang doesn't include this
874    # in -Wall but gcc does, and it gives false positives.
875    cflags += [ "-Wno-maybe-uninitialized" ]
876    cflags += [ "-Wno-deprecated-declarations" ]
877
878    # GCC assumes 'this' is never nullptr and optimizes away code
879    # like "if (this == nullptr) ...": [1].  However, some Chromium
880    # code relies on these types of null pointer checks [2], so
881    # disable this optimization.
882    # [1] https://gcc.gnu.org/gcc-6/porting_to.html#this-cannot-be-null
883    # [2] https://crbug.com/784492#c13
884    cflags += [ "-fno-delete-null-pointer-checks" ]
885
886    # -Wcomment gives too many false positives in the case a
887    # backslash ended comment line is followed by a new line of
888    # comments
889    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61638
890    cflags += [ "-Wno-comments" ]
891  }
892
893  # Common Clang and GCC warning setup.
894  if (!is_win || is_clang) {
895    cflags += [
896      # Disables.
897      "-Wno-missing-field-initializers",  # "struct foo f = {0};"
898      "-Wno-unused-parameter",  # Unused function parameters.
899    ]
900  }
901
902  if (is_mingw) {
903    cflags += [
904      "-Wno-error=c99-designator",
905      "-Wno-error=anon-enum-enum-conversion",
906      "-Wno-error=implicit-fallthrough",
907      "-Wno-error=sizeof-array-div",
908      "-Wno-error=reorder-init-list",
909      "-Wno-error=range-loop-construct",
910      "-Wno-error=deprecated-copy",
911      "-Wno-error=implicit-int-float-conversion",
912      "-Wno-error=inconsistent-dllimport",
913      "-Wno-error=unknown-warning-option",
914      "-Wno-error=abstract-final-class",
915      "-Wno-error=sign-compare",
916    ]
917  }
918
919  if (is_clang) {
920    cflags += [
921      # This warns on using ints as initializers for floats in
922      # initializer lists (e.g. |int a = f(); CGSize s = { a, a };|),
923      # which happens in several places in chrome code. Not sure if
924      # this is worth fixing.
925      "-Wno-c++11-narrowing",
926      "-Wno-unneeded-internal-declaration",
927    ]
928    if (build_cross_platform_version) {
929      cflags += [
930        "-Wno-error=implicit-int-float-conversion",
931        "-Wno-error=implicit-fallthrough",
932        "-Wno-error=sign-compare",
933        "-Wno-error=c99-designator",
934        "-Wno-error=anon-enum-enum-conversion",
935        "-Wno-error=sizeof-array-div",
936        "-Wno-error=deprecated-copy",
937        "-Wno-error=return-stack-address",
938        "-Wno-error=reserved-identifier",
939        "-Wno-error=suggest-destructor-override",
940        "-Wno-error=suggest-override",
941        "-Wno-error=unused-but-set-variable",
942        "-Wno-error=unused-but-set-parameter",
943        "-Wno-error=option-ignored",
944        "-mno-outline-atomics",
945        "-Wno-deprecated-declarations",
946      ]
947    }
948    if (use_musl) {
949      cflags += [
950        "-Wno-error=c99-designator",
951        "-Wno-error=anon-enum-enum-conversion",
952        "-Wno-error=implicit-fallthrough",
953        "-Wno-error=sizeof-array-div",
954        "-Wno-error=reorder-init-list",
955        "-Wno-error=range-loop-construct",
956        "-Wno-error=deprecated-copy",
957        "-Wno-error=implicit-int-float-conversion",
958        "-Wno-error=inconsistent-dllimport",
959        "-Wno-error=unknown-warning-option",
960        "-Wno-error=abstract-final-class",
961        "-Wno-error=sign-compare",
962        "-Wno-error=int-in-bool-context",
963        "-Wno-error=xor-used-as-pow",
964        "-Wno-error=return-stack-address",
965        "-Wno-error=dangling-gsl",
966        "-Wno-unused-but-set-variable",
967        "-Wno-deprecated-declarations",
968        "-Wno-unused-but-set-parameter",
969        "-Wno-null-pointer-subtraction",
970        "-Wno-unqualified-std-cast-call",
971      ]
972    }
973
974    # use_xcode_clang only refers to the iOS toolchain, host binaries use
975    # chromium's clang always.
976    if (!is_nacl) {
977      cflags += [ "-Wno-undefined-var-template" ]
978      if (current_toolchain == host_toolchain || !use_xcode_clang ||
979          xcode_version_int >= 930) {
980        cflags += [
981          "-Wno-nonportable-include-path",
982          "-Wno-user-defined-warnings",
983          "-Wno-unused-lambda-capture",
984        ]
985      }
986      if (current_toolchain == host_toolchain || !use_xcode_clang ||
987          xcode_version_int >= 1000) {
988        cflags += [ "-Wno-null-pointer-arithmetic" ]
989      }
990      if (current_toolchain == host_toolchain || !use_xcode_clang) {
991        # Flags NaCl (Clang 3.7) and Xcode 9.2 (Clang clang-900.0.39.2) do not
992        # recognize.
993        cflags += [ "-Wno-enum-compare-switch" ]
994      }
995    }
996  }
997}
998
999# chromium_code ---------------------------------------------------------------
1000#
1001# Toggles between higher and lower warnings for code that is (or isn't)
1002# part of Chromium.
1003
1004config("chromium_code") {
1005  if (is_win) {
1006    cflags = [ "/W4" ]  # Warning level 4.
1007
1008    if (is_clang) {
1009      # Opt in to additional [[nodiscard]] on standard library methods.
1010      defines = [ "_HAS_NODISCARD" ]
1011    }
1012  } else {
1013    cflags = [ "-Wall" ]
1014    if (treat_warnings_as_errors && !build_cross_platform_version) {
1015      cflags += [ "-Werror" ]
1016
1017      # The compiler driver can sometimes (rarely) emit warnings before calling
1018      # the actual linker.  Make sure these warnings are treated as errors as
1019      # well.
1020      ldflags = [ "-Werror" ]
1021    }
1022    if (is_clang) {
1023      # Enable extra warnings for chromium_code when we control the compiler.
1024      cflags += [ "-Wextra" ]
1025    }
1026
1027    # In Chromium code, we define __STDC_foo_MACROS in order to get the
1028    # C99 macros on Mac and Linux.
1029    defines = [
1030      "__STDC_CONSTANT_MACROS",
1031      "__STDC_FORMAT_MACROS",
1032    ]
1033
1034    if (!is_debug && !using_sanitizer &&
1035        (!is_linux || !is_clang || is_official_build)) {
1036      # _FORTIFY_SOURCE isn't really supported by Clang now, see
1037      # http://llvm.org/bugs/show_bug.cgi?id=16821.
1038      # It seems to work fine with Ubuntu 12 headers though, so use it in
1039      # official builds.
1040      #
1041      # Non-chromium code is not guaranteed to compile cleanly with
1042      # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are
1043      # disabled, so only do that for Release build.
1044      #
1045      # Need to support fortify ability first in musl libc, so disable the option temporarily
1046      # defines += [ "_FORTIFY_SOURCE=2" ]
1047    }
1048
1049    if (is_mac) {
1050      cflags_objc = [ "-Wobjc-missing-property-synthesis" ]
1051      cflags_objcc = [ "-Wobjc-missing-property-synthesis" ]
1052    }
1053  }
1054
1055  if (is_clang) {
1056    cflags += [
1057      # Warn on missing break statements at the end of switch cases.
1058      # For intentional fallthrough, use FALLTHROUGH; from
1059      # base/compiler_specific.h
1060      "-Wimplicit-fallthrough",
1061
1062      # Thread safety analysis. See base/thread_annotations.h and
1063      # https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
1064      "-Wthread-safety",
1065    ]
1066  }
1067
1068  configs = [ ":default_warnings" ]
1069}
1070
1071config("no_chromium_code") {
1072  cflags = []
1073  cflags_cc = []
1074  defines = []
1075
1076  if (is_win) {
1077    cflags += [
1078      "/W3",  # Warning level 3.
1079      "/wd4800",  # Disable warning when forcing value to bool.
1080      "/wd4267",  # size_t to int.
1081      "/wd4996",  # Deprecated function warning.
1082    ]
1083    defines += [
1084      "_CRT_NONSTDC_NO_WARNINGS",
1085      "_CRT_NONSTDC_NO_DEPRECATE",
1086    ]
1087  } else {
1088    # GCC may emit unsuppressible warnings so don't add -Werror for no chromium
1089    # code. crbug.com/589724
1090    if (treat_warnings_as_errors && is_clang) {
1091      cflags += [ "-Werror" ]
1092      ldflags = [ "-Werror" ]
1093    }
1094    if (is_clang && !is_nacl) {
1095      cflags += [ "-Wall" ]
1096    }
1097  }
1098
1099  if (is_clang) {
1100    cflags += [
1101      # Lots of third-party libraries have unused variables. Instead of
1102      # suppressing them individually, we just blanket suppress them here.
1103      "-Wno-unused-variable",
1104    ]
1105  }
1106
1107  configs = [ ":default_warnings" ]
1108}
1109
1110# noshadowing -----------------------------------------------------------------
1111#
1112# Allows turning -Wshadow on.
1113
1114config("noshadowing") {
1115  # This flag has to be disabled for nacl because the nacl compiler is too
1116  # strict about shadowing.
1117  if (is_clang && !is_nacl) {
1118    cflags = [ "-Wshadow" ]
1119  }
1120}
1121
1122# rtti ------------------------------------------------------------------------
1123#
1124# Allows turning Run-Time Type Identification on or off.
1125
1126config("rtti") {
1127  if (is_win) {
1128    cflags_cc = [ "/GR" ]
1129  } else {
1130    cflags_cc = [ "-frtti" ]
1131  }
1132}
1133
1134config("no_rtti") {
1135  # Some sanitizer configs may require RTTI to be left enabled globally
1136  if (!use_rtti) {
1137    if (is_win) {
1138      cflags_cc = [ "/GR-" ]
1139    } else {
1140      cflags_cc = [ "-fno-rtti" ]
1141      cflags_objcc = cflags_cc
1142    }
1143  }
1144}
1145
1146# export_dynamic ---------------------------------------------------------------
1147#
1148# Ensures all exported symbols are added to the dynamic symbol table.  This is
1149# necessary to expose Chrome's custom operator new() and operator delete() (and
1150# other memory-related symbols) to libraries.  Otherwise, they might
1151# (de)allocate memory on a different heap, which would spell trouble if pointers
1152# to heap-allocated memory are passed over shared library boundaries.
1153config("export_dynamic") {
1154  if (is_desktop_linux || export_libcxxabi_from_executables) {
1155    ldflags = [ "-rdynamic" ]
1156  }
1157}
1158
1159# thin_archive -----------------------------------------------------------------
1160#
1161# Enables thin archives on posix.  Regular archives directly include the object
1162# files used to generate it.  Thin archives merely reference the object files.
1163# This makes building them faster since it requires less disk IO, but is
1164# inappropriate if you wish to redistribute your static library.
1165# This config is added to the global config, so thin archives should already be
1166# enabled.  If you want to make a distributable static library, you need to do 2
1167# things:
1168# 1. Set complete_static_lib so that all dependencies of the library make it
1169#    into the library. See `gn help complete_static_lib` for details.
1170# 2. Remove the thin_archive config, so that the .a file actually contains all
1171#    .o files, instead of just references to .o files in the build directory
1172config("thin_archive") {
1173  # Mac and iOS use the mac-specific "libtool" command, not ar, which doesn't
1174  # have a "thin archive" mode (it does accept -T, but it means truncating
1175  # archive names to 16 characters, which is not what we want).
1176  if (is_posix && !is_nacl && !is_mac) {
1177    arflags = [ "-T" ]
1178  }
1179}
1180
1181# exceptions -------------------------------------------------------------------
1182#
1183# Allows turning Exceptions on or off.
1184
1185config("exceptions") {
1186  if (is_win) {
1187    # Enables exceptions in the STL.
1188    if (!use_custom_libcxx) {
1189      defines = [ "_HAS_EXCEPTIONS=1" ]
1190    }
1191    cflags_cc = [ "/EHsc" ]
1192  } else {
1193    cflags_cc = [ "-fexceptions" ]
1194    cflags_objcc = cflags_cc
1195  }
1196}
1197
1198config("no_exceptions") {
1199  if (is_win) {
1200    # Disables exceptions in the STL.
1201    # libc++ uses the __has_feature macro to control whether to use exceptions,
1202    # so defining this macro is unnecessary. Defining _HAS_EXCEPTIONS to 0 also
1203    # breaks libc++ because it depends on MSVC headers that only provide certain
1204    # declarations if _HAS_EXCEPTIONS is 1. Those MSVC headers do not use
1205    # exceptions, despite being conditional on _HAS_EXCEPTIONS.
1206    if (!use_custom_libcxx) {
1207      defines = [ "_HAS_EXCEPTIONS=0" ]
1208    }
1209  } else {
1210    cflags_cc = [ "-fno-exceptions" ]
1211    cflags_objcc = cflags_cc
1212  }
1213}
1214
1215# Warnings ---------------------------------------------------------------------
1216
1217# This will generate warnings when using Clang if code generates exit-time
1218# destructors, which will slow down closing the program.
1219config("wexit_time_destructors") {
1220  if (is_clang) {
1221    cflags = [ "-Wexit-time-destructors" ]
1222  }
1223}
1224
1225# On Windows compiling on x64, VC will issue a warning when converting
1226# size_t to int because it will truncate the value. Our code should not have
1227# these warnings and one should use a static_cast or a checked_cast for the
1228# conversion depending on the case. However, a lot of code still needs to be
1229# fixed. Apply this config to such targets to disable the warning.
1230#
1231# Note that this can be applied regardless of platform and architecture to
1232# clean up the call sites. This will only apply the flag when necessary.
1233#
1234# This config is just an alias to no_shorten_64_warnings and will
1235# suppress a superset of warning 4267 and any 64-bit -> 32-bit implicit
1236# conversions. Having both for a time means not having to go through and
1237# update all references to no_size_t_to_int_warning throughout the codebase
1238# atomically.
1239#
1240# Any new warning suppressions should use the no_shorten_64_warnings
1241# config below and not this.
1242config("no_size_t_to_int_warning") {
1243  configs = [ ":no_shorten_64_warnings" ]
1244}
1245
1246# As part of re-enabling -Wconversion (see issue 588506) some code
1247# will continue to generate warnings.
1248# The first warning to be enabled will be -Wshorten-64-to-32.
1249#
1250# Code that currently generates warnings for this can include this
1251# config to disable them.
1252config("no_shorten_64_warnings") {
1253  if (current_cpu == "x64" || current_cpu == "arm64") {
1254    if (is_clang) {
1255      cflags = [ "-Wno-shorten-64-to-32" ]
1256    } else {
1257      if (is_win) {
1258        # MSVC does not have an explicit warning equivalent to
1259        # -Wshorten-64-to-32 but 4267 warns for size_t -> int
1260        # on 64-bit builds, so is the closest.
1261        cflags = [ "/wd4267" ]
1262      }
1263    }
1264  }
1265}
1266
1267# Some code presumes that pointers to structures/objects are compatible
1268# regardless of whether what they point to is already known to be valid.
1269# gcc 4.9 and earlier had no way of suppressing this warning without
1270# suppressing the rest of them.  Here we centralize the identification of
1271# the gcc 4.9 toolchains.
1272config("no_incompatible_pointer_warnings") {
1273  cflags = []
1274  if (is_clang) {
1275    cflags += [ "-Wno-incompatible-pointer-types" ]
1276  } else if (is_chromeos && current_cpu == "arm") {
1277    cflags += [ "-w" ]
1278  }
1279}
1280
1281# Optimization -----------------------------------------------------------------
1282#
1283# The BUILDCONFIG file sets the "default_optimization" config on targets by
1284# default. It will be equivalent to either "optimize" (release) or
1285# "no_optimize" (debug) optimization configs.
1286#
1287# You can override the optimization level on a per-target basis by removing the
1288# default config and then adding the named one you want:
1289#
1290#   configs -= [ "//build/config/compiler:default_optimization" ]
1291#   configs += [ "//build/config/compiler:optimize_max" ]
1292
1293# Shared settings for both "optimize" and "optimize_max" configs.
1294# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
1295if (is_win) {
1296  common_optimize_on_cflags = [
1297    "/Ob2",  # Both explicit and auto inlining.
1298    "/Oy-",  # Disable omitting frame pointers, must be after /O2.
1299    "/Zc:inline",  # Remove unreferenced COMDAT (faster links).
1300  ]
1301  if (!is_asan) {
1302    common_optimize_on_cflags += [
1303      # Put data in separate COMDATs. This allows the linker
1304      # to put bit-identical constants at the same address even if
1305      # they're unrelated constants, which saves binary size.
1306      # This optimization can't be used when ASan is enabled because
1307      # it is not compatible with the ASan ODR checker.
1308      "/Gw",
1309    ]
1310  }
1311  common_optimize_on_ldflags = []
1312
1313  # /OPT:ICF is not desirable in Debug builds, since code-folding can result in
1314  # misleading symbols in stack traces. It is also incompatible with
1315  # incremental linking, which we enable for both Debug and component builds.
1316  if (!is_debug && !is_component_build) {
1317    common_optimize_on_ldflags += [ "/OPT:ICF" ]  # Redundant COMDAT folding.
1318  }
1319
1320  if (is_official_build) {
1321    common_optimize_on_ldflags += [ "/OPT:REF" ]  # Remove unreferenced data.
1322
1323    if (!use_lld && !is_clang) {
1324      common_optimize_on_ldflags += [
1325        # Set the number of LTCG code-gen threads to eight. The default is four.
1326        # This gives a 5-10% link speedup.
1327        "/cgthreads:8",
1328      ]
1329      if (use_incremental_wpo) {
1330        # Incremental Link-time code generation.
1331        common_optimize_on_ldflags += [ "/LTCG:INCREMENTAL" ]
1332      } else {
1333        common_optimize_on_ldflags += [ "/LTCG" ]  # Link-time code generation.
1334      }
1335    }
1336  }
1337} else {
1338  common_optimize_on_cflags = []
1339  common_optimize_on_ldflags = []
1340
1341  if (is_ohos) {
1342    common_optimize_on_ldflags += [
1343      # Warn in case of text relocations.
1344      "-Wl,--warn-shared-textrel",
1345    ]
1346  }
1347
1348  if (is_mac || is_ios) {
1349    if (symbol_level == 2) {
1350      # Mac dead code stripping requires symbols.
1351      common_optimize_on_ldflags += [ "-Wl,-dead_strip" ]
1352    }
1353  } else if (current_os != "aix") {
1354    # Non-Mac Posix flags.
1355    # Aix does not support these.
1356
1357    common_optimize_on_cflags += [
1358      # Don't emit the GCC version ident directives, they just end up in the
1359      # .comment section taking up binary size.
1360      "-fno-ident",
1361
1362      # Put data and code in their own sections, so that unused symbols
1363      # can be removed at link time with --gc-sections.
1364      "-fdata-sections",
1365      "-ffunction-sections",
1366    ]
1367
1368    common_optimize_on_ldflags += [
1369      # Specifically tell the linker to perform optimizations.
1370      # See http://lwn.net/Articles/192624/ .
1371      # -O2 enables string tail merge optimization in gold and lld.
1372      "-Wl,-O2",
1373    ]
1374    if (!is_mingw) {
1375      common_optimize_on_ldflags += [ "-Wl,--gc-sections" ]
1376    }
1377  }
1378}
1379
1380config("default_stack_frames") {
1381  if (is_posix) {
1382    if (enable_frame_pointers) {
1383      cflags = [ "-fno-omit-frame-pointer" ]
1384    } else {
1385      cflags = [ "-fomit-frame-pointer" ]
1386    }
1387  }
1388  # On Windows, the flag to enable framepointers "/Oy-" must always come after
1389  # the optimization flag [e.g. "/O2"]. The optimization flag is set by one of
1390  # the "optimize" configs, see rest of this file. The ordering that cflags are
1391  # applied is well-defined by the GN spec, and there is no way to ensure that
1392  # cflags set by "default_stack_frames" is applied after those set by an
1393  # "optimize" config. Similarly, there is no way to propagate state from this
1394  # config into the "optimize" config. We always apply the "/Oy-" config in the
1395  # definition for common_optimize_on_cflags definition, even though this may
1396  # not be correct.
1397}
1398
1399# Default "optimization on" config.
1400config("optimize") {
1401  if (optimize_for_size && !is_nacl) {
1402    # Favor size over speed.
1403    if (is_clang) {
1404      cflags = [ "-O2" ] + common_optimize_on_cflags
1405    } else {
1406      cflags = [ "-Os" ] + common_optimize_on_cflags
1407    }
1408  } else {
1409    cflags = [ "-O2" ] + common_optimize_on_cflags
1410  }
1411  ldflags = common_optimize_on_ldflags
1412}
1413
1414# Same config as 'optimize' but without the WPO flag.
1415config("optimize_no_wpo") {
1416  if (is_win) {
1417    # Favor size over speed, /O1 must be before the common flags. The GYP
1418    # build also specifies /Os and /GF but these are implied by /O1.
1419    cflags = [ "/O1" ] + common_optimize_on_cflags + [ "/Oi" ]
1420  } else if (optimize_for_size && !is_nacl) {
1421    # Favor size over speed.
1422    if (is_clang) {
1423      cflags = [ "-Oz" ] + common_optimize_on_cflags
1424    } else {
1425      cflags = [ "-Os" ] + common_optimize_on_cflags
1426    }
1427  } else if (optimize_for_fuzzing) {
1428    cflags = [ "-O0" ] + common_optimize_on_cflags
1429  } else {
1430    cflags = [ "-O2" ] + common_optimize_on_cflags
1431  }
1432  ldflags = common_optimize_on_ldflags
1433}
1434
1435# Turn off optimizations.
1436config("no_optimize") {
1437  if (is_win) {
1438    cflags = [
1439      "/Od",  # Disable optimization.
1440      "/Ob0",  # Disable all inlining (on by default).
1441      "/GF",  # Enable string pooling (off by default).
1442    ]
1443  } else if ((is_ohos || is_android) && !ohos_full_debug) {
1444    # On ohos we kind of optimize some things that don't affect debugging
1445    # much even when optimization is disabled to get the binary size down.
1446    if (is_clang) {
1447      cflags = [ "-Oz" ] + common_optimize_on_cflags
1448      ldflags = common_optimize_on_ldflags
1449    } else {
1450      cflags = [ "-Os" ] + common_optimize_on_cflags
1451      ldflags = common_optimize_on_ldflags
1452    }
1453  } else {
1454    # On ohos_full_debug mode, we close all optimization
1455    cflags = [ "-O0" ]
1456    ldflags = []
1457  }
1458}
1459
1460# Turns up the optimization level. On Windows, this implies whole program
1461# optimization and link-time code generation which is very expensive and should
1462# be used sparingly.
1463config("optimize_max") {
1464  if (is_nacl && is_nacl_irt) {
1465    # The NaCl IRT is a special case and always wants its own config.
1466    # Various components do:
1467    #   if (!is_debug) {
1468    #     configs -= [ "//build/config/compiler:default_optimization" ]
1469    #     configs += [ "//build/config/compiler:optimize_max" ]
1470    #   }
1471    # So this config has to have the selection logic just like
1472    # "default_optimization", below.
1473    configs = [ "//build/config/nacl:irt_optimize" ]
1474  } else {
1475    ldflags = common_optimize_on_ldflags
1476    if (is_win) {
1477      # Favor speed over size, /O2 must be before the common flags. The GYP
1478      # build also specifies /Ot, /Oi, and /GF, but these are implied by /O2.
1479      cflags = [ "/O2" ] + common_optimize_on_cflags
1480
1481      if (is_official_build) {
1482        if (!is_clang) {
1483          cflags += [
1484            "/GL",  # Whole program optimization.
1485
1486            # Disable Warning 4702 ("Unreachable code") for the WPO/PGO builds.
1487            # Probably anything that this would catch that wouldn't be caught
1488            # in a normal build isn't going to actually be a bug, so the
1489            # incremental value of C4702 for PGO builds is likely very small.
1490            "/wd4702",
1491          ]
1492        }
1493      }
1494    } else if (optimize_for_fuzzing) {
1495      cflags = [ "-O0" ] + common_optimize_on_cflags
1496    } else {
1497      cflags = [ "-O2" ] + common_optimize_on_cflags
1498    }
1499  }
1500}
1501
1502# This config can be used to override the default settings for per-component
1503# and whole-program optimization, optimizing the particular target for speed
1504# instead of code size. This config is exactly the same as "optimize_max"
1505# except that we use -O3 instead of -O2 on non-win, non-IRT platforms.
1506config("optimize_speed") {
1507  if (is_nacl && is_nacl_irt) {
1508    # The NaCl IRT is a special case and always wants its own config.
1509    # Various components do:
1510    #   if (!is_debug) {
1511    #     configs -= [ "//build/config/compiler:default_optimization" ]
1512    #     configs += [ "//build/config/compiler:optimize_max" ]
1513    #   }
1514    # So this config has to have the selection logic just like
1515    # "default_optimization", below.
1516    configs = [ "//build/config/nacl:irt_optimize" ]
1517  } else {
1518    ldflags = common_optimize_on_ldflags
1519    if (is_win) {
1520      # Favor speed over size, /O2 must be before the common flags. The GYP
1521      # build also specifies /Ot, /Oi, and /GF, but these are implied by /O2.
1522      cflags = [ "/O2" ] + common_optimize_on_cflags
1523
1524      if (is_official_build && !is_clang) {
1525        cflags += [
1526          "/GL",  # Whole program optimization.
1527
1528          # Disable Warning 4702 ("Unreachable code") for the WPO/PGO builds.
1529          # Probably anything that this would catch that wouldn't be caught in a
1530          # normal build isn't going to actually be a bug, so the incremental
1531          # value of C4702 for PGO builds is likely very small.
1532          "/wd4702",
1533        ]
1534      }
1535    } else if (optimize_for_fuzzing) {
1536      cflags = [ "-O0" ] + common_optimize_on_cflags
1537    } else {
1538      cflags = [ "-O3" ] + common_optimize_on_cflags
1539    }
1540  }
1541}
1542
1543config("optimize_fuzzing") {
1544  cflags = [ "-O0" ] + common_optimize_on_cflags
1545  ldflags = common_optimize_on_ldflags
1546  visibility = [ ":default_optimization" ]
1547}
1548
1549# The default optimization applied to all targets. This will be equivalent to
1550# either "optimize" or "no_optimize", depending on the build flags.
1551config("default_optimization") {
1552  if (is_nacl && is_nacl_irt) {
1553    # The NaCl IRT is a special case and always wants its own config.
1554    # It gets optimized the same way regardless of the type of build.
1555    configs = [ "//build/config/nacl:irt_optimize" ]
1556  } else if (is_debug) {
1557    configs = [ ":no_optimize" ]
1558  } else if (optimize_for_fuzzing) {
1559    assert(!is_win, "Fuzzing optimize level not supported on Windows")
1560
1561    # Coverage build is quite slow. Using "optimize_for_fuzzing" makes it even
1562    # slower as it uses "-O1" instead of "-O3". Prevent that from happening.
1563    assert(!use_clang_coverage,
1564           "optimize_for_fuzzing=true should not be used with " +
1565               "use_clang_coverage=true.")
1566    configs = [ ":optimize_fuzzing" ]
1567  } else {
1568    configs = [ ":optimize" ]
1569  }
1570}
1571
1572_clang_sample_profile = ""
1573if (is_clang && current_toolchain == default_toolchain) {
1574  if (clang_sample_profile_path != "") {
1575    _clang_sample_profile = clang_sample_profile_path
1576  } else if (clang_use_default_sample_profile) {
1577    assert(build_with_chromium,
1578           "Our default profiles currently only apply to Chromium")
1579    assert(is_ohos || is_android || is_desktop_linux,
1580           "The current platform has no default profile")
1581    _clang_sample_profile = ""
1582  }
1583}
1584
1585# Clang offers a way to assert that AFDO profiles are accurate, which causes it
1586# to optimize functions not represented in a profile more aggressively for size.
1587# This config can be toggled in cases where shaving off binary size hurts
1588# performance too much.
1589config("afdo_optimize_size") {
1590  if (_clang_sample_profile != "" && sample_profile_is_accurate) {
1591    cflags = [ "-fprofile-sample-accurate" ]
1592  }
1593}
1594
1595# GCC and clang support a form of profile-guided optimization called AFDO.
1596# There are some targeted places that AFDO regresses (and an icky interaction
1597# between //base/allocator:tcmalloc and AFDO on GCC), so we provide a separate
1598# config to allow AFDO to be disabled per-target.
1599config("afdo") {
1600  if (is_clang) {
1601    if (_clang_sample_profile != "") {
1602      rebased_clang_sample_profile =
1603          rebase_path(_clang_sample_profile, root_build_dir)
1604      cflags = [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
1605      inputs = [ _clang_sample_profile ]
1606    }
1607  } else if (auto_profile_path != "" &&
1608             current_toolchain == default_toolchain) {
1609    cflags = [ "-fauto-profile=${auto_profile_path}" ]
1610    inputs = [ auto_profile_path ]
1611  }
1612}
1613
1614# Symbols ----------------------------------------------------------------------
1615
1616# The BUILDCONFIG file sets the "default_symbols" config on targets by
1617# default. It will be equivalent to one the three specific symbol levels.
1618#
1619# You can override the symbol level on a per-target basis by removing the
1620# default config and then adding the named one you want:
1621#
1622#   configs -= [ "//build/config/compiler:default_symbols" ]
1623#   configs += [ "//build/config/compiler:symbols" ]
1624
1625# A helper config that all configs passing /DEBUG to the linker should
1626# include as sub-config.
1627config("win_pdbaltpath") {
1628  visibility = [
1629    ":minimal_symbols",
1630    ":symbols",
1631  ]
1632
1633  # /DEBUG causes the linker to generate a pdb file, and to write the absolute
1634  # path to it in the executable file it generates.  This flag turns that
1635  # absolute path into just the basename of the pdb file, which helps with
1636  # build reproducibility. Debuggers look for pdb files next to executables,
1637  # so there's no downside to always using this.
1638  ldflags = [ "/pdbaltpath:%_PDB%" ]
1639}
1640
1641# Full symbols.
1642config("symbols") {
1643  if (is_win) {
1644    if (is_clang) {
1645      # Note that with VC++ this requires is_win_fastlink, enforced elsewhere.
1646      cflags = [ "/Z7" ]  # Debug information in the .obj files.
1647    } else {
1648      cflags = [ "/Zi" ]  # Produce PDB file, no edit and continue.
1649    }
1650
1651    if (is_win_fastlink && !use_lld) {
1652      # Tell VS 2015+ to create a PDB that references debug
1653      # information in .obj and .lib files instead of copying
1654      # it all. This flag is incompatible with /PROFILE
1655      ldflags = [ "/DEBUG:FASTLINK" ]
1656    } else if (is_clang && use_lld && use_ghash) {
1657      cflags += [
1658        "-mllvm",
1659        "-emit-codeview-ghash-section",
1660      ]
1661      ldflags = [ "/DEBUG:GHASH" ]
1662    } else {
1663      ldflags = [ "/DEBUG" ]
1664    }
1665
1666    # All configs using /DEBUG should include this:
1667    configs = [ ":win_pdbaltpath" ]
1668
1669    if (is_clang) {
1670      # /DEBUG:FASTLINK requires every object file to have standalone debug
1671      # information.
1672      if (is_win_fastlink && !use_lld) {
1673        cflags += [ "-fstandalone-debug" ]
1674      } else {
1675        cflags += [ "-fno-standalone-debug" ]
1676      }
1677    }
1678  } else {
1679    if (is_mac) {
1680      cflags = [ "-gdwarf-2" ]
1681      if (is_mac && enable_dsyms) {
1682        # If generating dSYMs, specify -fno-standalone-debug. This was
1683        # originally specified for https://crbug.com/479841 because dsymutil
1684        # could not handle a 4GB dSYM file. But dsymutil from Xcodes prior to
1685        # version 7 also produces debug data that is incompatible with Breakpad
1686        # dump_syms, so this is still required (https://crbug.com/622406).
1687        cflags += [ "-fno-standalone-debug" ]
1688      }
1689    } else {
1690      cflags = []
1691      if (!use_debug_fission && current_cpu == "arm") {
1692        # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
1693        #
1694        # debug fission needs DWARF DIEs to be emitted at version 4.
1695        # Chrome OS emits Debug Frame in DWARF1 to make breakpad happy. [1]
1696        # Unless ohos needs debug fission, DWARF3 is the simplest solution.
1697        #
1698        # [1] crrev.com/a81d5ade0b043208e06ad71a38bcf9c348a1a52f
1699        cflags += [ "-gdwarf-3" ]
1700      }
1701      if (!ohos_full_debug) {
1702        cflags += [ "-g2" ]
1703      } else {
1704        # Set -g3 symbol level when ohos_full_debug is true
1705        cflags += [ "-g3" ]
1706      }
1707    }
1708    if (use_debug_fission && !is_nacl && !(is_ohos || is_android)) {
1709      # NOTE: Some Chrome OS builds globally set |use_debug_fission| to true,
1710      # but they also build some targets against ohos toolchains which aren't
1711      # compatible with it.
1712      cflags += [ "-gsplit-dwarf" ]
1713    }
1714    asmflags = cflags
1715    ldflags = []
1716
1717    if (!is_mac && !is_nacl && current_cpu != "x86" && (use_gold || use_lld)) {
1718      if (is_clang) {
1719        # This flag enables the GNU-format pubnames and pubtypes sections,
1720        # which lld needs in order to generate a correct GDB index.
1721        cflags += [ "-ggnu-pubnames" ]
1722      }
1723      ldflags += [ "-Wl,--gdb-index" ]
1724    }
1725  }
1726}
1727
1728# Minimal symbols.
1729# This config guarantees to hold symbol for stack trace which are shown to user
1730# when crash happens in unittests running on buildbot.
1731config("minimal_symbols") {
1732  if (is_win) {
1733    # Linker symbols for backtraces only.
1734    cflags = []
1735    ldflags = [ "/DEBUG" ]
1736
1737    # All configs using /DEBUG should include this:
1738    configs = [ ":win_pdbaltpath" ]
1739
1740    # For win/asan, get stack traces with full line numbers.
1741    # AddressSanitizerTests.TestAddressSanitizer needs this, and since
1742    # win/asan isn't a default cq bot the build time hit is ok.
1743    if (is_clang && using_sanitizer) {
1744      # -gline-tables-only is the same as -g1, but clang-cl only exposes the
1745      # former.
1746      cflags += [ "-gline-tables-only" ]
1747    }
1748  } else {
1749    cflags = []
1750    if (current_cpu == "arm") {
1751      # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
1752      cflags += [ "-gdwarf-3" ]
1753    }
1754    cflags += [ "-g1" ]
1755    ldflags = []
1756    if ((is_ohos || is_android) && is_clang) {
1757      # ohos defaults to symbol_level=1 builds in production builds
1758      # (https://crbug.com/648948), but clang, unlike gcc, doesn't emit
1759      # DW_AT_linkage_name in -g1 builds. -fdebug-info-for-profiling enables
1760      # that (and a bunch of other things we don't need), so that we get
1761      # qualified names in stacks.
1762      cflags += [ "-fdebug-info-for-profiling" ]
1763    }
1764
1765    # Note: -gsplit-dwarf implicitly turns on -g2 with clang, so don't pass it.
1766    asmflags = cflags
1767  }
1768}
1769
1770# No symbols.
1771config("no_symbols") {
1772  if (!is_win) {
1773    cflags = [ "-g0" ]
1774    asmflags = cflags
1775  }
1776}
1777
1778# Default symbols.
1779config("default_symbols") {
1780  if (symbol_level == 0) {
1781    configs = [ ":no_symbols" ]
1782  } else if (symbol_level == 1) {
1783    configs = [ ":minimal_symbols" ]
1784  } else if (symbol_level == 2) {
1785    configs = [ ":symbols" ]
1786  } else {
1787    assert(false)
1788  }
1789
1790  # This config is removed by base unittests app.
1791  if ((is_ohos || is_android) && is_clang && strip_debug_info) {
1792    configs += [ ":strip_debug" ]
1793  }
1794}
1795
1796config("strip_debug") {
1797  if (!defined(ldflags)) {
1798    ldflags = []
1799  }
1800  ldflags += [ "-Wl,--strip-debug" ]
1801}
1802
1803if (is_mac) {
1804  # On Mac and iOS, this enables support for ARC (automatic ref-counting).
1805  # See http://clang.llvm.org/docs/AutomaticReferenceCounting.html.
1806  config("enable_arc") {
1807    common_flags = [ "-fobjc-arc" ]
1808    cflags_objc = common_flags
1809    cflags_objcc = common_flags
1810  }
1811}
1812
1813config("no_common") {
1814  if (is_clang) {
1815    cflags = [ "-fno-common" ]
1816    asmflags = cflags
1817  }
1818}
1819