]> git.ipfire.org Git - thirdparty/gcc.git/blobdiff - gcc/cgraphunit.c
Correct a function pre/postcondition [PR102403].
[thirdparty/gcc.git] / gcc / cgraphunit.c
index 4bfcad78f59865e50f533d1547b69fd0e56b94df..55cb0347149c4658e603751f41f80f263438381d 100644 (file)
@@ -1,5 +1,5 @@
 /* Driver of optimization process
-   Copyright (C) 2003-2016 Free Software Foundation, Inc.
+   Copyright (C) 2003-2021 Free Software Foundation, Inc.
    Contributed by Jan Hubicka
 
 This file is part of GCC.
@@ -75,7 +75,7 @@ along with GCC; see the file COPYING3.  If not see
           a) early optimizations. These are local passes executed in
              the topological order on the callgraph.
 
-             The purpose of early optimiations is to optimize away simple
+             The purpose of early optimizations is to optimize away simple
              things that may otherwise confuse IP analysis. Very simple
              propagation across the callgraph is done i.e. to discover
              functions without side effects and simple inlining is performed.
@@ -83,7 +83,7 @@ along with GCC; see the file COPYING3.  If not see
           b) early small interprocedural passes.
 
              Those are interprocedural passes executed only at compilation
-             time.  These include, for example, transational memory lowering,
+             time.  These include, for example, transactional memory lowering,
              unreachable code removal and other simple transformations.
 
           c) IP analysis stage.  All interprocedural passes do their
@@ -95,7 +95,7 @@ along with GCC; see the file COPYING3.  If not see
              both reduce linking times and linktime memory usage by    
              not having to represent whole program in memory.
 
-          d) LTO sreaming.  When doing LTO, everything important gets
+          d) LTO streaming.  When doing LTO, everything important gets
              streamed into the object file.
 
        Compile time and or linktime analysis stage (WPA):
@@ -107,7 +107,7 @@ along with GCC; see the file COPYING3.  If not see
              IP propagation. This is done based on the earlier analysis
              without having function bodies at hand.
           f) Ltrans streaming.  When doing WHOPR LTO, the program
-             is partitioned and streamed into multple object files.
+             is partitioned and streamed into multiple object files.
 
        Compile time and/or parallel linktime stage (ltrans)
 
@@ -118,7 +118,7 @@ along with GCC; see the file COPYING3.  If not see
         2) Virtual clone materialization
            (cgraph_materialize_clone)
 
-           IP passes can produce copies of existing functoins (such
+           IP passes can produce copies of existing functions (such
            as versioned clones or inline clones) without actually
            manipulating their bodies by creating virtual clones in
            the callgraph. At this time the virtual clones are
@@ -190,10 +190,11 @@ along with GCC; see the file COPYING3.  If not see
 #include "toplev.h"
 #include "debug.h"
 #include "symbol-summary.h"
+#include "tree-vrp.h"
 #include "ipa-prop.h"
 #include "gimple-pretty-print.h"
 #include "plugin.h"
-#include "ipa-inline.h"
+#include "ipa-fnsummary.h"
 #include "ipa-utils.h"
 #include "except.h"
 #include "cfgloop.h"
@@ -201,8 +202,12 @@ along with GCC; see the file COPYING3.  If not see
 #include "pass_manager.h"
 #include "tree-nested.h"
 #include "dbgcnt.h"
-#include "tree-chkp.h"
 #include "lto-section-names.h"
+#include "stringpool.h"
+#include "attribs.h"
+#include "ipa-inline.h"
+#include "omp-offload.h"
+#include "symtab-thunks.h"
 
 /* Queue of cgraph nodes scheduled to be added into cgraph.  This is a
    secondary queue used during optimization to accommodate passes that
@@ -213,8 +218,18 @@ static void expand_all_functions (void);
 static void mark_functions_to_output (void);
 static void handle_alias_pairs (void);
 
-/* Used for vtable lookup in thunk adjusting.  */
-static GTY (()) tree vtable_entry_type;
+/* Return true if this symbol is a function from the C frontend specified
+   directly in RTL form (with "__RTL").  */
+
+bool
+symtab_node::native_rtl_p () const
+{
+  if (TREE_CODE (decl) != FUNCTION_DECL)
+    return false;
+  if (!DECL_STRUCT_FUNCTION (decl))
+    return false;
+  return DECL_STRUCT_FUNCTION (decl)->curr_properties & PROP_rtl;
+}
 
 /* Determine if symbol declaration is needed.  That is, visible to something
    either outside this translation unit, something magic in the system
@@ -224,8 +239,10 @@ symtab_node::needed_p (void)
 {
   /* Double check that no one output the function into assembly file
      early.  */
-  gcc_checking_assert (!DECL_ASSEMBLER_NAME_SET_P (decl)
-                      || !TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)));
+  if (!native_rtl_p ())
+      gcc_checking_assert
+       (!DECL_ASSEMBLER_NAME_SET_P (decl)
+        || !TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)));
 
   if (!definition)
     return false;
@@ -257,7 +274,7 @@ symtab_node::needed_p (void)
 /* Head and terminator of the queue of nodes to be processed while building
    callgraph.  */
 
-static symtab_node symtab_terminator;
+static symtab_node symtab_terminator (SYMTAB_SYMBOL);
 static symtab_node *queued_nodes = &symtab_terminator;
 
 /* Add NODE to queue starting at QUEUED_NODES. 
@@ -316,9 +333,20 @@ symbol_table::process_new_functions (void)
          push_cfun (DECL_STRUCT_FUNCTION (fndecl));
          if ((state == IPA_SSA || state == IPA_SSA_AFTER_INLINING)
              && !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (fndecl)))
-           g->get_passes ()->execute_early_local_passes ();
-         else if (inline_summaries != NULL)
-           compute_inline_parameters (node, true);
+           {
+             bool summaried_computed = ipa_fn_summaries != NULL;
+             g->get_passes ()->execute_early_local_passes ();
+             /* Early passes compute inline parameters to do inlining
+                and splitting.  This is redundant for functions added late.
+                Just throw away whatever it did.  */
+             if (!summaried_computed)
+               {
+                 ipa_free_fn_summary ();
+                 ipa_free_size_summary ();
+               }
+           }
+         else if (ipa_fn_summaries != NULL)
+           compute_fn_summary (node, true);
          free_dominance_info (CDI_POST_DOMINATORS);
          free_dominance_info (CDI_DOMINATORS);
          pop_cfun ();
@@ -363,8 +391,7 @@ cgraph_node::reset (void)
   gcc_assert (!process);
 
   /* Reset our data structures so we can analyze the function again.  */
-  memset (&local, 0, sizeof (local));
-  memset (&global, 0, sizeof (global));
+  inlined_to = NULL;
   memset (&rtl, 0, sizeof (rtl));
   analyzed = false;
   definition = false;
@@ -417,7 +444,7 @@ cgraph_node::finalize_function (tree decl, bool no_collect)
       gcc_assert (!DECL_CONTEXT (decl)
                  || TREE_CODE (DECL_CONTEXT (decl)) != FUNCTION_DECL);
       node->reset ();
-      node->local.redefined_extern_inline = true;
+      node->redefined_extern_inline = true;
     }
 
   /* Set definition first before calling notice_global_symbol so that
@@ -425,6 +452,8 @@ cgraph_node::finalize_function (tree decl, bool no_collect)
   node->definition = true;
   notice_global_symbol (decl);
   node->lowered = DECL_STRUCT_FUNCTION (decl)->cfg != NULL;
+  if (!flag_toplevel_reorder)
+    node->no_reorder = true;
 
   /* With -fkeep-inline-functions we are keeping all inline functions except
      for extern inline ones.  */
@@ -434,12 +463,21 @@ cgraph_node::finalize_function (tree decl, bool no_collect)
       && !DECL_DISREGARD_INLINE_LIMITS (decl))
     node->force_output = 1;
 
+  /* __RTL functions were already output as soon as they were parsed (due
+     to the large amount of global state in the backend).
+     Mark such functions as "force_output" to reflect the fact that they
+     will be in the asm file when considering the symbols they reference.
+     The attempt to output them later on will bail out immediately.  */
+  if (node->native_rtl_p ())
+    node->force_output = 1;
+
   /* When not optimizing, also output the static functions. (see
      PR24561), but don't do so for always_inline functions, functions
      declared inline and nested functions.  These were optimized out
      in the original implementation and it is unclear whether we want
      to change the behavior here.  */
