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