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