-  if (((!opt_for_fn (decl, optimize) || flag_keep_static_functions)
+  if (((!opt_for_fn (decl, optimize) || flag_keep_static_functions
+       || node->no_reorder)
        && !node->cpp_implicit_alias
        && !DECL_DISREGARD_INLINE_LIMITS (decl)
        && !DECL_DECLARED_INLINE_P (decl)
@@ -514,9 +552,11 @@ cgraph_node::add_new_function (tree fndecl, bool lowered)
        /* Bring the function into finalized state and enqueue for later
           analyzing and compilation.  */
        node = cgraph_node::get_create (fndecl);
-       node->local.local = false;
+       node->local = false;
        node->definition = true;
        node->force_output = true;
+       if (TREE_PUBLIC (fndecl))
+         node->externally_visible = true;
        if (!lowered && symtab->state == EXPANSION)
          {
            push_cfun (DECL_STRUCT_FUNCTION (fndecl));
@@ -567,32 +607,37 @@ cgraph_node::add_new_function (tree fndecl, bool lowered)
 void
 cgraph_node::analyze (void)
 {
+  if (native_rtl_p ())
+    {
+      analyzed = true;
+      return;
+    }
+
   tree decl = this->decl;
   location_t saved_loc = input_location;
   input_location = DECL_SOURCE_LOCATION (decl);
 
-  if (thunk.thunk_p)
+  if (thunk)
     {
-      cgraph_node *t = cgraph_node::get (thunk.alias);
+      thunk_info *info = thunk_info::get (this);
+      cgraph_node *t = cgraph_node::get (info->alias);
 
-      create_edge (t, NULL, 0, CGRAPH_FREQ_BASE);
+      create_edge (t, NULL, t->count);
       callees->can_throw_external = !TREE_NOTHROW (t->decl);
       /* Target code in expand_thunk may need the thunk's target
         to be analyzed, so recurse here.  */
-      if (!t->analyzed)
+      if (!t->analyzed && t->definition)
        t->analyze ();
       if (t->alias)
        {
          t = t->get_alias_target ();
-         if (!t->analyzed)
+         if (!t->analyzed && t->definition)
            t->analyze ();
        }
-      if (!expand_thunk (false, false))
-       {
-         thunk.alias = NULL;
-         return;
-       }
-      thunk.alias = NULL;
+      bool ret = expand_thunk (this, false, false);
+      thunk_info::get (this)->alias = NULL;
+      if (!ret)
+       return;
     }
   if (alias)
     resolve_alias (cgraph_node::get (alias_target), transparent_alias);
@@ -615,7 +660,7 @@ cgraph_node::analyze (void)
     {
       push_cfun (DECL_STRUCT_FUNCTION (decl));
 
-      assign_assembler_name_if_neeeded (decl);
+      assign_assembler_name_if_needed (decl);
 
       /* Make sure to gimplify bodies only once.  During analyzing a
         function we lower it, which will require gimplified nested
@@ -627,15 +672,12 @@ cgraph_node::analyze (void)
       /* Lower the function.  */
       if (!lowered)
        {
-         if (nested)
+         if (first_nested_function (this))
            lower_nested_functions (decl);
-         gcc_assert (!nested);
 
          gimple_register_cfg_hooks ();
          bitmap_obstack_initialize (NULL);
          execute_pass_list (cfun, g->get_passes ()->all_lowering_passes);
-         free_dominance_info (CDI_POST_DOMINATORS);
-         free_dominance_info (CDI_DOMINATORS);
          compact_blocks ();
          bitmap_obstack_release (NULL);
          lowered = true;
@@ -650,8 +692,8 @@ cgraph_node::analyze (void)
 
 /* C++ frontend produce same body aliases all over the place, even before PCH
    gets streamed out. It relies on us linking the aliases with their function
-   in order to do the fixups, but ipa-ref is not PCH safe.  Consequentely we
-   first produce aliases without links, but once C++ FE is sure he won't sream
+   in order to do the fixups, but ipa-ref is not PCH safe.  Consequently we
+   first produce aliases without links, but once C++ FE is sure he won't stream
    PCH we build the links via this function.  */
 
 void
@@ -661,12 +703,99 @@ symbol_table::process_same_body_aliases (void)
   FOR_EACH_SYMBOL (node)
     if (node->cpp_implicit_alias && !node->analyzed)
       node->resolve_alias
-       (TREE_CODE (node->alias_target) == VAR_DECL
+       (VAR_P (node->alias_target)
         ? (symtab_node *)varpool_node::get_create (node->alias_target)
         : (symtab_node *)cgraph_node::get_create (node->alias_target));
   cpp_implicit_aliases_done = true;
 }
 
+/* Process a symver attribute.  */
+
+static void
+process_symver_attribute (symtab_node *n)
+{
+  tree value = lookup_attribute ("symver", DECL_ATTRIBUTES (n->decl));
+
+  for (; value != NULL; value = TREE_CHAIN (value))
+    {
+      /* Starting from bintuils 2.35 gas supports:
+         # Assign foo to bar@V1 and baz@V2.
+         .symver foo, bar@V1
+         .symver foo, baz@V2
+      */
+      const char *purpose = IDENTIFIER_POINTER (TREE_PURPOSE (value));
+      if (strcmp (purpose, "symver") != 0)
+       continue;
+
+      tree symver = get_identifier_with_length
+       (TREE_STRING_POINTER (TREE_VALUE (TREE_VALUE (value))),
+        TREE_STRING_LENGTH (TREE_VALUE (TREE_VALUE (value))));
+      symtab_node *def = symtab_node::get_for_asmname (symver);
+
+      if (def)
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "duplicate definition of a symbol version");
+         inform (DECL_SOURCE_LOCATION (def->decl),
+                 "same version was previously defined here");
+         return;
+       }
+      if (!n->definition)
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "symbol needs to be defined to have a version");
+         return;
+       }
+      if (DECL_COMMON (n->decl))
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "common symbol cannot be versioned");
+         return;
+       }
+      if (DECL_COMDAT (n->decl))
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "comdat symbol cannot be versioned");
+         return;
+       }
+      if (n->weakref)
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "%<weakref%> cannot be versioned");
+         return;
+       }
+      if (!TREE_PUBLIC (n->decl))
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "versioned symbol must be public");
+         return;
+       }
+      if (DECL_VISIBILITY (n->decl) != VISIBILITY_DEFAULT)
+       {
+         error_at (DECL_SOURCE_LOCATION (n->decl),
+                   "versioned symbol must have default visibility");
+         return;
+       }
+
+      /* Create new symbol table entry representing the version.  */
+      tree new_decl = copy_node (n->decl);
+
+      DECL_INITIAL (new_decl) = NULL_TREE;
+      if (TREE_CODE (new_decl) == FUNCTION_DECL)
+       DECL_STRUCT_FUNCTION (new_decl) = NULL;
+      SET_DECL_ASSEMBLER_NAME (new_decl, symver);
+      TREE_PUBLIC (new_decl) = 1;
+      DECL_ATTRIBUTES (new_decl) = NULL;
+
+      symtab_node *symver_node = symtab_node::get_create (new_decl);
+      symver_node->alias = true;
+      symver_node->definition = true;
+      symver_node->symver = true;
+      symver_node->create_reference (n, IPA_REF_ALIAS, NULL);
+      symver_node->analyzed = true;
+    }
+}
+
 /* Process attributes common for vars and functions.  */
 
 static void
@@ -686,6 +815,7 @@ process_common_attributes (symtab_node *node, tree decl)
 
   if (lookup_attribute ("no_reorder", DECL_ATTRIBUTES (decl)))
     node->no_reorder = 1;
+  process_symver_attribute (node);
 }
 
 /* Look for externally_visible and used attributes and mark cgraph nodes
@@ -723,6 +853,16 @@ process_function_and_variable_attributes (cgraph_node *first,
        node = symtab->next_function (node))
     {
       tree decl = node->decl;
+
+      if (node->alias
+         && lookup_attribute ("flatten", DECL_ATTRIBUTES (decl)))
+       {
+         tree tdecl = node->get_alias_target_tree ();
+         if (!tdecl || !DECL_P (tdecl)
+             || !lookup_attribute ("flatten", DECL_ATTRIBUTES (tdecl)))
+           warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wattributes,
+                       "%<flatten%> attribute is ignored on aliases");
+       }
       if (DECL_PRESERVE_P (decl))
        node->mark_force_output ();
       else if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (decl)))
@@ -733,23 +873,38 @@ process_function_and_variable_attributes (cgraph_node *first,
                        " attribute have effect only on public objects");
        }
       if (lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
-         && (node->definition && !node->alias))
+         && node->definition
+         && (!node->alias || DECL_INITIAL (decl) != error_mark_node))
        {
-         warning_at (DECL_SOURCE_LOCATION (node->decl), OPT_Wattributes,
+         /* NODE->DEFINITION && NODE->ALIAS is nonzero for valid weakref
+            function declarations; DECL_INITIAL is non-null for invalid
+            weakref functions that are also defined.  */
+         warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wattributes,
                      "%<weakref%> attribute ignored"
                      " because function is defined");
          DECL_WEAK (decl) = 0;
          DECL_ATTRIBUTES (decl) = remove_attribute ("weakref",
                                                     DECL_ATTRIBUTES (decl));
+         DECL_ATTRIBUTES (decl) = remove_attribute ("alias",
+                                                    DECL_ATTRIBUTES (decl));
+         node->alias = false;
+         node->weakref = false;
+         node->transparent_alias = false;
        }
+      else if (lookup_attribute ("alias", DECL_ATTRIBUTES (decl))
+         && node->definition
+         && !node->alias)
+       warning_at (DECL_SOURCE_LOCATION (node->decl), OPT_Wattributes,
+                   "%<alias%> attribute ignored"
+                   " because function is defined");
 
       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (decl))
          && !DECL_DECLARED_INLINE_P (decl)
          /* redefining extern inline function makes it DECL_UNINLINABLE.  */
          && !DECL_UNINLINABLE (decl))
        warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wattributes,
-                   "always_inline function might not be inlinable");
-     
+                   "%<always_inline%> function might not be inlinable");
+
       process_common_attributes (node, decl);
     }
   for (vnode = symtab->first_variable (); vnode != first_var;
@@ -800,13 +955,13 @@ varpool_node::finalize_decl (tree decl)
      it is available to notice_global_symbol.  */
   node->definition = true;
   notice_global_symbol (decl);
+  if (!flag_toplevel_reorder)
+    node->no_reorder = true;
   if (TREE_THIS_VOLATILE (decl) || DECL_PRESERVE_P (decl)
       /* Traditionally we do not eliminate static variables when not
-        optimizing and when not doing toplevel reoder.  */
-      || node->no_reorder
-      || ((!flag_toplevel_reorder
-          && !DECL_COMDAT (node->decl)
-          && !DECL_ARTIFICIAL (node->decl))))
+        optimizing and when not doing toplevel reorder.  */
+      || (node->no_reorder && !DECL_COMDAT (node->decl)
+         && !DECL_ARTIFICIAL (node->decl)))
     node->force_output = true;
 
   if (symtab->state == CONSTRUCTION
@@ -817,18 +972,15 @@ varpool_node::finalize_decl (tree decl)
   /* Some frontends produce various interface variables after compilation
      finished.  */
   if (symtab->state == FINISHED
-      || (!flag_toplevel_reorder
-       && symtab->state == EXPANSION))
+      || (node->no_reorder
+         && symtab->state == EXPANSION))
     node->assemble_decl ();
-
-  if (DECL_INITIAL (decl))
-    chkp_register_var_initializer (decl);
 }
 
 /* EDGE is an polymorphic call.  Mark all possible targets as reachable
    and if there is only one target, perform trivial devirtualization. 
    REACHABLE_CALL_TARGETS collects target lists we already walked to
-   avoid udplicate work.  */
+   avoid duplicate work.  */
 
 static void
 walk_polymorphic_call_targets (hash_set<void *> *reachable_call_targets,
@@ -887,26 +1039,19 @@ walk_polymorphic_call_targets (hash_set<void *> *reachable_call_targets,
            }
           if (dump_enabled_p ())
             {
-             location_t locus = gimple_location_safe (edge->call_stmt);
-             dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, locus,
+             dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, edge->call_stmt,
                               "devirtualizing call in %s to %s\n",
-                              edge->caller->name (), target->name ());
+                              edge->caller->dump_name (),
+                              target->dump_name ());
            }
 
-         edge->make_direct (target);
-         edge->redirect_call_stmt_to_callee ();
-
-         /* Call to __builtin_unreachable shouldn't be instrumented.  */
-         if (!targets.length ())
-           gimple_call_set_with_bounds (edge->call_stmt, false);
+         edge = cgraph_edge::make_direct (edge, target);
+         gimple *new_call = cgraph_edge::redirect_call_stmt_to_callee (edge);
 
          if (symtab->dump_file)
            {
-             fprintf (symtab->dump_file,
-                      "Devirtualized as: ");
-             print_gimple_stmt (symtab->dump_file,
-                                edge->call_stmt, 0,
-                                TDF_SLIM);
+             fprintf (symtab->dump_file, "Devirtualized as: ");
+             print_gimple_stmt (symtab->dump_file, new_call, 0, TDF_SLIM);
            }
        }
     }
