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/buildflag_header.gni")
6import("//build/config/android/config.gni")
7import("//build/config/c++/c++.gni")
8import("//build/config/chrome_build.gni")
9import("//build/config/chromecast_build.gni")
10import("//build/config/chromeos/args.gni")
11import("//build/config/clang/clang.gni")
12import("//build/config/compiler/compiler.gni")
13import("//build/config/coverage/coverage.gni")
14import("//build/config/dcheck_always_on.gni")
15import("//build/config/gclient_args.gni")
16import("//build/config/host_byteorder.gni")
17import("//build/config/sanitizers/sanitizers.gni")
18import("//build/config/ui.gni")
19import("//build/toolchain/cc_wrapper.gni")
20import("//build/toolchain/goma.gni")
21import("//build/toolchain/toolchain.gni")
22import("//build_overrides/build.gni")
23
24if (current_cpu == "arm" || current_cpu == "arm64") {
25  import("//build/config/arm.gni")
26}
27if (current_cpu == "mipsel" || current_cpu == "mips64el" ||
28    current_cpu == "mips" || current_cpu == "mips64") {
29  import("//build/config/mips.gni")
30}
31if (current_cpu == "x64") {
32  import("//build/config/x64.gni")
33}
34if (is_mac) {
35  import("//build/config/mac/symbols.gni")
36}
37if (is_ios) {
38  import("//build/config/ios/ios_sdk.gni")
39}
40if (is_nacl) {
41  # To keep NaCl variables out of builds that don't include NaCl, all
42  # variables defined in nacl/config.gni referenced here should be protected by
43  # is_nacl conditions.
44  import("//build/config/nacl/config.gni")
45}
46
47declare_args() {
48  # Normally, Android builds are lightly optimized, even for debug builds, to
49  # keep binary size down. Setting this flag to true disables such optimization
50  android_full_debug = false
51
52  # Compile in such a way as to make it possible for the profiler to unwind full
53  # stack frames. Setting this flag has a large effect on the performance of the
54  # generated code than just setting profiling, but gives the profiler more
55  # information to analyze.
56  # Requires profiling to be set to true.
57  enable_full_stack_frames_for_profiling = false
58
59  # When we are going to use gold we need to find it.
60  # This is initialized below, after use_gold might have been overridden.
61  gold_path = ""
62
63  # Enable fatal linker warnings. Building Chromium with certain versions
64  # of binutils can cause linker warning.
65  fatal_linker_warnings = true
66
67  # Build with C++ RTTI enabled. Chromium builds without RTTI by default,
68  # but some sanitizers are known to require it, like CFI diagnostics
69  # and UBsan variants.
70  use_rtti = use_cfi_diag || is_ubsan_vptr || is_ubsan_security
71
72  # AFDO (Automatic Feedback Directed Optimizer) is a form of profile-guided
73  # optimization that GCC supports. It used by ChromeOS in their official
74  # builds. To use it, set auto_profile_path to the path to a file containing
75  # the needed gcov profiling data.
76  auto_profile_path = ""
77
78  # Allow projects that wish to stay on C++11 to override Chromium's default.
79  use_cxx11 = false
80
81  # Path to an AFDO profile to use while building with clang, if any. Empty
82  # implies none.
83  clang_sample_profile_path = ""
84
85  # Some configurations have default sample profiles. If this is true and
86  # clang_sample_profile_path is empty, we'll fall back to the default.
87  #
88  # We currently only have default profiles for Chromium in-tree, so we disable
89  # this by default for all downstream projects, since these profiles are likely
90  # nonsensical for said projects.
91  clang_use_default_sample_profile =
92      chrome_pgo_phase == 0 && build_with_chromium && is_official_build &&
93      (is_android || chromeos_is_browser_only || is_chromecast)
94
95  # This configuration is used to select a default profile in Chrome OS based on
96  # the microarchitectures we are using. This is only used if
97  # clang_use_default_sample_profile is true and clang_sample_profile_path is
98  # empty.
99  chromeos_afdo_platform = "atom"
100
101  # Emit debug information for profiling wile building with clang.
102  clang_emit_debug_info_for_profiling = false
103
104  # Turn this on to have the compiler output extra timing information.
105  compiler_timing = false
106
107  # Turn this on to use ghash feature of lld for faster debug link on Windows.
108  # http://blog.llvm.org/2018/01/improving-link-time-on-windows-with.html
109  use_ghash = true
110
111  # Whether to enable ThinLTO optimizations. Turning ThinLTO optimizations on
112  # can substantially increase link time and binary size, but they generally
113  # also make binaries a fair bit faster.
114  #
115  # TODO(gbiv): We disable optimizations by default on most platforms because
116  # the space overhead is too great. We should use some mixture of profiles and
117  # optimization settings to better tune the size increase.
118  thin_lto_enable_optimizations =
119      (is_chromeos || is_android || is_win) && is_official_build
120
121  # Initialize all local variables with a pattern. This flag will fill
122  # uninitialized floating-point types (and 32-bit pointers) with 0xFF and the
123  # rest with 0xAA. This makes behavior of uninitialized memory bugs consistent,
124  # recognizable in the debugger, and crashes on memory accesses through
125  # uninitialized pointers.
126  #
127  # TODO(crbug.com/1131993): Enabling this when 'is_android' is true breaks
128  # content_shell_test_apk on both ARM and x86.
129  #
130  # TODO(crbug.com/977230): Enabling this when 'use_xcode_clang' is true may
131  # call an old clang that doesn't support auto-init.
132  init_stack_vars = !is_android && !use_xcode_clang && !is_bsd
133
134  # This argument is to control whether enabling text section splitting in the
135  # final binary. When enabled, the separated text sections with prefix
136  # '.text.hot', '.text.unlikely', '.text.startup' and '.text.exit' will not be
137  # merged to '.text' section. This allows us to identify the hot code section
138  # ('.text.hot') in the binary which may be mlocked or mapped to huge page to
139  # reduce TLB misses which gives performance improvement on cpu usage.
140  # The gold linker by default has text section splitting enabled.
141  use_text_section_splitting = false
142
143  # Token limits may not be accurate for build configs not covered by the CQ,
144  # so only enable them by default for mainstream build configs.
145  enable_wmax_tokens =
146      !is_official_build &&
147      ((is_mac && target_cpu == "x64" && !use_system_xcode) ||
148       (is_linux && !is_chromeos && target_cpu == "x64") ||
149       (is_win && target_cpu == "x86") || (is_win && target_cpu == "x64") ||
150       (is_android && target_cpu == "arm") ||
151       (is_android && target_cpu == "arm64"))
152
153  # Turn off the --call-graph-profile-sort flag for lld by default. Enable
154  # selectively for targets where it's beneficial.
155  enable_call_graph_profile_sort = chrome_pgo_phase == 2
156}
157
158declare_args() {
159  # C++11 may not be an option if Android test infrastructure is used.
160  use_cxx11_on_android = use_cxx11
161}
162
163declare_args() {
164  # Set to true to use icf, Identical Code Folding.
165  #
166  # icf=all is broken in older golds, see
167  # https://sourceware.org/bugzilla/show_bug.cgi?id=17704
168  # chromeos binutils has been patched with the fix, so always use icf there.
169  # The bug only affects x86 and x64, so we can still use ICF when targeting
170  # other architectures.
171  #
172  # lld doesn't have the bug.
173  use_icf = (is_posix || is_fuchsia) && !is_debug && !using_sanitizer &&
174            !use_clang_coverage && !(is_android && use_order_profiling) &&
175            (use_lld || (use_gold && (is_chromeos || !(current_cpu == "x86" ||
176                                                       current_cpu == "x64"))))
177}
178
179if (is_win || is_android || (is_chromeos && is_chromeos_device)) {
180  # Set the path to use orderfile for linking Chrome
181  # Note that this is for using only one orderfile for linking
182  # the Chrome binary/library.
183  declare_args() {
184    chrome_orderfile_path = ""
185
186    if (defined(default_chrome_orderfile)) {
187      # Allow downstream tools to set orderfile path with
188      # another variable.
189      chrome_orderfile_path = default_chrome_orderfile
190    } else if (is_win && is_clang && is_official_build) {
191      chrome_orderfile_path = "//chrome/build/chrome.$target_cpu.orderfile"
192    } else if (is_chromeos && is_chromeos_device) {
193      chrome_orderfile_path = "//chromeos/profiles/chromeos.orderfile.txt"
194    }
195  }
196}
197
198assert(!(llvm_force_head_revision && use_goma),
199       "can't use goma with trunk clang")
200
201# default_include_dirs ---------------------------------------------------------
202#
203# This is a separate config so that third_party code (which would not use the
204# source root and might have conflicting versions of some headers) can remove
205# this and specify their own include paths.
206config("default_include_dirs") {
207  include_dirs = [
208    "//",
209    root_gen_dir,
210  ]
211}
212
213# compiler ---------------------------------------------------------------------
214#
215# Base compiler configuration.
216#
217# See also "runtime_library" below for related stuff and a discussion about
218# where stuff should go. Put warning related stuff in the "warnings" config.
219
220config("compiler") {
221  asmflags = []
222  cflags = []
223  cflags_c = []
224  cflags_cc = []
225  cflags_objc = []
226  cflags_objcc = []
227  ldflags = []
228  defines = []
229  configs = []
230
231  # System-specific flags. If your compiler flags apply to one of the
232  # categories here, add it to the associated file to keep this shared config
233  # smaller.
234  if (is_win) {
235    configs += [ "//build/config/win:compiler" ]
236  } else if (is_android) {
237    configs += [ "//build/config/android:compiler" ]
238  } else if (is_linux || is_chromeos) {
239    configs += [ "//build/config/linux:compiler" ]
240    if (is_chromeos) {
241      configs += [ "//build/config/chromeos:compiler" ]
242    }
243  } else if (is_nacl) {
244    configs += [ "//build/config/nacl:compiler" ]
245  } else if (is_mac) {
246    configs += [ "//build/config/mac:compiler" ]
247  } else if (is_ios) {
248    configs += [ "//build/config/ios:compiler" ]
249  } else if (is_fuchsia) {
250    configs += [ "//build/config/fuchsia:compiler" ]
251  } else if (current_os == "aix") {
252    configs += [ "//build/config/aix:compiler" ]
253  }
254
255  configs += [
256    # See the definitions below.
257    ":clang_revision",
258    ":compiler_cpu_abi",
259    ":compiler_codegen",
260    ":compiler_deterministic",
261  ]
262
263  # In general, Windows is totally different, but all the other builds share
264  # some common GCC configuration.
265  if (!is_win) {
266    # Common POSIX compiler flags setup.
267    # --------------------------------
268    cflags += [ "-fno-strict-aliasing" ]  # See http://crbug.com/32204
269
270    # Stack protection.
271    if (is_mac) {
272      # The strong variant of the stack protector significantly increases
273      # binary size, so only enable it in debug mode.
274      if (is_debug) {
275        cflags += [ "-fstack-protector-strong" ]
276      } else {
277        cflags += [ "-fstack-protector" ]
278      }
279    } else if ((is_posix && !is_chromeos && !is_nacl) || is_fuchsia) {
280      # TODO(phajdan.jr): Use -fstack-protector-strong when our gcc supports it.
281      # See also https://crbug.com/533294
282      cflags += [ "--param=ssp-buffer-size=4" ]
283
284      # The x86 toolchain currently has problems with stack-protector.
285      if (is_android && current_cpu == "x86") {
286        cflags += [ "-fno-stack-protector" ]
287      } else if (current_os != "aix") {
288        # Not available on aix.
289        cflags += [ "-fstack-protector" ]
290      }
291    }
292
293    # Linker warnings.
294    if (fatal_linker_warnings && !is_apple && !is_bsd && current_os != "aix") {
295      ldflags += [ "-Wl,--fatal-warnings" ]
296    }
297    if (fatal_linker_warnings && is_apple) {
298      ldflags += [ "-Wl,-fatal_warnings" ]
299    }
300  } else {
301  }
302
303  if (is_clang && is_debug) {
304    # Allow comparing the address of references and 'this' against 0
305    # in debug builds. Technically, these can never be null in
306    # well-defined C/C++ and Clang can optimize such checks away in
307    # release builds, but they may be used in asserts in debug builds.
308    cflags_cc += [
309      "-Wno-undefined-bool-conversion",
310      "-Wno-tautological-undefined-compare",
311    ]
312  }
313
314  # Non-Mac Posix and Fuchsia compiler flags setup.
315  # -----------------------------------
316  if ((is_posix && !is_apple) || is_fuchsia) {
317    if (enable_profiling) {
318      if (!is_debug) {
319        cflags += [ "-g" ]
320
321        if (enable_full_stack_frames_for_profiling) {
322          cflags += [
323            "-fno-inline",
324            "-fno-optimize-sibling-calls",
325          ]
326        }
327      }
328    }
329
330    # Explicitly pass --build-id to ld. Compilers used to always pass this
331    # implicitly but don't any more (in particular clang when built without
332    # ENABLE_LINKER_BUILD_ID=ON).
333    if (is_official_build) {
334      # The sha1 build id has lower risk of collision but is more expensive to
335      # compute, so only use it in the official build to avoid slowing down
336      # links.
337      ldflags += [ "-Wl,--build-id=sha1" ]
338    } else if (current_os != "aix") {
339      ldflags += [ "-Wl,--build-id" ]
340    }
341
342    if (!is_android) {
343      defines += [
344        # _FILE_OFFSET_BITS=64 should not be set on Android in order to maintain
345        # the behavior of the Android NDK from earlier versions.
346        # See https://android-developers.googleblog.com/2017/09/introducing-android-native-development.html
347        "_FILE_OFFSET_BITS=64",
348        "_LARGEFILE_SOURCE",
349        "_LARGEFILE64_SOURCE",
350      ]
351    }
352
353    if (!is_nacl) {
354      if (exclude_unwind_tables) {
355        cflags += [
356          "-fno-unwind-tables",
357          "-fno-asynchronous-unwind-tables",
358        ]
359        defines += [ "NO_UNWIND_TABLES" ]
360      } else {
361        cflags += [ "-funwind-tables" ]
362      }
363    }
364  }
365
366  # Linux/Android/Fuchsia common flags setup.
367  # ---------------------------------
368  if (is_linux || is_chromeos || is_android || is_fuchsia) {
369    asmflags += [ "-fPIC" ]
370    cflags += [ "-fPIC" ]
371    ldflags += [ "-fPIC" ]
372
373    if (!is_clang) {
374      # Use pipes for communicating between sub-processes. Faster.
375      # (This flag doesn't do anything with Clang.)
376      cflags += [ "-pipe" ]
377    }
378
379    ldflags += [
380      "-Wl,-z,noexecstack",
381      "-Wl,-z,relro",
382    ]
383
384    if (!is_component_build) {
385      ldflags += [ "-Wl,-z,now" ]
386    }
387
388    # Compiler instrumentation can introduce dependencies in DSOs to symbols in
389    # the executable they are loaded into, so they are unresolved at link-time.
390    if (!using_sanitizer && !is_bsd) {
391      ldflags += [
392        "-Wl,-z,defs",
393        "-Wl,--as-needed",
394      ]
395    }
396  }
397
398  # Linux-specific compiler flags setup.
399  # ------------------------------------
400  if ((is_posix || is_fuchsia) && use_lld) {
401    ldflags += [ "-fuse-ld=lld" ]
402    if (current_cpu == "arm64") {
403      # Reduce the page size from 65536 in order to reduce binary size slightly
404      # by shrinking the alignment gap between segments. This also causes all
405      # segments to be mapped adjacently, which breakpad relies on.
406      ldflags += [ "-Wl,-z,max-page-size=4096" ]
407    }
408  } else if (use_gold) {
409    ldflags += [ "-fuse-ld=gold" ]
410    if (!is_android) {
411      # On Android, this isn't needed.  gcc in the NDK knows to look next to
412      # it with -fuse-ld=gold, and clang gets a --gcc-toolchain flag passed
413      # above.
414      if (gold_path != "") {
415        ldflags += [ "-B$gold_path" ]
416      }
417
418      ldflags += [
419        # Experimentation found that using four linking threads
420        # saved ~20% of link time.
421        # https://groups.google.com/a/chromium.org/group/chromium-dev/browse_thread/thread/281527606915bb36
422        # Only apply this to the target linker, since the host
423        # linker might not be gold, but isn't used much anyway.
424        "-Wl,--threads",
425        "-Wl,--thread-count=4",
426      ]
427    }
428
429    # TODO(thestig): Make this flag work with GN.
430    #if (!is_official_build && !is_chromeos && !(is_asan || is_lsan || is_tsan || is_msan)) {
431    #  ldflags += [
432    #    "-Wl,--detect-odr-violations",
433    #  ]
434    #}
435  }
436
437  if (use_icf) {
438    ldflags += [ "-Wl,--icf=all" ]
439  }
440
441  if (is_linux || is_chromeos) {
442    cflags += [ "-pthread" ]
443    # Do not use the -pthread ldflag here since it becomes a no-op
444    # when using -nodefaultlibs, which would cause an unused argument
445    # error.  "-lpthread" is added in //build/config:default_libs.
446  }
447
448  # Clang-specific compiler flags setup.
449  # ------------------------------------
450  if (is_clang) {
451    cflags += [ "-fcolor-diagnostics" ]
452
453    # Enable -fmerge-all-constants. This used to be the default in clang
454    # for over a decade. It makes clang non-conforming, but is fairly safe
455    # in practice and saves some binary size. We might want to consider
456    # disabling this (https://bugs.llvm.org/show_bug.cgi?id=18538#c13),
457    # but for now it looks like our build might rely on it
458    # (https://crbug.com/829795).
459    cflags += [ "-fmerge-all-constants" ]
460  }
461
462  if (use_lld) {
463    # TODO(thakis): Make the driver pass --color-diagnostics to the linker
464    # if -fcolor-diagnostics is passed to it, and pass -fcolor-diagnostics
465    # in ldflags instead.
466    if (is_win) {
467      # On Windows, we call the linker directly, instead of calling it through
468      # the driver.
469      ldflags += [ "--color-diagnostics" ]
470    } else {
471      ldflags += [ "-Wl,--color-diagnostics" ]
472    }
473  }
474
475  # Enable text section splitting only on linux when using lld for now. Other
476  # platforms can be added later if needed.
477  if ((is_linux || is_chromeos) && use_lld && use_text_section_splitting) {
478    ldflags += [ "-Wl,-z,keep-text-section-prefix" ]
479  }
480
481  if (is_clang && !is_nacl && !use_xcode_clang && !is_bsd) {
482    cflags += [ "-fcrash-diagnostics-dir=" + clang_diagnostic_dir ]
483
484    cflags += [
485      # TODO(hans): Remove this once Clang generates better optimized debug info
486      # by default. https://crbug.com/765793
487      "-mllvm",
488      "-instcombine-lower-dbg-declare=0",
489    ]
490  }
491
492  # C11/C++11 compiler flags setup.
493  # ---------------------------
494  if (is_linux || is_chromeos || is_android || (is_nacl && is_clang) ||
495      current_os == "aix") {
496    if (target_os == "android") {
497      cxx11_override = use_cxx11_on_android
498    } else {
499      cxx11_override = use_cxx11
500    }
501
502    if (is_clang) {
503      standard_prefix = "c"
504
505      # Since we build with -std=c* and not -std=gnu*, _GNU_SOURCE will not be
506      # defined by the compiler.  However, lots of code relies on the
507      # non-standard features that _GNU_SOURCE enables, so define it manually.
508      defines += [ "_GNU_SOURCE" ]
509
510      if (is_nacl) {
511        # Undefine __STRICT_ANSI__ to get non-standard features which would
512        # otherwise not be enabled by NaCl's sysroots.
513        cflags += [ "-U__STRICT_ANSI__" ]
514      }
515    } else {
516      # Gcc does not support ##__VA_ARGS__ when in standards-conforming mode,
517      # but we use this feature in several places in Chromium.
518      # TODO(thomasanderson): Replace usages of ##__VA_ARGS__ with the
519      # standard-compliant __VA_OPT__ added by C++20, and switch the gcc build
520      # to -std=c*.
521      standard_prefix = "gnu"
522    }
523
524    cflags_c += [ "-std=${standard_prefix}11" ]
525    if (cxx11_override) {
526      # Override Chromium's default for projects that wish to stay on C++11.
527      cflags_cc += [ "-std=${standard_prefix}++11" ]
528    } else {
529      cflags_cc += [ "-std=${standard_prefix}++14" ]
530    }
531  } else if (!is_win && !is_nacl) {
532    if (target_os == "android") {
533      cxx11_override = use_cxx11_on_android
534    } else {
535      cxx11_override = use_cxx11
536    }
537
538    # TODO(mcgrathr) - the NaCl GCC toolchain doesn't support either gnu11/gnu++11
539    # or c11/c++11; we technically don't need this toolchain any more, but there
540    # are still a few buildbots using it, so until those are turned off
541    # we need the !is_nacl clause and the (is_nacl && is_clang) clause, above.
542    cflags_c += [ "-std=c11" ]
543    if (cxx11_override) {
544      cflags_cc += [ "-std=c++11" ]
545    } else {
546      cflags_cc += [ "-std=c++14" ]
547    }
548  }
549
550  # C++17 removes trigraph support, so preemptively disable trigraphs. This is
551  # especially useful given the collision with ecmascript's logical assignment
552  # operators: https://github.com/tc39/proposal-logical-assignment
553  if (is_clang) {
554    # clang-cl disables trigraphs by default
555    if (!is_win) {
556      # The gnu variants of C++11 and C++14 already disable trigraph support,
557      # but when building with clang, we use -std=c++11 / -std=c++14, which
558      # enables trigraph support: override that here.
559      cflags_cc += [ "-fno-trigraphs" ]
560    }
561
562    # Don't warn that trigraphs are ignored, since trigraphs are disabled
563    # anyway.
564    cflags_cc += [ "-Wno-trigraphs" ]
565  }
566
567  if (is_mac) {
568    # The system libc++ on Mac doesn't have aligned allocation in C++17.
569    defines += [ "_LIBCPP_HAS_NO_ALIGNED_ALLOCATION" ]
570    cflags_cc += [ "-stdlib=libc++" ]
571    ldflags += [ "-stdlib=libc++" ]
572  }
573
574  # Add flags for link-time optimization. These flags enable
575  # optimizations/transformations that require whole-program visibility at link
576  # time, so they need to be applied to all translation units, and we may end up
577  # with miscompiles if only part of the program is compiled with LTO flags. For
578  # that reason, we cannot allow targets to enable or disable these flags, for
579  # example by disabling the optimize configuration.
580  # TODO(pcc): Make this conditional on is_official_build rather than on gn
581  # flags for specific features.
582  if (!is_debug && use_thin_lto && is_a_target_toolchain) {
583    assert(use_lld, "LTO is only supported with lld")
584
585    cflags += [
586      "-flto=thin",
587      "-fsplit-lto-unit",
588    ]
589
590    if (thin_lto_enable_optimizations) {
591      lto_opt_level = 2
592    } else {
593      lto_opt_level = 0
594    }
595
596    if (is_win) {
597      # This is a straight translation of the non-Windows flags below,
598      # except we do not use the ThinLTO cache, which leaks temporary
599      # files on Windows (https://crbug.com/871962).
600      ldflags += [
601        "/opt:lldlto=" + lto_opt_level,
602        "/opt:lldltojobs=all",
603
604        # Experimentally determined to yield a reasonable trade-off between
605        # build time, run-time performance, and binary size.
606        "-mllvm:-import-instr-limit=10",
607
608        # TODO(https://crbug.com/1127713): Investigate, remove.
609        "-mllvm:-enable-dse-memoryssa=false",
610      ]
611    } else {
612      ldflags += [ "-flto=thin" ]
613
614      # Enabling ThinLTO on Chrome OS too, in an effort to reduce the memory
615      # usage in crbug.com/1038040. Note this will increase build time in
616      # Chrome OS.
617
618      # In ThinLTO builds, we run at most one link process at a time,
619      # and let it use all cores.
620      # TODO(thakis): Check if '=0' (that is, number of cores, instead
621      # of "all" which means number of hardware threads) is faster.
622      ldflags += [ "-Wl,--thinlto-jobs=all" ]
623
624      # Limit the size of the ThinLTO cache to the lesser of 10% of
625      # available disk space, 10GB and 100000 files.
626      cache_policy =
627          "cache_size=10%:cache_size_bytes=10g:cache_size_files=100000"
628      ldflags += [
629        "-Wl,--thinlto-cache-dir=" +
630            rebase_path("$root_out_dir/thinlto-cache", root_build_dir),
631        "-Wl,--thinlto-cache-policy,$cache_policy",
632      ]
633
634      # TODO(https://crbug.com/1127713): Investigate, remove.
635      ldflags += [ "-Wl,-mllvm,-enable-dse-memoryssa=false" ]
636
637      ldflags += [ "-Wl,--lto-O" + lto_opt_level ]
638      if (thin_lto_enable_optimizations) {
639        # TODO(gbiv): We ideally shouldn't need to specify this; ThinLTO
640        # should be able to better manage binary size increases on its own.
641        import_instr_limit = -1
642        if (is_android) {
643          import_instr_limit = 5
644        } else if (is_chromeos) {
645          # Not much performance difference was noted between the default (100)
646          # and these. ARM was originally set lower than x86 to keep the size
647          # bloat of ThinLTO to <10%, but that's potentially no longer true.
648          # FIXME(inglorion): maybe tune these?
649          if (target_cpu == "arm" || target_cpu == "arm64") {
650            import_instr_limit = 20
651          } else {
652            import_instr_limit = 30
653          }
654        }
655
656        if (import_instr_limit != -1) {
657          ldflags += [ "-Wl,-mllvm,-import-instr-limit=$import_instr_limit" ]
658        }
659      }
660    }
661
662    # TODO(pcc): Re-enable this flag on Android. This will require libc++ to be
663    # built with ThinLTO (see https://crbug.com/767901) as well as the GVR shim.
664    if (!is_android) {
665      cflags += [ "-fwhole-program-vtables" ]
666      if (!is_win) {
667        ldflags += [ "-fwhole-program-vtables" ]
668      }
669    }
670
671    # This flag causes LTO to create an .ARM.attributes section with the correct
672    # architecture. This is necessary because LLD will refuse to link a program
673    # unless the architecture revision in .ARM.attributes is sufficiently new.
674    # TODO(pcc): The contents of .ARM.attributes should be based on the
675    # -march flag passed at compile time (see llvm.org/pr36291).
676    if (current_cpu == "arm") {
677      ldflags += [ "-march=$arm_arch" ]
678    }
679  }
680
681  if (compiler_timing) {
682    if (is_clang && !is_nacl) {
683      if (is_win) {
684        cflags += [ "/clang:-ftime-trace" ]
685      } else {
686        cflags += [ "-ftime-trace" ]
687      }
688    } else if (is_win) {
689      cflags += [
690        # "Documented" here:
691        # http://aras-p.info/blog/2017/10/23/Best-unknown-MSVC-flag-d2cgsummary/
692        "/d2cgsummary",
693      ]
694    }
695  }
696
697  # Pass flag to LLD so Android builds can allow debuggerd to properly symbolize
698  # stack crashes (http://crbug.com/919499).
699  if (use_lld && is_android) {
700    ldflags += [ "-Wl,--no-rosegment" ]
701  }
702
703  # LLD does call-graph-sorted binary layout by default when profile data is
704  # present. On Android this increases binary size due to more thinks for long
705  # jumps. Turn it off by default and enable selectively for targets where it's
706  # beneficial.
707  if (use_lld && !enable_call_graph_profile_sort) {
708    if (is_win) {
709      ldflags += [ "/call-graph-profile-sort:no" ]
710    } else {
711      ldflags += [ "-Wl,--no-call-graph-profile-sort" ]
712    }
713  }
714
715  # This flag enforces that member pointer base types are complete. It helps
716  # prevent us from running into problems in the Microsoft C++ ABI (see
717  # https://crbug.com/847724).
718  if (is_clang && !is_nacl && target_os != "chromeos" && !use_xcode_clang &&
719      (is_win || use_custom_libcxx)) {
720    cflags += [ "-fcomplete-member-pointers" ]
721  }
722
723  # Pass the same C/C++ flags to the objective C/C++ compiler.
724  cflags_objc += cflags_c
725  cflags_objcc += cflags_cc
726
727  # Assign any flags set for the C compiler to asmflags so that they are sent
728  # to the assembler. The Windows assembler takes different types of flags
729  # so only do so for posix platforms.
730  if (is_posix || is_fuchsia) {
731    asmflags += cflags
732    asmflags += cflags_c
733  }
734}
735
736# This provides the basic options to select the target CPU and ABI.
737# It is factored out of "compiler" so that special cases can use this
738# without using everything that "compiler" brings in.  Options that
739# tweak code generation for a particular CPU do not belong here!
740# See "compiler_codegen", below.
741config("compiler_cpu_abi") {
742  cflags = []
743  ldflags = []
744  defines = []
745
746  if ((is_posix && !is_apple) || is_fuchsia) {
747    # CPU architecture. We may or may not be doing a cross compile now, so for
748    # simplicity we always explicitly set the architecture.
749    if (current_cpu == "x64") {
750      cflags += [
751        "-m64",
752        "-march=$x64_arch",
753      ]
754      ldflags += [ "-m64" ]
755    } else if (current_cpu == "x86") {
756      cflags += [ "-m32" ]
757      ldflags += [ "-m32" ]
758      if (!is_nacl) {
759        cflags += [
760          "-msse2",
761          "-mfpmath=sse",
762          "-mmmx",
763        ]
764      }
765    } else if (current_cpu == "arm") {
766      if (is_clang && !is_android && !is_nacl) {
767        cflags += [ "--target=arm-linux-gnueabihf" ]
768        ldflags += [ "--target=arm-linux-gnueabihf" ]
769      }
770      if (!is_nacl) {
771        cflags += [
772          "-march=$arm_arch",
773          "-mfloat-abi=$arm_float_abi",
774        ]
775      }
776      if (arm_tune != "") {
777        cflags += [ "-mtune=$arm_tune" ]
778      }
779    } else if (current_cpu == "arm64") {
780      if (is_clang && !is_android && !is_nacl && !is_fuchsia && !is_bsd) {
781        cflags += [ "--target=aarch64-linux-gnu" ]
782        ldflags += [ "--target=aarch64-linux-gnu" ]
783      }
784    } else if (current_cpu == "mipsel" && !is_nacl) {
785      ldflags += [ "-Wl,--hash-style=sysv" ]
786      if (custom_toolchain == "") {
787        if (is_clang) {
788          if (is_android) {
789            cflags += [ "--target=mipsel-linux-android" ]
790            ldflags += [ "--target=mipsel-linux-android" ]
791          } else {
792            cflags += [ "--target=mipsel-linux-gnu" ]
793            ldflags += [ "--target=mipsel-linux-gnu" ]
794          }
795        } else {
796          cflags += [ "-EL" ]
797          ldflags += [ "-EL" ]
798        }
799      }
800
801      if (mips_arch_variant == "r6") {
802        cflags += [ "-mno-odd-spreg" ]
803        ldflags += [ "-mips32r6" ]
804        if (is_clang) {
805          cflags += [
806            "-march=mipsel",
807            "-mcpu=mips32r6",
808          ]
809        } else {
810          cflags += [
811            "-mips32r6",
812            "-Wa,-mips32r6",
813          ]
814          if (is_android) {
815            ldflags += [ "-Wl,-melf32ltsmip" ]
816          }
817        }
818        if (mips_use_msa == true) {
819          cflags += [
820            "-mmsa",
821            "-mfp64",
822          ]
823        }
824      } else if (mips_arch_variant == "r2") {
825        ldflags += [ "-mips32r2" ]
826        if (is_clang) {
827          cflags += [
828            "-march=mipsel",
829            "-mcpu=mips32r2",
830          ]
831        } else {
832          cflags += [
833            "-mips32r2",
834            "-Wa,-mips32r2",
835          ]
836          if (mips_float_abi == "hard" && mips_fpu_mode != "") {
837            cflags += [ "-m$mips_fpu_mode" ]
838          }
839        }
840      } else if (mips_arch_variant == "r1") {
841        ldflags += [ "-mips32" ]
842        if (is_clang) {
843          cflags += [
844            "-march=mipsel",
845            "-mcpu=mips32",
846          ]
847        } else {
848          cflags += [
849            "-mips32",
850            "-Wa,-mips32",
851          ]
852        }
853      } else if (mips_arch_variant == "loongson3") {
854        defines += [ "_MIPS_ARCH_LOONGSON" ]
855        cflags += [
856          "-march=loongson3a",
857          "-mno-branch-likely",
858          "-Wa,-march=loongson3a",
859        ]
860      }
861
862      if (mips_dsp_rev == 1) {
863        cflags += [ "-mdsp" ]
864      } else if (mips_dsp_rev == 2) {
865        cflags += [ "-mdspr2" ]
866      }
867
868      cflags += [ "-m${mips_float_abi}-float" ]
869    } else if (current_cpu == "mips" && !is_nacl) {
870      ldflags += [ "-Wl,--hash-style=sysv" ]
871      if (custom_toolchain == "") {
872        if (is_clang) {
873          cflags += [ "--target=mips-linux-gnu" ]
874          ldflags += [ "--target=mips-linux-gnu" ]
875        } else {
876          cflags += [ "-EB" ]
877          ldflags += [ "-EB" ]
878        }
879      }
880
881      if (mips_arch_variant == "r6") {
882        cflags += [
883          "-mips32r6",
884          "-Wa,-mips32r6",
885        ]
886        if (mips_use_msa == true) {
887          cflags += [
888            "-mmsa",
889            "-mfp64",
890          ]
891        }
892      } else if (mips_arch_variant == "r2") {
893        cflags += [
894          "-mips32r2",
895          "-Wa,-mips32r2",
896        ]
897        if (mips_float_abi == "hard" && mips_fpu_mode != "") {
898          cflags += [ "-m$mips_fpu_mode" ]
899        }
900      } else if (mips_arch_variant == "r1") {
901        cflags += [
902          "-mips32",
903          "-Wa,-mips32",
904        ]
905      }
906
907      if (mips_dsp_rev == 1) {
908        cflags += [ "-mdsp" ]
909      } else if (mips_dsp_rev == 2) {
910        cflags += [ "-mdspr2" ]
911      }
912
913      cflags += [ "-m${mips_float_abi}-float" ]
914    } else if (current_cpu == "mips64el") {
915      cflags += [ "-D__SANE_USERSPACE_TYPES__" ]
916      ldflags += [ "-Wl,--hash-style=sysv" ]
917      if (custom_toolchain == "") {
918        if (is_clang) {
919          if (is_android) {
920            cflags += [ "--target=mips64el-linux-android" ]
921            ldflags += [ "--target=mips64el-linux-android" ]
922          } else {
923            cflags += [ "--target=mips64el-linux-gnuabi64" ]
924            ldflags += [ "--target=mips64el-linux-gnuabi64" ]
925          }
926        } else {
927          cflags += [
928            "-EL",
929            "-mabi=64",
930          ]
931          ldflags += [
932            "-EL",
933            "-mabi=64",
934          ]
935        }
936      }
937
938      if (mips_arch_variant == "r6") {
939        if (is_clang) {
940          cflags += [
941            "-march=mips64el",
942            "-mcpu=mips64r6",
943          ]
944        } else {
945          cflags += [
946            "-mips64r6",
947            "-Wa,-mips64r6",
948          ]
949          ldflags += [ "-mips64r6" ]
950        }
951        if (mips_use_msa == true) {
952          cflags += [
953            "-mmsa",
954            "-mfp64",
955          ]
956        }
957      } else if (mips_arch_variant == "r2") {
958        ldflags += [ "-mips64r2" ]
959        if (is_clang) {
960          cflags += [
961            "-march=mips64el",
962            "-mcpu=mips64r2",
963          ]
964        } else {
965          cflags += [
966            "-mips64r2",
967            "-Wa,-mips64r2",
968          ]
969        }
970      } else if (mips_arch_variant == "loongson3") {
971        defines += [ "_MIPS_ARCH_LOONGSON" ]
972        cflags += [
973          "-march=loongson3a",
974          "-mno-branch-likely",
975          "-Wa,-march=loongson3a",
976        ]
977      }
978    } else if (current_cpu == "mips64") {
979      ldflags += [ "-Wl,--hash-style=sysv" ]
980      if (custom_toolchain == "") {
981        if (is_clang) {
982          cflags += [ "--target=mips64-linux-gnuabi64" ]
983          ldflags += [ "--target=mips64-linux-gnuabi64" ]
984        } else {
985          cflags += [
986            "-EB",
987            "-mabi=64",
988          ]
989          ldflags += [
990            "-EB",
991            "-mabi=64",
992          ]
993        }
994      }
995
996      if (mips_arch_variant == "r6") {
997        cflags += [
998          "-mips64r6",
999          "-Wa,-mips64r6",
1000        ]
1001        ldflags += [ "-mips64r6" ]
1002
1003        if (mips_use_msa == true) {
1004          cflags += [
1005            "-mmsa",
1006            "-mfp64",
1007          ]
1008        }
1009      } else if (mips_arch_variant == "r2") {
1010        cflags += [
1011          "-mips64r2",
1012          "-Wa,-mips64r2",
1013        ]
1014        ldflags += [ "-mips64r2" ]
1015      }
1016    } else if (current_cpu == "pnacl" && is_nacl_nonsfi) {
1017      if (target_cpu == "x86" || target_cpu == "x64") {
1018        cflags += [
1019          "-arch",
1020          "x86-32-nonsfi",
1021          "--pnacl-bias=x86-32-nonsfi",
1022          "--target=i686-unknown-nacl",
1023        ]
1024        ldflags += [
1025          "-arch",
1026          "x86-32-nonsfi",
1027          "--target=i686-unknown-nacl",
1028        ]
1029      } else if (target_cpu == "arm") {
1030        cflags += [
1031          "-arch",
1032          "arm-nonsfi",
1033          "-mfloat-abi=hard",
1034          "--pnacl-bias=arm-nonsfi",
1035          "--target=armv7-unknown-nacl-gnueabihf",
1036        ]
1037        ldflags += [
1038          "-arch",
1039          "arm-nonsfi",
1040          "--target=armv7-unknown-nacl-gnueabihf",
1041        ]
1042      }
1043    } else if (current_cpu == "ppc64") {
1044      if (current_os == "aix") {
1045        cflags += [ "-maix64" ]
1046        ldflags += [ "-maix64" ]
1047      } else {
1048        cflags += [ "-m64" ]
1049        ldflags += [ "-m64" ]
1050      }
1051    } else if (current_cpu == "s390x") {
1052      cflags += [ "-m64" ]
1053      ldflags += [ "-m64" ]
1054    }
1055  }
1056
1057  asmflags = cflags
1058}
1059
1060# This provides options to tweak code generation that are necessary
1061# for particular Chromium code or for working around particular
1062# compiler bugs (or the combination of the two).
1063config("compiler_codegen") {
1064  configs = []
1065  cflags = []
1066  ldflags = []
1067
1068  if (is_nacl) {
1069    configs += [ "//build/config/nacl:compiler_codegen" ]
1070  }
1071
1072  if (current_cpu == "arm64" && is_android) {
1073    # On arm64 disable outlining for Android. See crbug.com/931297 for more
1074    # information.
1075    cflags += [ "-mno-outline" ]
1076
1077    # This can be removed once https://bugs.llvm.org/show_bug.cgi?id=40348
1078    # has been resolved, and -mno-outline is obeyed by the linker during
1079    # ThinLTO.
1080    ldflags += [ "-Wl,-mllvm,-enable-machine-outliner=never" ]
1081  }
1082
1083  asmflags = cflags
1084}
1085
1086# This provides options that make the build deterministic, so that the same
1087# revision produces the same output, independent of the name of the build
1088# directory and of the computer the build is done on.
1089# The relative path from build dir to source dir makes it into the build
1090# outputs, so it's recommended that you use a build dir two levels deep
1091# (e.g. "out/Release") so that you get the same "../.." path as all the bots
1092# in your build outputs.
1093config("compiler_deterministic") {
1094  cflags = []
1095  ldflags = []
1096
1097  # Eliminate build metadata (__DATE__, __TIME__ and __TIMESTAMP__) for
1098  # deterministic build.  See https://crbug.com/314403
1099  if (!is_official_build) {
1100    if (is_win && !is_clang) {
1101      cflags += [
1102        "/wd4117",  # Trying to define or undefine a predefined macro.
1103        "/D__DATE__=",
1104        "/D__TIME__=",
1105        "/D__TIMESTAMP__=",
1106      ]
1107    } else {
1108      cflags += [
1109        "-Wno-builtin-macro-redefined",
1110        "-D__DATE__=",
1111        "-D__TIME__=",
1112        "-D__TIMESTAMP__=",
1113      ]
1114    }
1115  }
1116
1117  # Makes builds independent of absolute file path.
1118  if (is_clang && strip_absolute_paths_from_debug_symbols) {
1119    # If debug option is given, clang includes $cwd in debug info by default.
1120    # For such build, this flag generates reproducible obj files even we use
1121    # different build directory like "out/feature_a" and "out/feature_b" if
1122    # we build same files with same compile flag.
1123    # Other paths are already given in relative, no need to normalize them.
1124    cflags += [
1125      "-Xclang",
1126      "-fdebug-compilation-dir",
1127      "-Xclang",
1128      ".",
1129    ]
1130    if (!is_win && !is_bsd) {
1131      # We don't use clang -cc1as on Windows (yet? https://crbug.com/762167)
1132      asmflags = [ "-Wa,-fdebug-compilation-dir,." ]
1133    }
1134
1135    if (is_win && use_lld) {
1136      if (symbol_level == 2 || (is_clang && using_sanitizer)) {
1137        # Absolutize source file paths for PDB. Pass the real build directory
1138        # if the pdb contains source-level debug information and if linker
1139        # reproducibility is not critical.
1140        ldflags += [ "/PDBSourcePath:" + rebase_path(root_build_dir) ]
1141      } else {
1142        # Use a fake fixed base directory for paths in the pdb to make the pdb
1143        # output fully deterministic and independent of the build directory.
1144        ldflags += [ "/PDBSourcePath:o:\fake\prefix" ]
1145      }
1146    }
1147  }
1148
1149  # Tells the compiler not to use absolute paths when passing the default
1150  # paths to the tools it invokes. We don't want this because we don't
1151  # really need it and it can mess up the goma cache entries.
1152  if (is_clang && !is_nacl) {
1153    cflags += [ "-no-canonical-prefixes" ]
1154  }
1155}
1156
1157config("clang_revision") {
1158  if (is_clang && clang_base_path == default_clang_base_path) {
1159    update_args = [
1160      "--print-revision",
1161      "--verify-version=$clang_version",
1162    ]
1163    if (llvm_force_head_revision) {
1164      update_args += [ "--llvm-force-head-revision" ]
1165    }
1166    clang_revision = exec_script("//tools/clang/scripts/update.py",
1167                                 update_args,
1168                                 "trim string")
1169
1170    # This is here so that all files get recompiled after a clang roll and
1171    # when turning clang on or off. (defines are passed via the command line,
1172    # and build system rebuild things when their commandline changes). Nothing
1173    # should ever read this define.
1174    defines = [ "CR_CLANG_REVISION=\"$clang_revision\"" ]
1175  }
1176}
1177
1178config("compiler_arm_fpu") {
1179  if (current_cpu == "arm" && !is_ios && !is_nacl) {
1180    cflags = [ "-mfpu=$arm_fpu" ]
1181    if (!arm_use_thumb) {
1182      cflags += [ "-marm" ]
1183    }
1184    asmflags = cflags
1185  }
1186}
1187
1188config("compiler_arm_thumb") {
1189  if (current_cpu == "arm" && arm_use_thumb && is_posix &&
1190      !(is_apple || is_nacl)) {
1191    cflags = [ "-mthumb" ]
1192  }
1193}
1194
1195config("compiler_arm") {
1196  if (current_cpu == "arm" && is_chromeos) {
1197    # arm is normally the default mode for clang, but on chromeos a wrapper
1198    # is used to pass -mthumb, and therefor change the default.
1199    cflags = [ "-marm" ]
1200  }
1201}
1202
1203# runtime_library -------------------------------------------------------------
1204#
1205# Sets the runtime library and associated options.
1206#
1207# How do you determine what should go in here vs. "compiler" above? Consider if
1208# a target might choose to use a different runtime library (ignore for a moment
1209# if this is possible or reasonable on your system). If such a target would want
1210# to change or remove your option, put it in the runtime_library config. If a
1211# target wants the option regardless, put it in the compiler config.
1212
1213config("runtime_library") {
1214  configs = []
1215
1216  # The order of this config is important: it must appear before
1217  # android:runtime_library.  This is to ensure libc++ appears before
1218  # libandroid_support in the -isystem include order.  Otherwise, there will be
1219  # build errors related to symbols declared in math.h.
1220  if (use_custom_libcxx) {
1221    configs += [ "//build/config/c++:runtime_library" ]
1222  }
1223
1224  # TODO(crbug.com/830987): Come up with a better name for is POSIX + Fuchsia
1225  # configuration.
1226  if (is_posix || is_fuchsia) {
1227    configs += [ "//build/config/posix:runtime_library" ]
1228  }
1229
1230  # System-specific flags. If your compiler flags apply to one of the
1231  # categories here, add it to the associated file to keep this shared config
1232  # smaller.
1233  if (is_win) {
1234    configs += [ "//build/config/win:runtime_library" ]
1235  } else if (is_linux || is_chromeos) {
1236    configs += [ "//build/config/linux:runtime_library" ]
1237  } else if (is_ios) {
1238    configs += [ "//build/config/ios:runtime_library" ]
1239  } else if (is_mac) {
1240    configs += [ "//build/config/mac:runtime_library" ]
1241  } else if (is_android) {
1242    configs += [ "//build/config/android:runtime_library" ]
1243  }
1244
1245  if (is_component_build) {
1246    defines = [ "COMPONENT_BUILD" ]
1247  }
1248}
1249
1250# default_warnings ------------------------------------------------------------
1251#
1252# Collects all warning flags that are used by default.  This is used as a
1253# subconfig of both chromium_code and no_chromium_code.  This way these
1254# flags are guaranteed to appear on the compile command line after -Wall.
1255config("default_warnings") {
1256  cflags = []
1257  cflags_c = []
1258  cflags_cc = []
1259  ldflags = []
1260
1261  if (is_win) {
1262    if (treat_warnings_as_errors) {
1263      cflags += [ "/WX" ]
1264    }
1265    if (fatal_linker_warnings) {
1266      ldflags = [ "/WX" ]
1267    }
1268
1269    cflags += [
1270      # Warnings permanently disabled:
1271
1272      # C4091: 'typedef ': ignored on left of 'X' when no variable is
1273      #                    declared.
1274      # This happens in a number of Windows headers. Dumb.
1275      "/wd4091",
1276
1277      # C4127: conditional expression is constant
1278      # This warning can in theory catch dead code and other problems, but
1279      # triggers in far too many desirable cases where the conditional
1280      # expression is either set by macros or corresponds some legitimate
1281      # compile-time constant expression (due to constant template args,
1282      # conditionals comparing the sizes of different types, etc.).  Some of
1283      # these can be worked around, but it's not worth it.
1284      "/wd4127",
1285
1286      # C4251: 'identifier' : class 'type' needs to have dll-interface to be
1287      #        used by clients of class 'type2'
1288      # This is necessary for the shared library build.
1289      "/wd4251",
1290
1291      # C4275:  non dll-interface class used as base for dll-interface class
1292      # This points out a potential (but rare) problem with referencing static
1293      # fields of a non-exported base, through the base's non-exported inline
1294      # functions, or directly. The warning is subtle enough that people just
1295      # suppressed it when they saw it, so it's not worth it.
1296      "/wd4275",
1297
1298      # C4312 is a VS 2015 64-bit warning for integer to larger pointer.
1299      # TODO(brucedawson): fix warnings, crbug.com/554200
1300      "/wd4312",
1301
1302      # C4324 warns when padding is added to fulfill alignas requirements,
1303      # but can trigger in benign cases that are difficult to individually
1304      # suppress.
1305      "/wd4324",
1306
1307      # C4351: new behavior: elements of array 'array' will be default
1308      #        initialized
1309      # This is a silly "warning" that basically just alerts you that the
1310      # compiler is going to actually follow the language spec like it's
1311      # supposed to, instead of not following it like old buggy versions did.
1312      # There's absolutely no reason to turn this on.
1313      "/wd4351",
1314
1315      # C4355: 'this': used in base member initializer list
1316      # It's commonly useful to pass |this| to objects in a class' initializer
1317      # list.  While this warning can catch real bugs, most of the time the
1318      # constructors in question don't attempt to call methods on the passed-in
1319      # pointer (until later), and annotating every legit usage of this is
1320      # simply more hassle than the warning is worth.
1321      "/wd4355",
1322
1323      # C4503: 'identifier': decorated name length exceeded, name was
1324      #        truncated
1325      # This only means that some long error messages might have truncated
1326      # identifiers in the presence of lots of templates.  It has no effect on
1327      # program correctness and there's no real reason to waste time trying to
1328      # prevent it.
1329      "/wd4503",
1330
1331      # Warning C4589 says: "Constructor of abstract class ignores
1332      # initializer for virtual base class." Disable this warning because it
1333      # is flaky in VS 2015 RTM. It triggers on compiler generated
1334      # copy-constructors in some cases.
1335      "/wd4589",
1336
1337      # C4611: interaction between 'function' and C++ object destruction is
1338      #        non-portable
1339      # This warning is unavoidable when using e.g. setjmp/longjmp.  MSDN
1340      # suggests using exceptions instead of setjmp/longjmp for C++, but
1341      # Chromium code compiles without exception support.  We therefore have to
1342      # use setjmp/longjmp for e.g. JPEG decode error handling, which means we
1343      # have to turn off this warning (and be careful about how object
1344      # destruction happens in such cases).
1345      "/wd4611",
1346
1347      # Warnings to evaluate and possibly fix/reenable later:
1348
1349      "/wd4100",  # Unreferenced formal function parameter.
1350      "/wd4121",  # Alignment of a member was sensitive to packing.
1351      "/wd4244",  # Conversion: possible loss of data.
1352      "/wd4505",  # Unreferenced local function has been removed.
1353      "/wd4510",  # Default constructor could not be generated.
1354      "/wd4512",  # Assignment operator could not be generated.
1355      "/wd4610",  # Class can never be instantiated, constructor required.
1356      "/wd4838",  # Narrowing conversion. Doesn't seem to be very useful.
1357      "/wd4995",  # 'X': name was marked as #pragma deprecated
1358      "/wd4996",  # Deprecated function warning.
1359
1360      # These are variable shadowing warnings that are new in VS2015. We
1361      # should work through these at some point -- they may be removed from
1362      # the RTM release in the /W4 set.
1363      "/wd4456",
1364      "/wd4457",
1365      "/wd4458",
1366      "/wd4459",
1367
1368      # All of our compilers support the extensions below.
1369      "/wd4200",  # nonstandard extension used: zero-sized array in struct/union
1370      "/wd4201",  # nonstandard extension used: nameless struct/union
1371      "/wd4204",  # nonstandard extension used : non-constant aggregate
1372                  # initializer
1373
1374      "/wd4221",  # nonstandard extension used : 'identifier' : cannot be
1375                  # initialized using address of automatic variable
1376
1377      # http://crbug.com/588506 - Conversion suppressions waiting on Clang
1378      # -Wconversion.
1379      "/wd4245",  # 'conversion' : conversion from 'type1' to 'type2',
1380                  # signed/unsigned mismatch
1381
1382      "/wd4267",  # 'var' : conversion from 'size_t' to 'type', possible loss of
1383                  # data
1384
1385      "/wd4305",  # 'identifier' : truncation from 'type1' to 'type2'
1386      "/wd4389",  # 'operator' : signed/unsigned mismatch
1387
1388      "/wd4702",  # unreachable code
1389
1390      # http://crbug.com/848979 - MSVC is more conservative than Clang with
1391      # regards to variables initialized and consumed in different branches.
1392      "/wd4701",  # Potentially uninitialized local variable 'name' used
1393      "/wd4703",  # Potentially uninitialized local pointer variable 'name' used
1394
1395      # http://crbug.com/848979 - Remaining Clang permitted warnings.
1396      "/wd4661",  # 'identifier' : no suitable definition provided for explicit
1397                  # template instantiation request
1398
1399      "/wd4706",  # assignment within conditional expression
1400                  # MSVC is stricter and requires a boolean expression.
1401
1402      "/wd4715",  # 'function' : not all control paths return a value'
1403                  # MSVC does not analyze switch (enum) for completeness.
1404    ]
1405
1406    cflags_cc += [
1407      # Allow "noexcept" annotations even though we compile with exceptions
1408      # disabled.
1409      "/wd4577",
1410    ]
1411
1412    if (current_cpu == "x86") {
1413      cflags += [
1414        # VC++ 2015 changes 32-bit size_t truncation warnings from 4244 to
1415        # 4267. Example: short TruncTest(size_t x) { return x; }
1416        # Since we disable 4244 we need to disable 4267 during migration.
1417        # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
1418        "/wd4267",
1419      ]
1420    }
1421  } else {
1422    if (is_apple && !is_nacl) {
1423      # When compiling Objective-C, warns if a method is used whose
1424      # availability is newer than the deployment target.
1425      cflags += [ "-Wunguarded-availability" ]
1426    }
1427
1428    if (is_ios) {
1429      # When compiling Objective-C, warns if a selector named via @selector has
1430      # not been defined in any visible interface.
1431      cflags += [ "-Wundeclared-selector" ]
1432    }
1433
1434    # Suppress warnings about ABI changes on ARM (Clang doesn't give this
1435    # warning).
1436    if (current_cpu == "arm" && !is_clang) {
1437      cflags += [ "-Wno-psabi" ]
1438    }
1439
1440    if (!is_clang) {
1441      cflags_cc += [
1442        # See comment for -Wno-c++11-narrowing.
1443        "-Wno-narrowing",
1444      ]
1445
1446      # -Wno-class-memaccess warns about hash table and vector in blink.
1447      # But the violation is intentional.
1448      if (!is_nacl) {
1449        cflags_cc += [ "-Wno-class-memaccess" ]
1450      }
1451
1452      # -Wunused-local-typedefs is broken in gcc,
1453      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63872
1454      cflags += [ "-Wno-unused-local-typedefs" ]
1455
1456      # Don't warn about "maybe" uninitialized. Clang doesn't include this
1457      # in -Wall but gcc does, and it gives false positives.
1458      cflags += [ "-Wno-maybe-uninitialized" ]
1459      cflags += [ "-Wno-deprecated-declarations" ]
1460
1461      # -Wcomment gives too many false positives in the case a
1462      # backslash ended comment line is followed by a new line of
1463      # comments
1464      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61638
1465      cflags += [ "-Wno-comments" ]
1466
1467      # -Wpacked-not-aligned complains all generated mojom-shared-internal.h
1468      # files.
1469      cflags += [ "-Wno-packed-not-aligned" ]
1470    }
1471  }
1472
1473  # Common Clang and GCC warning setup.
1474  if (!is_win || is_clang) {
1475    cflags += [
1476      # Disables.
1477      "-Wno-missing-field-initializers",  # "struct foo f = {0};"
1478      "-Wno-unused-parameter",  # Unused function parameters.
1479    ]
1480  }
1481
1482  if (is_clang) {
1483    cflags += [
1484      # TODO(thakis): Consider -Wloop-analysis (turns on
1485      # -Wrange-loop-analysis too).
1486
1487      # This warns on using ints as initializers for floats in
1488      # initializer lists (e.g. |int a = f(); CGSize s = { a, a };|),
1489      # which happens in several places in chrome code. Not sure if
1490      # this is worth fixing.
1491      "-Wno-c++11-narrowing",
1492
1493      # TODO(thakis): This used to be implied by -Wno-unused-function,
1494      # which we no longer use. Check if it makes sense to remove
1495      # this as well. http://crbug.com/316352
1496      "-Wno-unneeded-internal-declaration",
1497    ]
1498
1499    # use_xcode_clang only refers to the iOS toolchain, host binaries use
1500    # chromium's clang always.
1501    if (!is_nacl) {
1502      cflags += [
1503        # TODO(thakis): https://crbug.com/604888
1504        "-Wno-undefined-var-template",
1505      ]
1506
1507      if (is_win) {
1508        # TODO(thakis): https://crbug.com/617318
1509        # Currently goma can not handle case sensitiveness for windows well.
1510        cflags += [ "-Wno-nonportable-include-path" ]
1511      }
1512
1513      if ((current_toolchain == host_toolchain || !use_xcode_clang) && !is_bsd) {
1514        # Flags NaCl (Clang 3.7) and Xcode 9.2 (Clang clang-900.0.39.2) do not
1515        # recognize.
1516        cflags += [
1517          # An ABI compat warning we don't care about, https://crbug.com/1102157
1518          # TODO(thakis): Push this to the (few) targets that need it,
1519          # instead of having a global flag.
1520          "-Wno-psabi",
1521
1522          # Ignore warnings about MSVC optimization pragmas.
1523          # TODO(thakis): Only for no_chromium_code? http://crbug.com/912662
1524          "-Wno-ignored-pragma-optimize",
1525
1526          # TODO(https://crbug.com/989932): Evaluate and possibly enable.
1527          "-Wno-implicit-int-float-conversion",
1528
1529          # TODO(https://crbug.com/999886): Clean up, enable.
1530          "-Wno-final-dtor-non-final-class",
1531
1532          # TODO(https://crbug.com/1016945) Clean up, enable.
1533          "-Wno-builtin-assume-aligned-alignment",
1534
1535          # TODO(https://crbug.com/1028110): Evaluate and possible enable.
1536          "-Wno-deprecated-copy",
1537
1538          # TODO(https://crbug.com/1050281): Clean up, enable.
1539          "-Wno-non-c-typedef-for-linkage",
1540        ]
1541
1542        cflags_c += [
1543          # TODO(https://crbug.com/995993): Clean up and enable.
1544          "-Wno-implicit-fallthrough",
1545        ]
1546
1547        if (is_ios) {
1548          # TODO(https://crbug.com/1143700): Clean up and re-enable.
1549          cflags_objc = [ "-Wno-gnu-folding-constant" ]
1550        }
1551
1552        if (enable_wmax_tokens) {
1553          cflags += [ "-Wmax-tokens" ]
1554        } else {
1555          # TODO(https://crbug.com/1049569): Remove after Clang 87b235db.
1556          cflags += [ "-Wno-max-tokens" ]
1557        }
1558      }
1559    }
1560  }
1561}
1562
1563# chromium_code ---------------------------------------------------------------
1564#
1565# Toggles between higher and lower warnings for code that is (or isn't)
1566# part of Chromium.
1567
1568config("chromium_code") {
1569  if (is_win) {
1570    cflags = [ "/W4" ]  # Warning level 4.
1571
1572    if (is_clang) {
1573      # Opt in to additional [[nodiscard]] on standard library methods.
1574      defines = [ "_HAS_NODISCARD" ]
1575    }
1576  } else {
1577    cflags = [ "-Wall" ]
1578    if (treat_warnings_as_errors) {
1579      cflags += [ "-Werror" ]
1580
1581      # The compiler driver can sometimes (rarely) emit warnings before calling
1582      # the actual linker.  Make sure these warnings are treated as errors as
1583      # well.
1584      ldflags = [ "-Werror" ]
1585    }
1586    if (is_clang) {
1587      # Enable extra warnings for chromium_code when we control the compiler.
1588      cflags += [ "-Wextra" ]
1589    }
1590
1591    # In Chromium code, we define __STDC_foo_MACROS in order to get the
1592    # C99 macros on Mac and Linux.
1593    defines = [
1594      "__STDC_CONSTANT_MACROS",
1595      "__STDC_FORMAT_MACROS",
1596    ]
1597
1598    if (!is_debug && !using_sanitizer && current_cpu != "s390x" &&
1599        current_cpu != "s390" && current_cpu != "ppc64" &&
1600        current_cpu != "mips" && current_cpu != "mips64") {
1601      # Non-chromium code is not guaranteed to compile cleanly with
1602      # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are
1603      # disabled, so only do that for Release build.
1604      defines += [ "_FORTIFY_SOURCE=2" ]
1605    }
1606
1607    if (is_mac) {
1608      cflags_objc = [ "-Wobjc-missing-property-synthesis" ]
1609      cflags_objcc = [ "-Wobjc-missing-property-synthesis" ]
1610    }
1611  }
1612
1613  if (is_clang) {
1614    cflags += [
1615      # Warn on missing break statements at the end of switch cases.
1616      # For intentional fallthrough, use FALLTHROUGH; from
1617      # base/compiler_specific.h
1618      "-Wimplicit-fallthrough",
1619    ]
1620
1621    # TODO(thakis): Enable this more often, https://crbug.com/346399
1622    # use_libfuzzer: https://crbug.com/1063180
1623    if (!is_nacl && !use_libfuzzer) {
1624      cflags += [ "-Wunreachable-code" ]
1625    }
1626
1627    # Thread safety analysis is broken under nacl: https://crbug.com/982423.
1628    if (!is_nacl) {
1629      cflags += [
1630        # Thread safety analysis. See base/thread_annotations.h and
1631        # https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
1632        "-Wthread-safety",
1633      ]
1634    }
1635
1636    # TODO(thakis): Enable this for more platforms, https://crbug.com/926235
1637    # ChromeOS: http://crbug.com/940863
1638    # Chromecast: http://crbug.com/942554
1639    has_dchecks = is_debug || dcheck_always_on
1640    if (!has_dchecks && is_chromeos && is_chrome_branded) {
1641      # Temporarily disable -Wextra-semi for Chrome on Chrome OS.
1642    } else if (is_chromecast && chromecast_branding != "public") {
1643      # Temporarily disable -Wextra-semi for Chromecast.
1644    } else {
1645      cflags += [ "-Wextra-semi" ]
1646    }
1647  }
1648
1649  configs = [ ":default_warnings" ]
1650}
1651
1652config("no_chromium_code") {
1653  cflags = []
1654  cflags_cc = []
1655  defines = []
1656
1657  if (is_win) {
1658    cflags += [
1659      "/W3",  # Warning level 3.
1660      "/wd4800",  # Disable warning when forcing value to bool.
1661      "/wd4267",  # TODO(jschuh): size_t to int.
1662      "/wd4996",  # Deprecated function warning.
1663    ]
1664    defines += [
1665      "_CRT_NONSTDC_NO_WARNINGS",
1666      "_CRT_NONSTDC_NO_DEPRECATE",
1667    ]
1668  } else {
1669    # GCC may emit unsuppressible warnings so don't add -Werror for no chromium
1670    # code. crbug.com/589724
1671    if (treat_warnings_as_errors && is_clang) {
1672      cflags += [ "-Werror" ]
1673      ldflags = [ "-Werror" ]
1674    }
1675    if (is_clang && !is_nacl) {
1676      # TODO(thakis): Remove !is_nacl once
1677      # https://codereview.webrtc.org/1552863002/ made its way into chromium.
1678      cflags += [ "-Wall" ]
1679    }
1680  }
1681
1682  if (is_clang) {
1683    cflags += [
1684      # Lots of third-party libraries have unused variables. Instead of
1685      # suppressing them individually, we just blanket suppress them here.
1686      "-Wno-unused-variable",
1687    ]
1688    if (!is_nacl && (current_toolchain == host_toolchain || !use_xcode_clang) && !is_bsd) {
1689      cflags += [
1690        # TODO(https://crbug.com/1031169): Clean up and enable.
1691        "-Wno-misleading-indentation",
1692      ]
1693    }
1694  }
1695
1696  configs = [ ":default_warnings" ]
1697}
1698
1699# noshadowing -----------------------------------------------------------------
1700#
1701# Allows turning -Wshadow on.
1702
1703config("noshadowing") {
1704  # This flag has to be disabled for nacl because the nacl compiler is too
1705  # strict about shadowing.
1706  if (is_clang && !is_nacl) {
1707    cflags = [ "-Wshadow" ]
1708  }
1709}
1710
1711# rtti ------------------------------------------------------------------------
1712#
1713# Allows turning Run-Time Type Identification on or off.
1714
1715config("rtti") {
1716  if (is_win) {
1717    cflags_cc = [ "/GR" ]
1718  } else {
1719    cflags_cc = [ "-frtti" ]
1720  }
1721}
1722
1723config("no_rtti") {
1724  # Some sanitizer configs may require RTTI to be left enabled globally
1725  if (!use_rtti) {
1726    if (is_win) {
1727      cflags_cc = [ "/GR-" ]
1728    } else {
1729      cflags_cc = [ "-fno-rtti" ]
1730      cflags_objcc = cflags_cc
1731    }
1732  }
1733}
1734
1735# export_dynamic ---------------------------------------------------------------
1736#
1737# Ensures all exported symbols are added to the dynamic symbol table.  This is
1738# necessary to expose Chrome's custom operator new() and operator delete() (and
1739# other memory-related symbols) to libraries.  Otherwise, they might
1740# (de)allocate memory on a different heap, which would spell trouble if pointers
1741# to heap-allocated memory are passed over shared library boundaries.
1742config("export_dynamic") {
1743  if (is_linux || export_libcxxabi_from_executables) {
1744    ldflags = [ "-rdynamic" ]
1745  }
1746}
1747
1748# thin_archive -----------------------------------------------------------------
1749#
1750# Enables thin archives on posix, and on windows when the lld linker is used.
1751# Regular archives directly include the object files used to generate it.
1752# Thin archives merely reference the object files.
1753# This makes building them faster since it requires less disk IO, but is
1754# inappropriate if you wish to redistribute your static library.
1755# This config is added to the global config, so thin archives should already be
1756# enabled.  If you want to make a distributable static library, you need to do 2
1757# things:
1758# 1. Set complete_static_lib so that all dependencies of the library make it
1759#    into the library. See `gn help complete_static_lib` for details.
1760# 2. Remove the thin_archive config, so that the .a file actually contains all
1761#    .o files, instead of just references to .o files in the build directoy
1762config("thin_archive") {
1763  # Mac and iOS use the mac-specific "libtool" command, not ar, which doesn't
1764  # have a "thin archive" mode (it does accept -T, but it means truncating
1765  # archive names to 16 characters, which is not what we want).
1766  if ((is_posix && !is_nacl && !is_apple && !is_bsd) || is_fuchsia) {
1767    arflags = [ "-T" ]
1768  } else if (is_win && use_lld) {
1769    arflags = [ "/llvmlibthin" ]
1770  }
1771}
1772
1773# exceptions -------------------------------------------------------------------
1774#
1775# Allows turning Exceptions on or off.
1776# Note: exceptions are disallowed in Google code.
1777
1778config("exceptions") {
1779  if (is_win) {
1780    # Enables exceptions in the STL.
1781    if (!use_custom_libcxx) {
1782      defines = [ "_HAS_EXCEPTIONS=1" ]
1783    }
1784    cflags_cc = [ "/EHsc" ]
1785  } else {
1786    cflags_cc = [ "-fexceptions" ]
1787    cflags_objcc = cflags_cc
1788  }
1789}
1790
1791config("no_exceptions") {
1792  if (is_win) {
1793    # Disables exceptions in the STL.
1794    # libc++ uses the __has_feature macro to control whether to use exceptions,
1795    # so defining this macro is unnecessary. Defining _HAS_EXCEPTIONS to 0 also
1796    # breaks libc++ because it depends on MSVC headers that only provide certain
1797    # declarations if _HAS_EXCEPTIONS is 1. Those MSVC headers do not use
1798    # exceptions, despite being conditional on _HAS_EXCEPTIONS.
1799    if (!use_custom_libcxx) {
1800      defines = [ "_HAS_EXCEPTIONS=0" ]
1801    }
1802  } else {
1803    cflags_cc = [ "-fno-exceptions" ]
1804    cflags_objcc = cflags_cc
1805  }
1806}
1807
1808# Warnings ---------------------------------------------------------------------
1809
1810# Generate a warning for code that might emit a static initializer.
1811# See: //docs/static_initializers.md
1812# See: https://groups.google.com/a/chromium.org/d/topic/chromium-dev/B9Q5KTD7iCo/discussion
1813config("wglobal_constructors") {
1814  if (is_clang) {
1815    cflags = [ "-Wglobal-constructors" ]
1816  }
1817}
1818
1819# This will generate warnings when using Clang if code generates exit-time
1820# destructors, which will slow down closing the program.
1821# TODO(thakis): Make this a blocklist instead, http://crbug.com/101600
1822config("wexit_time_destructors") {
1823  if (is_clang) {
1824    cflags = [ "-Wexit-time-destructors" ]
1825  }
1826}
1827
1828# On Windows compiling on x64, VC will issue a warning when converting
1829# size_t to int because it will truncate the value. Our code should not have
1830# these warnings and one should use a static_cast or a checked_cast for the
1831# conversion depending on the case. However, a lot of code still needs to be
1832# fixed. Apply this config to such targets to disable the warning.
1833#
1834# Note that this can be applied regardless of platform and architecture to
1835# clean up the call sites. This will only apply the flag when necessary.
1836#
1837# This config is just an alias to no_shorten_64_warnings and will
1838# suppress a superset of warning 4267 and any 64-bit -> 32-bit implicit
1839# conversions. Having both for a time means not having to go through and
1840# update all references to no_size_t_to_int_warning throughout the codebase
1841# atomically.
1842#
1843# Any new warning suppressions should use the no_shorten_64_warnings
1844# config below and not this.
1845#
1846# TODO(jschuh): crbug.com/167187 fix this and delete this config.
1847config("no_size_t_to_int_warning") {
1848  configs = [ ":no_shorten_64_warnings" ]
1849}
1850
1851# As part of re-enabling -Wconversion (see issue 588506) some code
1852# will continue to generate warnings.
1853# The first warning to be enabled will be -Wshorten-64-to-32.
1854#
1855# Code that currently generates warnings for this can include this
1856# config to disable them.
1857config("no_shorten_64_warnings") {
1858  if (current_cpu == "x64" || current_cpu == "arm64") {
1859    if (is_clang) {
1860      cflags = [ "-Wno-shorten-64-to-32" ]
1861    } else {
1862      if (is_win) {
1863        # MSVC does not have an explicit warning equivalent to
1864        # -Wshorten-64-to-32 but 4267 warns for size_t -> int
1865        # on 64-bit builds, so is the closest.
1866        cflags = [ "/wd4267" ]
1867      }
1868    }
1869  }
1870}
1871
1872# Some code presumes that pointers to structures/objects are compatible
1873# regardless of whether what they point to is already known to be valid.
1874# gcc 4.9 and earlier had no way of suppressing this warning without
1875# suppressing the rest of them.  Here we centralize the identification of
1876# the gcc 4.9 toolchains.
1877config("no_incompatible_pointer_warnings") {
1878  cflags = []
1879  if (is_clang) {
1880    cflags += [ "-Wno-incompatible-pointer-types" ]
1881  } else if (current_cpu == "mipsel" || current_cpu == "mips64el") {
1882    cflags += [ "-w" ]
1883  } else if (is_chromeos && current_cpu == "arm") {
1884    cflags += [ "-w" ]
1885  }
1886}
1887
1888# Optimization -----------------------------------------------------------------
1889#
1890# The BUILDCONFIG file sets the "default_optimization" config on targets by
1891# default. It will be equivalent to either "optimize" (release) or
1892# "no_optimize" (debug) optimization configs.
1893#
1894# You can override the optimization level on a per-target basis by removing the
1895# default config and then adding the named one you want:
1896#
1897#   configs -= [ "//build/config/compiler:default_optimization" ]
1898#   configs += [ "//build/config/compiler:optimize_max" ]
1899
1900# Shared settings for both "optimize" and "optimize_max" configs.
1901# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
1902if (is_win) {
1903  common_optimize_on_cflags = [
1904    "/Ob2",  # Both explicit and auto inlining.
1905    "/Oy-",  # Disable omitting frame pointers, must be after /O2.
1906    "/Zc:inline",  # Remove unreferenced COMDAT (faster links).
1907  ]
1908  if (!is_asan) {
1909    common_optimize_on_cflags += [
1910      # Put data in separate COMDATs. This allows the linker
1911      # to put bit-identical constants at the same address even if
1912      # they're unrelated constants, which saves binary size.
1913      # This optimization can't be used when ASan is enabled because
1914      # it is not compatible with the ASan ODR checker.
1915      "/Gw",
1916    ]
1917  }
1918  common_optimize_on_ldflags = []
1919
1920  # /OPT:ICF is not desirable in Debug builds, since code-folding can result in
1921  # misleading symbols in stack traces.
1922  if (!is_debug && !is_component_build) {
1923    common_optimize_on_ldflags += [ "/OPT:ICF" ]  # Redundant COMDAT folding.
1924  }
1925
1926  if (is_official_build) {
1927    common_optimize_on_ldflags += [ "/OPT:REF" ]  # Remove unreferenced data.
1928    # TODO(thakis): Add LTO/PGO clang flags eventually, https://crbug.com/598772
1929  }
1930} else {
1931  common_optimize_on_cflags = []
1932  common_optimize_on_ldflags = []
1933
1934  if (is_android) {
1935    # TODO(jdduke) Re-enable on mips after resolving linking
1936    # issues with libc++ (crbug.com/456380).
1937    if (current_cpu != "mipsel" && current_cpu != "mips64el") {
1938      common_optimize_on_ldflags += [
1939        # Warn in case of text relocations.
1940        "-Wl,--warn-shared-textrel",
1941      ]
1942    }
1943  }
1944
1945  if (is_apple) {
1946    if (symbol_level == 2) {
1947      # Mac dead code stripping requires symbols.
1948      common_optimize_on_ldflags += [ "-Wl,-dead_strip" ]
1949    }
1950
1951    if (is_official_build) {
1952      common_optimize_on_ldflags += [
1953        "-Wl,-no_data_in_code_info",
1954        "-Wl,-no_function_starts",
1955      ]
1956    }
1957  } else if (current_os != "aix") {
1958    # Non-Mac Posix flags.
1959    # Aix does not support these.
1960
1961    common_optimize_on_cflags += [
1962      # Don't emit the GCC version ident directives, they just end up in the
1963      # .comment section taking up binary size.
1964      "-fno-ident",
1965
1966      # Put data and code in their own sections, so that unused symbols
1967      # can be removed at link time with --gc-sections.
1968      "-fdata-sections",
1969      "-ffunction-sections",
1970    ]
1971
1972    common_optimize_on_ldflags += [
1973      # Specifically tell the linker to perform optimizations.
1974      # See http://lwn.net/Articles/192624/ .
1975      # -O2 enables string tail merge optimization in gold and lld.
1976      "-Wl,-O2",
1977      "-Wl,--gc-sections",
1978    ]
1979  }
1980}
1981
1982config("default_stack_frames") {
1983  if (is_posix || is_fuchsia) {
1984    if (enable_frame_pointers) {
1985      cflags = [ "-fno-omit-frame-pointer" ]
1986
1987      # Omit frame pointers for leaf functions on x86, otherwise building libyuv
1988      # gives clang's register allocator issues, see llvm.org/PR15798 /
1989      # crbug.com/233709
1990      if (is_clang && current_cpu == "x86" && !is_apple) {
1991        cflags += [ "-momit-leaf-frame-pointer" ]
1992      }
1993    } else {
1994      cflags = [ "-fomit-frame-pointer" ]
1995    }
1996  }
1997  # On Windows, the flag to enable framepointers "/Oy-" must always come after
1998  # the optimization flag [e.g. "/O2"]. The optimization flag is set by one of
1999  # the "optimize" configs, see rest of this file. The ordering that cflags are
2000  # applied is well-defined by the GN spec, and there is no way to ensure that
2001  # cflags set by "default_stack_frames" is applied after those set by an
2002  # "optimize" config. Similarly, there is no way to propagate state from this
2003  # config into the "optimize" config. We always apply the "/Oy-" config in the
2004  # definition for common_optimize_on_cflags definition, even though this may
2005  # not be correct.
2006}
2007
2008# Default "optimization on" config.
2009config("optimize") {
2010  if (is_win) {
2011    if (chrome_pgo_phase != 2) {
2012      # Favor size over speed, /O1 must be before the common flags.
2013      # /O1 implies /Os and /GF.
2014      cflags = [ "/O1" ] + common_optimize_on_cflags + [ "/Oi" ]
2015    } else {
2016      # PGO requires all translation units to be compiled with /O2. The actual
2017      # optimization level will be decided based on the profiling data.
2018      cflags = [ "/O2" ] + common_optimize_on_cflags + [ "/Oi" ]
2019    }
2020  } else if (optimize_for_size && !is_nacl) {
2021    # Favor size over speed.
2022    # TODO(crbug.com/718650): Fix -Os in PNaCl compiler and remove the is_nacl
2023    # guard above.
2024    if (is_clang) {
2025      cflags = [ "-Oz" ] + common_optimize_on_cflags
2026    } else {
2027      cflags = [ "-Os" ] + common_optimize_on_cflags
2028    }
2029  } else if (is_chromeos) {
2030    # TODO(gbiv): This is partially favoring size over speed. CrOS exclusively
2031    # uses clang, and -Os in clang is more of a size-conscious -O2 than "size at
2032    # any cost" (AKA -Oz). It'd be nice to:
2033    # - Make `optimize_for_size` apply to all platforms where we're optimizing
2034    #   for size by default (so, also Windows)
2035    # - Investigate -Oz here, maybe just for ARM?
2036    cflags = [ "-Os" ] + common_optimize_on_cflags
2037  } else {
2038    cflags = [ "-O2" ] + common_optimize_on_cflags
2039  }
2040  ldflags = common_optimize_on_ldflags
2041}
2042
2043# Turn off optimizations.
2044config("no_optimize") {
2045  if (is_win) {
2046    cflags = [
2047      "/Od",  # Disable optimization.
2048      "/Ob0",  # Disable all inlining (on by default).
2049      "/GF",  # Enable string pooling (off by default).
2050    ]
2051
2052    if (target_cpu == "arm64") {
2053      # Disable omitting frame pointers for no_optimize build because stack
2054      # traces on Windows ARM64 rely on it.
2055      cflags += [ "/Oy-" ]
2056    }
2057  } else if (is_android && !android_full_debug) {
2058    # On Android we kind of optimize some things that don't affect debugging
2059    # much even when optimization is disabled to get the binary size down.
2060    if (is_clang) {
2061      cflags = [ "-Oz" ] + common_optimize_on_cflags
2062    } else {
2063      cflags = [ "-Os" ] + common_optimize_on_cflags
2064    }
2065
2066    if (!is_component_build) {
2067      # Required for library partitions. Without this all symbols just end up
2068      # in the base partition.
2069      ldflags = [ "-Wl,--gc-sections" ]
2070    }
2071  } else if (is_fuchsia) {
2072    # On Fuchsia, we optimize for size here to reduce the size of debug build
2073    # packages so they can be run in a KVM. See crbug.com/910243 for details.
2074    cflags = [ "-Og" ]
2075  } else {
2076    cflags = [ "-O0" ]
2077    ldflags = []
2078  }
2079}
2080
2081# Turns up the optimization level. On Windows, this implies whole program
2082# optimization and link-time code generation which is very expensive and should
2083# be used sparingly.
2084config("optimize_max") {
2085  if (is_nacl && is_nacl_irt) {
2086    # The NaCl IRT is a special case and always wants its own config.
2087    # Various components do:
2088    #   if (!is_debug) {
2089    #     configs -= [ "//build/config/compiler:default_optimization" ]
2090    #     configs += [ "//build/config/compiler:optimize_max" ]
2091    #   }
2092    # So this config has to have the selection logic just like
2093    # "default_optimization", below.
2094    configs = [ "//build/config/nacl:irt_optimize" ]
2095  } else {
2096    ldflags = common_optimize_on_ldflags
2097    if (is_win) {
2098      # Favor speed over size, /O2 must be before the common flags.
2099      # /O2 implies /Ot, /Oi, and /GF.
2100      cflags = [ "/O2" ] + common_optimize_on_cflags
2101    } else if (optimize_for_fuzzing) {
2102      cflags = [ "-O1" ] + common_optimize_on_cflags
2103    } else {
2104      cflags = [ "-O2" ] + common_optimize_on_cflags
2105    }
2106  }
2107}
2108
2109# This config can be used to override the default settings for per-component
2110# and whole-program optimization, optimizing the particular target for speed
2111# instead of code size. This config is exactly the same as "optimize_max"
2112# except that we use -O3 instead of -O2 on non-win, non-IRT platforms.
2113#
2114# TODO(crbug.com/621335) - rework how all of these configs are related
2115# so that we don't need this disclaimer.
2116config("optimize_speed") {
2117  if (is_nacl && is_nacl_irt) {
2118    # The NaCl IRT is a special case and always wants its own config.
2119    # Various components do:
2120    #   if (!is_debug) {
2121    #     configs -= [ "//build/config/compiler:default_optimization" ]
2122    #     configs += [ "//build/config/compiler:optimize_max" ]
2123    #   }
2124    # So this config has to have the selection logic just like
2125    # "default_optimization", below.
2126    configs = [ "//build/config/nacl:irt_optimize" ]
2127  } else {
2128    ldflags = common_optimize_on_ldflags
2129    if (is_win) {
2130      # Favor speed over size, /O2 must be before the common flags.
2131      # /O2 implies /Ot, /Oi, and /GF.
2132      cflags = [ "/O2" ] + common_optimize_on_cflags
2133    } else if (optimize_for_fuzzing) {
2134      cflags = [ "-O1" ] + common_optimize_on_cflags
2135    } else {
2136      cflags = [ "-O3" ] + common_optimize_on_cflags
2137    }
2138  }
2139}
2140
2141config("optimize_fuzzing") {
2142  cflags = [ "-O1" ] + common_optimize_on_cflags
2143  ldflags = common_optimize_on_ldflags
2144  visibility = [ ":default_optimization" ]
2145}
2146
2147# The default optimization applied to all targets. This will be equivalent to
2148# either "optimize" or "no_optimize", depending on the build flags.
2149config("default_optimization") {
2150  if (is_nacl && is_nacl_irt) {
2151    # The NaCl IRT is a special case and always wants its own config.
2152    # It gets optimized the same way regardless of the type of build.
2153    configs = [ "//build/config/nacl:irt_optimize" ]
2154  } else if (is_debug) {
2155    configs = [ ":no_optimize" ]
2156  } else if (optimize_for_fuzzing) {
2157    assert(!is_win, "Fuzzing optimize level not supported on Windows")
2158
2159    # Coverage build is quite slow. Using "optimize_for_fuzzing" makes it even
2160    # slower as it uses "-O1" instead of "-O3". Prevent that from happening.
2161    assert(!use_clang_coverage,
2162           "optimize_for_fuzzing=true should not be used with " +
2163               "use_clang_coverage=true.")
2164    configs = [ ":optimize_fuzzing" ]
2165  } else {
2166    configs = [ ":optimize" ]
2167  }
2168}
2169
2170_clang_sample_profile = ""
2171if (is_clang && is_a_target_toolchain) {
2172  if (clang_sample_profile_path != "") {
2173    _clang_sample_profile = clang_sample_profile_path
2174  } else if (clang_use_default_sample_profile) {
2175    assert(build_with_chromium,
2176           "Our default profiles currently only apply to Chromium")
2177    assert(
2178        is_android || chromeos_is_browser_only || is_chromeos || is_chromecast,
2179        "The current platform has no default profile")
2180    if (is_android || is_chromecast) {
2181      _clang_sample_profile = "//chrome/android/profiles/afdo.prof"
2182    } else {
2183      # TODO(crbug/1135245): Remove silvermont, airmont and broadwell after
2184      # the change atom and bigcore reaches Chrome OS.
2185      assert(
2186          chromeos_afdo_platform == "silvermont" ||
2187              chromeos_afdo_platform == "airmont" ||
2188              chromeos_afdo_platform == "broadwell" ||
2189              chromeos_afdo_platform == "atom" ||
2190              chromeos_afdo_platform == "bigcore",
2191          "Only silvermont, airmont and broadwell are valid Chrome OS profiles.")
2192      _clang_sample_profile =
2193          "//chromeos/profiles/${chromeos_afdo_platform}.afdo.prof"
2194    }
2195  }
2196}
2197
2198# Clang offers a way to assert that AFDO profiles are accurate, which causes it
2199# to optimize functions not represented in a profile more aggressively for size.
2200# This config can be toggled in cases where shaving off binary size hurts
2201# performance too much.
2202config("afdo_optimize_size") {
2203  if (_clang_sample_profile != "" && sample_profile_is_accurate) {
2204    cflags = [ "-fprofile-sample-accurate" ]
2205  }
2206}
2207
2208# GCC and clang support a form of profile-guided optimization called AFDO.
2209# There are some targeted places that AFDO regresses (and an icky interaction
2210# between //base/allocator:tcmalloc and AFDO on GCC), so we provide a separate
2211# config to allow AFDO to be disabled per-target.
2212config("afdo") {
2213  if (is_clang) {
2214    cflags = []
2215    if (clang_emit_debug_info_for_profiling) {
2216      # Add the following flags to generate debug info for profiling.
2217      cflags += [ "-gline-tables-only" ]
2218      if (!is_nacl) {
2219        cflags += [ "-fdebug-info-for-profiling" ]
2220      }
2221    }
2222    if (_clang_sample_profile != "") {
2223      assert(chrome_pgo_phase == 0, "AFDO can't be used in PGO builds")
2224      rebased_clang_sample_profile =
2225          rebase_path(_clang_sample_profile, root_build_dir)
2226      cflags += [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
2227      inputs = [ _clang_sample_profile ]
2228    }
2229  } else if (auto_profile_path != "" && is_a_target_toolchain) {
2230    cflags = [ "-fauto-profile=${auto_profile_path}" ]
2231    inputs = [ auto_profile_path ]
2232  }
2233}
2234
2235# Symbols ----------------------------------------------------------------------
2236
2237# The BUILDCONFIG file sets the "default_symbols" config on targets by
2238# default. It will be equivalent to one the three specific symbol levels.
2239#
2240# You can override the symbol level on a per-target basis by removing the
2241# default config and then adding the named one you want:
2242#
2243#   configs -= [ "//build/config/compiler:default_symbols" ]
2244#   configs += [ "//build/config/compiler:symbols" ]
2245
2246# A helper config that all configs passing /DEBUG to the linker should
2247# include as sub-config.
2248config("win_pdbaltpath") {
2249  visibility = [
2250    ":minimal_symbols",
2251    ":symbols",
2252  ]
2253
2254  # /DEBUG causes the linker to generate a pdb file, and to write the absolute
2255  # path to it in the executable file it generates.  This flag turns that
2256  # absolute path into just the basename of the pdb file, which helps with
2257  # build reproducibility. Debuggers look for pdb files next to executables,
2258  # so there's no downside to always using this.
2259  ldflags = [ "/pdbaltpath:%_PDB%" ]
2260
2261  if (enable_cet_shadow_stack && use_lld) {
2262    # TODO(crbug.com/1136664): Investigate why Windows does not recognize
2263    # CET in some binaries linked by LLD with /DEBUG.
2264    # This is the best place for work around as it follows all /DEBUG uses.
2265    ldflags += [ "/DEBUG:NONE" ]
2266  }
2267}
2268
2269# Full symbols.
2270config("symbols") {
2271  if (is_win) {
2272    if (is_clang) {
2273      cflags = [ "/Z7" ]  # Debug information in the .obj files.
2274    } else {
2275      cflags = [ "/Zi" ]  # Produce PDB file, no edit and continue.
2276    }
2277
2278    if (is_clang && use_lld && use_ghash) {
2279      cflags += [ "-gcodeview-ghash" ]
2280      ldflags = [ "/DEBUG:GHASH" ]
2281    } else {
2282      ldflags = [ "/DEBUG" ]
2283    }
2284
2285    # All configs using /DEBUG should include this:
2286    configs = [ ":win_pdbaltpath" ]
2287
2288    if (is_clang) {
2289      # Use constructor debug mode. This option reduces debug info more than
2290      # -fno-standalone-debug by emitting class type information only when
2291      # constructors are emitted.
2292      cflags += [
2293        "-Xclang",
2294        "-debug-info-kind=constructor",
2295      ]
2296    }
2297  } else {
2298    cflags = []
2299    if (is_mac && enable_dsyms) {
2300      # If generating dSYMs, specify -fno-standalone-debug. This was
2301      # originally specified for https://crbug.com/479841 because dsymutil
2302      # could not handle a 4GB dSYM file. But dsymutil from Xcodes prior to
2303      # version 7 also produces debug data that is incompatible with Breakpad
2304      # dump_syms, so this is still required (https://crbug.com/622406).
2305      cflags += [ "-fno-standalone-debug" ]
2306    } else if (is_mac) {
2307      # clang defaults to DWARF2 on macOS unless mac_deployment_target is
2308      # at least 10.11.
2309      # TODO(thakis): Remove this once mac_deployment_target is 10.11.
2310      cflags += [ "-gdwarf-4" ]
2311    }
2312
2313    # The gcc-based nacl compilers don't support -fdebug-compilation-dir (see
2314    # elsewhere in this file), so they can't have build-dir-independent output.
2315    # Disable symbols for nacl object files to get deterministic,
2316    # build-directory-independent output. pnacl and nacl-clang do support that
2317    # flag, so we can use use -g1 for pnacl and nacl-clang compiles.
2318    # gcc nacl is is_nacl && !is_clang, pnacl and nacl-clang are && is_clang.
2319    if (!is_nacl || is_clang) {
2320      cflags += [ "-g0" ]
2321    }
2322
2323    # TODO(https://crbug.com/1050118): Investigate missing debug info on mac.
2324    if (is_clang && !is_nacl && !use_xcode_clang && !is_apple) {
2325      cflags += [
2326        "-Xclang",
2327        "-debug-info-kind=constructor",
2328      ]
2329    }
2330
2331    if (is_apple) {
2332      swiftflags = [ "-g" ]
2333    }
2334
2335    if (use_debug_fission) {
2336      cflags += [ "-gsplit-dwarf" ]
2337    }
2338    asmflags = cflags
2339    ldflags = []
2340
2341    # TODO(agrieve): Not sure why this is Android-specific.
2342    if (use_debug_fission && use_thin_lto && is_android) {
2343      ldflags += [ "-gsplit-dwarf" ]
2344    }
2345
2346    # TODO(thakis): Figure out if there's a way to make this go for 32-bit,
2347    # currently we get "warning:
2348    # obj/native_client/src/trusted/service_runtime/sel_asm/nacl_switch_32.o:
2349    # DWARF info may be corrupt; offsets in a range list entry are in different
2350    # sections" there.  Maybe just a bug in nacl_switch_32.S.
2351    if (!is_apple && !is_nacl && current_cpu != "x86" &&
2352        (use_gold || use_lld) && !is_bsd) {
2353      if (is_clang) {
2354        # This flag enables the GNU-format pubnames and pubtypes sections,
2355        # which lld needs in order to generate a correct GDB index.
2356        # TODO(pcc): Try to make lld understand non-GNU-format pubnames
2357        # sections (llvm.org/PR34820).
2358        cflags += [ "-ggnu-pubnames" ]
2359      }
2360      ldflags += [ "-Wl,--gdb-index" ]
2361    }
2362  }
2363}
2364
2365# Minimal symbols.
2366# This config guarantees to hold symbol for stack trace which are shown to user
2367# when crash happens in unittests running on buildbot.
2368config("minimal_symbols") {
2369  if (is_win) {
2370    # Functions, files, and line tables only.
2371    cflags = []
2372    ldflags = [ "/DEBUG" ]
2373
2374    # All configs using /DEBUG should include this:
2375    configs = [ ":win_pdbaltpath" ]
2376
2377    # Enable line tables for clang. MSVC doesn't have an equivalent option.
2378    if (is_clang) {
2379      # -gline-tables-only is the same as -g1, but clang-cl only exposes the
2380      # former.
2381      cflags += [ "-gline-tables-only" ]
2382    }
2383  } else {
2384    cflags = []
2385    if (is_mac) {
2386      # clang defaults to DWARF2 on macOS unless mac_deployment_target is
2387      # at least 10.11.
2388      # TODO(thakis): Remove this once mac_deployment_target is 10.11.
2389      cflags += [ "-gdwarf-4" ]
2390    }
2391
2392    # The gcc-based nacl compilers don't support -fdebug-compilation-dir (see
2393    # elsewhere in this file), so they can't have build-dir-independent output.
2394    # Disable symbols for nacl object files to get deterministic,
2395    # build-directory-independent output. pnacl and nacl-clang do support that
2396    # flag, so we can use use -g1 for pnacl and nacl-clang compiles.
2397    # gcc nacl is is_nacl && !is_clang, pnacl and nacl-clang are && is_clang.
2398    if (!is_nacl || is_clang) {
2399      cflags += [ "-g1" ]
2400    }
2401    ldflags = []
2402    if (is_android && is_clang) {
2403      # Android defaults to symbol_level=1 builds in production builds
2404      # (https://crbug.com/648948), but clang, unlike gcc, doesn't emit
2405      # DW_AT_linkage_name in -g1 builds. -fdebug-info-for-profiling enables
2406      # that (and a bunch of other things we don't need), so that we get
2407      # qualified names in stacks.
2408      # TODO(thakis): Consider making clang emit DW_AT_linkage_name in -g1 mode;
2409      #               failing that consider doing this on non-Android too.
2410      cflags += [ "-fdebug-info-for-profiling" ]
2411    }
2412
2413    # Note: -gsplit-dwarf implicitly turns on -g2 with clang, so don't pass it.
2414    asmflags = cflags
2415  }
2416}
2417
2418# This configuration contains function names only. That is, the compiler is
2419# told to not generate debug information and the linker then just puts function
2420# names in the final debug information.
2421config("no_symbols") {
2422  if (is_win) {
2423    ldflags = [ "/DEBUG" ]
2424
2425    # All configs using /DEBUG should include this:
2426    configs = [ ":win_pdbaltpath" ]
2427  } else {
2428    cflags = [ "-g0" ]
2429    asmflags = cflags
2430  }
2431}
2432
2433# Default symbols.
2434config("default_symbols") {
2435  if (symbol_level == 0) {
2436    configs = [ ":no_symbols" ]
2437  } else if (symbol_level == 1) {
2438    configs = [ ":minimal_symbols" ]
2439  } else if (symbol_level == 2) {
2440    configs = [ ":symbols" ]
2441  } else {
2442    assert(false)
2443  }
2444
2445  # This config is removed by base unittests apk.
2446  if (is_android && is_clang && strip_debug_info) {
2447    configs += [ ":strip_debug" ]
2448  }
2449}
2450
2451config("strip_debug") {
2452  if (!defined(ldflags)) {
2453    ldflags = []
2454  }
2455  ldflags += [ "-Wl,--strip-debug" ]
2456}
2457
2458if (is_apple) {
2459  # On Mac and iOS, this enables support for ARC (automatic ref-counting).
2460  # See http://clang.llvm.org/docs/AutomaticReferenceCounting.html.
2461  config("enable_arc") {
2462    common_flags = [ "-fobjc-arc" ]
2463    cflags_objc = common_flags
2464    cflags_objcc = common_flags
2465  }
2466}
2467
2468if (is_chromeos && is_chromeos_device) {
2469  # This config is intended to be a temporary to facilitate
2470  # the transition to use orderfile in Chrome OS. Once orderfile
2471  # use becomes a default in Chrome OS, this config should not
2472  # be needed.
2473  config("use_orderfile_for_hugepage") {
2474    if (chrome_orderfile_path != "") {
2475      defines = [ "CHROMEOS_ORDERFILE_USE" ]
2476    }
2477  }
2478}
2479
2480if (is_win || is_android || (is_chromeos && is_chromeos_device)) {
2481  # Use orderfile for linking Chrome on win, android, and Chrome OS.
2482  # This config enables using an orderfile for linking in LLD.
2483  config("chrome_orderfile_config") {
2484    if (chrome_orderfile_path != "" && !enable_call_graph_profile_sort) {
2485      assert(use_lld)
2486      _rebased_orderfile = rebase_path(chrome_orderfile_path, root_build_dir)
2487      if (is_android || (is_chromeos && is_chromeos_device)) {
2488        ldflags = [
2489          "-Wl,--symbol-ordering-file",
2490          "-Wl,$_rebased_orderfile",
2491          "-Wl,--no-warn-symbol-ordering",
2492        ]
2493      } else {
2494        ldflags = [
2495          "/order:@$_rebased_orderfile",
2496
2497          # Ignore warnings about missing functions or functions not in their
2498          # own section.
2499          "/ignore:4037",
2500          "/ignore:4065",
2501        ]
2502      }
2503      inputs = [ chrome_orderfile_path ]
2504    }
2505  }
2506}
2507
2508# Initialize all variables on the stack if needed.
2509config("default_init_stack_vars") {
2510  cflags = []
2511  if (init_stack_vars && is_clang && !is_nacl && !using_sanitizer) {
2512    cflags += [ "-ftrivial-auto-var-init=pattern" ]
2513  }
2514}
2515
2516buildflag_header("compiler_buildflags") {
2517  header = "compiler_buildflags.h"
2518
2519  flags = [ "CLANG_PGO=$chrome_pgo_phase" ]
2520}
2521
2522config("cet_shadow_stack") {
2523  if (enable_cet_shadow_stack && is_win) {
2524    assert(target_cpu == "x64")
2525    ldflags = [ "/CETCOMPAT" ]
2526  }
2527}
2528