@@ -927,15 +1072,15 @@ check_global_declaration (symtab_node *snode)
       && DECL_INITIAL (decl) == 0
       && DECL_EXTERNAL (decl)
       && ! DECL_ARTIFICIAL (decl)
-      && ! TREE_NO_WARNING (decl)
-      && ! TREE_PUBLIC (decl)
-      && (warn_unused_function
-         || snode->referred_to_p (/*include_self=*/false)))
+      && ! TREE_PUBLIC (decl))
     {
-      if (snode->referred_to_p (/*include_self=*/false))
+      if (warning_suppressed_p (decl, OPT_Wunused))
+       ;
+      else if (snode->referred_to_p (/*include_self=*/false))
        pedwarn (input_location, 0, "%q+F used but never defined", decl);
       else
-       warning (OPT_Wunused_function, "%q+F declared %<static%> but never defined", decl);
+       warning (OPT_Wunused_function, "%q+F declared %<static%> but never "
+                                      "defined", decl);
       /* This symbol is effectively an "extern" declaration now.  */
       TREE_PUBLIC (decl) = 1;
     }
@@ -949,7 +1094,7 @@ check_global_declaration (symtab_node *snode)
                        && (decl_file = DECL_SOURCE_FILE (decl)) != NULL
                        && filename_cmp (main_input_filename,
                                         decl_file) == 0))))
-          && TREE_CODE (decl) == VAR_DECL))
+          && VAR_P (decl)))
       && ! DECL_IN_SYSTEM_HEADER (decl)
       && ! snode->referred_to_p (/*include_self=*/false)
       /* This TREE_USED check is needed in addition to referred_to_p
@@ -966,7 +1111,7 @@ check_global_declaration (symtab_node *snode)
       /* A volatile variable might be used in some non-obvious way.  */
       && (! VAR_P (decl) || ! TREE_THIS_VOLATILE (decl))
       /* Global register variables must be declared to reserve them.  */
-      && ! (TREE_CODE (decl) == VAR_DECL && DECL_REGISTER (decl))
+      && ! (VAR_P (decl) && DECL_REGISTER (decl))
       /* Global ctors and dtors are called by the runtime.  */
       && (TREE_CODE (decl) != FUNCTION_DECL
          || (!DECL_STATIC_CONSTRUCTOR (decl)
@@ -1011,7 +1156,9 @@ analyze_functions (bool first_time)
   symtab->state = CONSTRUCTION;
   input_location = UNKNOWN_LOCATION;
 
-  /* Ugly, but the fixup can not happen at a time same body alias is created;
+  thunk_info::process_early_thunks ();
+
+  /* Ugly, but the fixup cannot happen at a time same body alias is created;
      C++ FE is confused about the COMDAT groups being right.  */
   if (symtab->cpp_implicit_aliases_done)
     FOR_EACH_SYMBOL (node)
@@ -1019,6 +1166,9 @@ analyze_functions (bool first_time)
          node->fixup_same_cpp_alias_visibility (node->get_alias_target ());
   build_type_inheritance_graph ();
 
+  if (flag_openmp && first_time)
+    omp_discover_implicit_declare_target ();
+
   /* Analysis adds static variables that in turn adds references to new functions.
      So we need to iterate the process until it stabilize.  */
   while (changed)
@@ -1041,9 +1191,7 @@ analyze_functions (bool first_time)
                fprintf (symtab->dump_file, "Trivially needed symbols:");
              changed = true;
              if (symtab->dump_file)
-               fprintf (symtab->dump_file, " %s", node->asm_name ());
-             if (!changed && symtab->dump_file)
-               fprintf (symtab->dump_file, "\n");
+               fprintf (symtab->dump_file, " %s", node->dump_asm_name ());
            }
          if (node == first_analyzed
              || node == first_analyzed_var)
@@ -1074,11 +1222,11 @@ analyze_functions (bool first_time)
              See gcc.c-torture/compile/20011119-1.c  */
              if (!DECL_STRUCT_FUNCTION (decl)
                  && !cnode->alias
-                 && !cnode->thunk.thunk_p
+                 && !cnode->thunk
                  && !cnode->dispatcher_function)
                {
                  cnode->reset ();
-                 cnode->local.redefined_extern_inline = true;
+                 cnode->redefined_extern_inline = true;
                  continue;
                }
 
@@ -1093,7 +1241,7 @@ analyze_functions (bool first_time)
                        || opt_for_fn (edge->callee->decl, optimize)
                        /* Weakrefs needs to be preserved.  */
                        || edge->callee->alias
-                       /* always_inline functions are inlined aven at -O0.  */
+                       /* always_inline functions are inlined even at -O0.  */
                        || lookup_attribute
                                 ("always_inline",
                                  DECL_ATTRIBUTES (edge->callee->decl))
@@ -1116,15 +1264,22 @@ analyze_functions (bool first_time)
                }
 
              /* If decl is a clone of an abstract function,
-             mark that abstract function so that we don't release its body.
-             The DECL_INITIAL() of that abstract function declaration
-             will be later needed to output debug info.  */
+                mark that abstract function so that we don't release its body.
+                The DECL_INITIAL() of that abstract function declaration
+                will be later needed to output debug info.  */
              if (DECL_ABSTRACT_ORIGIN (decl))
                {
                  cgraph_node *origin_node
                    = cgraph_node::get_create (DECL_ABSTRACT_ORIGIN (decl));
                  origin_node->used_as_abstract_origin = true;
                }
+             /* Preserve a functions function context node.  It will
+                later be needed to output debug info.  */
+             if (tree fn = decl_function_context (decl))
+               {
+                 cgraph_node *origin_node = cgraph_node::get_create (fn);
+                 enqueue_node (origin_node);
+               }
            }
          else
            {
@@ -1161,7 +1316,7 @@ analyze_functions (bool first_time)
   if (symtab->dump_file)
     {
       fprintf (symtab->dump_file, "\n\nInitial ");
-      symtab_node::dump_table (symtab->dump_file);
+      symtab->dump (symtab->dump_file);
     }
 
   if (first_time)
@@ -1179,10 +1334,19 @@ analyze_functions (bool first_time)
        && node != first_handled_var; node = next)
     {
       next = node->next;
+      /* For symbols declared locally we clear TREE_READONLY when emitting
+        the constructor (if one is needed).  For external declarations we can
+        not safely assume that the type is readonly because we may be called
+        during its construction.  */
+      if (TREE_CODE (node->decl) == VAR_DECL
+         && TYPE_P (TREE_TYPE (node->decl))
+         && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (node->decl))
+         && DECL_EXTERNAL (node->decl))
+       TREE_READONLY (node->decl) = 0;
       if (!node->aux && !node->referred_to_p ())
        {
          if (symtab->dump_file)
-           fprintf (symtab->dump_file, " %s", node->name ());
+           fprintf (symtab->dump_file, " %s", node->dump_name ());
 
          /* See if the debugger can use anything before the DECL
             passes away.  Perhaps it can notice a DECL that is now a
@@ -1193,8 +1357,16 @@ analyze_functions (bool first_time)
             at looking at optimized away DECLs, since
             late_global_decl will subsequently be called from the
             contents of the now pruned symbol table.  */
-         if (!decl_function_context (node->decl))
-           (*debug_hooks->late_global_decl) (node->decl);
+         if (VAR_P (node->decl)
+             && !decl_function_context (node->decl))
+           {
+             /* We are reclaiming totally unreachable code and variables
+                so they effectively appear as readonly.  Show that to
+                the debug machinery.  */
+             TREE_READONLY (node->decl) = 1;
+             node->definition = false;
+             (*debug_hooks->late_global_decl) (node->decl);
+           }
 
          node->remove ();
          continue;
@@ -1205,12 +1377,13 @@ analyze_functions (bool first_time)
 
          if (cnode->definition && !gimple_has_body_p (decl)
              && !cnode->alias
-             && !cnode->thunk.thunk_p)
+             && !cnode->thunk)
            cnode->reset ();
 
-         gcc_assert (!cnode->definition || cnode->thunk.thunk_p
+         gcc_assert (!cnode->definition || cnode->thunk
                      || cnode->alias
-                     || gimple_has_body_p (decl));
+                     || gimple_has_body_p (decl)
+                     || cnode->native_rtl_p ());
          gcc_assert (cnode->analyzed == cnode->definition);
        }
       node->aux = NULL;
@@ -1222,7 +1395,7 @@ analyze_functions (bool first_time)
   if (symtab->dump_file)
     {
       fprintf (symtab->dump_file, "\n\nReclaimed ");
-      symtab_node::dump_table (symtab->dump_file);
+      symtab->dump (symtab->dump_file);
     }
   bitmap_obstack_release (NULL);
   ggc_collect ();
@@ -1235,6 +1408,98 @@ analyze_functions (bool first_time)
   input_location = saved_loc;
 }
 
+/* Check declaration of the type of ALIAS for compatibility with its TARGET
+   (which may be an ifunc resolver) and issue a diagnostic when they are
+   not compatible according to language rules (plus a C++ extension for
+   non-static member functions).  */
+
+static void
+maybe_diag_incompatible_alias (tree alias, tree target)
+{
+  tree altype = TREE_TYPE (alias);
+  tree targtype = TREE_TYPE (target);
+
+  bool ifunc = cgraph_node::get (alias)->ifunc_resolver;
+  tree funcptr = altype;
+
+  if (ifunc)
+    {
+      /* Handle attribute ifunc first.  */
+      if (TREE_CODE (altype) == METHOD_TYPE)
+       {
+         /* Set FUNCPTR to the type of the alias target.  If the type
+            is a non-static member function of class C, construct a type
+            of an ordinary function taking C* as the first argument,
+            followed by the member function argument list, and use it
+            instead to check for incompatibility.  This conversion is
+            not defined by the language but an extension provided by
+            G++.  */
+
+         tree rettype = TREE_TYPE (altype);
+         tree args = TYPE_ARG_TYPES (altype);
+         altype = build_function_type (rettype, args);
+         funcptr = altype;
+       }
+
+      targtype = TREE_TYPE (targtype);
+
+      if (POINTER_TYPE_P (targtype))
+       {
+         targtype = TREE_TYPE (targtype);
+
+         /* Only issue Wattribute-alias for conversions to void* with
+            -Wextra.  */
+         if (VOID_TYPE_P (targtype) && !extra_warnings)
+           return;
+
+         /* Proceed to handle incompatible ifunc resolvers below.  */
+       }
+      else
+       {
+         funcptr = build_pointer_type (funcptr);
+
+         error_at (DECL_SOURCE_LOCATION (target),
+                   "%<ifunc%> resolver for %qD must return %qT",
+                alias, funcptr);
+         inform (DECL_SOURCE_LOCATION (alias),
+                 "resolver indirect function declared here");
+         return;
+       }
+    }
+
+  if ((!FUNC_OR_METHOD_TYPE_P (targtype)
+       || (prototype_p (altype)
+          && prototype_p (targtype)
+          && !types_compatible_p (altype, targtype))))
+    {
+      /* Warn for incompatibilities.  Avoid warning for functions
+        without a prototype to make it possible to declare aliases
+        without knowing the exact type, as libstdc++ does.  */
+      if (ifunc)
+       {
+         funcptr = build_pointer_type (funcptr);
+
+         auto_diagnostic_group d;
+         if (warning_at (DECL_SOURCE_LOCATION (target),
+                         OPT_Wattribute_alias_,
+                         "%<ifunc%> resolver for %qD should return %qT",
+                         alias, funcptr))
+           inform (DECL_SOURCE_LOCATION (alias),
+                   "resolver indirect function declared here");
+       }
+      else
+       {
+         auto_diagnostic_group d;
+         if (warning_at (DECL_SOURCE_LOCATION (alias),
+                           OPT_Wattribute_alias_,
+                           "%qD alias between functions of incompatible "
+                           "types %qT and %qT", alias, altype, targtype))
+           inform (DECL_SOURCE_LOCATION (target),
+                   "aliased declaration here");
+       }
+    }
+}
+
 /* Translate the ugly representation of aliases as alias pairs into nice
    representation in callgraph.  We don't handle all cases yet,
    unfortunately.  */
@@ -1244,7 +1509,7 @@ handle_alias_pairs (void)
 {
   alias_pair *p;
   unsigned i;
-  
+
   for (i = 0; alias_pairs && alias_pairs->iterate (i, &p);)
     {
       symtab_node *target_node = symtab_node::get_for_asmname (p->target);
@@ -1291,13 +1556,17 @@ handle_alias_pairs (void)
       if (TREE_CODE (p->decl) == FUNCTION_DECL
           && target_node && is_a <cgraph_node *> (target_node))
        {
+         maybe_diag_incompatible_alias (p->decl, target_node->decl);
+
+         maybe_diag_alias_attributes (p->decl, target_node->decl);
+
          cgraph_node *src_node = cgraph_node::get (p->decl);
          if (src_node && src_node->definition)
            src_node->reset ();
          cgraph_node::create_alias (p->decl, target_node->decl);
          alias_pairs->unordered_remove (i);
        }
-      else if (TREE_CODE (p->decl) == VAR_DECL
+      else if (VAR_P (p->decl)
               && target_node && is_a <varpool_node *> (target_node))
        {
          varpool_node::create_alias (p->decl, target_node->decl);
@@ -1305,10 +1574,11 @@ handle_alias_pairs (void)
        }
       else
        {
-         error ("%q+D alias in between function and variable is not supported",
+         error ("%q+D alias between function and variable is not supported",
                 p->decl);
-         warning (0, "%q+D aliased declaration",
-                  target_node->decl);
+         inform (DECL_SOURCE_LOCATION (target_node->decl),
+                 "aliased declaration here");
+
          alias_pairs->unordered_remove (i);
        }
     }
@@ -1340,9 +1610,9 @@ mark_functions_to_output (void)
         always inlined, as well as those that are reachable from
         outside the current compilation unit.  */
       if (node->analyzed
-         && !node->thunk.thunk_p
+         && !node->thunk
          && !node->alias
-         && !node->global.inlined_to
+         && !node->inlined_to
          && !TREE_ASM_WRITTEN (decl)
          && !DECL_EXTERNAL (decl))
        {
@@ -1353,7 +1623,7 @@ mark_functions_to_output (void)
              for (next = dyn_cast<cgraph_node *> (node->same_comdat_group);
                   next != node;
                   next = dyn_cast<cgraph_node *> (next->same_comdat_group))
-               if (!next->thunk.thunk_p && !next->alias
+               if (!next->thunk && !next->alias
                    && !next->comdat_local_p ())
                  next->process = 1;
            }
@@ -1367,7 +1637,7 @@ mark_functions_to_output (void)
        {
          /* We should've reclaimed all functions that are not needed.  */
          if (flag_checking
-             && !node->global.inlined_to
+             && !node->inlined_to
              && gimple_has_body_p (decl)
              /* FIXME: in ltrans unit when offline copy is outside partition but inline copies
                 are inside partition, we can end up not removing the body since we no longer
@@ -1380,7 +1650,7 @@ mark_functions_to_output (void)
              node->debug ();
              internal_error ("failed to reclaim unneeded function");
            }
-         gcc_assert (node->global.inlined_to
+         gcc_assert (node->inlined_to
                      || !gimple_has_body_p (decl)
                      || node->in_other_partition
                      || node->clones
@@ -1395,7 +1665,7 @@ mark_functions_to_output (void)
       if (node->same_comdat_group && !node->process)
        {
          tree decl = node->decl;
-         if (!node->global.inlined_to
+         if (!node->inlined_to
              && gimple_has_body_p (decl)
              /* FIXME: in an ltrans unit when the offline copy is outside a
                 partition but inline copies are inside a partition, we can
@@ -1419,7 +1689,7 @@ mark_functions_to_output (void)
    return basic block in the function body.  */
 
 basic_block
-init_lowered_empty_function (tree decl, bool in_ssa, gcov_type count)
+init_lowered_empty_function (tree decl, bool in_ssa, profile_count count)
 {
   basic_block bb;
   edge e;
@@ -1438,6 +1708,7 @@ init_lowered_empty_function (tree decl, bool in_ssa, gcov_type count)
     }
 
   DECL_INITIAL (decl) = make_node (BLOCK);
+  BLOCK_SUPERCONTEXT (DECL_INITIAL (decl)) = decl;
 
   DECL_SAVED_TREE (decl) = error_mark_node;
   cfun->curr_properties |= (PROP_gimple_lcf | PROP_gimple_leh | PROP_gimple_any
@@ -1449,454 +1720,18 @@ init_lowered_empty_function (tree decl, bool in_ssa, gcov_type count)
 
   /* Create BB for body of the function and connect it properly.  */
   ENTRY_BLOCK_PTR_FOR_FN (cfun)->count = count;
-  ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency = REG_BR_PROB_BASE;
   EXIT_BLOCK_PTR_FOR_FN (cfun)->count = count;
-  EXIT_BLOCK_PTR_FOR_FN (cfun)->frequency = REG_BR_PROB_BASE;
   bb = create_basic_block (NULL, ENTRY_BLOCK_PTR_FOR_FN (cfun));
   bb->count = count;
-  bb->frequency = BB_FREQ_MAX;
   e = make_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun), bb, EDGE_FALLTHRU);
-  e->count = count;
-  e->probability = REG_BR_PROB_BASE;
+  e->probability = profile_probability::always ();
   e = make_edge (bb, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
-  e->count = count;
-  e->probability = REG_BR_PROB_BASE;
+  e->probability = profile_probability::always ();
   add_bb_to_loop (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun)->loop_father);
 
   return bb;
 }
 
-/* Adjust PTR by the constant FIXED_OFFSET, and by the vtable
-   offset indicated by VIRTUAL_OFFSET, if that is
-   non-null. THIS_ADJUSTING is nonzero for a this adjusting thunk and
-   zero for a result adjusting thunk.  */
-
-tree
-thunk_adjust (gimple_stmt_iterator * bsi,
-             tree ptr, bool this_adjusting,
-             HOST_WIDE_INT fixed_offset, tree virtual_offset)
-{
-  gassign *stmt;
-  tree ret;
-
-  if (this_adjusting
-      && fixed_offset != 0)
-    {
-      stmt = gimple_build_assign
-               (ptr, fold_build_pointer_plus_hwi_loc (input_location,
-                                                      ptr,
-                                                      fixed_offset));
-      gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-    }
-
-  /* If there's a virtual offset, look up that value in the vtable and
-     adjust the pointer again.  */
-  if (virtual_offset)
-    {
-      tree vtabletmp;
-      tree vtabletmp2;
-      tree vtabletmp3;
-
-      if (!vtable_entry_type)
-       {
-         tree vfunc_type = make_node (FUNCTION_TYPE);
-         TREE_TYPE (vfunc_type) = integer_type_node;
-         TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
-         layout_type (vfunc_type);
-
-         vtable_entry_type = build_pointer_type (vfunc_type);
-       }
-
-      vtabletmp =
-       create_tmp_reg (build_pointer_type
-                         (build_pointer_type (vtable_entry_type)), "vptr");
-
-      /* The vptr is always at offset zero in the object.  */
-      stmt = gimple_build_assign (vtabletmp,
-                                 build1 (NOP_EXPR, TREE_TYPE (vtabletmp),
-                                         ptr));
-      gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-
-      /* Form the vtable address.  */
-      vtabletmp2 = create_tmp_reg (TREE_TYPE (TREE_TYPE (vtabletmp)),
-                                    "vtableaddr");
-      stmt = gimple_build_assign (vtabletmp2,
-                                 build_simple_mem_ref (vtabletmp));
-      gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-
-      /* Find the entry with the vcall offset.  */
-      stmt = gimple_build_assign (vtabletmp2,
-                                 fold_build_pointer_plus_loc (input_location,
-                                                              vtabletmp2,
-                                                              virtual_offset));
-      gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-
-      /* Get the offset itself.  */
-      vtabletmp3 = create_tmp_reg (TREE_TYPE (TREE_TYPE (vtabletmp2)),
-                                    "vcalloffset");
-      stmt = gimple_build_assign (vtabletmp3,
-                                 build_simple_mem_ref (vtabletmp2));
-      gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-
-      /* Adjust the `this' pointer.  */
-      ptr = fold_build_pointer_plus_loc (input_location, ptr, vtabletmp3);
-      ptr = force_gimple_operand_gsi (bsi, ptr, true, NULL_TREE, false,
-                                     GSI_CONTINUE_LINKING);
-    }
-
-  if (!this_adjusting
-      && fixed_offset != 0)
-    /* Adjust the pointer by the constant.  */
-    {
-      tree ptrtmp;
-
-      if (TREE_CODE (ptr) == VAR_DECL)
-        ptrtmp = ptr;
-      else
-        {
-          ptrtmp = create_tmp_reg (TREE_TYPE (ptr), "ptr");
-          stmt = gimple_build_assign (ptrtmp, ptr);
-         gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-       }
-      ptr = fold_build_pointer_plus_hwi_loc (input_location,
-                                            ptrtmp, fixed_offset);
-    }
-
-  /* Emit the statement and gimplify the adjustment expression.  */
-  ret = create_tmp_reg (TREE_TYPE (ptr), "adjusted_this");
-  stmt = gimple_build_assign (ret, ptr);
-  gsi_insert_after (bsi, stmt, GSI_NEW_STMT);
-
-  return ret;
-}
-
-/* Expand thunk NODE to gimple if possible.
-   When FORCE_GIMPLE_THUNK is true, gimple thunk is created and
-   no assembler is produced.
-   When OUTPUT_ASM_THUNK is true, also produce assembler for
-   thunks that are not lowered.  */
-
-bool
-cgraph_node::expand_thunk (bool output_asm_thunks, bool force_gimple_thunk)
-{
-  bool this_adjusting = thunk.this_adjusting;
-  HOST_WIDE_INT fixed_offset = thunk.fixed_offset;
-  HOST_WIDE_INT virtual_value = thunk.virtual_value;
-  tree virtual_offset = NULL;
-  tree alias = callees->callee->decl;
-  tree thunk_fndecl = decl;
-  tree a;
-
-  /* Instrumentation thunk is the same function with
-     a different signature.  Never need to expand it.  */
-  if (thunk.add_pointer_bounds_args)
-    return false;
-
-  if (!force_gimple_thunk && this_adjusting
-      && targetm.asm_out.can_output_mi_thunk (thunk_fndecl, fixed_offset,
-                                             virtual_value, alias))
-    {
-      const char *fnname;
-      tree fn_block;
-      tree restype = TREE_TYPE (TREE_TYPE (thunk_fndecl));
-
-      if (!output_asm_thunks)
-       {
-         analyzed = true;
-         return false;
-       }
-
-      if (in_lto_p)
-       get_untransformed_body ();
-      a = DECL_ARGUMENTS (thunk_fndecl);
-      
-      current_function_decl = thunk_fndecl;
-
-      /* Ensure thunks are emitted in their correct sections.  */
-      resolve_unique_section (thunk_fndecl, 0,
-                             flag_function_sections);
-
-      DECL_RESULT (thunk_fndecl)
-       = build_decl (DECL_SOURCE_LOCATION (thunk_fndecl),
-                     RESULT_DECL, 0, restype);
-      DECL_CONTEXT (DECL_RESULT (thunk_fndecl)) = thunk_fndecl;
-      fnname = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk_fndecl));
-
-      /* The back end expects DECL_INITIAL to contain a BLOCK, so we
-        create one.  */
-      fn_block = make_node (BLOCK);
-      BLOCK_VARS (fn_block) = a;
-      DECL_INITIAL (thunk_fndecl) = fn_block;
-      allocate_struct_function (thunk_fndecl, false);
-      init_function_start (thunk_fndecl);
-      cfun->is_thunk = 1;
-      insn_locations_init ();
-      set_curr_insn_location (DECL_SOURCE_LOCATION (thunk_fndecl));
-      prologue_location = curr_insn_location ();
-      assemble_start_function (thunk_fndecl, fnname);
-
-      targetm.asm_out.output_mi_thunk (asm_out_file, thunk_fndecl,
-                                      fixed_offset, virtual_value, alias);
-
-      assemble_end_function (thunk_fndecl, fnname);
-      insn_locations_finalize ();
-      init_insn_lengths ();
-      free_after_compilation (cfun);
-      TREE_ASM_WRITTEN (thunk_fndecl) = 1;
-      thunk.thunk_p = false;
-      analyzed = false;
-    }
-  else if (stdarg_p (TREE_TYPE (thunk_fndecl)))
-    {
-      error ("generic thunk code fails for method %qD which uses %<...%>",
-            thunk_fndecl);
-      TREE_ASM_WRITTEN (thunk_fndecl) = 1;
-      analyzed = true;
-      return false;
-    }
-  else
-    {
-      tree restype;
-      basic_block bb, then_bb, else_bb, return_bb;
-      gimple_stmt_iterator bsi;
-      int nargs = 0;
-      tree arg;
-      int i;
-      tree resdecl;
-      tree restmp = NULL;
-      tree resbnd = NULL;
-
-      gcall *call;
-      greturn *ret;
-      bool alias_is_noreturn = TREE_THIS_VOLATILE (alias);
-
-      /* We may be called from expand_thunk that releses body except for
-        DECL_ARGUMENTS.  In this case force_gimple_thunk is true.  */
-      if (in_lto_p && !force_gimple_thunk)
-       get_untransformed_body ();
-      a = DECL_ARGUMENTS (thunk_fndecl);
-
-      current_function_decl = thunk_fndecl;
-
-      /* Ensure thunks are emitted in their correct sections.  */
-      resolve_unique_section (thunk_fndecl, 0,
-                             flag_function_sections);
-
-      DECL_IGNORED_P (thunk_fndecl) = 1;
-      bitmap_obstack_initialize (NULL);
-
-      if (thunk.virtual_offset_p)
-        virtual_offset = size_int (virtual_value);
-
-      /* Build the return declaration for the function.  */
-      restype = TREE_TYPE (TREE_TYPE (thunk_fndecl));
-      if (DECL_RESULT (thunk_fndecl) == NULL_TREE)
-       {
-         resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
-         DECL_ARTIFICIAL (resdecl) = 1;
-         DECL_IGNORED_P (resdecl) = 1;
-         DECL_RESULT (thunk_fndecl) = resdecl;
-          DECL_CONTEXT (DECL_RESULT (thunk_fndecl)) = thunk_fndecl;
-       }
-      else
-       resdecl = DECL_RESULT (thunk_fndecl);
-
-      bb = then_bb = else_bb = return_bb
-       = init_lowered_empty_function (thunk_fndecl, true, count);
-
-      bsi = gsi_start_bb (bb);
-
-      /* Build call to the function being thunked.  */
-      if (!VOID_TYPE_P (restype)
-         && (!alias_is_noreturn
-             || TREE_ADDRESSABLE (restype)
-             || TREE_CODE (TYPE_SIZE_UNIT (restype)) != INTEGER_CST))
-       {
-         if (DECL_BY_REFERENCE (resdecl))
-           {
-             restmp = gimple_fold_indirect_ref (resdecl);
-             if (!restmp)
-               restmp = build2 (MEM_REF,
-                                TREE_TYPE (TREE_TYPE (DECL_RESULT (alias))),
-                                resdecl,
-                                build_int_cst (TREE_TYPE
-                                  (DECL_RESULT (alias)), 0));
-           }
-         else if (!is_gimple_reg_type (restype))
-           {
-             if (aggregate_value_p (resdecl, TREE_TYPE (thunk_fndecl)))
-               {
-                 restmp = resdecl;
-
-                 if (TREE_CODE (restmp) == VAR_DECL)
-                   add_local_decl (cfun, restmp);
-                 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = restmp;
-               }
-             else
-               restmp = create_tmp_var (restype, "retval");
-           }
-         else
-           restmp = create_tmp_reg (restype, "retval");
-       }
-
-      for (arg = a; arg; arg = DECL_CHAIN (arg))
-        nargs++;
-      auto_vec<tree> vargs (nargs);
-      i = 0;
-      arg = a;
-      if (this_adjusting)
-       {
-         vargs.quick_push (thunk_adjust (&bsi, a, 1, fixed_offset,
-                                         virtual_offset));
-         arg = DECL_CHAIN (a);
-         i = 1;
-       }
-
-      if (nargs)
-       for (; i < nargs; i++, arg = DECL_CHAIN (arg))
-         {
-           tree tmp = arg;
-           if (!is_gimple_val (arg))
-             {
-               tmp = create_tmp_reg (TYPE_MAIN_VARIANT
-                                     (TREE_TYPE (arg)), "arg");
-               gimple *stmt = gimple_build_assign (tmp, arg);
-               gsi_insert_after (&bsi, stmt, GSI_NEW_STMT);
-             }
-           vargs.quick_push (tmp);
-         }
-      call = gimple_build_call_vec (build_fold_addr_expr_loc (0, alias), vargs);
-      callees->call_stmt = call;
-      gimple_call_set_from_thunk (call, true);
-      gimple_call_set_with_bounds (call, instrumentation_clone);
-
-      /* Return slot optimization is always possible and in fact requred to
-         return values with DECL_BY_REFERENCE.  */
-      if (aggregate_value_p (resdecl, TREE_TYPE (thunk_fndecl))
-         && (!is_gimple_reg_type (TREE_TYPE (resdecl))
-             || DECL_BY_REFERENCE (resdecl)))
-        gimple_call_set_return_slot_opt (call, true);
-
-      if (restmp)
-       {
-          gimple_call_set_lhs (call, restmp);
-         gcc_assert (useless_type_conversion_p (TREE_TYPE (restmp),
-                                                TREE_TYPE (TREE_TYPE (alias))));
-       }
-      gsi_insert_after (&bsi, call, GSI_NEW_STMT);
-      if (!alias_is_noreturn)
-       {
-         if (instrumentation_clone
-             && !DECL_BY_REFERENCE (resdecl)
-             && restmp
-             && BOUNDED_P (restmp))
-           {
-             resbnd = chkp_insert_retbnd_call (NULL, restmp, &bsi);
-             create_edge (get_create (gimple_call_fndecl (gsi_stmt (bsi))),
-                          as_a <gcall *> (gsi_stmt (bsi)),
-                          callees->count, callees->frequency);
-           }
-
-         if (restmp && !this_adjusting
-             && (fixed_offset || virtual_offset))
-           {
-             tree true_label = NULL_TREE;
-
-             if (TREE_CODE (TREE_TYPE (restmp)) == POINTER_TYPE)
-               {
-                 gimple *stmt;
-                 edge e;
-                 /* If the return type is a pointer, we need to
-                    protect against NULL.  We know there will be an
-                    adjustment, because that's why we're emitting a
-                    thunk.  */
-                 then_bb = create_basic_block (NULL, bb);
-                 then_bb->count = count - count / 16;
-                 then_bb->frequency = BB_FREQ_MAX - BB_FREQ_MAX / 16;
-                 return_bb = create_basic_block (NULL, then_bb);
-                 return_bb->count = count;
-                 return_bb->frequency = BB_FREQ_MAX;
-                 else_bb = create_basic_block (NULL, else_bb);
-                 then_bb->count = count / 16;
-                 then_bb->frequency = BB_FREQ_MAX / 16;
-                 add_bb_to_loop (then_bb, bb->loop_father);
-                 add_bb_to_loop (return_bb, bb->loop_father);
-                 add_bb_to_loop (else_bb, bb->loop_father);
-                 remove_edge (single_succ_edge (bb));
-                 true_label = gimple_block_label (then_bb);
-                 stmt = gimple_build_cond (NE_EXPR, restmp,
-                                           build_zero_cst (TREE_TYPE (restmp)),
-                                           NULL_TREE, NULL_TREE);
-                 gsi_insert_after (&bsi, stmt, GSI_NEW_STMT);
-                 e = make_edge (bb, then_bb, EDGE_TRUE_VALUE);
-                 e->probability = REG_BR_PROB_BASE - REG_BR_PROB_BASE / 16;
-                 e->count = count - count / 16;
-                 e = make_edge (bb, else_bb, EDGE_FALSE_VALUE);
-                 e->probability = REG_BR_PROB_BASE / 16;
-                 e->count = count / 16;
-                 e = make_edge (return_bb, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
-                 e->probability = REG_BR_PROB_BASE;
-                 e->count = count;
-                 e = make_edge (then_bb, return_bb, EDGE_FALLTHRU);
-                 e->probability = REG_BR_PROB_BASE;
-                 e->count = count - count / 16;
-                 e = make_edge (else_bb, return_bb, EDGE_FALLTHRU);
-                 e->probability = REG_BR_PROB_BASE;
-                 e->count = count / 16;
-                 bsi = gsi_last_bb (then_bb);
-               }
-
-             restmp = thunk_adjust (&bsi, restmp, /*this_adjusting=*/0,
-                                    fixed_offset, virtual_offset);
-             if (true_label)
-               {
-                 gimple *stmt;
-                 bsi = gsi_last_bb (else_bb);
-                 stmt = gimple_build_assign (restmp,
-                                             build_zero_cst (TREE_TYPE (restmp)));
-                 gsi_insert_after (&bsi, stmt, GSI_NEW_STMT);
-                 bsi = gsi_last_bb (return_bb);
-               }
-           }
-         else
-           gimple_call_set_tail (call, true);
-
-         /* Build return value.  */
-         if (!DECL_BY_REFERENCE (resdecl))
-           ret = gimple_build_return (restmp);
-         else
-           ret = gimple_build_return (resdecl);
-         gimple_return_set_retbnd (ret, resbnd);
-
-         gsi_insert_after (&bsi, ret, GSI_NEW_STMT);
-       }
-      else
-       {
-         gimple_call_set_tail (call, true);
-         remove_edge (single_succ_edge (bb));
-       }
-
-      cfun->gimple_df->in_ssa_p = true;
-      profile_status_for_fn (cfun)
-        = count ? PROFILE_READ : PROFILE_GUESSED;
-      /* FIXME: C++ FE should stop setting TREE_ASM_WRITTEN on thunks.  */
-      TREE_ASM_WRITTEN (thunk_fndecl) = false;
-      delete_unreachable_blocks ();
-      update_ssa (TODO_update_ssa);
-      checking_verify_flow_info ();
-      free_dominance_info (CDI_DOMINATORS);
-
-      /* Since we want to emit the thunk, we explicitly mark its name as
-        referenced.  */
-      thunk.thunk_p = false;
-      lowered = true;
-      bitmap_obstack_release (NULL);
-    }
-  current_function_decl = NULL;
-  set_cfun (NULL);
-  return true;
-}
-
 /* Assemble thunks and aliases associated to node.  */
 
 void
@@ -1906,14 +1741,13 @@ cgraph_node::assemble_thunks_and_aliases (void)
   ipa_ref *ref;
 
   for (e = callers; e;)
-    if (e->caller->thunk.thunk_p
-       && !e->caller->global.inlined_to
-       && !e->caller->thunk.add_pointer_bounds_args)
+    if (e->caller->thunk
+       && !e->caller->inlined_to)
       {
        cgraph_node *thunk = e->caller;
 
        e = e->next_caller;
-       thunk->expand_thunk (true, false);
+       expand_thunk (thunk, true, false);
        thunk->assemble_thunks_and_aliases ();
       }
     else
@@ -1929,8 +1763,12 @@ cgraph_node::assemble_thunks_and_aliases (void)
          /* Force assemble_alias to really output the alias this time instead
             of buffering it in same alias pairs.  */
          TREE_ASM_WRITTEN (decl) = 1;
-         do_assemble_alias (alias->decl,
-                            DECL_ASSEMBLER_NAME (decl));
+         if (alias->symver)
+           do_assemble_symver (alias->decl,
+                               DECL_ASSEMBLER_NAME (decl));
+         else
+           do_assemble_alias (alias->decl,
+                              DECL_ASSEMBLER_NAME (decl));
          alias->assemble_thunks_and_aliases ();
          TREE_ASM_WRITTEN (decl) = saved_written;
        }
@@ -1945,11 +1783,19 @@ cgraph_node::expand (void)
   location_t saved_loc;
 
   /* We ought to not compile any inline clones.  */
-  gcc_assert (!global.inlined_to);
+  gcc_assert (!inlined_to);
+
+  /* __RTL functions are compiled as soon as they are parsed, so don't
+     do it again.  */
+  if (native_rtl_p ())
+    return;
 
   announce_function (decl);
   process = 0;
   gcc_assert (lowered);
+
+  /* Initialize the default bitmap obstack.  */
+  bitmap_obstack_initialize (NULL);
   get_untransformed_body ();
 
   /* Generate RTL for the body of DECL.  */
@@ -1958,9 +1804,6 @@ cgraph_node::expand (void)
 
   gcc_assert (symtab->global_info_ready);
 
-  /* Initialize the default bitmap obstack.  */
-  bitmap_obstack_initialize (NULL);
-
   /* Initialize the RTL code for the function.  */
   saved_loc = input_location;
   input_location = DECL_SOURCE_LOCATION (decl);
@@ -1973,7 +1816,9 @@ cgraph_node::expand (void)
 
   bitmap_obstack_initialize (&reg_obstack); /* FIXME, only at RTL generation*/
 
-  execute_all_ipa_transforms ();
+  update_ssa (TODO_update_ssa_only_virtuals);
+  if (ipa_transforms_to_apply.exists ())
+    execute_all_ipa_transforms (false);
 
   /* Perform all tree transforms and optimizations.  */
 
@@ -1993,36 +1838,35 @@ cgraph_node::expand (void)
   /* If requested, warn about function definitions where the function will
      return a value (usually of some struct or union type) which itself will
      take up a lot of stack space.  */
-  if (warn_larger_than && !DECL_EXTERNAL (decl) && TREE_TYPE (decl))
+  if (!DECL_EXTERNAL (decl) && TREE_TYPE (decl))
     {
       tree ret_type = TREE_TYPE (TREE_TYPE (decl));
 
       if (ret_type && TYPE_SIZE_UNIT (ret_type)
          && TREE_CODE (TYPE_SIZE_UNIT (ret_type)) == INTEGER_CST
-         && 0 < compare_tree_int (TYPE_SIZE_UNIT (ret_type),
-                                  larger_than_size))
+         && compare_tree_int (TYPE_SIZE_UNIT (ret_type),
+                              warn_larger_than_size) > 0)
        {
          unsigned int size_as_int
            = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (ret_type));
 
          if (compare_tree_int (TYPE_SIZE_UNIT (ret_type), size_as_int) == 0)
-           warning (OPT_Wlarger_than_, "size of return value of %q+D is %u bytes",
+           warning (OPT_Wlarger_than_,
+                    "size of return value of %q+D is %u bytes",
                      decl, size_as_int);
          else
-           warning (OPT_Wlarger_than_, "size of return value of %q+D is larger than %wd bytes",
-                     decl, larger_than_size);
+           warning (OPT_Wlarger_than_,
+                    "size of return value of %q+D is larger than %wu bytes",
+                    decl, warn_larger_than_size);
        }
     }
 
   gimple_set_body (decl, NULL);
-  if (DECL_STRUCT_FUNCTION (decl) == 0
-      && !cgraph_node::get (decl)->origin)
+  if (DECL_STRUCT_FUNCTION (decl) == 0)
     {
       /* Stop pointing to the local nodes about to be freed.
         But DECL_INITIAL must remain nonzero so we know this
-        was an actual function definition.
-        For a nested function, this is done in c_pop_function_context.
-        If rest_of_compilation set this to 0, leave it 0.  */
+        was an actual function definition.  */
       if (DECL_INITIAL (decl) != 0)
        DECL_INITIAL (decl) = error_mark_node;
     }
@@ -2037,36 +1881,43 @@ cgraph_node::expand (void)
   if (cfun)
     pop_cfun ();
 
-  /* It would make a lot more sense to output thunks before function body to get more
-     forward and lest backwarding jumps.  This however would need solving problem
-     with comdats. See PR48668.  Also aliases must come after function itself to
-     make one pass assemblers, like one on AIX, happy.  See PR 50689.
-     FIXME: Perhaps thunks should be move before function IFF they are not in comdat
-     groups.  */
+  /* It would make a lot more sense to output thunks before function body to
+     get more forward and fewer backward jumps.  This however would need
+     solving problem with comdats.  See PR48668.  Also aliases must come after
+     function itself to make one pass assemblers, like one on AIX, happy.
+     See PR 50689.
+     FIXME: Perhaps thunks should be move before function IFF they are not in
+     comdat groups.  */
   assemble_thunks_and_aliases ();
   release_body ();
-  /* Eliminate all call edges.  This is important so the GIMPLE_CALL no longer
-     points to the dead function body.  */
-  remove_callees ();
-  remove_all_references ();
 }
 
-/* Node comparer that is responsible for the order that corresponds
+/* Node comparator that is responsible for the order that corresponds
    to time when a function was launched for the first time.  */
 
-static int
-node_cmp (const void *pa, const void *pb)
+int
+tp_first_run_node_cmp (const void *pa, const void *pb)
 {
   const cgraph_node *a = *(const cgraph_node * const *) pa;
   const cgraph_node *b = *(const cgraph_node * const *) pb;
+  unsigned int tp_first_run_a = a->tp_first_run;
+  unsigned int tp_first_run_b = b->tp_first_run;
+
+  if (!opt_for_fn (a->decl, flag_profile_reorder_functions)
+      || a->no_reorder)
+    tp_first_run_a = 0;
+  if (!opt_for_fn (b->decl, flag_profile_reorder_functions)
+      || b->no_reorder)
+    tp_first_run_b = 0;
+
+  if (tp_first_run_a == tp_first_run_b)
+    return a->order - b->order;
 
   /* Functions with time profile must be before these without profile.  */
-  if (!a->tp_first_run || !b->tp_first_run)
-    return a->tp_first_run - b->tp_first_run;
+  tp_first_run_a = (tp_first_run_a - 1) & INT_MAX;
+  tp_first_run_b = (tp_first_run_b - 1) & INT_MAX;
 
-  return a->tp_first_run != b->tp_first_run
-        ? b->tp_first_run - a->tp_first_run
-        : b->order - a->order;
+  return tp_first_run_a - tp_first_run_b;
 }
 
 /* Expand all functions that must be output.
@@ -2085,8 +1936,10 @@ expand_all_functions (void)
   cgraph_node *node;
   cgraph_node **order = XCNEWVEC (cgraph_node *,
                                         symtab->cgraph_count);
+  cgraph_node **tp_first_run_order = XCNEWVEC (cgraph_node *,
+                                        symtab->cgraph_count);
   unsigned int expanded_func_count = 0, profiled_func_count = 0;
-  int order_pos, new_order_pos = 0;
+  int order_pos, tp_first_run_order_pos = 0, new_order_pos = 0;
   int i;
 
   order_pos = ipa_reverse_postorder (order);
@@ -2096,56 +1949,102 @@ expand_all_functions (void)
      optimization.  So we must be sure to not reference them.  */
   for (i = 0; i < order_pos; i++)
     if (order[i]->process)
-      order[new_order_pos++] = order[i];
-
-  if (flag_profile_reorder_functions)
-    qsort (order, new_order_pos, sizeof (cgraph_node *), node_cmp);
+      {
+       if (order[i]->tp_first_run
+           && opt_for_fn (order[i]->decl, flag_profile_reorder_functions))
+         tp_first_run_order[tp_first_run_order_pos++] = order[i];
+       else
+          order[new_order_pos++] = order[i];
+      }
 
-  for (i = new_order_pos - 1; i >= 0; i--)
+  /* First output functions with time profile in specified order.  */
+  qsort (tp_first_run_order, tp_first_run_order_pos,
+        sizeof (cgraph_node *), tp_first_run_node_cmp);
+  for (i = 0; i < tp_first_run_order_pos; i++)
     {
-      node = order[i];
+      node = tp_first_run_order[i];
 
       if (node->process)
        {
          expanded_func_count++;
-         if(node->tp_first_run)
-           profiled_func_count++;
+         profiled_func_count++;
 
          if (symtab->dump_file)
            fprintf (symtab->dump_file,
                     "Time profile order in expand_all_functions:%s:%d\n",
-                    node->asm_name (), node->tp_first_run);
+                    node->dump_asm_name (), node->tp_first_run);
+         node->process = 0;
+         node->expand ();
+       }
+    }
+
+  /* Output functions in RPO so callees get optimized before callers.  This
+     makes ipa-ra and other propagators to work.
+     FIXME: This is far from optimal code layout.  */
+  for (i = new_order_pos - 1; i >= 0; i--)
+    {
+      node = order[i];
+
+      if (node->process)
+       {
+         expanded_func_count++;
          node->process = 0;
          node->expand ();
        }
     }
 
-    if (dump_file)
-      fprintf (dump_file, "Expanded functions with time profile (%s):%u/%u\n",
-               main_input_filename, profiled_func_count, expanded_func_count);
+  if (dump_file)
+    fprintf (dump_file, "Expanded functions with time profile (%s):%u/%u\n",
+            main_input_filename, profiled_func_count, expanded_func_count);
 
-  if (symtab->dump_file && flag_profile_reorder_functions)
+  if (symtab->dump_file && tp_first_run_order_pos)
     fprintf (symtab->dump_file, "Expanded functions with time profile:%u/%u\n",
              profiled_func_count, expanded_func_count);
 
   symtab->process_new_functions ();
   free_gimplify_stack ();
-
+  delete ipa_saved_clone_sources;
+  ipa_saved_clone_sources = NULL;
   free (order);
+  free (tp_first_run_order);
 }
 
 /* This is used to sort the node types by the cgraph order number.  */
 
 enum cgraph_order_sort_kind
 {
-  ORDER_UNDEFINED = 0,
   ORDER_FUNCTION,
   ORDER_VAR,
+  ORDER_VAR_UNDEF,
   ORDER_ASM
 };
 
 struct cgraph_order_sort
 {
+  /* Construct from a cgraph_node.  */
+  cgraph_order_sort (cgraph_node *node)
+  : kind (ORDER_FUNCTION), order (node->order)
+  {
+    u.f = node;
+  }
+
+  /* Construct from a varpool_node.  */
+  cgraph_order_sort (varpool_node *node)
+  : kind (node->definition ? ORDER_VAR : ORDER_VAR_UNDEF), order (node->order)
+  {
+    u.v = node;
+  }
+
+  /* Construct from a asm_node.  */
+  cgraph_order_sort (asm_node *node)
+  : kind (ORDER_ASM), order (node->order)
+  {
+    u.a = node;
+  }
+
+  /* Assembly cgraph_order_sort based on its type.  */
+  void process ();
+
   enum cgraph_order_sort_kind kind;
   union
   {
@@ -2153,100 +2052,89 @@ struct cgraph_order_sort
     varpool_node *v;
     asm_node *a;
   } u;
+  int order;
 };
 
+/* Assembly cgraph_order_sort based on its type.  */
+
+void
+cgraph_order_sort::process ()
+{
+  switch (kind)
+    {
+    case ORDER_FUNCTION:
+      u.f->process = 0;
+      u.f->expand ();
+      break;
+    case ORDER_VAR:
+      u.v->assemble_decl ();
+      break;
+    case ORDER_VAR_UNDEF:
+      assemble_undefined_decl (u.v->decl);
+      break;
+    case ORDER_ASM:
+      assemble_asm (u.a->asm_str);
+      break;
+    default:
+      gcc_unreachable ();
+    }
+}
+
+/* Compare cgraph_order_sort by order.  */
+
+static int
+cgraph_order_cmp (const void *a_p, const void *b_p)
+{
+  const cgraph_order_sort *nodea = (const cgraph_order_sort *)a_p;
+  const cgraph_order_sort *nodeb = (const cgraph_order_sort *)b_p;
+
+  return nodea->order - nodeb->order;
+}
+
 /* Output all functions, variables, and asm statements in the order
    according to their order fields, which is the order in which they
    appeared in the file.  This implements -fno-toplevel-reorder.  In
    this mode we may output functions and variables which don't really
-   need to be output.
-   When NO_REORDER is true only do this for symbols marked no reorder. */
+   need to be output.  */
 
 static void
-output_in_order (bool no_reorder)
+output_in_order (void)
 {
-  int max;
-  cgraph_order_sort *nodes;
   int i;
-  cgraph_node *pf;
-  varpool_node *pv;
-  asm_node *pa;
-  max = symtab->order;
-  nodes = XCNEWVEC (cgraph_order_sort, max);
-
-  FOR_EACH_DEFINED_FUNCTION (pf)
-    {
-      if (pf->process && !pf->thunk.thunk_p && !pf->alias)
-       {
-         if (no_reorder && !pf->no_reorder)
-           continue;
-         i = pf->order;
-         gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
-         nodes[i].kind = ORDER_FUNCTION;
-         nodes[i].u.f = pf;
-       }
-    }
-
-  FOR_EACH_DEFINED_VARIABLE (pv)
-    if (!DECL_EXTERNAL (pv->decl))
-      {
-       if (no_reorder && !pv->no_reorder)
-           continue;
-       i = pv->order;
-       gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
-       nodes[i].kind = ORDER_VAR;
-       nodes[i].u.v = pv;
-      }
-
-  for (pa = symtab->first_asm_symbol (); pa; pa = pa->next)
-    {
-      i = pa->order;
-      gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
-      nodes[i].kind = ORDER_ASM;
-      nodes[i].u.a = pa;
-    }
-
-  /* In toplevel reorder mode we output all statics; mark them as needed.  */
+  cgraph_node *cnode;
+  varpool_node *vnode;
+  asm_node *anode;
+  auto_vec<cgraph_order_sort> nodes;
+  cgraph_order_sort *node;
 
-  for (i = 0; i < max; ++i)
-    if (nodes[i].kind == ORDER_VAR)
-      nodes[i].u.v->finalize_named_section_flags ();
+  FOR_EACH_DEFINED_FUNCTION (cnode)
+    if (cnode->process && !cnode->thunk
+       && !cnode->alias && cnode->no_reorder)
+      nodes.safe_push (cgraph_order_sort (cnode));
 
-  for (i = 0; i < max; ++i)
-    {
-      switch (nodes[i].kind)
-       {
-       case ORDER_FUNCTION:
-         nodes[i].u.f->process = 0;
-         nodes[i].u.f->expand ();
-         break;
+  /* There is a similar loop in symbol_table::output_variables.
+     Please keep them in sync.  */
+  FOR_EACH_VARIABLE (vnode)
+    if (vnode->no_reorder
+       && !DECL_HARD_REGISTER (vnode->decl)
+       && !DECL_HAS_VALUE_EXPR_P (vnode->decl))
+      nodes.safe_push (cgraph_order_sort (vnode));
 
-       case ORDER_VAR:
-#ifdef ACCEL_COMPILER
-         /* Do not assemble "omp declare target link" vars.  */
-         if (DECL_HAS_VALUE_EXPR_P (nodes[i].u.v->decl)
-             && lookup_attribute ("omp declare target link",
-                                  DECL_ATTRIBUTES (nodes[i].u.v->decl)))
-           break;
-#endif
-         nodes[i].u.v->assemble_decl ();
-         break;
+  for (anode = symtab->first_asm_symbol (); anode; anode = anode->next)
+    nodes.safe_push (cgraph_order_sort (anode));
 
-       case ORDER_ASM:
-         assemble_asm (nodes[i].u.a->asm_str);
-         break;
+  /* Sort nodes by order.  */
+  nodes.qsort (cgraph_order_cmp);
 
-       case ORDER_UNDEFINED:
-         break;
+  /* In toplevel reorder mode we output all statics; mark them as needed.  */
+  FOR_EACH_VEC_ELT (nodes, i, node)
+    if (node->kind == ORDER_VAR)
+      node->u.v->finalize_named_section_flags ();
 
-       default:
-         gcc_unreachable ();
-       }
-    }
+  FOR_EACH_VEC_ELT (nodes, i, node)
+    node->process ();
 
   symtab->clear_asm_symbols ();
-
-  free (nodes);
 }
 
 static void
@@ -2295,8 +2183,11 @@ ipa_passes (void)
   if (flag_generate_lto || flag_generate_offload)
     targetm.asm_out.lto_start ();
 
-  if (!in_lto_p)
+  if (!in_lto_p
+      || flag_incremental_link == INCREMENTAL_LINK_LTO)
     {
+      if (!quiet_flag)
+       fprintf (stderr, "Streaming LTO\n");
       if (g->have_offload)
        {
          section_name_prefix = OFFLOAD_SECTION_NAME_PREFIX;
@@ -2315,7 +2206,9 @@ ipa_passes (void)
   if (flag_generate_lto || flag_generate_offload)
     targetm.asm_out.lto_end ();
 
-  if (!flag_ltrans && (in_lto_p || !flag_lto || flag_fat_lto_objects))
+  if (!flag_ltrans
+      && ((in_lto_p && flag_incremental_link != INCREMENTAL_LINK_LTO)
+         || !flag_lto || flag_fat_lto_objects))
     execute_ipa_pass_list (passes->all_regular_ipa_passes);
   invoke_plugin_callbacks (PLUGIN_ALL_IPA_PASSES_END, NULL);
 
@@ -2341,13 +2234,9 @@ void
 symbol_table::output_weakrefs (void)
 {
   symtab_node *node;
-  cgraph_node *cnode;
   FOR_EACH_SYMBOL (node)
     if (node->alias
         && !TREE_ASM_WRITTEN (node->decl)
-       && (!(cnode = dyn_cast <cgraph_node *> (node))
-           || !cnode->instrumented_version
-           || !TREE_ASM_WRITTEN (cnode->instrumented_version->decl))
        && node->weakref)
       {
        tree target;
@@ -2384,29 +2273,26 @@ symbol_table::compile (void)
 
   timevar_push (TV_CGRAPHOPT);
   if (pre_ipa_mem_report)
-    {
-      fprintf (stderr, "Memory consumption before IPA\n");
-      dump_memory_report (false);
-    }
+    dump_memory_report ("Memory consumption before IPA");
   if (!quiet_flag)
     fprintf (stderr, "Performing interprocedural optimizations\n");
   state = IPA;
 
-  /* Offloading requires LTO infrastructure.  */
-  if (!in_lto_p && g->have_offload)
-    flag_generate_offload = 1;
-
   /* If LTO is enabled, initialize the streamer hooks needed by GIMPLE.  */
   if (flag_generate_lto || flag_generate_offload)
     lto_streamer_hooks_init ();
 
   /* Don't run the IPA passes if there was any error or sorry messages.  */
   if (!seen_error ())
+  {
+    timevar_start (TV_CGRAPH_IPA_PASSES);
     ipa_passes ();
-
+    timevar_stop (TV_CGRAPH_IPA_PASSES);
+  }
   /* Do nothing else if any IPA pass found errors or if we are just streaming LTO.  */
   if (seen_error ()
-      || (!in_lto_p && flag_lto && !flag_fat_lto_objects))
+      || ((!in_lto_p || flag_incremental_link == INCREMENTAL_LINK_LTO)
+         && flag_lto && !flag_fat_lto_objects))
     {
       timevar_pop (TV_CGRAPHOPT);
       return;
@@ -2416,37 +2302,34 @@ symbol_table::compile (void)
   if (dump_file)
     {
       fprintf (dump_file, "Optimized ");
-      symtab_node:: dump_table (dump_file);
+      symtab->dump (dump_file);
     }
   if (post_ipa_mem_report)
-    {
-      fprintf (stderr, "Memory consumption after IPA\n");
-      dump_memory_report (false);
-    }
+    dump_memory_report ("Memory consumption after IPA");
   timevar_pop (TV_CGRAPHOPT);
 
   /* Output everything.  */
+  switch_to_section (text_section);
   (*debug_hooks->assembly_start) ();
   if (!quiet_flag)
     fprintf (stderr, "Assembling functions:\n");
   symtab_node::checking_verify_symtab_nodes ();
 
-  materialize_all_clones ();
   bitmap_obstack_initialize (NULL);
   execute_ipa_pass_list (g->get_passes ()->all_late_ipa_passes);
   bitmap_obstack_release (NULL);
   mark_functions_to_output ();
 
-  /* When weakref support is missing, we autmatically translate all
+  /* When weakref support is missing, we automatically translate all
      references to NODE to references to its ultimate alias target.
-     The renaming mechanizm uses flag IDENTIFIER_TRANSPARENT_ALIAS and
+     The renaming mechanism uses flag IDENTIFIER_TRANSPARENT_ALIAS and
      TREE_CHAIN.
 
      Set up this mapping before we output any assembler but once we are sure
      that all symbol renaming is done.
 
-     FIXME: All this uglyness can go away if we just do renaming at gimple
-     level by physically rewritting the IL.  At the moment we can only redirect
+     FIXME: All this ugliness can go away if we just do renaming at gimple
+     level by physically rewriting the IL.  At the moment we can only redirect
      calls, so we need infrastructure for renaming references as well.  */
 #ifndef ASM_OUTPUT_WEAKREF
   symtab_node *node;
@@ -2465,16 +2348,15 @@ symbol_table::compile (void)
 
   state = EXPANSION;
 
-  if (!flag_toplevel_reorder)
-    output_in_order (false);
-  else
-    {
-      /* Output first asm statements and anything ordered. The process
-         flag is cleared for these nodes, so we skip them later.  */
-      output_in_order (true);
-      expand_all_functions ();
-      output_variables ();
-    }
+  /* Output first asm statements and anything ordered. The process
+     flag is cleared for these nodes, so we skip them later.  */
+  output_in_order ();
+
+  timevar_start (TV_CGRAPH_FUNC_EXPANSION);
+  expand_all_functions ();
+  timevar_stop (TV_CGRAPH_FUNC_EXPANSION);
+
+  output_variables ();
 
   process_new_functions ();
   state = FINISHED;
@@ -2483,7 +2365,7 @@ symbol_table::compile (void)
   if (dump_file)
     {
       fprintf (dump_file, "\nFinal ");
-      symtab_node::dump_table (dump_file);
+      symtab->dump (dump_file);
     }
   if (!flag_checking)
     return;
@@ -2496,7 +2378,7 @@ symbol_table::compile (void)
       bool error_found = false;
 
       FOR_EACH_DEFINED_FUNCTION (node)
-       if (node->global.inlined_to
+       if (node->inlined_to
            || gimple_has_body_p (node->decl))
          {
            error_found = true;
@@ -2507,6 +2389,89 @@ symbol_table::compile (void)
     }
 }
 
+/* Earlydebug dump file, flags, and number.  */
+
+static int debuginfo_early_dump_nr;
+static FILE *debuginfo_early_dump_file;
+static dump_flags_t debuginfo_early_dump_flags;
+
+/* Debug dump file, flags, and number.  */
+
+static int debuginfo_dump_nr;
+static FILE *debuginfo_dump_file;
+static dump_flags_t debuginfo_dump_flags;
+
+/* Register the debug and earlydebug dump files.  */
+
+void
+debuginfo_early_init (void)
+{
+  gcc::dump_manager *dumps = g->get_dumps ();
+  debuginfo_early_dump_nr = dumps->dump_register (".earlydebug", "earlydebug",
+                                                 "earlydebug", DK_tree,
+                                                 OPTGROUP_NONE,
+                                                 false);
+  debuginfo_dump_nr = dumps->dump_register (".debug", "debug",
+                                            "debug", DK_tree,
+                                            OPTGROUP_NONE,
+                                            false);
+}
+
+/* Initialize the debug and earlydebug dump files.  */
+
+void
+debuginfo_init (void)
+{
+  gcc::dump_manager *dumps = g->get_dumps ();
+  debuginfo_dump_file = dump_begin (debuginfo_dump_nr, NULL);
+  debuginfo_dump_flags = dumps->get_dump_file_info (debuginfo_dump_nr)->pflags;
+  debuginfo_early_dump_file = dump_begin (debuginfo_early_dump_nr, NULL);
+  debuginfo_early_dump_flags
+    = dumps->get_dump_file_info (debuginfo_early_dump_nr)->pflags;
+}
+
+/* Finalize the debug and earlydebug dump files.  */
+
+void
+debuginfo_fini (void)
+{
+  if (debuginfo_dump_file)
+    dump_end (debuginfo_dump_nr, debuginfo_dump_file);
+  if (debuginfo_early_dump_file)
+    dump_end (debuginfo_early_dump_nr, debuginfo_early_dump_file);
+}
+
+/* Set dump_file to the debug dump file.  */
+
+void
+debuginfo_start (void)
+{
+  set_dump_file (debuginfo_dump_file);
+}
+
+/* Undo setting dump_file to the debug dump file.  */
+
+void
+debuginfo_stop (void)
+{
+  set_dump_file (NULL);
+}
+
+/* Set dump_file to the earlydebug dump file.  */
+
+void
+debuginfo_early_start (void)
+{
+  set_dump_file (debuginfo_early_dump_file);
+}
+
+/* Undo setting dump_file to the earlydebug dump file.  */
+
+void
+debuginfo_early_stop (void)
+{
+  set_dump_file (NULL);
+}
 
 /* Analyze the whole compilation unit once it is parsed completely.  */
 
@@ -2548,17 +2513,24 @@ symbol_table::finalize_compilation_unit (void)
   /* Gimplify and lower thunks.  */
   analyze_functions (/*first_time=*/false);
 
+  /* All nested functions should be lowered now.  */
+  nested_function_info::release ();
+
+  /* Offloading requires LTO infrastructure.  */
+  if (!in_lto_p && g->have_offload)
+    flag_generate_offload = 1;
+
   if (!seen_error ())
     {
-      /* Emit early debug for reachable functions, and by consequence,
-        locally scoped symbols.  */
-      struct cgraph_node *cnode;
-      FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (cnode)
-       (*debug_hooks->early_global_decl) (cnode->decl);
+      /* Give the frontends the chance to emit early debug based on
+        what is still reachable in the TU.  */
+      (*lang_hooks.finalize_early_debug) ();
 
       /* Clean up anything that needs cleaning up after initial debug
         generation.  */
-      (*debug_hooks->early_finish) ();
+      debuginfo_early_start ();
+      (*debug_hooks->early_finish) (main_input_filename);
+      debuginfo_early_stop ();
     }
 
   /* Finally drive the pass manager.  */
@@ -2576,7 +2548,6 @@ cgraphunit_c_finalize (void)
   gcc_assert (cgraph_new_nodes.length () == 0);
   cgraph_new_nodes.truncate (0);
 
-  vtable_entry_type = NULL;
   queued_nodes = &symtab_terminator;
 
   first_analyzed = NULL;
@@ -2606,9 +2577,12 @@ cgraph_node::create_wrapper (cgraph_node *target)
   /* Turn alias into thunk and expand it into GIMPLE representation.  */
   definition = true;
 
-  memset (&thunk, 0, sizeof (cgraph_thunk_info));
-  thunk.thunk_p = true;
-  create_edge (target, NULL, count, CGRAPH_FREQ_BASE);
+  /* Create empty thunk, but be sure we did not keep former thunk around.
+     In that case we would need to preserve the info.  */
+  gcc_checking_assert (!thunk_info::get (this));
+  thunk_info::get_create (this);
+  thunk = true;
+  create_edge (target, NULL, count);
   callees->can_throw_external = !TREE_NOTHROW (target->decl);
 
   tree arguments = DECL_ARGUMENTS (decl);
@@ -2619,11 +2593,10 @@ cgraph_node::create_wrapper (cgraph_node *target)
       arguments = TREE_CHAIN (arguments);
     }
 
-  expand_thunk (false, true);
+  expand_thunk (this, false, true);
+  thunk_info::remove (this);
 
   /* Inline summary set-up.  */
   analyze ();
   inline_analyze_function (this);
 }
-
-#include "gt-cgraphunit.h"