LCOV - code coverage report
Current view: top level - gcc/analyzer - region-model.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 92.5 % 4431 4099
Test Date: 2026-12-05 16:10:02 Functions: 92.0 % 324 298
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Classes for modeling the state of memory.
       2              :    Copyright (C) 2019-2026 Free Software Foundation, Inc.
       3              :    Contributed by David Malcolm <dmalcolm@redhat.com>.
       4              : 
       5              : This file is part of GCC.
       6              : 
       7              : GCC is free software; you can redistribute it and/or modify it
       8              : under the terms of the GNU General Public License as published by
       9              : the Free Software Foundation; either version 3, or (at your option)
      10              : any later version.
      11              : 
      12              : GCC is distributed in the hope that it will be useful, but
      13              : WITHOUT ANY WARRANTY; without even the implied warranty of
      14              : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15              : General Public License for more details.
      16              : 
      17              : You should have received a copy of the GNU General Public License
      18              : along with GCC; see the file COPYING3.  If not see
      19              : <http://www.gnu.org/licenses/>.  */
      20              : 
      21              : #define INCLUDE_ALGORITHM
      22              : #include "analyzer/common.h"
      23              : 
      24              : #include "ordered-hash-map.h"
      25              : #include "options.h"
      26              : #include "cgraph.h"
      27              : #include "cfg.h"
      28              : #include "sbitmap.h"
      29              : #include "diagnostics/event-id.h"
      30              : #include "stringpool.h"
      31              : #include "attribs.h"
      32              : #include "tree-object-size.h"
      33              : #include "gimple-ssa.h"
      34              : #include "tree-phinodes.h"
      35              : #include "tree-ssa-operands.h"
      36              : #include "ssa-iterators.h"
      37              : #include "target.h"
      38              : #include "calls.h"
      39              : #include "is-a.h"
      40              : #include "gcc-rich-location.h"
      41              : #include "gcc-urlifier.h"
      42              : #include "diagnostics/sarif-sink.h"
      43              : #include "tree-pretty-print.h"
      44              : #include "fold-const.h"
      45              : #include "selftest-tree.h"
      46              : #include "context.h"
      47              : #include "channels.h"
      48              : #include "value-relation.h"
      49              : #include "range-op.h"
      50              : #include "ipa-utils.h"
      51              : #include "gimple-iterator.h"
      52              : #include "gimple-fold.h"
      53              : #include "attr-fnspec.h"
      54              : 
      55              : #include "diagnostics/markup.h"
      56              : #include "text-art/tree-widget.h"
      57              : 
      58              : #include "analyzer/analyzer-logging.h"
      59              : #include "analyzer/supergraph.h"
      60              : #include "analyzer/call-string.h"
      61              : #include "analyzer/program-point.h"
      62              : #include "analyzer/store.h"
      63              : #include "analyzer/region-model.h"
      64              : #include "analyzer/constraint-manager.h"
      65              : #include "analyzer/sm.h"
      66              : #include "analyzer/pending-diagnostic.h"
      67              : #include "analyzer/region-model-reachability.h"
      68              : #include "analyzer/analyzer-selftests.h"
      69              : #include "analyzer/program-state.h"
      70              : #include "analyzer/call-summary.h"
      71              : #include "analyzer/checker-event.h"
      72              : #include "analyzer/checker-path.h"
      73              : #include "analyzer/feasible-graph.h"
      74              : #include "analyzer/record-layout.h"
      75              : #include "analyzer/function-set.h"
      76              : #include "analyzer/state-transition.h"
      77              : 
      78              : #if ENABLE_ANALYZER
      79              : 
      80              : namespace ana {
      81              : 
      82              : static bool
      83              : unusable_in_infinite_loop_constraint_p (const svalue *sval);
      84              : 
      85              : /* Dump T to PP in language-independent form, for debugging/logging/dumping
      86              :    purposes.  */
      87              : 
      88              : void
      89        16512 : dump_tree (pretty_printer *pp, tree t)
      90              : {
      91        16512 :   dump_generic_node (pp, t, 0, TDF_SLIM, 0);
      92        16512 : }
      93              : 
      94              : /* Dump T to PP in language-independent form in quotes, for
      95              :    debugging/logging/dumping purposes.  */
      96              : 
      97              : void
      98          413 : dump_quoted_tree (pretty_printer *pp, tree t)
      99              : {
     100          413 :   pp_begin_quote (pp, pp_show_color (pp));
     101          413 :   dump_tree (pp, t);
     102          413 :   pp_end_quote (pp, pp_show_color (pp));
     103          413 : }
     104              : 
     105              : /* Equivalent to pp_printf (pp, "%qT", t), to avoid nesting pp_printf
     106              :    calls within other pp_printf calls.
     107              : 
     108              :    default_tree_printer handles 'T' and some other codes by calling
     109              :      dump_generic_node (pp, t, 0, TDF_SLIM, 0);
     110              :    dump_generic_node calls pp_printf in various places, leading to
     111              :    garbled output.
     112              : 
     113              :    Ideally pp_printf could be made to be reentrant, but in the meantime
     114              :    this function provides a workaround.  */
     115              : 
     116              : void
     117         1084 : print_quoted_type (pretty_printer *pp, tree t)
     118              : {
     119         1084 :   if (!t)
     120              :     return;
     121         1071 :   pp_begin_quote (pp, pp_show_color (pp));
     122         1071 :   dump_generic_node (pp, t, 0, TDF_SLIM, 0);
     123         1071 :   pp_end_quote (pp, pp_show_color (pp));
     124              : }
     125              : 
     126              : /* Print EXPR to PP, without quotes.
     127              :    For use within svalue::maybe_print_for_user
     128              :    and region::maybe_print_for_user. */
     129              : 
     130              : void
     131           78 : print_expr_for_user (pretty_printer *pp, tree expr)
     132              : {
     133              :   /* Workaround for C++'s lang_hooks.decl_printable_name,
     134              :      which unhelpfully (for us) prefixes the decl with its
     135              :      type.  */
     136           78 :   if (DECL_P (expr))
     137           78 :     dump_generic_node (pp, expr, 0, TDF_SLIM, 0);
     138              :   else
     139            0 :     pp_printf (pp, "%E", expr);
     140           78 : }
     141              : 
     142              : /* class region_to_value_map.  */
     143              : 
     144              : /* Assignment operator for region_to_value_map.  */
     145              : 
     146              : region_to_value_map &
     147        59363 : region_to_value_map::operator= (const region_to_value_map &other)
     148              : {
     149        59363 :   m_hash_map.empty ();
     150        98922 :   for (auto iter : other.m_hash_map)
     151              :     {
     152        39559 :       const region *reg = iter.first;
     153        39559 :       const svalue *sval = iter.second;
     154        39559 :       m_hash_map.put (reg, sval);
     155              :     }
     156        59363 :   return *this;
     157              : }
     158              : 
     159              : /* Equality operator for region_to_value_map.  */
     160              : 
     161              : bool
     162       427938 : region_to_value_map::operator== (const region_to_value_map &other) const
     163              : {
     164       427938 :   if (m_hash_map.elements () != other.m_hash_map.elements ())
     165              :     return false;
     166              : 
     167       561245 :   for (auto iter : *this)
     168              :     {
     169       136355 :       const region *reg = iter.first;
     170       136355 :       const svalue *sval = iter.second;
     171       136355 :       const svalue * const *other_slot = other.get (reg);
     172       136355 :       if (other_slot == nullptr)
     173          161 :         return false;
     174       136332 :       if (sval != *other_slot)
     175              :         return false;
     176              :     }
     177              : 
     178       424890 :   return true;
     179              : }
     180              : 
     181              : /* Generate a JSON value for this region_to_value_map.
     182              :    This is intended for debugging the analyzer rather than
     183              :    serialization.  */
     184              : 
     185              : std::unique_ptr<json::object>
     186            4 : region_to_value_map::to_json () const
     187              : {
     188            4 :   auto map_obj = std::make_unique<json::object> ();
     189              : 
     190            4 :   auto_vec<const region *> regs;
     191            4 :   for (iterator iter = begin (); iter != end (); ++iter)
     192            0 :     regs.safe_push ((*iter).first);
     193            4 :   regs.qsort (region::cmp_ptr_ptr);
     194              : 
     195            4 :   unsigned i;
     196            4 :   const region *reg;
     197            4 :   FOR_EACH_VEC_ELT (regs, i, reg)
     198              :     {
     199            0 :       label_text reg_desc = reg->get_desc ();
     200            0 :       const svalue *sval = *get (reg);
     201            0 :       map_obj->set (reg_desc.get (), sval->to_json ());
     202            0 :     }
     203              : 
     204            4 :   return map_obj;
     205            4 : }
     206              : 
     207              : std::unique_ptr<text_art::tree_widget>
     208          720 : region_to_value_map::
     209              : make_dump_widget (symbolic::node_dump_state &nds) const
     210              : {
     211          720 :   if (is_empty ())
     212          720 :     return nullptr;
     213              : 
     214            0 :   std::unique_ptr<text_art::tree_widget> w
     215            0 :     (text_art::tree_widget::make (nds, "Dynamic Extents"));
     216              : 
     217            0 :   auto_vec<const region *> regs;
     218            0 :   for (iterator iter = begin (); iter != end (); ++iter)
     219            0 :     regs.safe_push ((*iter).first);
     220            0 :   regs.qsort (region::cmp_ptr_ptr);
     221              : 
     222            0 :   unsigned i;
     223            0 :   const region *reg;
     224            0 :   FOR_EACH_VEC_ELT (regs, i, reg)
     225              :     {
     226            0 :       pretty_printer the_pp;
     227            0 :       pretty_printer * const pp = &the_pp;
     228            0 :       pp_format_decoder (pp) = default_tree_printer;
     229            0 :       const bool simple = true;
     230              : 
     231            0 :       reg->dump_to_pp (pp, simple);
     232            0 :       pp_string (pp, ": ");
     233            0 :       const svalue *sval = *get (reg);
     234            0 :       sval->dump_to_pp (pp, true);
     235            0 :       w->add_child (text_art::tree_widget::make (nds, pp));
     236            0 :     }
     237            0 :   return w;
     238            0 : }
     239              : 
     240              : /* Attempt to merge THIS with OTHER, writing the result
     241              :    to OUT.
     242              : 
     243              :    For now, write (region, value) mappings that are in common between THIS
     244              :    and OTHER to OUT, effectively taking the intersection.
     245              : 
     246              :    Reject merger of different values.  */
     247              : 
     248              : bool
     249        47349 : region_to_value_map::can_merge_with_p (const region_to_value_map &other,
     250              :                                        region_to_value_map *out) const
     251              : {
     252        55316 :   for (auto iter : *this)
     253              :     {
     254        13064 :       const region *iter_reg = iter.first;
     255        13064 :       const svalue *iter_sval = iter.second;
     256        13064 :       const svalue * const * other_slot = other.get (iter_reg);
     257        13064 :       if (other_slot)
     258              :         {
     259        12897 :           if (iter_sval == *other_slot)
     260         7800 :             out->put (iter_reg, iter_sval);
     261              :           else
     262         5097 :             return false;
     263              :         }
     264              :     }
     265        42252 :   return true;
     266              : }
     267              : 
     268              : /* Purge any state involving SVAL.  */
     269              : 
     270              : void
     271        24951 : region_to_value_map::purge_state_involving (const symbolic::node &node)
     272              : {
     273        24951 :   auto_vec<const region *> to_purge;
     274        40899 :   for (auto iter : *this)
     275              :     {
     276        15948 :       const region *iter_reg = iter.first;
     277        15948 :       const svalue *iter_sval = iter.second;
     278        15948 :       if (iter_reg->involves_p (node) || iter_sval->involves_p (node))
     279           12 :         to_purge.safe_push (iter_reg);
     280              :     }
     281        24987 :   for (auto iter : to_purge)
     282           12 :     m_hash_map.remove (iter);
     283        24951 : }
     284              : 
     285              : // struct exception_node
     286              : 
     287              : bool
     288        16068 : exception_node::operator== (const exception_node &other) const
     289              : {
     290        16068 :   return (m_exception_sval == other.m_exception_sval
     291        15774 :           && m_typeinfo_sval == other.m_typeinfo_sval
     292        27566 :           && m_destructor_sval == other.m_destructor_sval);
     293              : }
     294              : 
     295              : DEBUG_FUNCTION void
     296            0 : exception_node::dump () const
     297              : {
     298            0 :   symbolic::dump_node_tree_to_stderr<exception_node> (*this);
     299            0 : }
     300              : 
     301              : void
     302            0 : exception_node::dump_to_logger (logger &log) const
     303              : {
     304            0 :   symbolic::dump_node_tree_to_logger<exception_node> (*this, log);
     305            0 : }
     306              : 
     307              : std::unique_ptr<json::object>
     308            0 : exception_node::to_json () const
     309              : {
     310            0 :   auto obj = std::make_unique<json::object> ();
     311            0 :   obj->set ("exception", m_exception_sval->to_json ());
     312            0 :   obj->set ("typeinfo", m_typeinfo_sval->to_json ());
     313            0 :   obj->set ("destructor", m_destructor_sval->to_json ());
     314            0 :   return obj;
     315              : }
     316              : 
     317              : std::unique_ptr<text_art::tree_widget>
     318            0 : exception_node::make_dump_widget (symbolic::node_dump_state &nds) const
     319              : {
     320            0 :   using text_art::tree_widget;
     321            0 :   std::unique_ptr<tree_widget> w
     322            0 :     (tree_widget::from_fmt (nds, nullptr, "Exception Node"));
     323              : 
     324            0 :   w->add_child (m_exception_sval->make_dump_widget (nds, "exception"));
     325            0 :   w->add_child (m_typeinfo_sval->make_dump_widget (nds, "typeinfo"));
     326            0 :   w->add_child (m_destructor_sval->make_dump_widget (nds, "destructor"));
     327              : 
     328            0 :   return w;
     329              : }
     330              : 
     331              : tree
     332          712 : exception_node::maybe_get_type () const
     333              : {
     334          712 :   return m_typeinfo_sval->maybe_get_type_from_typeinfo ();
     335              : }
     336              : 
     337              : void
     338           70 : exception_node::add_to_reachable_regions (reachable_regions &regs) const
     339              : {
     340           70 :   regs.handle_value (*m_exception_sval);
     341           70 :   regs.handle_value (*m_typeinfo_sval);
     342           70 :   regs.handle_value (*m_destructor_sval);
     343           70 : }
     344              : 
     345              : /* class region_model.  */
     346              : 
     347              : /* Ctor for region_model: construct an "empty" model.  */
     348              : 
     349       197982 : region_model::region_model (symbolic::node_manager &node_mgr)
     350       197982 : : m_node_mgr (node_mgr),
     351       197982 :   m_mgr (&node_mgr.get_region_model_manager ()),
     352       197982 :   m_store (node_mgr),
     353       197982 :   m_current_frame (nullptr),
     354       197982 :   m_thrown_exceptions_stack (),
     355       197982 :   m_caught_exceptions_stack (),
     356       197982 :   m_dynamic_extents ()
     357              : {
     358       197982 :   m_constraints = new constraint_manager (m_mgr);
     359       197982 : }
     360              : 
     361              : /* region_model's copy ctor.  */
     362              : 
     363      2734970 : region_model::region_model (const region_model &other)
     364      2734970 : : m_node_mgr (other.m_node_mgr),
     365      2734970 :   m_mgr (other.m_mgr),
     366      2734970 :   m_store (other.m_store),
     367      2734970 :   m_constraints (new constraint_manager (*other.m_constraints)),
     368      2734970 :   m_current_frame (other.m_current_frame),
     369      2734970 :   m_thrown_exceptions_stack (other.m_thrown_exceptions_stack),
     370      2734970 :   m_caught_exceptions_stack (other.m_caught_exceptions_stack),
     371      2734970 :   m_dynamic_extents (other.m_dynamic_extents)
     372              : {
     373      2734970 : }
     374              : 
     375              : /* region_model's dtor.  */
     376              : 
     377      2932952 : region_model::~region_model ()
     378              : {
     379      2932952 :   delete m_constraints;
     380      2932952 : }
     381              : 
     382              : /* region_model's assignment operator.  */
     383              : 
     384              : region_model &
     385        59363 : region_model::operator= (const region_model &other)
     386              : {
     387              :   /* m_mgr is const.  */
     388        59363 :   gcc_assert (m_mgr == other.m_mgr);
     389              : 
     390        59363 :   m_store = other.m_store;
     391              : 
     392        59363 :   delete m_constraints;
     393        59363 :   m_constraints = new constraint_manager (*other.m_constraints);
     394              : 
     395        59363 :   m_current_frame = other.m_current_frame;
     396              : 
     397        59363 :   m_thrown_exceptions_stack = other.m_thrown_exceptions_stack;
     398        59363 :   m_caught_exceptions_stack = other.m_caught_exceptions_stack;
     399              : 
     400        59363 :   m_dynamic_extents = other.m_dynamic_extents;
     401              : 
     402        59363 :   return *this;
     403              : }
     404              : 
     405              : /* Equality operator for region_model.
     406              : 
     407              :    Amongst other things this directly compares the stores and the constraint
     408              :    managers, so for this to be meaningful both this and OTHER should
     409              :    have been canonicalized.  */
     410              : 
     411              : bool
     412       439243 : region_model::operator== (const region_model &other) const
     413              : {
     414              :   /* We can only compare instances that use the same manager.  */
     415       439243 :   gcc_assert (m_mgr == other.m_mgr);
     416              : 
     417       439243 :   if (m_store != other.m_store)
     418              :     return false;
     419              : 
     420       386372 :   if (*m_constraints != *other.m_constraints)
     421              :     return false;
     422              : 
     423       381619 :   if (m_current_frame != other.m_current_frame)
     424              :     return false;
     425              : 
     426       381611 :   if (m_thrown_exceptions_stack != other.m_thrown_exceptions_stack)
     427              :     return false;
     428       381611 :   if (m_caught_exceptions_stack != other.m_caught_exceptions_stack)
     429              :     return false;
     430              : 
     431       381611 :   if (m_dynamic_extents != other.m_dynamic_extents)
     432              :     return false;
     433              : 
     434       381293 :   gcc_checking_assert (hash () == other.hash ());
     435              : 
     436              :   return true;
     437              : }
     438              : 
     439              : /* Generate a hash value for this region_model.  */
     440              : 
     441              : hashval_t
     442      1180123 : region_model::hash () const
     443              : {
     444      1180123 :   hashval_t result = m_store.hash ();
     445      1180123 :   result ^= m_constraints->hash ();
     446      1180123 :   return result;
     447              : }
     448              : 
     449              : /* Dump a tree-like representation of this region_model to stderr.  */
     450              : 
     451              : DEBUG_FUNCTION void
     452            0 : region_model::dump () const
     453              : {
     454            0 :   symbolic::dump_node_tree_to_stderr<region_model> (*this);
     455            0 : }
     456              : 
     457              : /* Dump a tree-like representation of this region_model to PP.  */
     458              : 
     459              : void
     460           74 : region_model::dump_to_pp (pretty_printer *pp) const
     461              : {
     462           74 :   text_art::theme *theme = global_dc->get_diagram_theme ();
     463           74 :   symbolic::dump_node_tree_to_pp<region_model> (*this, theme, pp, true, true);
     464           74 : }
     465              : 
     466              : /* Dump a tree-like representation of this region_model to LOG.  */
     467              : 
     468              : void
     469            3 : region_model::dump_to_logger (logger &log) const
     470              : {
     471            3 :   symbolic::dump_node_tree_to_logger<region_model> (*this, log);
     472            3 : }
     473              : 
     474              : /* Generate a JSON value for this region_model.
     475              :    This is intended for debugging the analyzer rather than
     476              :    serialization.  */
     477              : 
     478              : std::unique_ptr<json::object>
     479            4 : region_model::to_json () const
     480              : {
     481            4 :   auto model_obj = std::make_unique<json::object> ();
     482            4 :   model_obj->set ("store", m_store.to_json ());
     483            4 :   model_obj->set ("constraints", m_constraints->to_json ());
     484            4 :   if (m_current_frame)
     485            4 :     model_obj->set ("current_frame", m_current_frame->to_json ());
     486              : 
     487            4 :   auto thrown_exceptions_arr = std::make_unique<json::array> ();
     488            4 :   for (auto &node : m_thrown_exceptions_stack)
     489            0 :     thrown_exceptions_arr->append (node.to_json ());
     490            4 :   model_obj->set ("thrown_exception_stack", std::move (thrown_exceptions_arr));
     491              : 
     492            4 :   auto caught_exceptions_arr = std::make_unique<json::array> ();
     493            4 :   for (auto &node : m_caught_exceptions_stack)
     494            0 :     caught_exceptions_arr->append (node.to_json ());
     495            4 :   model_obj->set ("caught_exception_stack", std::move (caught_exceptions_arr));
     496              : 
     497            4 :   model_obj->set ("dynamic_extents", m_dynamic_extents.to_json ());
     498            8 :   return model_obj;
     499            4 : }
     500              : 
     501              : std::unique_ptr<text_art::tree_widget>
     502          720 : region_model::make_dump_widget (symbolic::node_dump_state &nds) const
     503              : {
     504          720 :   using text_art::tree_widget;
     505          720 :   std::unique_ptr<tree_widget> model_widget
     506          720 :     (tree_widget::from_fmt (nds, nullptr, "Region Model"));
     507              : 
     508          720 :   if (m_current_frame)
     509              :     {
     510          693 :       pretty_printer the_pp;
     511          693 :       pretty_printer * const pp = &the_pp;
     512          693 :       pp_format_decoder (pp) = default_tree_printer;
     513          693 :       pp_show_color (pp) = true;
     514          693 :       const bool simple = true;
     515              : 
     516          693 :       pp_string (pp, "Current Frame: ");
     517          693 :       m_current_frame->dump_to_pp (pp, simple);
     518         1386 :       model_widget->add_child (tree_widget::make (nds, pp));
     519          693 :     }
     520              : 
     521          720 :   if (m_thrown_exceptions_stack.size () > 0)
     522              :     {
     523            0 :       auto thrown_exceptions_widget
     524            0 :         = tree_widget::make (nds, "Thrown Exceptions");
     525            0 :       for (auto &thrown_exception : m_thrown_exceptions_stack)
     526            0 :         thrown_exceptions_widget->add_child
     527            0 :           (thrown_exception.make_dump_widget (nds));
     528            0 :       model_widget->add_child (std::move (thrown_exceptions_widget));
     529            0 :     }
     530          720 :   if (m_caught_exceptions_stack.size () > 0)
     531              :     {
     532            0 :       auto caught_exceptions_widget
     533            0 :         = tree_widget::make (nds, "Caught Exceptions");
     534            0 :       for (auto &caught_exception : m_caught_exceptions_stack)
     535            0 :         caught_exceptions_widget->add_child
     536            0 :           (caught_exception.make_dump_widget (nds));
     537            0 :       model_widget->add_child (std::move (caught_exceptions_widget));
     538            0 :     }
     539              : 
     540         1440 :   model_widget->add_child (m_store.make_dump_widget (nds));
     541         1197 :   model_widget->add_child (m_constraints->make_dump_widget (nds));
     542          720 :   model_widget->add_child (m_dynamic_extents.make_dump_widget (nds));
     543          720 :   return model_widget;
     544              : }
     545              : 
     546              : /* Assert that this object is valid.  */
     547              : 
     548              : void
     549      1608030 : region_model::validate () const
     550              : {
     551      1608030 :   m_store.validate ();
     552      1608030 : }
     553              : 
     554              : /* Canonicalize the store and constraints, to maximize the chance of
     555              :    equality between region_model instances.  */
     556              : 
     557              : void
     558       785401 : region_model::canonicalize ()
     559              : {
     560       785401 :   m_store.canonicalize ();
     561       785401 :   m_constraints->canonicalize ();
     562       785401 : }
     563              : 
     564              : /* Return true if this region_model is in canonical form.  */
     565              : 
     566              : bool
     567       373094 : region_model::canonicalized_p () const
     568              : {
     569       373094 :   region_model copy (*this);
     570       373094 :   copy.canonicalize ();
     571       373094 :   return *this == copy;
     572       373094 : }
     573              : 
     574              : /* See the comment for store::loop_replay_fixup.  */
     575              : 
     576              : void
     577         1554 : region_model::loop_replay_fixup (const region_model *dst_state)
     578              : {
     579         1554 :   m_store.loop_replay_fixup (dst_state->get_store (),
     580              :                              get_baseline_state (),
     581         1554 :                              m_mgr);
     582         1554 : }
     583              : 
     584              : /* A subclass of pending_diagnostic for complaining about pointer
     585              :    subtractions involving unrelated buffers.  */
     586              : 
     587              : class undefined_ptrdiff_diagnostic
     588              : : public pending_diagnostic_subclass<undefined_ptrdiff_diagnostic>
     589              : {
     590              : public:
     591              :   /* Region_creation_event subclass to give a custom wording when
     592              :      talking about creation of buffers for LHS and RHS of the
     593              :      subtraction.  */
     594              :   class ptrdiff_region_creation_event : public region_creation_event
     595              :   {
     596              :   public:
     597           56 :     ptrdiff_region_creation_event (const event_loc_info &loc_info,
     598              :                                    bool is_lhs)
     599              :     : region_creation_event (loc_info),
     600           56 :       m_is_lhs (is_lhs)
     601              :     {
     602              :     }
     603              : 
     604          112 :     void print_desc (pretty_printer &pp) const final override
     605              :     {
     606          112 :       if (m_is_lhs)
     607           56 :         pp_string (&pp,
     608              :                    "underlying object for left-hand side"
     609              :                    " of subtraction created here");
     610              :       else
     611           56 :         pp_string (&pp,
     612              :                    "underlying object for right-hand side"
     613              :                    " of subtraction created here");
     614          112 :     }
     615              : 
     616              :   private:
     617              :     bool m_is_lhs;
     618              :   };
     619              : 
     620           64 :   undefined_ptrdiff_diagnostic (const gassign *assign,
     621              :                                 const svalue *sval_a,
     622              :                                 const svalue *sval_b,
     623              :                                 const region *base_reg_a,
     624              :                                 const region *base_reg_b)
     625           64 :   : m_assign (assign),
     626           64 :     m_sval_a (sval_a),
     627           64 :     m_sval_b (sval_b),
     628           64 :     m_base_reg_a (base_reg_a),
     629           64 :     m_base_reg_b (base_reg_b)
     630              :   {
     631           64 :     gcc_assert (m_base_reg_a != m_base_reg_b);
     632              :   }
     633              : 
     634          428 :   const char *get_kind () const final override
     635              :   {
     636          428 :     return "undefined_ptrdiff_diagnostic";
     637              :   }
     638              : 
     639           56 :   bool operator== (const undefined_ptrdiff_diagnostic &other) const
     640              :   {
     641           56 :     return (m_assign == other.m_assign
     642           56 :             && m_sval_a == other.m_sval_a
     643           56 :             && m_sval_b == other.m_sval_b
     644           56 :             && m_base_reg_a == other.m_base_reg_a
     645          112 :             && m_base_reg_b == other.m_base_reg_b);
     646              :   }
     647              : 
     648           84 :   int get_controlling_option () const final override
     649              :   {
     650           84 :     return OPT_Wanalyzer_undefined_behavior_ptrdiff;
     651              :   }
     652              : 
     653           28 :   bool emit (diagnostic_emission_context &ctxt) final override
     654              :   {
     655              :     /* CWE-469: Use of Pointer Subtraction to Determine Size.  */
     656           28 :     ctxt.add_cwe (469);
     657           28 :     return ctxt.warn ("undefined behavior when subtracting pointers");
     658              :   }
     659              : 
     660           56 :   void add_region_creation_events (const region *reg,
     661              :                                    tree /*capacity*/,
     662              :                                    const event_loc_info &loc_info,
     663              :                                    checker_path &emission_path) final override
     664              :   {
     665           56 :     if (reg == m_base_reg_a)
     666           28 :       emission_path.add_event
     667           28 :         (std::make_unique<ptrdiff_region_creation_event> (loc_info, true));
     668           28 :     else if (reg == m_base_reg_b)
     669           28 :       emission_path.add_event
     670           28 :         (std::make_unique<ptrdiff_region_creation_event> (loc_info, false));
     671           56 :   }
     672              : 
     673              :   bool
     674           56 :   describe_final_event (pretty_printer &pp,
     675              :                         const evdesc::final_event &) final override
     676              :   {
     677           56 :     pp_string (&pp,
     678              :                "subtraction of pointers has undefined behavior if"
     679              :                " they do not point into the same array object");
     680           56 :     return true;
     681              :   }
     682              : 
     683           56 :   void mark_interesting_stuff (interesting_t *interesting) final override
     684              :   {
     685           56 :     interesting->add_region_creation (m_base_reg_a);
     686           56 :     interesting->add_region_creation (m_base_reg_b);
     687           56 :   }
     688              : 
     689              : private:
     690              :   const gassign *m_assign;
     691              :   const svalue *m_sval_a;
     692              :   const svalue *m_sval_b;
     693              :   const region *m_base_reg_a;
     694              :   const region *m_base_reg_b;
     695              : };
     696              : 
     697              : /* Locate the parameter with the given index within FNDECL.
     698              :    ARGNUM is zero based, -1 indicates the `this' argument of a method.
     699              :    Return the location of the FNDECL itself if there are problems.  */
     700              : 
     701              : bool
     702           23 : callsite_expr::maybe_get_param_location (tree fndecl,
     703              :                                          location_t *out_loc) const
     704              : {
     705           23 :   gcc_assert (fndecl);
     706              : 
     707           23 :   if (DECL_ARTIFICIAL (fndecl))
     708              :     return false;
     709              : 
     710           23 :   tree param = get_param_tree (fndecl);
     711           23 :   if (!param)
     712              :     return false;
     713              : 
     714           22 :   *out_loc = DECL_SOURCE_LOCATION (param);
     715           22 :   return true;
     716              : }
     717              : 
     718              : /* If this callsite_expr refers to a parameter, get the PARM_DECL from
     719              :    FNDECL.
     720              :    Return NULL_TREE on any problems.  */
     721              : 
     722              : tree
     723           69 : callsite_expr::get_param_tree (tree fndecl) const
     724              : {
     725           69 :   if (!param_p ())
     726              :     return NULL_TREE;
     727              : 
     728           66 :   int i;
     729           66 :   tree param;
     730              : 
     731              :   /* Locate param by index within DECL_ARGUMENTS (fndecl).  */
     732           66 :   for (i = 1, param = DECL_ARGUMENTS (fndecl);
     733          126 :        i < param_num () && param;
     734           60 :        i++, param = TREE_CHAIN (param))
     735              :     ;
     736              : 
     737              :   return param;
     738              : }
     739              : 
     740              : class div_by_zero_diagnostic
     741              : : public pending_diagnostic_subclass<div_by_zero_diagnostic>
     742              : {
     743              : public:
     744           74 :   div_by_zero_diagnostic (const gassign *assign,
     745              :                           const region *divisor_reg)
     746           74 :   : m_assign (assign),
     747           74 :     m_divisor_reg (divisor_reg)
     748              :   {}
     749              : 
     750          409 :   const char *get_kind () const final override
     751              :   {
     752          409 :     return "div_by_zero_diagnostic";
     753              :   }
     754              : 
     755           74 :   bool operator== (const div_by_zero_diagnostic &other) const
     756              :   {
     757           74 :     return m_assign == other.m_assign;
     758              :   }
     759              : 
     760          107 :   int get_controlling_option () const final override
     761              :   {
     762          107 :     return OPT_Wanalyzer_div_by_zero;
     763              :   }
     764              : 
     765           33 :   bool emit (diagnostic_emission_context &ctxt) final override
     766              :   {
     767           33 :     return ctxt.warn ("division by zero");
     768              :   }
     769              : 
     770              :   bool
     771           66 :   describe_final_event (pretty_printer &pp,
     772              :                         const evdesc::final_event &) final override
     773              :   {
     774           66 :     pp_printf (&pp, "division by zero");
     775           66 :     return true;
     776              :   }
     777              : 
     778              :   void
     779           66 :   mark_interesting_stuff (interesting_t *interest) override
     780              :   {
     781           66 :     interest->add_read_region (m_divisor_reg, "divisor zero value");
     782           66 :   }
     783              : 
     784              :   void
     785           57 :   add_function_entry_event (const exploded_edge &eedge,
     786              :                             checker_path *emission_path,
     787              :                             const state_transition_at_call *state_trans)
     788              :                             override
     789              :   {
     790            0 :     class custom_function_entry_event : public function_entry_event
     791              :     {
     792              :     public:
     793           57 :       custom_function_entry_event (const event_loc_info &loc_info,
     794              :                                    const program_state &state,
     795              :                                    const state_transition_at_call *state_trans)
     796              :       : function_entry_event (loc_info,
     797              :                               state,
     798           57 :                               state_trans)
     799              :       {
     800              :       }
     801              : 
     802           72 :       void print_desc (pretty_printer &pp) const override
     803              :       {
     804           72 :         if (auto state_trans = get_state_transition_at_call ())
     805              :           {
     806            4 :             auto expr = state_trans->get_callsite_expr ();
     807            4 :             if (tree parm = expr.get_param_tree (m_effective_fndecl))
     808              :               {
     809            4 :                 auto src_event_id = state_trans->get_src_event_id ();
     810            4 :                 if (src_event_id.known_p ())
     811            4 :                   pp_printf (&pp, "entry to %qE with zero from %@ for %qE",
     812            4 :                              m_effective_fndecl,
     813              :                              &src_event_id,
     814              :                              parm);
     815              :                 else
     816            0 :                   pp_printf (&pp, "entry to %qE with zero for %qE",
     817            0 :                              m_effective_fndecl, parm);
     818            4 :                 return;
     819              :               }
     820              :           }
     821           68 :         return function_entry_event::print_desc (pp);
     822              :       }
     823              :     };
     824              : 
     825           57 :     const exploded_node *dst_node = eedge.m_dest;
     826           57 :     const program_point &dst_point = dst_node->get_point ();
     827           57 :     const program_state &dst_state = dst_node->get_state ();
     828           57 :     auto loc_info {event_loc_info_for_function_entry (dst_point, state_trans)};
     829           57 :     emission_path->add_event
     830           57 :       (std::make_unique<custom_function_entry_event> (loc_info,
     831              :                                                       dst_state,
     832              :                                                       state_trans));
     833           57 :   }
     834              : 
     835              :   bool
     836           44 :   describe_origin_of_state (pretty_printer &pp,
     837              :                             const evdesc::origin_of_state &) final override
     838              :   {
     839           44 :     pp_printf (&pp, "zero value originates here");
     840           44 :     return true;
     841              :   }
     842              : 
     843              :   bool
     844            4 :   describe_call_with_state (pretty_printer &pp,
     845              :                             const evdesc::call_with_state &evd) final override
     846              :   {
     847            4 :     if (evd.m_state_trans)
     848              :       {
     849            4 :         callsite_expr expr = evd.m_state_trans->get_callsite_expr ();
     850            4 :         if (expr.param_p ())
     851              :           {
     852            4 :             if (evd.m_src_event_id.known_p ())
     853            4 :               pp_printf (&pp, "passing zero from %@ from %qE to %qE via parameter %i",
     854              :                          &evd.m_src_event_id,
     855            4 :                          evd.m_caller_fndecl,
     856            4 :                          evd.m_callee_fndecl,
     857              :                          expr.param_num ());
     858              :             else
     859            0 :               pp_printf (&pp, "passing zero from %qE to %qE via parameter %i",
     860            0 :                          evd.m_caller_fndecl,
     861            0 :                          evd.m_callee_fndecl,
     862              :                          expr.param_num ());
     863            4 :             return true;
     864              :           }
     865              :       }
     866              : 
     867              :     return false;
     868              :   }
     869              : 
     870              :   bool
     871           24 :   describe_return_of_state (pretty_printer &pp,
     872              :                             const evdesc::return_of_state &evd) final override
     873              :   {
     874           24 :     if (evd.m_src_event_id.known_p ())
     875           24 :       pp_printf (&pp, "returning zero from %@ from %qE here",
     876              :                  &evd.m_src_event_id,
     877           24 :                  evd.m_callee_fndecl);
     878              :     else
     879            0 :       pp_printf (&pp, "returning zero from %qE here",
     880            0 :                evd.m_callee_fndecl);
     881           24 :     return true;
     882              :   }
     883              : 
     884              :   bool
     885           12 :   describe_copy_of_state (pretty_printer &pp,
     886              :                           const evdesc::copy_of_state &evd) final override
     887              :   {
     888           12 :     if (evd.m_src_event_id.known_p ())
     889           12 :       pp_printf (&pp, "copying zero value from %@ from %qE to %qE",
     890              :                  &evd.m_src_event_id,
     891           12 :                  evd.m_src_reg_expr, evd.m_dst_reg_expr);
     892              :     else
     893            0 :       pp_printf (&pp, "copying zero value from %qE to %qE",
     894            0 :                  evd.m_src_reg_expr, evd.m_dst_reg_expr);
     895           12 :     return true;
     896              :   }
     897              : 
     898              :   bool
     899           16 :   describe_use_of_state (pretty_printer &pp,
     900              :                          const evdesc::use_of_state &evd) final override
     901              :   {
     902           16 :     if (evd.m_src_event_id.known_p ())
     903            8 :       pp_printf (&pp, "using zero value from %@ from %qE",
     904              :                  &evd.m_src_event_id,
     905            8 :                  evd.m_src_reg_expr);
     906              :     else
     907            8 :       pp_printf (&pp, "using zero value from %qE",
     908            8 :                  evd.m_src_reg_expr);
     909           16 :     return true;
     910              :   }
     911              : 
     912              : private:
     913              :   const gassign *m_assign;
     914              :   const region *m_divisor_reg;
     915              : };
     916              : 
     917              : /* Check the pointer subtraction SVAL_A - SVAL_B at ASSIGN and add
     918              :    a warning to CTXT if they're not within the same base region.  */
     919              : 
     920              : static void
     921          624 : check_for_invalid_ptrdiff (const gassign *assign,
     922              :                            region_model_context &ctxt,
     923              :                            const svalue *sval_a, const svalue *sval_b)
     924              : {
     925          624 :   const region *base_reg_a = sval_a->maybe_get_deref_base_region ();
     926          624 :   if (!base_reg_a)
     927          560 :     return;
     928          198 :   const region *base_reg_b = sval_b->maybe_get_deref_base_region ();
     929          198 :   if (!base_reg_b)
     930              :     return;
     931              : 
     932          182 :   if (base_reg_a == base_reg_b)
     933              :     return;
     934              : 
     935           64 :   if (base_reg_a->get_kind () == RK_SYMBOLIC)
     936              :     return;
     937           64 :   if (base_reg_b->get_kind () == RK_SYMBOLIC)
     938              :     return;
     939              : 
     940           64 :   ctxt.warn
     941           64 :     (std::make_unique<undefined_ptrdiff_diagnostic> (assign,
     942              :                                                      sval_a,
     943              :                                                      sval_b,
     944              :                                                      base_reg_a,
     945              :                                                      base_reg_b));
     946              : }
     947              : 
     948              : /* If ASSIGN is a stmt that can be modelled via
     949              :      set_value (lhs_reg, SVALUE, CTXT)
     950              :    for some SVALUE, get the SVALUE.
     951              :    Otherwise return nullptr.  */
     952              : 
     953              : const svalue *
     954       316644 : region_model::get_gassign_result (const gassign *assign,
     955              :                                    region_model_context *ctxt)
     956              : {
     957       316644 :   tree lhs = gimple_assign_lhs (assign);
     958              : 
     959       316644 :   if (gimple_has_volatile_ops (assign)
     960       316644 :       && !gimple_clobber_p (assign))
     961              :     {
     962          116 :       conjured_purge p (this, ctxt);
     963          116 :       return m_mgr->get_or_create_conjured_svalue (TREE_TYPE (lhs),
     964              :                                                    assign,
     965              :                                                    get_lvalue (lhs, ctxt),
     966              :                                                    p);
     967              :     }
     968              : 
     969       316528 :   tree rhs1 = gimple_assign_rhs1 (assign);
     970       316528 :   enum tree_code op = gimple_assign_rhs_code (assign);
     971       316528 :   switch (op)
     972              :     {
     973              :     default:
     974              :       return nullptr;
     975              : 
     976        26641 :     case POINTER_PLUS_EXPR:
     977        26641 :       {
     978              :         /* e.g. "_1 = a_10(D) + 12;" */
     979        26641 :         tree ptr = rhs1;
     980        26641 :         tree offset = gimple_assign_rhs2 (assign);
     981              : 
     982        26641 :         const svalue *ptr_sval = get_rvalue (ptr, ctxt);
     983        26641 :         const svalue *offset_sval = get_rvalue (offset, ctxt);
     984              :         /* Quoting tree.def, "the second operand [of a POINTER_PLUS_EXPR]
     985              :            is an integer of type sizetype".  */
     986        26641 :         offset_sval = m_mgr->get_or_create_cast (size_type_node, offset_sval);
     987              : 
     988        26641 :         const svalue *sval_binop
     989        26641 :           = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
     990              :                                         ptr_sval, offset_sval);
     991        26641 :         return sval_binop;
     992              :       }
     993          696 :       break;
     994              : 
     995          696 :     case POINTER_DIFF_EXPR:
     996          696 :       {
     997              :         /* e.g. "_1 = p_2(D) - q_3(D);".  */
     998          696 :         tree rhs2 = gimple_assign_rhs2 (assign);
     999          696 :         const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
    1000          696 :         const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
    1001              : 
    1002              :         // TODO: perhaps fold to zero if they're known to be equal?
    1003              : 
    1004          696 :         if (ctxt)
    1005          624 :           check_for_invalid_ptrdiff (assign, *ctxt, rhs1_sval, rhs2_sval);
    1006              : 
    1007          696 :         const svalue *sval_binop
    1008          696 :           = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
    1009              :                                         rhs1_sval, rhs2_sval);
    1010          696 :         return sval_binop;
    1011              :       }
    1012       175283 :       break;
    1013              : 
    1014              :     /* Assignments of the form
    1015              :         set_value (lvalue (LHS), rvalue (EXPR))
    1016              :        for various EXPR.
    1017              :        We already have the lvalue for the LHS above, as "lhs_reg".  */
    1018       175283 :     case ADDR_EXPR: /* LHS = &RHS;  */
    1019       175283 :     case BIT_FIELD_REF:
    1020       175283 :     case COMPONENT_REF: /* LHS = op0.op1;  */
    1021       175283 :     case MEM_REF:
    1022       175283 :     case REAL_CST:
    1023       175283 :     case COMPLEX_CST:
    1024       175283 :     case VECTOR_CST:
    1025       175283 :     case INTEGER_CST:
    1026       175283 :     case ARRAY_REF:
    1027       175283 :     case SSA_NAME: /* LHS = VAR; */
    1028       175283 :     case VAR_DECL: /* LHS = VAR; */
    1029       175283 :     case PARM_DECL:/* LHS = VAR; */
    1030       175283 :     case REALPART_EXPR:
    1031       175283 :     case IMAGPART_EXPR:
    1032       175283 :       return get_rvalue (rhs1, ctxt);
    1033              : 
    1034        38214 :     case ABS_EXPR:
    1035        38214 :     case ABSU_EXPR:
    1036        38214 :     case CONJ_EXPR:
    1037        38214 :     case BIT_NOT_EXPR:
    1038        38214 :     case FIX_TRUNC_EXPR:
    1039        38214 :     case FLOAT_EXPR:
    1040        38214 :     case NEGATE_EXPR:
    1041        38214 :     case NOP_EXPR:
    1042        38214 :     case VIEW_CONVERT_EXPR:
    1043        38214 :       {
    1044              :         /* Unary ops.  */
    1045        38214 :         const svalue *rhs_sval = get_rvalue (rhs1, ctxt);
    1046        38214 :         const svalue *sval_unaryop
    1047        38214 :           = m_mgr->get_or_create_unaryop (TREE_TYPE (lhs), op, rhs_sval);
    1048        38214 :         return sval_unaryop;
    1049              :       }
    1050              : 
    1051        16230 :     case EQ_EXPR:
    1052        16230 :     case GE_EXPR:
    1053        16230 :     case LE_EXPR:
    1054        16230 :     case NE_EXPR:
    1055        16230 :     case GT_EXPR:
    1056        16230 :     case LT_EXPR:
    1057        16230 :     case UNORDERED_EXPR:
    1058        16230 :     case ORDERED_EXPR:
    1059        16230 :       {
    1060        16230 :         tree rhs2 = gimple_assign_rhs2 (assign);
    1061              : 
    1062        16230 :         const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
    1063        16230 :         const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
    1064              : 
    1065        16230 :         if (TREE_TYPE (lhs) == boolean_type_node)
    1066              :           {
    1067              :             /* Consider constraints between svalues.  */
    1068              : 
    1069              :             /* Update infinite loop detection before eval_condition
    1070              :                does any folding.  */
    1071        16074 :             if (ctxt && ctxt->checking_for_infinite_loop_p ())
    1072          825 :               if (unusable_in_infinite_loop_constraint_p (rhs1_sval)
    1073        16102 :                   || unusable_in_infinite_loop_constraint_p (rhs2_sval))
    1074           28 :                 ctxt->on_unusable_in_infinite_loop ();
    1075              : 
    1076        16074 :             tristate t = eval_condition (rhs1_sval, op, rhs2_sval);
    1077        16074 :             if (t.is_known ())
    1078         9457 :               return m_mgr->get_or_create_constant_svalue
    1079         9457 :                 (t.is_true () ? boolean_true_node : boolean_false_node);
    1080              :           }
    1081              : 
    1082              :         /* Otherwise, generate a symbolic binary op.  */
    1083         6773 :         const svalue *sval_binop
    1084         6773 :           = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
    1085              :                                         rhs1_sval, rhs2_sval);
    1086         6773 :         return sval_binop;
    1087              :       }
    1088        44722 :       break;
    1089              : 
    1090        44722 :     case PLUS_EXPR:
    1091        44722 :     case MINUS_EXPR:
    1092        44722 :     case MULT_EXPR:
    1093        44722 :     case MULT_HIGHPART_EXPR:
    1094        44722 :     case TRUNC_DIV_EXPR:
    1095        44722 :     case CEIL_DIV_EXPR:
    1096        44722 :     case FLOOR_DIV_EXPR:
    1097        44722 :     case ROUND_DIV_EXPR:
    1098        44722 :     case TRUNC_MOD_EXPR:
    1099        44722 :     case CEIL_MOD_EXPR:
    1100        44722 :     case FLOOR_MOD_EXPR:
    1101        44722 :     case ROUND_MOD_EXPR:
    1102        44722 :     case RDIV_EXPR:
    1103        44722 :     case EXACT_DIV_EXPR:
    1104        44722 :     case LSHIFT_EXPR:
    1105        44722 :     case RSHIFT_EXPR:
    1106        44722 :     case LROTATE_EXPR:
    1107        44722 :     case RROTATE_EXPR:
    1108        44722 :     case BIT_IOR_EXPR:
    1109        44722 :     case BIT_XOR_EXPR:
    1110        44722 :     case BIT_AND_EXPR:
    1111        44722 :     case MIN_EXPR:
    1112        44722 :     case MAX_EXPR:
    1113        44722 :     case COMPLEX_EXPR:
    1114        44722 :       {
    1115              :         /* Binary ops.  */
    1116        44722 :         tree rhs2 = gimple_assign_rhs2 (assign);
    1117              : 
    1118        44722 :         const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
    1119        44722 :         const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
    1120              : 
    1121        44722 :         if (ctxt && (op == LSHIFT_EXPR || op == RSHIFT_EXPR))
    1122              :           {
    1123              :             /* "INT34-C. Do not shift an expression by a negative number of bits
    1124              :                or by greater than or equal to the number of bits that exist in
    1125              :                the operand."  */
    1126         2415 :             if (const tree rhs2_cst = rhs2_sval->maybe_get_constant ())
    1127         2131 :               if (TREE_CODE (rhs2_cst) == INTEGER_CST
    1128         2131 :                   && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
    1129              :                 {
    1130         2129 :                   if (tree_int_cst_sgn (rhs2_cst) < 0)
    1131              :                     {
    1132           24 :                       const region *rhs2_reg
    1133           48 :                         = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
    1134           24 :                       ctxt->warn
    1135           24 :                         (make_shift_count_negative_diagnostic (assign,
    1136              :                                                                rhs2_cst,
    1137              :                                                                rhs2_reg));
    1138              :                     }
    1139         2105 :                   else if (compare_tree_int (rhs2_cst,
    1140         2105 :                                              TYPE_PRECISION (TREE_TYPE (rhs1)))
    1141              :                            >= 0)
    1142              :                     {
    1143           24 :                       const region *rhs2_reg
    1144           48 :                         = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
    1145           48 :                       ctxt->warn (make_shift_count_overflow_diagnostic
    1146           24 :                                   (assign,
    1147           24 :                                    int (TYPE_PRECISION (TREE_TYPE (rhs1))),
    1148              :                                    rhs2_cst,
    1149              :                                    rhs2_reg));
    1150              :                     }
    1151              :                 }
    1152              :           }
    1153              : 
    1154        44722 :         if (op == TRUNC_DIV_EXPR
    1155              :             || op == CEIL_DIV_EXPR
    1156              :             || op == FLOOR_DIV_EXPR
    1157              :             || op == ROUND_DIV_EXPR
    1158              :             || op == TRUNC_MOD_EXPR
    1159              :             || op == CEIL_MOD_EXPR
    1160              :             || op == FLOOR_MOD_EXPR
    1161              :             || op == ROUND_MOD_EXPR
    1162              :             || op == RDIV_EXPR
    1163        44722 :             || op == EXACT_DIV_EXPR)
    1164              :           {
    1165         1197 :             value_range rhs_vr;
    1166         1197 :             if (rhs2_sval->maybe_get_value_range (rhs_vr))
    1167         1091 :               if (rhs_vr.zero_p ())
    1168              :                 {
    1169           74 :                   if (ctxt)
    1170              :                     {
    1171           74 :                       const region *rhs2_reg
    1172          148 :                         = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
    1173           74 :                       ctxt->warn
    1174           74 :                         (std::make_unique<div_by_zero_diagnostic> (assign,
    1175              :                                                                    rhs2_reg));
    1176           74 :                       ctxt->terminate_path ();
    1177              :                     }
    1178           74 :                   return nullptr;
    1179              :                 }
    1180         1197 :           }
    1181              : 
    1182        44648 :         const svalue *sval_binop
    1183        44648 :           = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
    1184              :                                         rhs1_sval, rhs2_sval);
    1185        44648 :         return sval_binop;
    1186              :       }
    1187              : 
    1188              :     /* Vector expressions.  In theory we could implement these elementwise,
    1189              :        but for now, simply return unknown values.  */
    1190            0 :     case VEC_DUPLICATE_EXPR:
    1191            0 :     case VEC_SERIES_EXPR:
    1192            0 :     case VEC_COND_EXPR:
    1193            0 :     case VEC_PERM_EXPR:
    1194            0 :     case VEC_WIDEN_MULT_HI_EXPR:
    1195            0 :     case VEC_WIDEN_MULT_LO_EXPR:
    1196            0 :     case VEC_WIDEN_MULT_EVEN_EXPR:
    1197            0 :     case VEC_WIDEN_MULT_ODD_EXPR:
    1198            0 :     case VEC_UNPACK_HI_EXPR:
    1199            0 :     case VEC_UNPACK_LO_EXPR:
    1200            0 :     case VEC_UNPACK_FLOAT_HI_EXPR:
    1201            0 :     case VEC_UNPACK_FLOAT_LO_EXPR:
    1202            0 :     case VEC_UNPACK_FIX_TRUNC_HI_EXPR:
    1203            0 :     case VEC_UNPACK_FIX_TRUNC_LO_EXPR:
    1204            0 :     case VEC_PACK_TRUNC_EXPR:
    1205            0 :     case VEC_PACK_SAT_EXPR:
    1206            0 :     case VEC_PACK_FIX_TRUNC_EXPR:
    1207            0 :     case VEC_PACK_FLOAT_EXPR:
    1208            0 :     case VEC_WIDEN_LSHIFT_HI_EXPR:
    1209            0 :     case VEC_WIDEN_LSHIFT_LO_EXPR:
    1210            0 :       return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (lhs));
    1211              :     }
    1212              : }
    1213              : 
    1214              : /* Workaround for discarding certain false positives from
    1215              :    -Wanalyzer-use-of-uninitialized-value
    1216              :    of the form:
    1217              :      ((A OR-IF B) OR-IF C)
    1218              :    and:
    1219              :      ((A AND-IF B) AND-IF C)
    1220              :    where evaluating B is redundant, but could involve simple accesses of
    1221              :    uninitialized locals.
    1222              : 
    1223              :    When optimization is turned on the FE can immediately fold compound
    1224              :    conditionals.  Specifically, c_parser_condition parses this condition:
    1225              :      ((A OR-IF B) OR-IF C)
    1226              :    and calls c_fully_fold on the condition.
    1227              :    Within c_fully_fold, fold_truth_andor is called, which bails when
    1228              :    optimization is off, but if any optimization is turned on can convert the
    1229              :      ((A OR-IF B) OR-IF C)
    1230              :    into:
    1231              :      ((A OR B) OR_IF C)
    1232              :    for sufficiently simple B
    1233              :    i.e. the inner OR-IF becomes an OR.
    1234              :    At gimplification time the inner OR becomes BIT_IOR_EXPR (in gimplify_expr),
    1235              :    giving this for the inner condition:
    1236              :       tmp = A | B;
    1237              :       if (tmp)
    1238              :    thus effectively synthesizing a redundant access of B when optimization
    1239              :    is turned on, when compared to:
    1240              :       if (A) goto L1; else goto L4;
    1241              :   L1: if (B) goto L2; else goto L4;
    1242              :   L2: if (C) goto L3; else goto L4;
    1243              :    for the unoptimized case.
    1244              : 
    1245              :    Return true if CTXT appears to be  handling such a short-circuitable stmt,
    1246              :    such as the def-stmt for B for the:
    1247              :       tmp = A | B;
    1248              :    case above, for the case where A is true and thus B would have been
    1249              :    short-circuited without optimization, using MODEL for the value of A.  */
    1250              : 
    1251              : static bool
    1252         1275 : within_short_circuited_stmt_p (const region_model *model,
    1253              :                                const gassign *assign_stmt)
    1254              : {
    1255              :   /* We must have an assignment to a temporary of _Bool type.  */
    1256         1275 :   tree lhs = gimple_assign_lhs (assign_stmt);
    1257         1275 :   if (TREE_TYPE (lhs) != boolean_type_node)
    1258              :     return false;
    1259           40 :   if (TREE_CODE (lhs) != SSA_NAME)
    1260              :     return false;
    1261           40 :   if (SSA_NAME_VAR (lhs) != NULL_TREE)
    1262              :     return false;
    1263              : 
    1264              :   /* The temporary bool must be used exactly once: as the second arg of
    1265              :      a BIT_IOR_EXPR or BIT_AND_EXPR.  */
    1266           40 :   use_operand_p use_op;
    1267           40 :   gimple *use_stmt;
    1268           40 :   if (!single_imm_use (lhs, &use_op, &use_stmt))
    1269              :     return false;
    1270           40 :   const gassign *use_assign = dyn_cast <const gassign *> (use_stmt);
    1271           40 :   if (!use_assign)
    1272              :     return false;
    1273           40 :   enum tree_code op = gimple_assign_rhs_code (use_assign);
    1274           40 :   if (!(op == BIT_IOR_EXPR ||op == BIT_AND_EXPR))
    1275              :     return false;
    1276           28 :   if (!(gimple_assign_rhs1 (use_assign) != lhs
    1277           28 :         && gimple_assign_rhs2 (use_assign) == lhs))
    1278              :     return false;
    1279              : 
    1280              :   /* The first arg of the bitwise stmt must have a known value in MODEL
    1281              :      that implies that the value of the second arg doesn't matter, i.e.
    1282              :      1 for bitwise or, 0 for bitwise and.  */
    1283           28 :   tree other_arg = gimple_assign_rhs1 (use_assign);
    1284              :   /* Use a nullptr ctxt here to avoid generating warnings.  */
    1285           28 :   const svalue *other_arg_sval = model->get_rvalue (other_arg, nullptr);
    1286           28 :   tree other_arg_cst = other_arg_sval->maybe_get_constant ();
    1287           28 :   if (!other_arg_cst)
    1288              :     return false;
    1289           12 :   switch (op)
    1290              :     {
    1291              :     default:
    1292              :       gcc_unreachable ();
    1293           12 :     case BIT_IOR_EXPR:
    1294           12 :       if (zerop (other_arg_cst))
    1295            0 :         return false;
    1296              :       break;
    1297            0 :     case BIT_AND_EXPR:
    1298            0 :       if (!zerop (other_arg_cst))
    1299              :         return false;
    1300              :       break;
    1301              :     }
    1302              : 
    1303              :   /* All tests passed.  We appear to be in a stmt that generates a boolean
    1304              :      temporary with a value that won't matter.  */
    1305              :   return true;
    1306              : }
    1307              : 
    1308              : /* Workaround for discarding certain false positives from
    1309              :    -Wanalyzer-use-of-uninitialized-value
    1310              :    seen with -ftrivial-auto-var-init=.
    1311              : 
    1312              :    -ftrivial-auto-var-init= will generate calls to IFN_DEFERRED_INIT.
    1313              : 
    1314              :    If the address of the var is taken, gimplification will give us
    1315              :    something like:
    1316              : 
    1317              :      _1 = .DEFERRED_INIT (4, 2, &"len"[0]);
    1318              :      len = _1;
    1319              : 
    1320              :    The result of DEFERRED_INIT will be an uninit value; we don't
    1321              :    want to emit a false positive for "len = _1;"
    1322              : 
    1323              :    Return true if ASSIGN_STMT is such a stmt.  */
    1324              : 
    1325              : static bool
    1326         1263 : due_to_ifn_deferred_init_p (const gassign *assign_stmt)
    1327              : 
    1328              : {
    1329              :   /* We must have an assignment to a decl from an SSA name that's the
    1330              :      result of a IFN_DEFERRED_INIT call.  */
    1331         2346 :   if (gimple_assign_rhs_code (assign_stmt) != SSA_NAME)
    1332              :     return false;
    1333          326 :   tree lhs = gimple_assign_lhs (assign_stmt);
    1334          326 :   if (TREE_CODE (lhs) != VAR_DECL)
    1335              :     return false;
    1336          261 :   tree rhs = gimple_assign_rhs1 (assign_stmt);
    1337          261 :   if (TREE_CODE (rhs) != SSA_NAME)
    1338              :     return false;
    1339          261 :   const gimple *def_stmt = SSA_NAME_DEF_STMT (rhs);
    1340          261 :   const gcall *call = dyn_cast <const gcall *> (def_stmt);
    1341          261 :   if (!call)
    1342              :     return false;
    1343          261 :   if (gimple_call_internal_p (call)
    1344          261 :       && gimple_call_internal_fn (call) == IFN_DEFERRED_INIT)
    1345          249 :     return true;
    1346              :   return false;
    1347              : }
    1348              : 
    1349              : const svalue *
    1350         2682 : region_model::complain_about_poison (const svalue *sval,
    1351              :                                      tree expr,
    1352              :                                      const region *src_region,
    1353              :                                      region_model_context *ctxt,
    1354              :                                      enum poison_kind pkind) const
    1355              : {
    1356              :   /* Ignore uninitialized uses of empty types; there's nothing
    1357              :      to initialize.  */
    1358         2682 :   if (pkind == poison_kind::uninit
    1359         2632 :       && sval->get_type ()
    1360         5208 :       && is_empty_type (sval->get_type ()))
    1361              :     return sval;
    1362              : 
    1363         2442 :   if (pkind == poison_kind::uninit)
    1364         2392 :     if (const gimple *curr_stmt = ctxt->get_stmt ())
    1365         1611 :       if (const gassign *assign_stmt
    1366         3456 :           = dyn_cast <const gassign *> (curr_stmt))
    1367              :         {
    1368              :           /* Special case to avoid certain false positives.  */
    1369         1275 :           if (within_short_circuited_stmt_p (this, assign_stmt))
    1370              :             return sval;
    1371              : 
    1372              :           /* Special case to avoid false positive on
    1373              :              -ftrivial-auto-var-init=.  */
    1374         1263 :           if (due_to_ifn_deferred_init_p (assign_stmt))
    1375              :             return sval;
    1376              :         }
    1377              : 
    1378              :   /* If we have an SSA name for a temporary, we don't want to print
    1379              :      '<unknown>'.
    1380              :      Poisoned values are shared by type, and so we can't reconstruct
    1381              :      the tree other than via the def stmts, using
    1382              :      fixup_tree_for_diagnostic.  */
    1383         2181 :   tree diag_arg = fixup_tree_for_diagnostic (expr);
    1384         2181 :   if (src_region == nullptr && pkind == poison_kind::uninit)
    1385         1995 :     src_region = get_region_for_poisoned_expr (expr);
    1386              : 
    1387              :   /* Can we reliably get the poisoned value from "expr"?
    1388              :      This is for use by poisoned_value_diagnostic::check_valid_fpath_p.
    1389              :      Unfortunately, we might not have a reliable value for EXPR.
    1390              :      Hence we only query its value now, and only use it if we get the
    1391              :      poisoned value back again.  */
    1392         2181 :   tree check_expr = expr;
    1393         2181 :   const svalue *foo_sval = get_rvalue (expr, nullptr);
    1394         2181 :   if (foo_sval == sval)
    1395              :     check_expr = expr;
    1396              :   else
    1397          147 :     check_expr = nullptr;
    1398         2181 :   if (ctxt->warn (make_poisoned_value_diagnostic (diag_arg,
    1399              :                                                   pkind,
    1400              :                                                   src_region,
    1401              :                                                   check_expr)))
    1402              :     {
    1403              :       /* We only want to report use of a poisoned value at the first
    1404              :          place it gets used; return an unknown value to avoid generating
    1405              :          a chain of followup warnings.  */
    1406         1407 :       sval = m_mgr->get_or_create_unknown_svalue (sval->get_type ());
    1407              :     }
    1408              : 
    1409              :   return sval;
    1410              : }
    1411              : 
    1412              : /* Check for SVAL being poisoned, adding a warning to CTXT.
    1413              :    Return SVAL, or, if a warning is added, another value, to avoid
    1414              :    repeatedly complaining about the same poisoned value in followup code.
    1415              :    SRC_REGION is a hint about where SVAL came from, and can be nullptr.  */
    1416              : 
    1417              : const svalue *
    1418      2876897 : region_model::check_for_poison (const svalue *sval,
    1419              :                                 tree expr,
    1420              :                                 const region *src_region,
    1421              :                                 region_model_context *ctxt) const
    1422              : {
    1423      2876897 :   if (!ctxt)
    1424              :     return sval;
    1425              : 
    1426              :   // Complain about SVAL being fully poisoned:
    1427      1488660 :   if (auto *sval_from_bv = sval->dyn_cast_svalue_from_bit_vector ())
    1428              :     {
    1429        81988 :       auto &bv = sval_from_bv->get_bit_vector ();
    1430        81988 :       if (auto *poison = bv.dyn_cast_poisoned_bit_vector ())
    1431         2576 :         return complain_about_poison (sval, expr, src_region, ctxt,
    1432         2576 :                                       poison->get_poison_kind ());
    1433              :     }
    1434              : 
    1435              :   return sval;
    1436              : }
    1437              : 
    1438              : void
    1439         4599 : region_model::
    1440              : check_bytes_for_poison (const symbolic::bit_vector &bv,
    1441              :                         symbolic::pointer sym_ptr,
    1442              :                         tree sym_ptr_expr,
    1443              :                         region_model_context *ctxt) const
    1444              : {
    1445         4599 :   if (!ctxt)
    1446          444 :     return;
    1447              : 
    1448              :   // Complain about any poison being found in BV:
    1449         4155 :   auto *sval = m_mgr->get_svalue_from_bit_vector (NULL_TREE, bv);
    1450         4155 :   poison_finder v;
    1451         4155 :   sval->accept_node_visitor (v);
    1452         4155 :   if (v.m_found_poison)
    1453              :     {
    1454          106 :       auto &base_reg = sym_ptr.get_base_region ();
    1455          106 :       auto *byte_offset_sval
    1456          106 :         = m_mgr->get_svalue_from_scalar (size_type_node,
    1457          106 :                                          sym_ptr.get_byte_offset ());
    1458          106 :       auto *byte_size_sval
    1459          106 :         = m_mgr->get_svalue_from_scalar (size_type_node,
    1460          106 :                                          *bv.maybe_get_size_in_bytes ());
    1461              :       
    1462          106 :       auto *src_region = m_mgr->get_sized_region
    1463          106 :         (m_mgr->get_offset_region (&base_reg, NULL_TREE,
    1464              :                                    byte_offset_sval),
    1465              :          NULL_TREE,
    1466              :          byte_size_sval);
    1467          106 :       complain_about_poison (sval, sym_ptr_expr, src_region, ctxt, v.m_pkind);
    1468              :     }
    1469         4155 : }
    1470              : 
    1471              : /* Attempt to get a region for describing EXPR, the source of region of
    1472              :    a poisoned_svalue for use in a poisoned_value_diagnostic.
    1473              :    Return nullptr if there is no good region to use.  */
    1474              : 
    1475              : const region *
    1476         1995 : region_model::get_region_for_poisoned_expr (tree expr) const
    1477              : {
    1478         1995 :   if (TREE_CODE (expr) == SSA_NAME)
    1479              :     {
    1480         1252 :       tree decl = SSA_NAME_VAR (expr);
    1481         1206 :       if (decl && DECL_P (decl))
    1482              :         expr = decl;
    1483              :       else
    1484              :         return nullptr;
    1485              :     }
    1486         1949 :   return get_lvalue (expr, nullptr);
    1487              : }
    1488              : 
    1489              : /* Update this model for the ASSIGN stmt, using CTXT to report any
    1490              :    diagnostics.  */
    1491              : 
    1492              : void
    1493       180392 : region_model::on_assignment (const gassign *assign, region_model_context *ctxt)
    1494              : {
    1495       180392 :   tree lhs = gimple_assign_lhs (assign);
    1496       180392 :   tree rhs1 = gimple_assign_rhs1 (assign);
    1497              : 
    1498       180392 :   const region *lhs_reg = get_lvalue (lhs, ctxt);
    1499              : 
    1500              :   /* Any writes other than to the stack are treated
    1501              :      as externally visible.  */
    1502       180392 :   if (ctxt)
    1503              :     {
    1504       131618 :       memory_space memspace = lhs_reg->get_memory_space ();
    1505       131618 :       if (memspace != memory_space::stack)
    1506        12224 :         ctxt->maybe_did_work ();
    1507              :     }
    1508              : 
    1509              :   /* Most assignments are handled by:
    1510              :        set_value (lhs_reg, SVALUE, CTXT)
    1511              :      for some SVALUE.  */
    1512       180392 :   if (const svalue *sval = get_gassign_result (assign, ctxt))
    1513              :     {
    1514       172246 :       tree expr = get_diagnostic_tree_for_gassign (assign);
    1515       172246 :       check_for_poison (sval, expr, nullptr, ctxt);
    1516       172246 :       set_value (lhs_reg, sval, ctxt);
    1517       172246 :       return;
    1518              :     }
    1519              : 
    1520         8146 :   enum tree_code op = gimple_assign_rhs_code (assign);
    1521         8146 :   switch (op)
    1522              :     {
    1523           37 :     default:
    1524           37 :       {
    1525           37 :         if (0)
    1526              :           sorry_at (assign->location, "unhandled assignment op: %qs",
    1527              :                     get_tree_code_name (op));
    1528           37 :         const svalue *unknown_sval
    1529           37 :           = m_mgr->get_or_create_unknown_svalue (TREE_TYPE (lhs));
    1530           37 :         set_value (lhs_reg, unknown_sval, ctxt);
    1531              :       }
    1532           37 :       break;
    1533              : 
    1534         7548 :     case CONSTRUCTOR:
    1535         7548 :       {
    1536         7548 :         if (TREE_CLOBBER_P (rhs1))
    1537              :           {
    1538              :             /* e.g. "x ={v} {CLOBBER};"  */
    1539         7380 :             clobber_region (lhs_reg);
    1540              :           }
    1541              :         else
    1542              :           {
    1543              :             /* Any CONSTRUCTOR that survives to this point is either
    1544              :                just a zero-init of everything, or a vector.  */
    1545          168 :             if (!CONSTRUCTOR_NO_CLEARING (rhs1))
    1546          168 :               zero_fill_region (lhs_reg, ctxt);
    1547          168 :             unsigned ix;
    1548          168 :             tree index;
    1549          168 :             tree val;
    1550          330 :             FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (rhs1), ix, index, val)
    1551              :               {
    1552          162 :                 gcc_assert (TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE);
    1553          162 :                 if (!index)
    1554           22 :                   index = build_int_cst (integer_type_node, ix);
    1555          162 :                 gcc_assert (TREE_CODE (index) == INTEGER_CST);
    1556          162 :                 const svalue *index_sval
    1557          162 :                   = m_mgr->get_or_create_constant_svalue (index);
    1558          162 :                 gcc_assert (index_sval);
    1559          162 :                 const region *sub_reg
    1560          162 :                   = m_mgr->get_element_region (lhs_reg,
    1561          162 :                                                TREE_TYPE (val),
    1562              :                                                index_sval);
    1563          162 :                 const svalue *val_sval = get_rvalue (val, ctxt);
    1564          162 :                 set_value (sub_reg, val_sval, ctxt);
    1565              :               }
    1566              :           }
    1567              :       }
    1568              :       break;
    1569              : 
    1570          561 :     case STRING_CST:
    1571          561 :       {
    1572              :         /* e.g. "struct s2 x = {{'A', 'B', 'C', 'D'}};".  */
    1573          561 :         const svalue *rhs_sval = get_rvalue (rhs1, ctxt);
    1574          561 :         set_value (lhs_reg, rhs_sval, ctxt);
    1575              :       }
    1576          561 :       break;
    1577              :     }
    1578              : }
    1579              : 
    1580              : /* Handle the pre-sm-state part of STMT, modifying this object in-place.
    1581              :    Write true to *OUT_UNKNOWN_SIDE_EFFECTS if the stmt has unknown
    1582              :    side effects.  */
    1583              : 
    1584              : void
    1585       258649 : region_model::on_stmt_pre (const gimple *stmt,
    1586              :                            bool *out_unknown_side_effects,
    1587              :                            region_model_context *ctxt)
    1588              : {
    1589       258649 :   switch (gimple_code (stmt))
    1590              :     {
    1591              :     case GIMPLE_COND:
    1592              :     case GIMPLE_EH_DISPATCH:
    1593              :     case GIMPLE_GOTO:
    1594              :     case GIMPLE_LABEL:
    1595              :     case GIMPLE_NOP:
    1596              :     case GIMPLE_PREDICT:
    1597              :     case GIMPLE_RESX:
    1598              :     case GIMPLE_SWITCH:
    1599              :       /* No-ops here.  */
    1600              :       break;
    1601              : 
    1602       180392 :     case GIMPLE_ASSIGN:
    1603       180392 :       {
    1604       180392 :         const gassign *assign = as_a <const gassign *> (stmt);
    1605       180392 :         on_assignment (assign, ctxt);
    1606              :       }
    1607       180392 :       break;
    1608              : 
    1609          384 :     case GIMPLE_ASM:
    1610          384 :       {
    1611          384 :         const gasm *asm_stmt = as_a <const gasm *> (stmt);
    1612          384 :         on_asm_stmt (asm_stmt, ctxt);
    1613          384 :         if (ctxt)
    1614          342 :           ctxt->maybe_did_work ();
    1615              :       }
    1616              :       break;
    1617              : 
    1618        74445 :     case GIMPLE_CALL:
    1619        74445 :       {
    1620              :         /* Track whether we have a gcall to a function that's not recognized by
    1621              :            anything, for which we don't have a function body, or for which we
    1622              :            don't know the fndecl.  */
    1623        74445 :         const gcall *call = as_a <const gcall *> (stmt);
    1624        74445 :         *out_unknown_side_effects = on_call_pre (*call, ctxt);
    1625              :       }
    1626        74445 :       break;
    1627              : 
    1628            0 :     case GIMPLE_RETURN:
    1629            0 :       {
    1630            0 :         const greturn *return_ = as_a <const greturn *> (stmt);
    1631            0 :         on_return (return_, ctxt);
    1632              :       }
    1633            0 :       break;
    1634              : 
    1635              :     /* We don't expect to see any other statement kinds in the analyzer.  */
    1636            0 :     case GIMPLE_DEBUG: // should have stripped these out when building the supergraph
    1637            0 :     default:
    1638            0 :       internal_error ("unexpected gimple stmt code: %qs",
    1639            0 :                       gimple_code_name[gimple_code (stmt)]);
    1640       258649 :       break;
    1641              :     }
    1642       258649 : }
    1643              : 
    1644              : /* Given a call CD with function attribute FORMAT_ATTR, check that the
    1645              :    format arg to the call is a valid null-terminated string.  */
    1646              : 
    1647              : void
    1648         1064 : region_model::check_call_format_attr (const call_details &cd,
    1649              :                                       tree format_attr) const
    1650              : {
    1651              :   /* We assume that FORMAT_ATTR has already been validated.  */
    1652              : 
    1653              :   /* arg0 of the attribute should be kind of format strings
    1654              :      that this function expects (e.g. "printf").  */
    1655         1064 :   const tree arg0_tree_list = TREE_VALUE (format_attr);
    1656         1064 :   if (!arg0_tree_list)
    1657            0 :     return;
    1658              : 
    1659              :   /* arg1 of the attribute should be the 1-based parameter index
    1660              :      to treat as the format string.  */
    1661         1064 :   const tree arg1_tree_list = TREE_CHAIN (arg0_tree_list);
    1662         1064 :   if (!arg1_tree_list)
    1663              :     return;
    1664         1064 :   const tree arg1_value = TREE_VALUE (arg1_tree_list);
    1665         1064 :   if (!arg1_value)
    1666              :     return;
    1667              : 
    1668         1064 :   unsigned format_arg_idx = TREE_INT_CST_LOW (arg1_value) - 1;
    1669         1064 :   if (cd.num_args () <= format_arg_idx)
    1670              :     return;
    1671              : 
    1672              :   /* Subclass of annotating_context that
    1673              :      adds a note about the format attr to any saved diagnostics.  */
    1674         1064 :   class annotating_ctxt : public annotating_context
    1675              :   {
    1676              :   public:
    1677         1064 :     annotating_ctxt (const call_details &cd,
    1678              :                      unsigned fmt_param_idx)
    1679              :     : annotating_context (cd.get_ctxt ()),
    1680         1064 :       m_cd (cd),
    1681         1064 :       m_fmt_param_idx (fmt_param_idx)
    1682              :     {
    1683              :     }
    1684           13 :     void add_annotations () final override
    1685              :     {
    1686            0 :       class reason_format_attr
    1687              :         : public pending_note_subclass<reason_format_attr>
    1688              :       {
    1689              :       public:
    1690           13 :         reason_format_attr (const call_arg_details &arg_details)
    1691           13 :           : m_arg_details (arg_details)
    1692              :         {
    1693              :         }
    1694              : 
    1695           74 :         const char *get_kind () const final override
    1696              :         {
    1697           74 :           return "reason_format_attr";
    1698              :         }
    1699              : 
    1700           13 :         void emit () const final override
    1701              :         {
    1702           13 :           inform (DECL_SOURCE_LOCATION (m_arg_details.m_called_fndecl),
    1703              :                   "parameter %i of %qD marked as a format string"
    1704              :                   " via %qs attribute",
    1705           13 :                   m_arg_details.m_arg_idx + 1, m_arg_details.m_called_fndecl,
    1706              :                   "format");
    1707           13 :         }
    1708              : 
    1709           37 :         bool operator== (const reason_format_attr &other) const
    1710              :         {
    1711           37 :           return m_arg_details == other.m_arg_details;
    1712              :         }
    1713              : 
    1714              :       private:
    1715              :         call_arg_details m_arg_details;
    1716              :       };
    1717              : 
    1718           13 :       call_arg_details arg_details (m_cd, m_fmt_param_idx);
    1719           13 :       add_note (std::make_unique<reason_format_attr> (arg_details));
    1720           13 :     }
    1721              :   private:
    1722              :     const call_details &m_cd;
    1723              :     unsigned m_fmt_param_idx;
    1724              :   };
    1725              : 
    1726         1064 :   annotating_ctxt my_ctxt (cd, format_arg_idx);
    1727         1064 :   call_details my_cd (cd, &my_ctxt);
    1728         1064 :   my_cd.check_for_null_terminated_string_arg (format_arg_idx);
    1729              : }
    1730              : 
    1731              : /* Ensure that all arguments at the call described by CD are checked
    1732              :    for poisoned values, by calling get_rvalue on each argument.
    1733              : 
    1734              :    Check that calls to functions with "format" attribute have valid
    1735              :    null-terminated strings for their format argument.  */
    1736              : 
    1737              : void
    1738        49051 : region_model::check_call_args (const call_details &cd) const
    1739              : {
    1740       111711 :   for (unsigned arg_idx = 0; arg_idx < cd.num_args (); arg_idx++)
    1741        62660 :     cd.get_arg_svalue (arg_idx);
    1742              : 
    1743              :   /* Handle attribute "format".  */
    1744        49051 :   if (tree format_attr = cd.lookup_function_attribute ("format"))
    1745         1064 :     check_call_format_attr (cd, format_attr);
    1746        49051 : }
    1747              : 
    1748              : /* Update this model for an outcome of a call that returns a specific
    1749              :    integer constant.
    1750              :    If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
    1751              :    the state-merger code from merging success and failure outcomes.  */
    1752              : 
    1753              : void
    1754          777 : region_model::update_for_int_cst_return (const call_details &cd,
    1755              :                                          int retval,
    1756              :                                          bool unmergeable)
    1757              : {
    1758          777 :   if (!cd.get_lhs_type ())
    1759              :     return;
    1760          537 :   if (TREE_CODE (cd.get_lhs_type ()) != INTEGER_TYPE)
    1761              :     return;
    1762          537 :   const svalue *result
    1763          537 :     = m_mgr->get_or_create_int_cst (cd.get_lhs_type (), retval);
    1764          537 :   if (unmergeable)
    1765          537 :     result = m_mgr->get_or_create_unmergeable (result);
    1766          537 :   set_value (cd.get_lhs_region (), result, cd.get_ctxt ());
    1767              : }
    1768              : 
    1769              : /* Update this model for an outcome of a call that returns zero.
    1770              :    If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
    1771              :    the state-merger code from merging success and failure outcomes.  */
    1772              : 
    1773              : void
    1774          244 : region_model::update_for_zero_return (const call_details &cd,
    1775              :                                       bool unmergeable)
    1776              : {
    1777          244 :   update_for_int_cst_return (cd, 0, unmergeable);
    1778          244 : }
    1779              : 
    1780              : /* Update this model for an outcome of a call that returns a NULL
    1781              :    pointer.
    1782              :    If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
    1783              :    the state-merger code from merging success and failure outcomes.  */
    1784              : 
    1785              : void
    1786           15 : region_model::update_for_null_return (const call_details &cd, bool unmergeable)
    1787              : {
    1788           15 :   if (!cd.get_lhs_type ())
    1789              :     return;
    1790            3 :   if (!POINTER_TYPE_P (cd.get_lhs_type ()))
    1791              :     return;
    1792            3 :   const svalue *result = m_mgr->get_or_create_null_ptr (cd.get_lhs_type ());
    1793            3 :   if (unmergeable)
    1794            3 :     result = m_mgr->get_or_create_unmergeable (result);
    1795            3 :   set_value (cd.get_lhs_region (), result, cd.get_ctxt ());
    1796              : }
    1797              : 
    1798              : /* Update this model for an outcome of a call that returns non-zero.
    1799              :    Specifically, assign an svalue to the LHS, and add a constraint that
    1800              :    that svalue is non-zero.  */
    1801              : 
    1802              : void
    1803          134 : region_model::update_for_nonzero_return (const call_details &cd)
    1804              : {
    1805          134 :   if (!cd.get_lhs_type ())
    1806              :     return;
    1807           98 :   if (TREE_CODE (cd.get_lhs_type ()) != INTEGER_TYPE)
    1808              :     return;
    1809           98 :   cd.set_any_lhs_with_defaults ();
    1810           98 :   const svalue *zero
    1811           98 :     = m_mgr->get_or_create_int_cst (cd.get_lhs_type (), 0);
    1812           98 :   const svalue *result
    1813           98 :     = get_store_value (cd.get_lhs_region (), cd.get_ctxt ());
    1814           98 :   add_constraint (result, NE_EXPR, zero, cd.get_ctxt ());
    1815              : }
    1816              : 
    1817              : /* Subroutine of region_model::maybe_get_copy_bounds.
    1818              :    The Linux kernel commonly uses
    1819              :      min_t([unsigned] long, VAR, sizeof(T));
    1820              :    to set an upper bound on the size of a copy_to_user.
    1821              :    Attempt to simplify such sizes by trying to get the upper bound as a
    1822              :    constant.
    1823              :    Return the simplified svalue if possible, or nullptr otherwise.  */
    1824              : 
    1825              : static const svalue *
    1826           48 : maybe_simplify_upper_bound (const svalue *num_bytes_sval,
    1827              :                             region_model_manager *mgr)
    1828              : {
    1829           48 :   tree type = num_bytes_sval->get_type ();
    1830           69 :   while (const svalue *raw = num_bytes_sval->maybe_undo_cast ())
    1831              :     num_bytes_sval = raw;
    1832           48 :   if (const binop_svalue *binop_sval = num_bytes_sval->dyn_cast_binop_svalue ())
    1833           34 :     if (binop_sval->get_op () == MIN_EXPR)
    1834           10 :       if (binop_sval->get_arg1 ()->get_kind () == SK_CONSTANT)
    1835              :         {
    1836           10 :           return mgr->get_or_create_cast (type, binop_sval->get_arg1 ());
    1837              :           /* TODO: we might want to also capture the constraint
    1838              :              when recording the diagnostic, or note that we're using
    1839              :              the upper bound.  */
    1840              :         }
    1841              :   return nullptr;
    1842              : }
    1843              : 
    1844              : /* Attempt to get an upper bound for the size of a copy when simulating a
    1845              :    copy function.
    1846              : 
    1847              :    NUM_BYTES_SVAL is the symbolic value for the size of the copy.
    1848              :    Use it if it's constant, otherwise try to simplify it.  Failing
    1849              :    that, use the size of SRC_REG if constant.
    1850              : 
    1851              :    Return a symbolic value for an upper limit on the number of bytes
    1852              :    copied, or nullptr if no such value could be determined.  */
    1853              : 
    1854              : const svalue *
    1855          151 : region_model::maybe_get_copy_bounds (const region *src_reg,
    1856              :                                      const svalue *num_bytes_sval)
    1857              : {
    1858          151 :   if (num_bytes_sval->maybe_get_constant ())
    1859              :     return num_bytes_sval;
    1860              : 
    1861           96 :   if (const svalue *simplified
    1862           48 :       = maybe_simplify_upper_bound (num_bytes_sval, m_mgr))
    1863           10 :     num_bytes_sval = simplified;
    1864              : 
    1865           48 :   if (num_bytes_sval->maybe_get_constant ())
    1866              :     return num_bytes_sval;
    1867              : 
    1868              :   /* For now, try just guessing the size as the capacity of the
    1869              :      base region of the src.
    1870              :      This is a hack; we might get too large a value.  */
    1871           38 :   const region *src_base_reg = src_reg->get_base_region ();
    1872           38 :   num_bytes_sval = get_capacity (src_base_reg);
    1873              : 
    1874           38 :   if (num_bytes_sval->maybe_get_constant ())
    1875            4 :     return num_bytes_sval;
    1876              : 
    1877              :   /* Non-constant: give up. */
    1878              :   return nullptr;
    1879              : }
    1880              : 
    1881              : /* Get any known_function for FNDECL for call CD.
    1882              : 
    1883              :    The call must match all assumptions made by the known_function (such as
    1884              :    e.g. "argument 1's type must be a pointer type").
    1885              : 
    1886              :    Return nullptr if no known_function is found, or it does not match the
    1887              :    assumption(s).  */
    1888              : 
    1889              : const known_function *
    1890       298096 : region_model::get_known_function (tree fndecl, const call_details &cd) const
    1891              : {
    1892       298096 :   known_function_manager *known_fn_mgr = m_mgr->get_known_function_manager ();
    1893       298096 :   return known_fn_mgr->get_match (fndecl, cd);
    1894              : }
    1895              : 
    1896              : /* Get any known_function for IFN, or nullptr.  */
    1897              : 
    1898              : const known_function *
    1899         1436 : region_model::get_known_function (enum internal_fn ifn) const
    1900              : {
    1901         1436 :   known_function_manager *known_fn_mgr = m_mgr->get_known_function_manager ();
    1902         1436 :   return known_fn_mgr->get_internal_fn (ifn);
    1903              : }
    1904              : 
    1905              : /* Get any builtin_known_function for CALL and emit any warning to CTXT
    1906              :    if not nullptr.
    1907              : 
    1908              :    The call must match all assumptions made by the known_function (such as
    1909              :    e.g. "argument 1's type must be a pointer type").
    1910              : 
    1911              :    Return nullptr if no builtin_known_function is found, or it does
    1912              :    not match the assumption(s).
    1913              : 
    1914              :    Internally calls get_known_function to find a known_function and cast it
    1915              :    to a builtin_known_function.
    1916              : 
    1917              :    For instance, calloc is a C builtin, defined in gcc/builtins.def
    1918              :    by the DEF_LIB_BUILTIN macro. Such builtins are recognized by the
    1919              :    analyzer by their name, so that even in C++ or if the user redeclares
    1920              :    them but mismatch their signature, they are still recognized as builtins.
    1921              : 
    1922              :    Cases when a supposed builtin is not flagged as one by the FE:
    1923              : 
    1924              :     The C++ FE does not recognize calloc as a builtin if it has not been
    1925              :     included from a standard header, but the C FE does. Hence in C++ if
    1926              :     CALL comes from a calloc and stdlib is not included,
    1927              :     gcc/tree.h:fndecl_built_in_p (CALL) would be false.
    1928              : 
    1929              :     In C code, a __SIZE_TYPE__ calloc (__SIZE_TYPE__, __SIZE_TYPE__) user
    1930              :     declaration has obviously a mismatching signature from the standard, and
    1931              :     its function_decl tree won't be unified by
    1932              :     gcc/c-decl.cc:match_builtin_function_types.
    1933              : 
    1934              :    Yet in both cases the analyzer should treat the calls as a builtin calloc
    1935              :    so that extra attributes unspecified by the standard but added by GCC
    1936              :    (e.g. sprintf attributes in gcc/builtins.def), useful for the detection of
    1937              :    dangerous behavior, are indeed processed.
    1938              : 
    1939              :    Therefore for those cases when a "builtin flag" is not added by the FE,
    1940              :    builtins' kf are derived from builtin_known_function, whose method
    1941              :    builtin_known_function::builtin_decl returns the builtin's
    1942              :    function_decl tree as defined in gcc/builtins.def, with all the extra
    1943              :    attributes.  */
    1944              : 
    1945              : const builtin_known_function *
    1946       163256 : region_model::get_builtin_kf (const gcall &call,
    1947              :                                region_model_context *ctxt /* = nullptr */) const
    1948              : {
    1949       163256 :   region_model *mut_this = const_cast <region_model *> (this);
    1950       163256 :   tree callee_fndecl = mut_this->get_fndecl_for_call (call, ctxt);
    1951       163256 :   if (! callee_fndecl)
    1952              :     return nullptr;
    1953              : 
    1954       163256 :   call_details cd (call, mut_this, ctxt);
    1955       163256 :   if (const known_function *kf = get_known_function (callee_fndecl, cd))
    1956       112533 :     return kf->dyn_cast_builtin_kf ();
    1957              : 
    1958              :   return nullptr;
    1959              : }
    1960              : 
    1961              : /* Subclass of custom_edge_info for use by exploded_edges that represent
    1962              :    an exception being thrown from a call we don't have the code for.  */
    1963              : 
    1964              : class exception_thrown_from_unrecognized_call : public custom_edge_info
    1965              : {
    1966              : public:
    1967         5515 :   exception_thrown_from_unrecognized_call (const gcall &call,
    1968              :                                            tree fndecl)
    1969         5515 :   : m_call (call),
    1970         5515 :     m_fndecl (fndecl)
    1971              :   {
    1972              :   }
    1973              : 
    1974           12 :   void print (pretty_printer *pp) const final override
    1975              :   {
    1976           12 :     if (m_fndecl)
    1977           12 :       pp_printf (pp, "if %qD throws an exception...", m_fndecl);
    1978              :     else
    1979            0 :       pp_printf (pp, "if the called function throws an exception...");
    1980           12 :   };
    1981              : 
    1982              :   bool
    1983         5578 :   update_model (region_model *model,
    1984              :                 const exploded_edge *,
    1985              :                 region_model_context *ctxt) const final override
    1986              :   {
    1987              :     /* Allocate an exception and set it as the current exception.  */
    1988         5578 :     const region *exception_reg
    1989              :       = model->get_or_create_region_for_heap_alloc
    1990         5578 :           (nullptr, /* We don't know the size of the region.  */
    1991              :            ctxt);
    1992              : 
    1993         5578 :     region_model_manager *mgr = model->get_manager ();
    1994         5578 :     conjured_purge p (model, ctxt);
    1995              : 
    1996              :     /* Conjure a bit_contents for the exception region.  */
    1997         5578 :     auto &bc_mgr = mgr->get_node_manager ().get_bit_contents_manager ();
    1998        11156 :     auto &exception_bc = bc_mgr.get_conjured_bit_contents (*exception_reg,
    1999         5578 :                                                            &m_call,
    2000              :                                                            p, 0);
    2001         5578 :     model->set_bit_contents_raw (*exception_reg, exception_bc);
    2002              : 
    2003         5578 :     const svalue *exception_ptr_sval
    2004         5578 :       = mgr->get_ptr_svalue (ptr_type_node, exception_reg);
    2005         5578 :     const svalue *tinfo_sval
    2006        11156 :       = mgr->get_or_create_conjured_svalue (ptr_type_node,
    2007         5578 :                                             &m_call,
    2008              :                                             exception_reg, p, 1);
    2009         5578 :     const svalue *destructor_sval
    2010        11156 :       = mgr->get_or_create_conjured_svalue (ptr_type_node,
    2011         5578 :                                             &m_call,
    2012              :                                             exception_reg, p, 2);
    2013              : 
    2014              :     /* Push a new exception_node on the model's thrown exception stack.  */
    2015         5578 :     exception_node eh_node (exception_ptr_sval, tinfo_sval, destructor_sval);
    2016         5578 :     model->push_thrown_exception (eh_node);
    2017              : 
    2018         5578 :     return true;
    2019              :   }
    2020              : 
    2021              :   void
    2022           35 :   add_events_to_path (checker_path *emission_path,
    2023              :                       const exploded_edge &eedge,
    2024              :                       pending_diagnostic &,
    2025              :                       const state_transition *) const final override
    2026              :   {
    2027           35 :     const exploded_node *dst_node = eedge.m_dest;
    2028           35 :     const program_point &dst_point = dst_node->get_point ();
    2029           35 :     const int dst_stack_depth = dst_point.get_stack_depth ();
    2030              : 
    2031           35 :     emission_path->add_event
    2032           35 :       (std::make_unique<throw_from_call_to_external_fn_event>
    2033           35 :          (event_loc_info (m_call.location,
    2034              :                           dst_point.get_fndecl (),
    2035           35 :                           dst_stack_depth),
    2036              :           dst_node,
    2037              :           m_call,
    2038           35 :           m_fndecl));
    2039           35 :   }
    2040              : 
    2041              :   exploded_node *
    2042         5408 :   create_enode (exploded_graph &eg,
    2043              :                 const program_point &point,
    2044              :                 program_state &&state,
    2045              :                 exploded_node *enode_for_diag,
    2046              :                 region_model_context *ctxt) const final override
    2047              :   {
    2048         5408 :     exploded_node *thrown_enode
    2049         5408 :       = eg.get_or_create_node (point, state, enode_for_diag,
    2050              :                                /* Don't add to worklist.  */
    2051              :                                false);
    2052         5408 :     if (!thrown_enode)
    2053              :       return nullptr;
    2054              : 
    2055              :     /* Add successor edges for thrown_enode "by hand" for the exception.  */
    2056         5378 :     eg.unwind_from_exception (*thrown_enode,
    2057         5378 :                               &m_call,
    2058              :                               ctxt);
    2059         5378 :     return thrown_enode;
    2060              :   }
    2061              : 
    2062              : private:
    2063              :   const gcall &m_call;
    2064              :   tree m_fndecl; // could be null
    2065              : };
    2066              : 
    2067              : /* Get a set of functions that are assumed to not throw exceptions.  */
    2068              : 
    2069              : static function_set
    2070         5385 : get_fns_assumed_not_to_throw ()
    2071              : {
    2072              :   // TODO: populate this list more fully
    2073         5385 :   static const char * const fn_names[] = {
    2074              :     /* This array must be kept sorted.  */
    2075              : 
    2076              :     "fclose"
    2077              :   };
    2078         5385 :   const size_t count = ARRAY_SIZE (fn_names);
    2079         5385 :   function_set fs (fn_names, count);
    2080         5385 :   return fs;
    2081              : }
    2082              : 
    2083              : /* Return true if CALL could throw an exception.
    2084              :    FNDECL could be NULL_TREE.  */
    2085              : 
    2086              : static bool
    2087        12557 : can_throw_p (const gcall &call, tree fndecl)
    2088              : {
    2089        12557 :   if (!flag_exceptions)
    2090              :     return false;
    2091              : 
    2092              :   /* Compatibility flag to allow the user to assume external functions
    2093              :      never throw exceptions.  This may be useful when using the analyzer
    2094              :      on C code that is compiled with -fexceptions, but for which the headers
    2095              :      haven't yet had "nothrow" attributes systematically added.  */
    2096         6078 :   if (flag_analyzer_assume_nothrow)
    2097              :     return false;
    2098              : 
    2099         6076 :   if (gimple_call_nothrow_p (&call))
    2100              :     return false;
    2101              : 
    2102         5525 :   if (fndecl)
    2103              :     {
    2104              :       /* If we are checking a thunk, we want to verify whether or not the
    2105              :          underlying function is nothrow.  */
    2106         5388 :       if (cgraph_node *n = cgraph_node::get (fndecl))
    2107         5388 :         fndecl = n->function_symbol ()->decl;
    2108              : 
    2109         5388 :       if (TREE_NOTHROW (fndecl))
    2110           10 :         return false;
    2111              : 
    2112         5385 :       const function_set fs = get_fns_assumed_not_to_throw ();
    2113         5385 :       if (fs.contains_decl_p (fndecl))
    2114              :         return false;
    2115              :     }
    2116              : 
    2117              :   return true;
    2118              : }
    2119              : 
    2120              : /* Given CALL where we don't know what code is being called
    2121              :    (by not having the body of FNDECL, or having NULL_TREE for FNDECL),
    2122              :   potentially bifurcate control flow to simulate the call throwing
    2123              :   an exception.  */
    2124              : 
    2125              : void
    2126        18233 : region_model::check_for_throw_inside_call (const gcall &call,
    2127              :                                            tree fndecl,
    2128              :                                            region_model_context *ctxt)
    2129              : {
    2130        18233 :   if (!ctxt)
    2131        12718 :     return;
    2132              : 
    2133              :   /* Could this function throw an exception?
    2134              :      If so, add an extra e-edge for that.  */
    2135        12557 :   if (!can_throw_p (call, fndecl))
    2136              :     return;
    2137              : 
    2138         5515 :   auto throws_exception
    2139         5515 :     = std::make_unique<exception_thrown_from_unrecognized_call> (call, fndecl);
    2140         5515 :   ctxt->bifurcate (std::move (throws_exception));
    2141         5515 : }
    2142              : 
    2143              : /* A subclass of pending_diagnostic for complaining about jumps through NULL
    2144              :    function pointers.  */
    2145              : 
    2146              : class jump_through_null : public pending_diagnostic_subclass<jump_through_null>
    2147              : {
    2148              : public:
    2149           16 :   jump_through_null (const gcall &call)
    2150           16 :   : m_call (call)
    2151              :   {}
    2152              : 
    2153          152 :   const char *get_kind () const final override
    2154              :   {
    2155          152 :     return "jump_through_null";
    2156              :   }
    2157              : 
    2158           16 :   bool operator== (const jump_through_null &other) const
    2159              :   {
    2160           16 :     return &m_call == &other.m_call;
    2161              :   }
    2162              : 
    2163           32 :   int get_controlling_option () const final override
    2164              :   {
    2165           32 :     return OPT_Wanalyzer_jump_through_null;
    2166              :   }
    2167              : 
    2168           16 :   bool emit (diagnostic_emission_context &ctxt) final override
    2169              :   {
    2170           16 :     return ctxt.warn ("jump through null pointer");
    2171              :   }
    2172              : 
    2173           32 :   bool describe_final_event (pretty_printer &pp,
    2174              :                              const evdesc::final_event &) final override
    2175              :   {
    2176           32 :     pp_string (&pp, "jump through null pointer here");
    2177           32 :     return true;
    2178              :   }
    2179              : 
    2180              : private:
    2181              :   const gcall &m_call;
    2182              : };
    2183              : /* Update this model for the CALL stmt, using CTXT to report any
    2184              :    diagnostics - the first half.
    2185              : 
    2186              :    Updates to the region_model that should be made *before* sm-states
    2187              :    are updated are done here; other updates to the region_model are done
    2188              :    in region_model::on_call_post.
    2189              : 
    2190              :    Return true if the function call has unknown side effects (it wasn't
    2191              :    recognized and we don't have a body for it, or are unable to tell which
    2192              :    fndecl it is).  */
    2193              : 
    2194              : bool
    2195        74445 : region_model::on_call_pre (const gcall &call, region_model_context *ctxt)
    2196              : {
    2197        74445 :   call_details cd (call, this, ctxt);
    2198              : 
    2199              :   /* Special-case for IFN_DEFERRED_INIT.
    2200              :      We want to report uninitialized variables with -fanalyzer (treating
    2201              :      -ftrivial-auto-var-init= as purely a mitigation feature).
    2202              :      Handle IFN_DEFERRED_INIT by treating it as no-op: don't touch the
    2203              :      lhs of the call, so that it is still uninitialized from the point of
    2204              :      view of the analyzer.  */
    2205        74445 :   if (gimple_call_internal_p (&call)
    2206        74445 :       && gimple_call_internal_fn (&call) == IFN_DEFERRED_INIT)
    2207              :     return false; /* No side effects.  */
    2208              : 
    2209              :   /* Get svalues for all of the arguments at the callsite, to ensure that we
    2210              :      complain about any uninitialized arguments.  This might lead to
    2211              :      duplicates if any of the handling below also looks up the svalues,
    2212              :      but the deduplication code should deal with that.  */
    2213        69449 :   if (ctxt)
    2214        49051 :     check_call_args (cd);
    2215              : 
    2216        69449 :   tree callee_fndecl = get_fndecl_for_call (call, ctxt);
    2217              : 
    2218        69449 :   if (gimple_call_internal_p (&call))
    2219         2872 :     if (const known_function *kf
    2220         1436 :           = get_known_function (gimple_call_internal_fn (&call)))
    2221              :       {
    2222         1402 :         kf->impl_call_pre (cd);
    2223         1402 :         return false; /* No further side effects.  */
    2224              :       }
    2225              : 
    2226        68047 :   if (!callee_fndecl)
    2227              :     {
    2228              :       /* Check for jump through nullptr.  */
    2229          524 :       if (ctxt)
    2230          416 :         if (tree fn_ptr = gimple_call_fn (&call))
    2231              :           {
    2232          390 :             const svalue *fn_ptr_sval = get_rvalue (fn_ptr, ctxt);
    2233          390 :             if (fn_ptr_sval->all_zeroes_p ())
    2234              :               {
    2235           16 :                 ctxt->warn
    2236           16 :                   (std::make_unique<jump_through_null> (call));
    2237           16 :                 ctxt->terminate_path ();
    2238           16 :                 return true;
    2239              :               }
    2240              :           }
    2241              : 
    2242          508 :       check_for_throw_inside_call (call, NULL_TREE, ctxt);
    2243          508 :       cd.set_any_lhs_with_defaults ();
    2244          508 :       return true; /* Unknown side effects.  */
    2245              :     }
    2246              : 
    2247        67523 :   if (const known_function *kf = get_known_function (callee_fndecl, cd))
    2248              :     {
    2249        47823 :       kf->impl_call_pre (cd);
    2250        47823 :       return false; /* No further side effects.  */
    2251              :     }
    2252              : 
    2253        19700 :   cd.set_any_lhs_with_defaults ();
    2254              : 
    2255        19700 :   const int callee_fndecl_flags = flags_from_decl_or_type (callee_fndecl);
    2256        19700 :   if (callee_fndecl_flags & (ECF_CONST | ECF_PURE))
    2257              :     return false; /* No side effects.  */
    2258              : 
    2259        18533 :   attr_fnspec fnspec = gimple_call_fnspec (&call);
    2260        18533 :   if (fnspec.known_p () && fnspec.errno_maybe_written_p ())
    2261              :     {
    2262              :       bool args_written = false;
    2263           58 :       for (unsigned i = 0; i < gimple_call_num_args (&call); i++)
    2264           58 :         if (POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (&call, i)))
    2265           31 :             && (!fnspec.arg_specified_p (i) || fnspec.arg_maybe_written_p (i)))
    2266              :           args_written = true;
    2267           27 :       if (!args_written)
    2268              :         {
    2269           23 :           mark_region_as_conjured (*m_mgr->get_errno_region (), call, ctxt);
    2270           23 :           return false; /* No side effects other than on errno.  */
    2271              :         }
    2272              :     }
    2273              : 
    2274        18510 :   if (fndecl_built_in_p (callee_fndecl))
    2275              :     return true; /* Unknown side effects.  */
    2276              : 
    2277        17725 :   if (!fndecl_has_gimple_body_p (callee_fndecl))
    2278              :     {
    2279        17725 :       check_for_throw_inside_call (call, callee_fndecl, ctxt);
    2280        17725 :       return true; /* Unknown side effects.  */
    2281              :     }
    2282              : 
    2283              :   return false; /* No side effects.  */
    2284              : }
    2285              : 
    2286              : /* Update this model for the CALL stmt, using CTXT to report any
    2287              :    diagnostics - the second half.
    2288              : 
    2289              :    Updates to the region_model that should be made *after* sm-states
    2290              :    are updated are done here; other updates to the region_model are done
    2291              :    in region_model::on_call_pre.
    2292              : 
    2293              :    If UNKNOWN_SIDE_EFFECTS is true, also call handle_unrecognized_call
    2294              :    to purge state.  */
    2295              : 
    2296              : void
    2297        74192 : region_model::on_call_post (const gcall &call,
    2298              :                             bool unknown_side_effects,
    2299              :                             region_model_context *ctxt)
    2300              : {
    2301        74192 :   if (tree callee_fndecl = get_fndecl_for_call (call, ctxt))
    2302              :     {
    2303        67317 :       call_details cd (call, this, ctxt);
    2304        67317 :       if (const known_function *kf = get_known_function (callee_fndecl, cd))
    2305              :         {
    2306        47671 :           kf->impl_call_post (cd);
    2307        95824 :           return;
    2308              :         }
    2309              :       /* Was this fndecl referenced by
    2310              :          __attribute__((malloc(FOO)))?  */
    2311        19646 :       if (lookup_attribute ("*dealloc", DECL_ATTRIBUTES (callee_fndecl)))
    2312              :         {
    2313          482 :           impl_deallocation_call (cd);
    2314          482 :           return;
    2315              :         }
    2316              :     }
    2317              : 
    2318        26039 :   if (unknown_side_effects)
    2319              :     {
    2320        17576 :       handle_unrecognized_call (call, ctxt);
    2321        17576 :       if (ctxt)
    2322        12157 :         ctxt->maybe_did_work ();
    2323              :     }
    2324              : }
    2325              : 
    2326              : /* Purge state involving NODE from this region_model, using CTXT
    2327              :    (if non-NULL) to purge other state in a program_state.
    2328              : 
    2329              :    For example, if we're at the def-stmt of an SSA name, then we need to
    2330              :    purge any state for svalues that involve that SSA name.  This avoids
    2331              :    false positives in loops, since a symbolic value referring to the
    2332              :    SSA name will be referring to the previous value of that SSA name.
    2333              : 
    2334              :    For example, in:
    2335              :      while ((e = hashmap_iter_next(&iter))) {
    2336              :        struct oid2strbuf *e_strbuf = (struct oid2strbuf *)e;
    2337              :        free (e_strbuf->value);
    2338              :      }
    2339              :    at the def-stmt of e_8:
    2340              :      e_8 = hashmap_iter_next (&iter);
    2341              :    we should purge the "freed" state of:
    2342              :      INIT_VAL(CAST_REG(‘struct oid2strbuf’, (*INIT_VAL(e_8))).value)
    2343              :    which is the "e_strbuf->value" value from the previous iteration,
    2344              :    or we will erroneously report a double-free - the "e_8" within it
    2345              :    refers to the previous value.  */
    2346              : 
    2347              : void
    2348        24951 : region_model::purge_state_involving (const symbolic::node &node,
    2349              :                                      region_model_context *ctxt)
    2350              : {
    2351        24951 :   m_store.purge_state_involving (node);
    2352        24951 :   m_constraints->purge_state_involving (node);
    2353        24951 :   m_dynamic_extents.purge_state_involving (node);
    2354        24951 :   if (ctxt)
    2355        13429 :     ctxt->purge_state_involving (node);
    2356        24951 : }
    2357              : 
    2358              : /* A pending_note subclass for adding a note about an
    2359              :    __attribute__((access, ...)) to a diagnostic.  */
    2360              : 
    2361              : class reason_attr_access : public pending_note_subclass<reason_attr_access>
    2362              : {
    2363              : public:
    2364           22 :   reason_attr_access (tree callee_fndecl, const attr_access &access)
    2365           22 :   : m_callee_fndecl (callee_fndecl),
    2366           22 :     m_ptr_argno (access.ptrarg),
    2367           22 :     m_access_str (TREE_STRING_POINTER (access.to_external_string ()))
    2368              :   {
    2369           22 :   }
    2370              : 
    2371          116 :   const char *get_kind () const final override { return "reason_attr_access"; }
    2372              : 
    2373           18 :   void emit () const final override
    2374              :   {
    2375           18 :     auto_urlify_attributes sentinel;
    2376           18 :     inform (DECL_SOURCE_LOCATION (m_callee_fndecl),
    2377              :             "parameter %i of %qD marked with attribute %qs",
    2378           18 :             m_ptr_argno + 1, m_callee_fndecl, m_access_str);
    2379           18 :   }
    2380              : 
    2381           58 :   bool operator== (const reason_attr_access &other) const
    2382              :   {
    2383           58 :     return (m_callee_fndecl == other.m_callee_fndecl
    2384           22 :             && m_ptr_argno == other.m_ptr_argno
    2385           80 :             && !strcmp (m_access_str, other.m_access_str));
    2386              :   }
    2387              : 
    2388              : private:
    2389              :   tree m_callee_fndecl;
    2390              :   unsigned m_ptr_argno;
    2391              :   const char *m_access_str;
    2392              : };
    2393              : 
    2394              : /* Check CALL a call to external function CALLEE_FNDECL based on
    2395              :    any __attribute__ ((access, ....) on the latter, complaining to
    2396              :    CTXT about any issues.
    2397              : 
    2398              :    Currently we merely call check_region_for_write on any regions
    2399              :    pointed to by arguments marked with a "write_only" or "read_write"
    2400              :    attribute.  */
    2401              : 
    2402              : void
    2403         1247 : region_model::check_function_attr_access (const gcall &call,
    2404              :                                           tree callee_fndecl,
    2405              :                                           region_model_context *ctxt,
    2406              :                                           rdwr_map &rdwr_idx) const
    2407              : {
    2408         1247 :   gcc_assert (callee_fndecl);
    2409         1247 :   gcc_assert (ctxt);
    2410              : 
    2411         1247 :   tree fntype = TREE_TYPE (callee_fndecl);
    2412         1247 :   gcc_assert (fntype);
    2413              : 
    2414         1247 :   unsigned argno = 0;
    2415              : 
    2416         4752 :   for (tree iter = TYPE_ARG_TYPES (fntype); iter;
    2417         3505 :        iter = TREE_CHAIN (iter), ++argno)
    2418              :     {
    2419         3505 :       const attr_access* access = rdwr_idx.get (argno);
    2420         3505 :       if (!access)
    2421         3227 :         continue;
    2422              : 
    2423              :       /* Ignore any duplicate entry in the map for the size argument.  */
    2424          278 :       if (access->ptrarg != argno)
    2425          114 :         continue;
    2426              : 
    2427          164 :       if (access->mode == access_write_only
    2428          164 :           || access->mode == access_read_write)
    2429              :         {
    2430              :           /* Subclass of annotating_context that
    2431              :              adds a note about the attr access to any saved diagnostics.  */
    2432           40 :           class annotating_ctxt : public annotating_context
    2433              :           {
    2434              :           public:
    2435           40 :             annotating_ctxt (tree callee_fndecl,
    2436              :                              const attr_access &access,
    2437              :                              region_model_context *ctxt)
    2438              :             : annotating_context (ctxt),
    2439           40 :               m_callee_fndecl (callee_fndecl),
    2440           40 :               m_access (access)
    2441              :             {
    2442              :             }
    2443           22 :             void add_annotations () final override
    2444              :             {
    2445           22 :               add_note (std::make_unique<reason_attr_access>
    2446           22 :                           (m_callee_fndecl, m_access));
    2447           22 :             }
    2448              :           private:
    2449              :             tree m_callee_fndecl;
    2450              :             const attr_access &m_access;
    2451              :           };
    2452              : 
    2453              :           /* Use this ctxt below so that any diagnostics get the
    2454              :              note added to them.  */
    2455           40 :           annotating_ctxt my_ctxt (callee_fndecl, *access, ctxt);
    2456              : 
    2457           40 :           tree ptr_tree = gimple_call_arg (&call, access->ptrarg);
    2458           40 :           const svalue *ptr_sval = get_rvalue (ptr_tree, &my_ctxt);
    2459           40 :           const region *reg = deref_rvalue (ptr_sval, ptr_tree, &my_ctxt);
    2460           40 :           check_region_for_write (reg, nullptr, &my_ctxt);
    2461              :           /* We don't use the size arg for now.  */
    2462              :         }
    2463              :     }
    2464         1247 : }
    2465              : 
    2466              : /* Subroutine of region_model::check_function_attr_null_terminated_string_arg,
    2467              :    checking one instance of __attribute__((null_terminated_string_arg)).  */
    2468              : 
    2469              : void
    2470          200 : region_model::
    2471              : check_one_function_attr_null_terminated_string_arg (const gcall &call,
    2472              :                                                     tree callee_fndecl,
    2473              :                                                     region_model_context *ctxt,
    2474              :                                                     rdwr_map &rdwr_idx,
    2475              :                                                     tree attr)
    2476              : {
    2477          200 :   gcc_assert (callee_fndecl);
    2478          200 :   gcc_assert (ctxt);
    2479          200 :   gcc_assert (attr);
    2480              : 
    2481          200 :   tree arg = TREE_VALUE (attr);
    2482          200 :   if (!arg)
    2483           76 :     return;
    2484              : 
    2485              :   /* Convert from 1-based to 0-based index.  */
    2486          200 :   unsigned int arg_idx = TREE_INT_CST_LOW (TREE_VALUE (arg)) - 1;
    2487              : 
    2488              :   /* If there's also an "access" attribute on the ptr param
    2489              :      for reading with a size param specified, then that size
    2490              :      limits the size of the possible read from the pointer.  */
    2491          200 :   if (const attr_access* access = rdwr_idx.get (arg_idx))
    2492          104 :     if ((access->mode == access_read_only
    2493          104 :          || access->mode == access_read_write)
    2494          104 :         && access->sizarg != UINT_MAX)
    2495              :       {
    2496           76 :         call_details cd_checked (call, this, ctxt);
    2497           76 :         auto &limit_num_bytes = cd_checked.get_arg_as_num_bytes (access->sizarg);
    2498           76 :         auto sym_ptr = cd_checked.get_arg_as_sym_ptr (arg_idx);
    2499              :         /* Try reading all of the bytes expressed by the size param,
    2500              :            but without emitting warnings (via a null context).  */
    2501           76 :         auto &bv = read_bytes (sym_ptr,
    2502              :                                NULL_TREE,
    2503              :                                limit_num_bytes,
    2504              :                                nullptr);
    2505              : 
    2506           76 :         poison_finder v;
    2507           76 :         bv.accept_node_visitor (v);
    2508           76 :         if (v.m_found_poison)
    2509              :           {
    2510              :             /* Reading up to the truncation limit caused issues.
    2511              :                Assume that the string is meant to be terminated
    2512              :                before then, so perform a *checked* check for the
    2513              :                terminator.  */
    2514           36 :             check_for_null_terminated_string_arg (cd_checked,
    2515              :                                                   arg_idx);
    2516              :           }
    2517              :         else
    2518              :           {
    2519              :             /* Reading up to the truncation limit seems OK; repeat
    2520              :                the read, but with checking enabled.  */
    2521           40 :             read_bytes (sym_ptr,
    2522              :                         NULL_TREE,
    2523              :                         limit_num_bytes,
    2524              :                         ctxt);
    2525              :           }
    2526           76 :         return;
    2527           76 :       }
    2528              : 
    2529              :   /* Otherwise, we don't have an access-attribute limiting the read.
    2530              :      Simulate a read up to the null terminator (if any).  */
    2531              : 
    2532          124 :   call_details cd (call, this, ctxt);
    2533          124 :   check_for_null_terminated_string_arg (cd, arg_idx);
    2534              : }
    2535              : 
    2536              : /* Check CALL a call to external function CALLEE_FNDECL for any uses
    2537              :    of __attribute__ ((null_terminated_string_arg)), complaining
    2538              :    to CTXT about any issues.
    2539              : 
    2540              :    Use RDWR_IDX for tracking uses of __attribute__ ((access, ....).  */
    2541              : 
    2542              : void
    2543         1247 : region_model::
    2544              : check_function_attr_null_terminated_string_arg (const gcall &call,
    2545              :                                                 tree callee_fndecl,
    2546              :                                                 region_model_context *ctxt,
    2547              :                                                 rdwr_map &rdwr_idx)
    2548              : {
    2549         1247 :   gcc_assert (callee_fndecl);
    2550         1247 :   gcc_assert (ctxt);
    2551              : 
    2552         1247 :   tree fntype = TREE_TYPE (callee_fndecl);
    2553         1247 :   gcc_assert (fntype);
    2554              : 
    2555              :   /* A function declaration can specify multiple attribute
    2556              :      null_terminated_string_arg, each with one argument.  */
    2557         1447 :   for (tree attr = TYPE_ATTRIBUTES (fntype); attr; attr = TREE_CHAIN (attr))
    2558              :     {
    2559         1271 :       attr = lookup_attribute ("null_terminated_string_arg", attr);
    2560         1271 :       if (!attr)
    2561              :         return;
    2562              : 
    2563          200 :       check_one_function_attr_null_terminated_string_arg (call, callee_fndecl,
    2564              :                                                           ctxt, rdwr_idx,
    2565              :                                                           attr);
    2566              :     }
    2567              : }
    2568              : 
    2569              : /* Check CALL a call to external function CALLEE_FNDECL for any
    2570              :    function attributes, complaining to CTXT about any issues.  */
    2571              : 
    2572              : void
    2573        11762 : region_model::check_function_attrs (const gcall &call,
    2574              :                                     tree callee_fndecl,
    2575              :                                     region_model_context *ctxt)
    2576              : {
    2577        11762 :   gcc_assert (callee_fndecl);
    2578        11762 :   gcc_assert (ctxt);
    2579              : 
    2580        11762 :   tree fntype = TREE_TYPE (callee_fndecl);
    2581        11762 :   if (!fntype)
    2582        10515 :     return;
    2583              : 
    2584        11762 :   if (!TYPE_ATTRIBUTES (fntype))
    2585              :     return;
    2586              : 
    2587              :   /* Initialize a map of attribute access specifications for arguments
    2588              :      to the function call.  */
    2589         1247 :   rdwr_map rdwr_idx;
    2590         1247 :   init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
    2591              : 
    2592         1247 :   check_function_attr_access (call, callee_fndecl, ctxt, rdwr_idx);
    2593         1247 :   check_function_attr_null_terminated_string_arg (call, callee_fndecl,
    2594              :                                                   ctxt, rdwr_idx);
    2595         1247 : }
    2596              : 
    2597              : /* Handle a call CALL to a function with unknown behavior.
    2598              : 
    2599              :    Traverse the regions in this model, determining what regions are
    2600              :    reachable from pointer arguments to CALL and from global variables,
    2601              :    recursively.
    2602              : 
    2603              :    Set all reachable regions to new unknown values and purge sm-state
    2604              :    from their values, and from values that point to them.  */
    2605              : 
    2606              : void
    2607        17576 : region_model::handle_unrecognized_call (const gcall &call,
    2608              :                                         region_model_context *ctxt)
    2609              : {
    2610        17576 :   tree fndecl = get_fndecl_for_call (call, ctxt);
    2611              : 
    2612        17576 :   if (fndecl && ctxt)
    2613        11762 :     check_function_attrs (call, fndecl, ctxt);
    2614              : 
    2615        17576 :   reachable_regions reachable_regs (this);
    2616              : 
    2617              :   /* Determine the reachable regions and their mutability.  */
    2618        17576 :   {
    2619              :     /* Add globals and regions that already escaped in previous
    2620              :        unknown calls.  */
    2621        17576 :     m_store.for_each_cluster (reachable_regions::init_cluster_cb,
    2622              :                               &reachable_regs);
    2623              : 
    2624              :     /* Params that are pointers.  */
    2625        17576 :     tree iter_param_types = NULL_TREE;
    2626        17576 :     if (fndecl)
    2627        17073 :       iter_param_types = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
    2628        37063 :     for (unsigned arg_idx = 0; arg_idx < gimple_call_num_args (&call);
    2629              :          arg_idx++)
    2630              :       {
    2631              :         /* Track expected param type, where available.  */
    2632        19487 :         tree param_type = NULL_TREE;
    2633        19487 :         if (iter_param_types)
    2634              :           {
    2635        17983 :             param_type = TREE_VALUE (iter_param_types);
    2636        17983 :             gcc_assert (param_type);
    2637        17983 :             iter_param_types = TREE_CHAIN (iter_param_types);
    2638              :           }
    2639              : 
    2640        19487 :         tree parm = gimple_call_arg (&call, arg_idx);
    2641        19487 :         const svalue *parm_sval = get_rvalue (parm, ctxt);
    2642        19487 :         reachable_regs.handle_parm (parm_sval, param_type);
    2643              :       }
    2644              :   }
    2645              : 
    2646        17576 :   uncertainty_t *uncertainty = ctxt ? ctxt->get_uncertainty () : nullptr;
    2647              : 
    2648              :   /* Purge sm-state for the svalues that were reachable,
    2649              :      both in non-mutable and mutable form.  */
    2650        30720 :   for (value_set::iterator iter
    2651        17576 :          = reachable_regs.begin_reachable_svals ();
    2652        30720 :        iter != reachable_regs.end_reachable_svals (); ++iter)
    2653              :     {
    2654        13144 :       if (ctxt)
    2655        10043 :         ctxt->on_unknown_change (**iter, false);
    2656              :     }
    2657        43674 :   for (value_set::iterator iter
    2658        17576 :          = reachable_regs.begin_mutable_svals ();
    2659        43674 :        iter != reachable_regs.end_mutable_svals (); ++iter)
    2660              :     {
    2661        26098 :       if (ctxt)
    2662        20398 :         ctxt->on_unknown_change (**iter, true);
    2663        26098 :       if (uncertainty)
    2664        19673 :         uncertainty->on_mutable_value_at_unknown_call (**iter);
    2665              :     }
    2666              : 
    2667              :   /* Mark any clusters that have escaped.  */
    2668        17576 :   reachable_regs.mark_escaped_clusters (ctxt);
    2669              : 
    2670              :   /* Update bindings for all clusters that have escaped, whether above,
    2671              :      or previously.  */
    2672        17576 :   m_store.on_unknown_fncall (call,
    2673        17576 :                              conjured_purge (this, ctxt));
    2674              : 
    2675              :   /* Purge dynamic extents from any regions that have escaped mutably:
    2676              :      realloc could have been called on them.  */
    2677        41122 :   for (hash_set<const region *>::iterator
    2678        17576 :          iter = reachable_regs.begin_mutable_base_regs ();
    2679        41122 :        iter != reachable_regs.end_mutable_base_regs ();
    2680        23546 :        ++iter)
    2681              :     {
    2682        23546 :       const region *base_reg = (*iter);
    2683        23546 :       unset_dynamic_extents (base_reg);
    2684              :     }
    2685        17576 : }
    2686              : 
    2687              : /* Traverse the regions in this model, determining what regions are
    2688              :    reachable from the store and populating *OUT.
    2689              : 
    2690              :    If EXTRA_SVAL is non-NULL, treat it as an additional "root"
    2691              :    for reachability (for handling return values from functions when
    2692              :    analyzing return of the only function on the stack).
    2693              : 
    2694              :    If UNCERTAINTY is non-NULL, treat any svalues that were recorded
    2695              :    within it as being maybe-bound as additional "roots" for reachability.
    2696              : 
    2697              :    Find svalues that haven't leaked.    */
    2698              : 
    2699              : void
    2700       871232 : region_model::get_reachable_svalues (value_set *out,
    2701              :                                      const svalue *extra_sval,
    2702              :                                      const uncertainty_t *uncertainty)
    2703              : {
    2704       871232 :   reachable_regions reachable_regs (this);
    2705              : 
    2706              :   /* Add globals and regions that already escaped in previous
    2707              :      unknown calls.  */
    2708       871232 :   m_store.for_each_cluster (reachable_regions::init_cluster_cb,
    2709              :                             &reachable_regs);
    2710              : 
    2711       871232 :   if (extra_sval)
    2712         5318 :     reachable_regs.handle_value (*extra_sval);
    2713              : 
    2714       871232 :   if (uncertainty)
    2715       408877 :     for (uncertainty_t::iterator iter
    2716       384669 :            = uncertainty->begin_maybe_bound_svals ();
    2717       793546 :          iter != uncertainty->end_maybe_bound_svals (); ++iter)
    2718        24208 :       reachable_regs.handle_value (**iter);
    2719              : 
    2720              :   /* Get regions for locals that have explicitly bound values.  */
    2721      5872788 :   for (store::cluster_map_t::iterator iter = m_store.begin ();
    2722      5872788 :        iter != m_store.end (); ++iter)
    2723              :     {
    2724      5001556 :       const region *base_reg = (*iter).first;
    2725      5001556 :       if (const region *parent = base_reg->get_parent_region ())
    2726      5001556 :         if (parent->get_kind () == RK_FRAME)
    2727      3174969 :           reachable_regs.add (base_reg, false);
    2728              :     }
    2729              : 
    2730              :   /* Populate *OUT based on the values that were reachable.  */
    2731     10142217 :   for (value_set::iterator iter
    2732       871232 :          = reachable_regs.begin_reachable_svals ();
    2733     10142217 :        iter != reachable_regs.end_reachable_svals (); ++iter)
    2734      9270985 :     out->add (*iter);
    2735       871232 : }
    2736              : 
    2737              : /* Update this model for the RETURN_STMT, using CTXT to report any
    2738              :    diagnostics.  */
    2739              : 
    2740              : void
    2741            0 : region_model::on_return (const greturn *return_stmt, region_model_context *ctxt)
    2742              : {
    2743            0 :   tree callee = get_current_function ()->decl;
    2744            0 :   tree lhs = DECL_RESULT (callee);
    2745            0 :   tree rhs = gimple_return_retval (return_stmt);
    2746              : 
    2747            0 :   if (lhs && rhs)
    2748              :     {
    2749            0 :       const svalue *sval = get_rvalue (rhs, ctxt);
    2750            0 :       const region *ret_reg = get_lvalue (lhs, ctxt);
    2751            0 :       set_value (ret_reg, sval, ctxt);
    2752              :     }
    2753            0 : }
    2754              : 
    2755              : /* Implementation of region_model::get_lvalue; the latter adds type-checking.
    2756              : 
    2757              :    Get the id of the region for PV within this region_model,
    2758              :    emitting any diagnostics to CTXT.  */
    2759              : 
    2760              : const region *
    2761      2304959 : region_model::get_lvalue_1 (path_var pv, region_model_context *ctxt) const
    2762              : {
    2763      2304959 :   tree expr = pv.m_tree;
    2764              : 
    2765      2304959 :   gcc_assert (expr);
    2766              : 
    2767      2304959 :   switch (TREE_CODE (expr))
    2768              :     {
    2769          122 :     default:
    2770          122 :       return m_mgr->get_region_for_unexpected_tree_code (ctxt, expr,
    2771          122 :                                                          dump_location_t ());
    2772              : 
    2773        13649 :     case ARRAY_REF:
    2774        13649 :       {
    2775        13649 :         tree array = TREE_OPERAND (expr, 0);
    2776        13649 :         tree index = TREE_OPERAND (expr, 1);
    2777              : 
    2778        13649 :         const region *array_reg = get_lvalue (array, ctxt);
    2779        13649 :         const svalue *index_sval = get_rvalue (index, ctxt);
    2780        13649 :         return m_mgr->get_element_region (array_reg,
    2781        13649 :                                           TREE_TYPE (TREE_TYPE (array)),
    2782        13649 :                                           index_sval);
    2783              :       }
    2784          189 :       break;
    2785              : 
    2786          189 :     case BIT_FIELD_REF:
    2787          189 :       {
    2788          189 :         tree inner_expr = TREE_OPERAND (expr, 0);
    2789          189 :         const region *inner_reg = get_lvalue (inner_expr, ctxt);
    2790          189 :         tree num_bits = TREE_OPERAND (expr, 1);
    2791          189 :         tree first_bit_offset = TREE_OPERAND (expr, 2);
    2792          189 :         gcc_assert (TREE_CODE (num_bits) == INTEGER_CST);
    2793          189 :         gcc_assert (TREE_CODE (first_bit_offset) == INTEGER_CST);
    2794          189 :         concrete_bit_range bits
    2795          378 :           (concrete_bit_offset (convert_from_integer_cst (first_bit_offset)),
    2796          567 :            concrete_bit_size (convert_from_integer_cst (num_bits)));
    2797          189 :         return m_mgr->get_bit_range (inner_reg, TREE_TYPE (expr), bits);
    2798          189 :       }
    2799        70814 :       break;
    2800              : 
    2801        70814 :     case MEM_REF:
    2802        70814 :       {
    2803        70814 :         tree ptr = TREE_OPERAND (expr, 0);
    2804        70814 :         tree offset = TREE_OPERAND (expr, 1);
    2805        70814 :         const svalue *ptr_sval = get_rvalue (ptr, ctxt);
    2806        70814 :         const svalue *offset_sval = get_rvalue (offset, ctxt);
    2807        70814 :         const region *star_ptr = deref_rvalue (ptr_sval, ptr, ctxt);
    2808        70814 :         return m_mgr->get_offset_region (star_ptr,
    2809        70814 :                                          TREE_TYPE (expr),
    2810        70814 :                                          offset_sval);
    2811              :       }
    2812       890782 :       break;
    2813              : 
    2814       890782 :     case FUNCTION_DECL:
    2815       890782 :       return m_mgr->get_region_for_fndecl (expr);
    2816              : 
    2817          340 :     case LABEL_DECL:
    2818          340 :       return m_mgr->get_region_for_label (expr);
    2819              : 
    2820       130576 :     case VAR_DECL:
    2821              :       /* Handle globals.  */
    2822       130576 :       if (is_global_var (expr))
    2823        45194 :         return m_mgr->get_region_for_global (expr);
    2824              : 
    2825              :       /* Fall through.  */
    2826              : 
    2827      1210781 :     case SSA_NAME:
    2828      1210781 :     case PARM_DECL:
    2829      1210781 :     case RESULT_DECL:
    2830      1210781 :       {
    2831      1210781 :         gcc_assert (TREE_CODE (expr) == SSA_NAME
    2832              :                     || TREE_CODE (expr) == PARM_DECL
    2833              :                     || VAR_P (expr)
    2834              :                     || TREE_CODE (expr) == RESULT_DECL);
    2835              : 
    2836      1210781 :         int stack_index = pv.m_stack_depth;
    2837      1210781 :         const frame_region *frame = get_frame_at_index (stack_index);
    2838      1210781 :         gcc_assert (frame);
    2839      1210781 :         return frame->get_region_for_local (m_mgr, expr, ctxt);
    2840              :       }
    2841              : 
    2842        59215 :     case COMPONENT_REF:
    2843        59215 :       {
    2844              :         /* obj.field  */
    2845        59215 :         tree obj = TREE_OPERAND (expr, 0);
    2846        59215 :         tree field = TREE_OPERAND (expr, 1);
    2847        59215 :         const region *obj_reg = get_lvalue (obj, ctxt);
    2848        59215 :         return m_mgr->get_field_region (obj_reg, field);
    2849              :       }
    2850        13873 :       break;
    2851              : 
    2852        13873 :     case STRING_CST:
    2853        13873 :       return m_mgr->get_region_for_string (expr);
    2854              :     }
    2855              : }
    2856              : 
    2857              : /* Assert that SRC_TYPE can be converted to DST_TYPE as a no-op.  */
    2858              : 
    2859              : static void
    2860      5021950 : assert_compat_types (tree src_type, tree dst_type)
    2861              : {
    2862      5021950 :   if (src_type && dst_type && !VOID_TYPE_P (dst_type))
    2863              :     {
    2864              : #if CHECKING_P
    2865      5021576 :       if (!(useless_type_conversion_p (src_type, dst_type)))
    2866            0 :         internal_error ("incompatible types: %qT and %qT", src_type, dst_type);
    2867              : #endif
    2868              :     }
    2869      5021950 : }
    2870              : 
    2871              : /* Return true if SRC_TYPE can be converted to DST_TYPE as a no-op.  */
    2872              : 
    2873              : bool
    2874        14693 : compat_types_p (tree src_type, tree dst_type)
    2875              : {
    2876        14693 :   if (src_type && dst_type && !VOID_TYPE_P (dst_type))
    2877        14693 :     if (!(useless_type_conversion_p (src_type, dst_type)))
    2878              :       return false;
    2879              :   return true;
    2880              : }
    2881              : 
    2882              : /* Get the region for PV within this region_model,
    2883              :    emitting any diagnostics to CTXT.  */
    2884              : 
    2885              : const region *
    2886      2304959 : region_model::get_lvalue (path_var pv, region_model_context *ctxt) const
    2887              : {
    2888      2304959 :   if (pv.m_tree == NULL_TREE)
    2889              :     return nullptr;
    2890              : 
    2891      2304959 :   const region *result_reg = get_lvalue_1 (pv, ctxt);
    2892      2304959 :   assert_compat_types (result_reg->get_type (), TREE_TYPE (pv.m_tree));
    2893      2304959 :   return result_reg;
    2894              : }
    2895              : 
    2896              : /* Get the region for EXPR within this region_model (assuming the most
    2897              :    recent stack frame if it's a local).  */
    2898              : 
    2899              : const region *
    2900      1495409 : region_model::get_lvalue (tree expr, region_model_context *ctxt) const
    2901              : {
    2902      1495409 :   return get_lvalue (path_var (expr, get_stack_depth () - 1), ctxt);
    2903              : }
    2904              : 
    2905              : /* Implementation of region_model::get_rvalue; the latter adds type-checking.
    2906              : 
    2907              :    Get the value of PV within this region_model,
    2908              :    emitting any diagnostics to CTXT.  */
    2909              : 
    2910              : const svalue *
    2911      2702687 : region_model::get_rvalue_1 (path_var pv, region_model_context *ctxt) const
    2912              : {
    2913      2702687 :   gcc_assert (pv.m_tree);
    2914              : 
    2915      2702687 :   switch (TREE_CODE (pv.m_tree))
    2916              :     {
    2917          103 :     default:
    2918          103 :       return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (pv.m_tree));
    2919              : 
    2920       949243 :     case ADDR_EXPR:
    2921       949243 :       {
    2922              :         /* "&EXPR".  */
    2923       949243 :         tree expr = pv.m_tree;
    2924       949243 :         tree op0 = TREE_OPERAND (expr, 0);
    2925       949243 :         const region *expr_reg = get_lvalue (op0, ctxt);
    2926       949243 :         return m_mgr->get_ptr_svalue (TREE_TYPE (expr), expr_reg);
    2927              :       }
    2928          132 :       break;
    2929              : 
    2930          132 :     case BIT_FIELD_REF:
    2931          132 :       {
    2932          132 :         tree expr = pv.m_tree;
    2933          132 :         tree op0 = TREE_OPERAND (expr, 0);
    2934          132 :         const region *reg = get_lvalue (op0, ctxt);
    2935          132 :         tree num_bits = TREE_OPERAND (expr, 1);
    2936          132 :         tree first_bit_offset = TREE_OPERAND (expr, 2);
    2937          132 :         gcc_assert (TREE_CODE (num_bits) == INTEGER_CST);
    2938          132 :         gcc_assert (TREE_CODE (first_bit_offset) == INTEGER_CST);
    2939          132 :         bit_range bits (TREE_INT_CST_LOW (first_bit_offset),
    2940          132 :                         TREE_INT_CST_LOW (num_bits));
    2941          132 :         return get_rvalue_for_bits (TREE_TYPE (expr), reg, bits, ctxt);
    2942              :       }
    2943              : 
    2944        28936 :     case VAR_DECL:
    2945        28936 :       if (DECL_HARD_REGISTER (pv.m_tree))
    2946              :         {
    2947              :           /* If it has a hard register, it doesn't have a memory region
    2948              :              and can't be referred to as an lvalue.  */
    2949           43 :           return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (pv.m_tree));
    2950              :         }
    2951              :       /* Fall through. */
    2952       760266 :     case PARM_DECL:
    2953       760266 :     case SSA_NAME:
    2954       760266 :     case RESULT_DECL:
    2955       760266 :     case ARRAY_REF:
    2956       760266 :       {
    2957       760266 :         const region *reg = get_lvalue (pv, ctxt);
    2958       760266 :         return get_store_value (reg, ctxt);
    2959              :       }
    2960              : 
    2961          176 :     case REALPART_EXPR:
    2962          176 :     case IMAGPART_EXPR:
    2963          176 :     case VIEW_CONVERT_EXPR:
    2964          176 :       {
    2965          176 :         tree expr = pv.m_tree;
    2966          176 :         tree arg = TREE_OPERAND (expr, 0);
    2967          176 :         const svalue *arg_sval = get_rvalue (arg, ctxt);
    2968          176 :         const svalue *sval_unaryop
    2969          176 :           = m_mgr->get_or_create_unaryop (TREE_TYPE (expr), TREE_CODE (expr),
    2970              :                                           arg_sval);
    2971          176 :         return sval_unaryop;
    2972       943214 :       };
    2973              : 
    2974       943214 :     case INTEGER_CST:
    2975       943214 :     case REAL_CST:
    2976       943214 :     case COMPLEX_CST:
    2977       943214 :     case VECTOR_CST:
    2978       943214 :     case STRING_CST:
    2979       943214 :     case RAW_DATA_CST:
    2980       943214 :       return m_mgr->get_or_create_constant_svalue (pv.m_tree);
    2981              : 
    2982           41 :     case POINTER_PLUS_EXPR:
    2983           41 :         {
    2984           41 :           tree expr = pv.m_tree;
    2985           41 :           tree ptr = TREE_OPERAND (expr, 0);
    2986           41 :           tree offset = TREE_OPERAND (expr, 1);
    2987           41 :           const svalue *ptr_sval = get_rvalue (ptr, ctxt);
    2988           41 :           const svalue *offset_sval = get_rvalue (offset, ctxt);
    2989           41 :           const svalue *sval_binop
    2990           41 :             = m_mgr->get_or_create_binop (TREE_TYPE (expr), POINTER_PLUS_EXPR,
    2991              :                                           ptr_sval, offset_sval);
    2992           41 :           return sval_binop;
    2993              :         }
    2994              : 
    2995              :     /* Binary ops.  */
    2996           93 :     case PLUS_EXPR:
    2997           93 :     case MULT_EXPR:
    2998           93 :     case BIT_AND_EXPR:
    2999           93 :     case BIT_IOR_EXPR:
    3000           93 :     case BIT_XOR_EXPR:
    3001           93 :         {
    3002           93 :           tree expr = pv.m_tree;
    3003           93 :           tree arg0 = TREE_OPERAND (expr, 0);
    3004           93 :           tree arg1 = TREE_OPERAND (expr, 1);
    3005           93 :           const svalue *arg0_sval = get_rvalue (arg0, ctxt);
    3006           93 :           const svalue *arg1_sval = get_rvalue (arg1, ctxt);
    3007           93 :           const svalue *sval_binop
    3008           93 :             = m_mgr->get_or_create_binop (TREE_TYPE (expr), TREE_CODE (expr),
    3009              :                                           arg0_sval, arg1_sval);
    3010           93 :           return sval_binop;
    3011              :         }
    3012              : 
    3013        49244 :     case COMPONENT_REF:
    3014        49244 :     case MEM_REF:
    3015        49244 :       {
    3016        49244 :         const region *ref_reg = get_lvalue (pv, ctxt);
    3017        49244 :         return get_store_value (ref_reg, ctxt);
    3018              :       }
    3019          132 :     case OBJ_TYPE_REF:
    3020          132 :       {
    3021          132 :         tree expr = OBJ_TYPE_REF_EXPR (pv.m_tree);
    3022          132 :         return get_rvalue (expr, ctxt);
    3023              :       }
    3024              :     }
    3025              : }
    3026              : 
    3027              : /* Get the value of PV within this region_model,
    3028              :    emitting any diagnostics to CTXT.  */
    3029              : 
    3030              : const svalue *
    3031      2738271 : region_model::get_rvalue (path_var pv, region_model_context *ctxt) const
    3032              : {
    3033      2738271 :   if (pv.m_tree == NULL_TREE)
    3034              :     return nullptr;
    3035              : 
    3036      2702687 :   const svalue *result_sval = get_rvalue_1 (pv, ctxt);
    3037              : 
    3038      2702687 :   assert_compat_types (result_sval->get_type (), TREE_TYPE (pv.m_tree));
    3039              : 
    3040      2702687 :   result_sval = check_for_poison (result_sval, pv.m_tree, nullptr, ctxt);
    3041              : 
    3042      2702687 :   return result_sval;
    3043              : }
    3044              : 
    3045              : /* Get the value of EXPR within this region_model (assuming the most
    3046              :    recent stack frame if it's a local).  */
    3047              : 
    3048              : const svalue *
    3049      2737392 : region_model::get_rvalue (tree expr, region_model_context *ctxt) const
    3050              : {
    3051      2737392 :   return get_rvalue (path_var (expr, get_stack_depth () - 1), ctxt);
    3052              : }
    3053              : 
    3054              : /* Return true if this model is on a path with "main" as the entrypoint
    3055              :    (as opposed to one in which we're merely analyzing a subset of the
    3056              :    path through the code).  */
    3057              : 
    3058              : bool
    3059      3492539 : region_model::called_from_main_p () const
    3060              : {
    3061      3492539 :   if (!m_current_frame)
    3062              :     return false;
    3063              :   /* Determine if the oldest stack frame in this model is for "main".  */
    3064      3483876 :   const frame_region *frame0 = get_frame_at_index (0);
    3065      3483876 :   gcc_assert (frame0);
    3066      3483876 :   return id_equal (DECL_NAME (frame0->get_function ().decl), "main");
    3067              : }
    3068              : 
    3069              : baseline_state
    3070      3492483 : region_model::get_baseline_state () const
    3071              : {
    3072      3492483 :   if (called_from_main_p ())
    3073              :     return baseline_state::main;
    3074              :   else
    3075      3356974 :     return baseline_state::after_main;
    3076              : }
    3077              : 
    3078              : /* Subroutine of region_model::get_store_value for when REG is (or is within)
    3079              :    a global variable that hasn't been touched since the start of this path
    3080              :    (or was implicitly touched due to a call to an unknown function).  */
    3081              : 
    3082              : const svalue *
    3083            0 : region_model::get_initial_value_for_global (const region *reg) const
    3084              : {
    3085              :   /* Get the decl that REG is for (or is within).  */
    3086            0 :   const decl_region *base_reg
    3087            0 :     = reg->get_base_region ()->dyn_cast_decl_region ();
    3088            0 :   gcc_assert (base_reg);
    3089            0 :   tree decl = base_reg->get_decl ();
    3090              : 
    3091              :   /* Special-case: to avoid having to explicitly update all previously
    3092              :      untracked globals when calling an unknown fn, they implicitly have
    3093              :      an unknown value if an unknown call has occurred, unless this is
    3094              :      static to-this-TU and hasn't escaped.  Globals that have escaped
    3095              :      are explicitly tracked, so we shouldn't hit this case for them.  */
    3096            0 :   if (m_store.called_unknown_fn_p ()
    3097            0 :       && TREE_PUBLIC (decl)
    3098            0 :       && !TREE_READONLY (decl))
    3099            0 :     return m_mgr->get_or_create_unknown_svalue (reg->get_type ());
    3100              : 
    3101              :   /* If we are on a path from the entrypoint from "main" and we have a
    3102              :      global decl defined in this TU that hasn't been touched yet, then
    3103              :      the initial value of REG can be taken from the initialization value
    3104              :      of the decl.  */
    3105            0 :   if (called_from_main_p () || TREE_READONLY (decl))
    3106            0 :     return reg->get_initial_value_at_main (m_mgr);
    3107              : 
    3108              :   /* Otherwise, return INIT_VAL(REG).  */
    3109            0 :   return m_mgr->get_or_create_initial_value (reg);
    3110              : }
    3111              : 
    3112              : /* Get a value for REG, looking it up in the store, or otherwise falling
    3113              :    back to "initial" or "unknown" values.
    3114              :    Use CTXT to report any warnings associated with reading from REG. */
    3115              : 
    3116              : const svalue *
    3117      2122582 : region_model::get_store_value (const region *reg,
    3118              :                                region_model_context *ctxt) const
    3119              : {
    3120              :   /* Getting the value of an empty region gives an unknown_svalue.  */
    3121      2122582 :   if (reg->empty_p (*m_mgr))
    3122            8 :     return m_mgr->get_or_create_unknown_svalue (reg->get_type ());
    3123              : 
    3124              :   /* Special-case: handle var_decls in the constant pool.  */
    3125      2122574 :   if (const decl_region *decl_reg = reg->dyn_cast_decl_region ())
    3126      2058152 :     if (const svalue *sval = decl_reg->maybe_get_constant_value (m_mgr))
    3127              :       return sval;
    3128              : 
    3129      2122558 :   auto &bv = get_store_bits (reg->get_memory_range (*m_mgr), ctxt);
    3130      2122558 :   return m_mgr->get_svalue_from_bit_vector (reg->get_type (), bv);
    3131              : }
    3132              : 
    3133              : /* Simulate reading the bits for MEM_RANGE.
    3134              :    If CTXT is non-null, complain to CTXT about any problems associated
    3135              :    with the read.  */
    3136              : 
    3137              : const symbolic::bit_vector &
    3138      2127289 : region_model::get_store_bits (const symbolic::memory_range &mem_range,
    3139              :                               region_model_context *ctxt) const
    3140              : {
    3141      2127289 :   if (check_memory_range_access (mem_range,
    3142              :                                  access_direction::read,
    3143              :                                  nullptr,
    3144              :                                  ctxt))
    3145              :     {
    3146              :       /* Return a dummy bit_vector if any part of the access is invalid.  */
    3147          472 :       auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
    3148          472 :       return bv_mgr.get_unknown_bits (mem_range.get_size ());
    3149              :     }
    3150      2126817 :   return m_store.get_bits (mem_range, get_baseline_state ());
    3151              : }
    3152              : 
    3153              : /* Get the bit_contents of CLUSTER_REG.
    3154              :    No access checking is performed.  */
    3155              : 
    3156              : const symbolic::bit_contents &
    3157         6607 : region_model::get_bit_contents (const cluster_region &cluster_reg) const
    3158              : {
    3159         6607 :   return get_store ()->get_bit_contents (cluster_reg, get_baseline_state ());
    3160              : }
    3161              : 
    3162              : /* Set the bit_contents of BASE_REG.
    3163              :    No access checking or alias-handling is performed.  */
    3164              : 
    3165              : void
    3166         5578 : region_model::set_bit_contents_raw (const region &base_reg,
    3167              :                                     const symbolic::bit_contents &new_bc)
    3168              : {
    3169         5578 :   return get_store ()->set_bit_contents_raw (base_reg, new_bc, *this);
    3170              : }
    3171              : 
    3172              : /* Return false if REG does not exist, true if it may do.
    3173              :    This is for detecting regions within the stack that don't exist anymore
    3174              :    after frames are popped.  */
    3175              : 
    3176              : bool
    3177      1127706 : region_model::region_exists_p (const region *reg) const
    3178              : {
    3179              :   /* If within a stack frame, check that the stack frame is live.  */
    3180      1127706 :   if (const frame_region *enclosing_frame = reg->maybe_get_frame_region ())
    3181              :     {
    3182              :       /* Check that the current frame is the enclosing frame, or is called
    3183              :          by it.  */
    3184      1560367 :       for (const frame_region *iter_frame = get_current_frame (); iter_frame;
    3185       535945 :            iter_frame = iter_frame->get_calling_frame ())
    3186      1545775 :         if (iter_frame == enclosing_frame)
    3187              :           return true;
    3188              :       return false;
    3189              :     }
    3190              : 
    3191              :   return true;
    3192              : }
    3193              : 
    3194              : /* Get a region for referencing PTR_SVAL, creating a region if need be, and
    3195              :    potentially generating warnings via CTXT.
    3196              :    PTR_SVAL must be of pointer type.
    3197              :    PTR_TREE if non-NULL can be used when emitting diagnostics.  */
    3198              : 
    3199              : const region *
    3200       108384 : region_model::deref_rvalue (const svalue *ptr_sval, tree ptr_tree,
    3201              :                             region_model_context *ctxt,
    3202              :                             bool add_nonnull_constraint) const
    3203              : {
    3204       108384 :   gcc_assert (ptr_sval);
    3205       108384 :   gcc_assert (ptr_sval->get_type ());
    3206       108384 :   gcc_assert (POINTER_TYPE_P (ptr_sval->get_type ()));
    3207              : 
    3208              :   /* If we're dereferencing PTR_SVAL, assume that it is non-NULL; add this
    3209              :      as a constraint.  This suppresses false positives from
    3210              :      -Wanalyzer-null-dereference for the case where we later have an
    3211              :      if (PTR_SVAL) that would occur if we considered the false branch
    3212              :      and transitioned the malloc state machine from start->null.  */
    3213       108384 :   if (add_nonnull_constraint)
    3214              :     {
    3215        99827 :       tree null_ptr_cst = build_int_cst (ptr_sval->get_type (), 0);
    3216        99827 :       const svalue *null_ptr
    3217        99827 :         = m_mgr->get_or_create_constant_svalue (null_ptr_cst);
    3218        99827 :       m_constraints->add_constraint (ptr_sval, NE_EXPR, null_ptr);
    3219              :     }
    3220              : 
    3221       108384 :   switch (ptr_sval->get_kind ())
    3222              :     {
    3223              :     default:
    3224              :       break;
    3225              : 
    3226         6588 :     case SK_BINOP:
    3227         6588 :       {
    3228         6588 :         const binop_svalue *binop_sval
    3229         6588 :           = as_a <const binop_svalue *> (ptr_sval);
    3230         6588 :         switch (binop_sval->get_op ())
    3231              :           {
    3232         6588 :           case POINTER_PLUS_EXPR:
    3233         6588 :             {
    3234              :               /* If we have a symbolic value expressing pointer arithmetic,
    3235              :                  try to convert it to a suitable region.  */
    3236         6588 :               const region *parent_region
    3237         6588 :                 = deref_rvalue (binop_sval->get_arg0 (), NULL_TREE, ctxt);
    3238         6588 :               const svalue *offset = binop_sval->get_arg1 ();
    3239         6588 :               tree type= TREE_TYPE (ptr_sval->get_type ());
    3240         6588 :               return m_mgr->get_offset_region (parent_region, type, offset);
    3241              :             }
    3242              :           default:
    3243              :             break;
    3244              :           }
    3245              :       }
    3246              :       break;
    3247              : 
    3248            0 :     case SK_POISONED:
    3249            0 :       {
    3250            0 :         if (ctxt)
    3251              :           {
    3252            0 :             tree ptr = get_representative_tree (ptr_sval);
    3253              :             /* If we can't get a representative tree for PTR_SVAL
    3254              :                (e.g. if it hasn't been bound into the store), then
    3255              :                fall back on PTR_TREE, if non-NULL.  */
    3256            0 :             if (!ptr)
    3257            0 :               ptr = ptr_tree;
    3258            0 :             if (ptr)
    3259              :               {
    3260            0 :                 const poisoned_svalue *poisoned_sval
    3261            0 :                   = as_a <const poisoned_svalue *> (ptr_sval);
    3262            0 :                 enum poison_kind pkind = poisoned_sval->get_poison_kind ();
    3263            0 :                 ctxt->warn (make_poisoned_value_diagnostic
    3264            0 :                               (ptr, pkind, nullptr, nullptr));
    3265              :               }
    3266              :           }
    3267              :       }
    3268              :       break;
    3269              :     }
    3270              : 
    3271       101796 :   return m_mgr->get_symbolic_region (ptr_sval);
    3272              : }
    3273              : 
    3274              : /* Attempt to get BITS within any value of REG, as TYPE.
    3275              :    In particular, extract values from compound_svalues for the case
    3276              :    where there's a concrete binding at BITS.
    3277              :    Return an unknown svalue if we can't handle the given case.
    3278              :    Use CTXT to report any warnings associated with reading from REG.  */
    3279              : 
    3280              : const svalue *
    3281          132 : region_model::get_rvalue_for_bits (tree type,
    3282              :                                    const region *reg,
    3283              :                                    const bit_range &bits,
    3284              :                                    region_model_context *ctxt) const
    3285              : {
    3286          132 :   auto &bv = get_store_bits (reg->get_memory_range (*m_mgr), ctxt);
    3287          132 :   auto &cropped = bv.get_cropped_bits (convert_from_bit_range (bits));
    3288          132 :   return get_manager ()->get_svalue_from_bit_vector (type, cropped);
    3289              : }
    3290              : 
    3291              : /* Use CTXT to warn If BASE_REG is a region that shouldn't be written to.  */
    3292              : 
    3293              : void
    3294       202204 : region_model::check_for_writable_region (const region *base_reg,
    3295              :                                          region_model_context *ctxt) const
    3296              : {
    3297              :   /* Fail gracefully if CTXT is nullptr.  */
    3298       202204 :   if (!ctxt)
    3299              :     return;
    3300              : 
    3301       202204 :   switch (base_reg->get_kind ())
    3302              :     {
    3303              :     default:
    3304              :       break;
    3305            9 :     case RK_FUNCTION:
    3306            9 :       {
    3307            9 :         const function_region *func_reg = as_a <const function_region *> (base_reg);
    3308            9 :         tree fndecl = func_reg->get_fndecl ();
    3309            9 :         ctxt->warn (make_write_to_const_diagnostic (func_reg, fndecl));
    3310              :       }
    3311            9 :       break;
    3312            4 :     case RK_LABEL:
    3313            4 :       {
    3314            4 :         const label_region *label_reg = as_a <const label_region *> (base_reg);
    3315            4 :         tree label = label_reg->get_label ();
    3316            4 :         ctxt->warn (make_write_to_const_diagnostic (label_reg, label));
    3317              :       }
    3318            4 :       break;
    3319       189888 :     case RK_DECL:
    3320       189888 :       {
    3321       189888 :         const decl_region *decl_reg = as_a <const decl_region *> (base_reg);
    3322       189888 :         tree decl = decl_reg->get_decl ();
    3323              :         /* Warn about writes to const globals.
    3324              :            Don't warn for writes to const locals, and params in particular,
    3325              :            since we would warn in push_frame when setting them up (e.g the
    3326              :            "this" param is "T* const").  */
    3327       189888 :         if (TREE_READONLY (decl)
    3328       189888 :             && is_global_var (decl))
    3329           20 :           ctxt->warn (make_write_to_const_diagnostic (base_reg, decl));
    3330              :       }
    3331              :       break;
    3332           51 :     case RK_STRING:
    3333           51 :       ctxt->warn (make_write_to_string_literal_diagnostic (base_reg));
    3334           51 :       break;
    3335              :     }
    3336              : }
    3337              : 
    3338              : /* Get the capacity of REG in bytes.  */
    3339              : 
    3340              : const svalue *
    3341       712832 : region_model::get_capacity (const region *reg) const
    3342              : {
    3343       715190 :   switch (reg->get_kind ())
    3344              :     {
    3345              :     default:
    3346              :       break;
    3347       620012 :     case RK_DECL:
    3348       620012 :       {
    3349       620012 :         const decl_region *decl_reg = as_a <const decl_region *> (reg);
    3350       620012 :         tree decl = decl_reg->get_decl ();
    3351       620012 :         if (TREE_CODE (decl) == SSA_NAME)
    3352              :           {
    3353       544320 :             tree type = TREE_TYPE (decl);
    3354       544320 :             tree size = TYPE_SIZE (type);
    3355       544320 :             return get_rvalue (size, nullptr);
    3356              :           }
    3357              :         else
    3358              :           {
    3359        75692 :             tree size = decl_init_size (decl, false);
    3360        75692 :             if (size)
    3361        75335 :               return get_rvalue (size, nullptr);
    3362              :           }
    3363              :       }
    3364              :       break;
    3365         2358 :     case RK_SIZED:
    3366              :       /* Look through sized regions to get at the capacity
    3367              :          of the underlying regions.  */
    3368         2358 :       return get_capacity (reg->get_parent_region ());
    3369         3355 :     case RK_STRING:
    3370         3355 :       {
    3371              :         /* "Capacity" here means "size".  */
    3372         3355 :         const string_region *string_reg = as_a <const string_region *> (reg);
    3373         3355 :         tree string_cst = string_reg->get_string_cst ();
    3374         3355 :         return m_mgr->get_or_create_int_cst (size_type_node,
    3375         3355 :                                              TREE_STRING_LENGTH (string_cst));
    3376              :       }
    3377        89822 :       break;
    3378              :     }
    3379              : 
    3380        89822 :   if (const svalue *recorded = get_dynamic_extents (reg))
    3381              :     return recorded;
    3382              : 
    3383        75889 :   return m_mgr->get_or_create_unknown_svalue (sizetype);
    3384              : }
    3385              : 
    3386              : const symbolic::scalar<integer_with_unit<units::byte>> &
    3387       665169 : region_model::get_capacity_as_scalar (const region *reg) const
    3388              : {
    3389       665169 :   const svalue *sval = get_capacity (reg);
    3390              : 
    3391       665169 :   auto &byte_mgr = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
    3392       665169 :   return byte_mgr.get_scalar_from_svalue (*sval);
    3393              : }
    3394              : 
    3395              : /* If CTXT is non-NULL, use it to warn about any problems accessing MEM_RANGE,
    3396              :    using DIR to determine if this access is a read or write.
    3397              :    Return TRUE if an OOB access was detected.
    3398              :    If SVAL_HINT is non-NULL, use it as a hint in diagnostics
    3399              :    about the value that would be written to the memory.  */
    3400              : 
    3401              : bool
    3402      2409951 : region_model::
    3403              : check_memory_range_access (const symbolic::memory_range &mem_range,
    3404              :                            enum access_direction dir,
    3405              :                            const svalue *sval_hint,
    3406              :                            region_model_context *ctxt) const
    3407              : {
    3408              :   /* Fail gracefully if CTXT is NULL.  */
    3409      2409951 :   if (!ctxt)
    3410              :     return false;
    3411              : 
    3412       663776 :   bool oob_access_detected = false;
    3413       663776 :   check_memory_range_for_taint (mem_range, ctxt);
    3414       663776 :   if (!check_memory_range_bounds (mem_range, dir, sval_hint, ctxt))
    3415          861 :     oob_access_detected = true;
    3416              : 
    3417       663776 :   switch (dir)
    3418              :     {
    3419            0 :     default:
    3420            0 :       gcc_unreachable ();
    3421              :     case access_direction::read:
    3422              :       /* Currently a no-op.  */
    3423              :       break;
    3424       202204 :     case access_direction::write:
    3425       202204 :       check_for_writable_region (&mem_range.get_base_region (), ctxt);
    3426       202204 :       break;
    3427              :     }
    3428              :   return oob_access_detected;
    3429              : }
    3430              : 
    3431              : /* If CTXT is non-NULL, use it to warn about any problems accessing REG,
    3432              :    using DIR to determine if this access is a read or write.
    3433              :    Return TRUE if an OOB access was detected.
    3434              :    If SVAL_HINT is non-NULL, use it as a hint in diagnostics
    3435              :    about the value that would be written to REG.  */
    3436              : 
    3437              : bool
    3438           97 : region_model::check_region_access (const region *reg,
    3439              :                                    enum access_direction dir,
    3440              :                                    const svalue *sval_hint,
    3441              :                                    region_model_context *ctxt) const
    3442              : {
    3443           97 :   return check_memory_range_access (reg->get_memory_range (*get_manager ()),
    3444              :                                     dir,
    3445              :                                     sval_hint,
    3446           97 :                                     ctxt);
    3447              : }
    3448              : 
    3449              : /* If CTXT is non-NULL, use it to warn about any problems writing to REG.  */
    3450              : 
    3451              : void
    3452           97 : region_model::check_region_for_write (const region *dest_reg,
    3453              :                                       const svalue *sval_hint,
    3454              :                                       region_model_context *ctxt) const
    3455              : {
    3456           97 :   check_region_access (dest_reg, access_direction::write, sval_hint, ctxt);
    3457           97 : }
    3458              : 
    3459              : /* Concrete subclass for casts of pointers that lead to trailing bytes.  */
    3460              : 
    3461              : class dubious_allocation_size
    3462              : : public pending_diagnostic_subclass<dubious_allocation_size>
    3463              : {
    3464              : public:
    3465          122 :   dubious_allocation_size (const region *lhs, const region *rhs,
    3466              :                            const svalue *capacity_sval, tree expr,
    3467              :                            const gimple *stmt)
    3468          122 :   : m_lhs (lhs), m_rhs (rhs),
    3469          122 :     m_capacity_sval (capacity_sval), m_expr (expr),
    3470          122 :     m_stmt (stmt),
    3471          122 :     m_has_allocation_event (false)
    3472              :   {
    3473          122 :     gcc_assert (m_capacity_sval);
    3474              :   }
    3475              : 
    3476         1253 :   const char *get_kind () const final override
    3477              :   {
    3478         1253 :     return "dubious_allocation_size";
    3479              :   }
    3480              : 
    3481          122 :   bool operator== (const dubious_allocation_size &other) const
    3482              :   {
    3483          122 :     return (m_stmt == other.m_stmt
    3484          122 :             && pending_diagnostic::same_tree_p (m_expr, other.m_expr));
    3485              :   }
    3486              : 
    3487          244 :   int get_controlling_option () const final override
    3488              :   {
    3489          244 :     return OPT_Wanalyzer_allocation_size;
    3490              :   }
    3491              : 
    3492          122 :   bool emit (diagnostic_emission_context &ctxt) final override
    3493              :   {
    3494          122 :     ctxt.add_cwe (131);
    3495              : 
    3496          122 :     return ctxt.warn ("allocated buffer size is not a multiple"
    3497          122 :                       " of the pointee's size");
    3498              :   }
    3499              : 
    3500              :   bool
    3501          244 :   describe_final_event (pretty_printer &pp,
    3502              :                         const evdesc::final_event &) final override
    3503              :   {
    3504          244 :     tree pointee_type = TREE_TYPE (m_lhs->get_type ());
    3505          244 :     if (m_has_allocation_event)
    3506              :       {
    3507          236 :         pp_printf (&pp,
    3508              :                    "assigned to %qT here;"
    3509              :                    " %<sizeof (%T)%> is %qE",
    3510          236 :                    m_lhs->get_type (), pointee_type,
    3511              :                    size_in_bytes (pointee_type));
    3512          236 :         return true;
    3513              :       }
    3514              :     /* Fallback: Typically, we should always see an allocation_event
    3515              :        before.  */
    3516            8 :     if (m_expr)
    3517              :       {
    3518            8 :         if (TREE_CODE (m_expr) == INTEGER_CST)
    3519              :           {
    3520            8 :             pp_printf (&pp,
    3521              :                        "allocated %E bytes and assigned to"
    3522              :                        " %qT here; %<sizeof (%T)%> is %qE",
    3523            8 :                        m_expr, m_lhs->get_type (), pointee_type,
    3524              :                        size_in_bytes (pointee_type));
    3525            8 :             return true;
    3526              :           }
    3527              :         else
    3528              :           {
    3529            0 :             pp_printf (&pp,
    3530              :                        "allocated %qE bytes and assigned to"
    3531              :                        " %qT here; %<sizeof (%T)%> is %qE",
    3532            0 :                        m_expr, m_lhs->get_type (), pointee_type,
    3533              :                        size_in_bytes (pointee_type));
    3534            0 :             return true;
    3535              :           }
    3536              :       }
    3537              : 
    3538            0 :     pp_printf (&pp,
    3539              :                "allocated and assigned to %qT here;"
    3540              :                " %<sizeof (%T)%> is %qE",
    3541            0 :                m_lhs->get_type (), pointee_type,
    3542              :                size_in_bytes (pointee_type));
    3543            0 :     return true;
    3544              :   }
    3545              : 
    3546              :   void
    3547          118 :   add_region_creation_events (const region *,
    3548              :                               tree capacity,
    3549              :                               const event_loc_info &loc_info,
    3550              :                               checker_path &emission_path) final override
    3551              :   {
    3552          118 :     emission_path.add_event
    3553          118 :       (std::make_unique<region_creation_event_allocation_size>
    3554          118 :          (capacity, loc_info));
    3555              : 
    3556          118 :     m_has_allocation_event = true;
    3557          118 :   }
    3558              : 
    3559          244 :   void mark_interesting_stuff (interesting_t *interest) final override
    3560              :   {
    3561          244 :     interest->add_region_creation (m_rhs);
    3562          244 :   }
    3563              : 
    3564              :   void
    3565            0 :   maybe_add_sarif_properties (diagnostics::sarif_object &result_obj)
    3566              :     const final override
    3567              :   {
    3568            0 :     auto &props = result_obj.get_or_create_properties ();
    3569              : #define PROPERTY_PREFIX "gcc/analyzer/dubious_allocation_size/"
    3570            0 :     props.set (PROPERTY_PREFIX "lhs", m_lhs->to_json ());
    3571            0 :     props.set (PROPERTY_PREFIX "rhs", m_rhs->to_json ());
    3572            0 :     props.set (PROPERTY_PREFIX "capacity_sval", m_capacity_sval->to_json ());
    3573              : #undef PROPERTY_PREFIX
    3574            0 :   }
    3575              : 
    3576              : private:
    3577              :   const region *m_lhs;
    3578              :   const region *m_rhs;
    3579              :   const svalue *m_capacity_sval;
    3580              :   const tree m_expr;
    3581              :   const gimple *m_stmt;
    3582              :   bool m_has_allocation_event;
    3583              : };
    3584              : 
    3585              : /* Return true on dubious allocation sizes for constant sizes.  */
    3586              : 
    3587              : static bool
    3588         2074 : capacity_compatible_with_type (tree cst, tree pointee_size_tree,
    3589              :                                bool is_struct)
    3590              : {
    3591         2074 :   gcc_assert (TREE_CODE (cst) == INTEGER_CST);
    3592         2074 :   gcc_assert (TREE_CODE (pointee_size_tree) == INTEGER_CST);
    3593              : 
    3594         2074 :   unsigned HOST_WIDE_INT pointee_size = TREE_INT_CST_LOW (pointee_size_tree);
    3595         2074 :   unsigned HOST_WIDE_INT alloc_size = TREE_INT_CST_LOW (cst);
    3596              : 
    3597         2074 :   if (is_struct)
    3598          636 :     return alloc_size == 0 || alloc_size >= pointee_size;
    3599         1438 :   return alloc_size % pointee_size == 0;
    3600              : }
    3601              : 
    3602              : static bool
    3603          386 : capacity_compatible_with_type (tree cst, tree pointee_size_tree)
    3604              : {
    3605            0 :   return capacity_compatible_with_type (cst, pointee_size_tree, false);
    3606              : }
    3607              : 
    3608              : /* Checks whether SVAL could be a multiple of SIZE_CST.
    3609              : 
    3610              :    It works by visiting all svalues inside SVAL until it reaches
    3611              :    atomic nodes.  From those, it goes back up again and adds each
    3612              :    node that is not a multiple of SIZE_CST to the RESULT_SET.  */
    3613              : 
    3614         6616 : class size_visitor : public visitor
    3615              : {
    3616              : public:
    3617         3308 :   size_visitor (tree size_cst, const svalue *root_sval, constraint_manager *cm)
    3618         3308 :   : m_size_cst (size_cst), m_root_sval (root_sval), m_cm (cm)
    3619              :   {
    3620         3308 :     m_root_sval->accept (this);
    3621              :   }
    3622              : 
    3623         3308 :   bool is_dubious_capacity ()
    3624              :   {
    3625         3308 :     return result_set.contains (m_root_sval);
    3626              :   }
    3627              : 
    3628          394 :   void visit_constant_svalue (const constant_svalue *sval) final override
    3629              :   {
    3630          394 :     check_constant (sval->get_constant (), sval);
    3631          394 :   }
    3632              : 
    3633          242 :   void visit_unaryop_svalue (const unaryop_svalue *sval) final override
    3634              :   {
    3635          242 :     if (CONVERT_EXPR_CODE_P (sval->get_op ())
    3636          242 :           && result_set.contains (sval->get_arg ()))
    3637          109 :       result_set.add (sval);
    3638          242 :   }
    3639              : 
    3640          386 :   void visit_binop_svalue (const binop_svalue *sval) final override
    3641              :   {
    3642          386 :     const svalue *arg0 = sval->get_arg0 ();
    3643          386 :     const svalue *arg1 = sval->get_arg1 ();
    3644              : 
    3645          386 :     switch (sval->get_op ())
    3646              :       {
    3647          276 :         case MULT_EXPR:
    3648          276 :           if (result_set.contains (arg0) && result_set.contains (arg1))
    3649           24 :             result_set.add (sval);
    3650              :           break;
    3651           90 :         case PLUS_EXPR:
    3652           90 :         case MINUS_EXPR:
    3653           90 :           if (result_set.contains (arg0) || result_set.contains (arg1))
    3654           28 :             result_set.add (sval);
    3655              :           break;
    3656              :         default:
    3657              :           break;
    3658              :       }
    3659          386 :   }
    3660              : 
    3661            0 :   void visit_unmergeable_svalue (const unmergeable_svalue *sval) final override
    3662              :   {
    3663            0 :     if (result_set.contains (sval->get_arg ()))
    3664            0 :       result_set.add (sval);
    3665            0 :   }
    3666              : 
    3667           12 :   void visit_widening_svalue (const widening_svalue *sval) final override
    3668              :   {
    3669           12 :     const svalue *base = sval->get_base_svalue ();
    3670           12 :     const svalue *iter = sval->get_iter_svalue ();
    3671              : 
    3672           12 :     if (result_set.contains (base) || result_set.contains (iter))
    3673            8 :       result_set.add (sval);
    3674           12 :   }
    3675              : 
    3676          291 :   void visit_initial_svalue (const initial_svalue *sval) final override
    3677              :   {
    3678          291 :     equiv_class_id id = equiv_class_id::null ();
    3679          291 :     if (m_cm->get_equiv_class_by_svalue (sval, &id))
    3680              :       {
    3681           63 :         if (tree cst = id.get_obj (*m_cm).get_any_constant ())
    3682            0 :           check_constant (cst, sval);
    3683              :       }
    3684          228 :     else if (!m_cm->sval_constrained_p (sval))
    3685              :       {
    3686          174 :         result_set.add (sval);
    3687              :       }
    3688          291 :   }
    3689              : 
    3690              :   void
    3691           38 :   visit_svalue_from_bit_vector (const svalue_from_bit_vector *sval)
    3692              :     final override
    3693              :   {
    3694           38 :     equiv_class_id id = equiv_class_id::null ();
    3695           38 :     if (m_cm->get_equiv_class_by_svalue (sval, &id))
    3696           17 :       if (tree cst = id.get_obj (*m_cm).get_any_constant ())
    3697              :         {
    3698           12 :           check_constant (cst, sval);
    3699           12 :           return;
    3700              :         }
    3701              : 
    3702           26 :     tree type = sval->get_type ();
    3703           26 :     if (type && INTEGRAL_TYPE_P (type))
    3704           13 :       if (tree cst = m_cm->get_any_constant_for_bit_vector
    3705           13 :                        (sval->get_bit_vector ()))
    3706            4 :         check_constant (fold_convert (type, cst), sval);
    3707              :   }
    3708              : 
    3709              : private:
    3710          410 :   void check_constant (tree cst, const svalue *sval)
    3711              :   {
    3712          410 :     switch (TREE_CODE (cst))
    3713              :       {
    3714              :       default:
    3715              :         /* Assume all unhandled operands are compatible.  */
    3716              :         break;
    3717          386 :       case INTEGER_CST:
    3718          386 :         if (!capacity_compatible_with_type (cst, m_size_cst))
    3719           68 :           result_set.add (sval);
    3720              :         break;
    3721              :       }
    3722          410 :   }
    3723              : 
    3724              :   tree m_size_cst;
    3725              :   const svalue *m_root_sval;
    3726              :   constraint_manager *m_cm;
    3727              :   value_set result_set; /* Used as a mapping of svalue*->bool.  */
    3728              : };
    3729              : 
    3730              : /* Return true if SIZE_CST is a power of 2, and we have
    3731              :    CAPACITY_SVAL == ((X | (Y - 1) ) + 1), since it is then a multiple
    3732              :    of SIZE_CST, as used by Linux kernel's round_up macro.  */
    3733              : 
    3734              : static bool
    3735         3312 : is_round_up (tree size_cst,
    3736              :              const svalue *capacity_sval)
    3737              : {
    3738         3312 :   if (!integer_pow2p (size_cst))
    3739              :     return false;
    3740         3304 :   const binop_svalue *binop_sval = capacity_sval->dyn_cast_binop_svalue ();
    3741         3304 :   if (!binop_sval)
    3742              :     return false;
    3743          264 :   if (binop_sval->get_op () != PLUS_EXPR)
    3744              :     return false;
    3745           70 :   tree rhs_cst = binop_sval->get_arg1 ()->maybe_get_constant ();
    3746           70 :   if (!rhs_cst)
    3747              :     return false;
    3748           70 :   if (!integer_onep (rhs_cst))
    3749              :     return false;
    3750              : 
    3751              :   /* We have CAPACITY_SVAL == (LHS + 1) for some LHS expression.  */
    3752              : 
    3753            4 :   const binop_svalue *lhs_binop_sval
    3754            4 :     = binop_sval->get_arg0 ()->dyn_cast_binop_svalue ();
    3755            4 :   if (!lhs_binop_sval)
    3756              :     return false;
    3757            4 :   if (lhs_binop_sval->get_op () != BIT_IOR_EXPR)
    3758              :     return false;
    3759              : 
    3760            4 :   tree inner_rhs_cst = lhs_binop_sval->get_arg1 ()->maybe_get_constant ();
    3761            4 :   if (!inner_rhs_cst)
    3762              :     return false;
    3763              : 
    3764            4 :   if (wi::to_widest (inner_rhs_cst) + 1 != wi::to_widest (size_cst))
    3765              :     return false;
    3766              :   return true;
    3767              : }
    3768              : 
    3769              : /* Return true if CAPACITY_SVAL is known to be a multiple of SIZE_CST.  */
    3770              : 
    3771              : static bool
    3772         3312 : is_multiple_p (tree size_cst,
    3773              :                const svalue *capacity_sval)
    3774              : {
    3775         3372 :   if (const svalue *sval = capacity_sval->maybe_undo_cast ())
    3776              :     return is_multiple_p (size_cst, sval);
    3777              : 
    3778         3312 :   if (is_round_up (size_cst, capacity_sval))
    3779              :     return true;
    3780              : 
    3781              :   return false;
    3782              : }
    3783              : 
    3784              : /* Return true if we should emit a dubious_allocation_size warning
    3785              :    on assigning a region of capacity CAPACITY_SVAL bytes to a pointer
    3786              :    of type with size SIZE_CST, where CM expresses known constraints.  */
    3787              : 
    3788              : static bool
    3789         3312 : is_dubious_capacity (tree size_cst,
    3790              :                      const svalue *capacity_sval,
    3791              :                      constraint_manager *cm)
    3792              : {
    3793         3312 :   if (is_multiple_p (size_cst, capacity_sval))
    3794              :     return false;
    3795         3308 :   size_visitor v (size_cst, capacity_sval, cm);
    3796         3308 :   return v.is_dubious_capacity ();
    3797         3308 : }
    3798              : 
    3799              : 
    3800              : /* Return true if a struct or union either uses the inheritance pattern,
    3801              :    where the first field is a base struct, or the flexible array member
    3802              :    pattern, where the last field is an array without a specified size.  */
    3803              : 
    3804              : static bool
    3805         2600 : struct_or_union_with_inheritance_p (tree struc)
    3806              : {
    3807         2600 :   tree iter = TYPE_FIELDS (struc);
    3808         2600 :   if (iter == NULL_TREE)
    3809              :           return false;
    3810         2592 :   if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (iter)))
    3811              :           return true;
    3812              : 
    3813              :   tree last_field;
    3814        52400 :   while (iter != NULL_TREE)
    3815              :     {
    3816        50207 :       last_field = iter;
    3817        50207 :       iter = DECL_CHAIN (iter);
    3818              :     }
    3819              : 
    3820         2193 :   if (last_field != NULL_TREE
    3821         2193 :       && TREE_CODE (TREE_TYPE (last_field)) == ARRAY_TYPE)
    3822           24 :           return true;
    3823              : 
    3824              :   return false;
    3825              : }
    3826              : 
    3827              : /* Return true if the lhs and rhs of an assignment have different types,
    3828              :    ignoring qualifiers and typedefs.  */
    3829              : 
    3830              : static bool
    3831       154701 : is_any_cast_p (const gimple *stmt)
    3832              : {
    3833       154701 :   if (const gassign *assign = dyn_cast <const gassign *> (stmt))
    3834       117713 :     return gimple_assign_cast_p (assign)
    3835       323639 :            || !pending_diagnostic::same_tree_p (
    3836       102963 :                   TYPE_MAIN_VARIANT (TREE_TYPE (gimple_assign_lhs (assign))),
    3837       102963 :                   TYPE_MAIN_VARIANT (TREE_TYPE (gimple_assign_rhs1 (assign))));
    3838        36988 :   else if (const gcall *call = dyn_cast <const gcall *> (stmt))
    3839              :     {
    3840        36580 :       tree lhs = gimple_call_lhs (call);
    3841        65989 :       return lhs != NULL_TREE && !pending_diagnostic::same_tree_p (
    3842        29409 :                   TYPE_MAIN_VARIANT (TREE_TYPE (lhs)),
    3843        29409 :                   TYPE_MAIN_VARIANT (gimple_call_return_type (call)));
    3844              :     }
    3845              : 
    3846              :   return false;
    3847              : }
    3848              : 
    3849              : /* On pointer assignments, check whether the buffer size of
    3850              :    RHS_SVAL is compatible with the type of the LHS_REG.
    3851              :    Use a non-null CTXT to report allocation size warnings.  */
    3852              : 
    3853              : void
    3854       278520 : region_model::check_region_size (const region *lhs_reg, const svalue *rhs_sval,
    3855              :                                  region_model_context *ctxt) const
    3856              : {
    3857       278520 :   if (!ctxt || ctxt->get_stmt () == nullptr)
    3858       272452 :     return;
    3859              :   /* Only report warnings on assignments that actually change the type.  */
    3860       154701 :   if (!is_any_cast_p (ctxt->get_stmt ()))
    3861              :     return;
    3862              : 
    3863        32356 :   tree pointer_type = lhs_reg->get_type ();
    3864        32356 :   if (pointer_type == NULL_TREE || !POINTER_TYPE_P (pointer_type))
    3865              :     return;
    3866              : 
    3867        10391 :   tree pointee_type = TREE_TYPE (pointer_type);
    3868              :   /* Make sure that the type on the left-hand size actually has a size.  */
    3869        10391 :   if (pointee_type == NULL_TREE || VOID_TYPE_P (pointee_type)
    3870        20031 :       || TYPE_SIZE_UNIT (pointee_type) == NULL_TREE)
    3871              :     return;
    3872              : 
    3873              :   /* Bail out early on function pointers.  */
    3874         9587 :   if (TREE_CODE (pointee_type) == FUNCTION_TYPE)
    3875              :     return;
    3876              : 
    3877              :   /* Bail out early on pointers to structs where we can
    3878              :      not deduce whether the buffer size is compatible.  */
    3879         9511 :   bool is_struct = RECORD_OR_UNION_TYPE_P (pointee_type);
    3880         9511 :   if (is_struct && struct_or_union_with_inheritance_p (pointee_type))
    3881              :     return;
    3882              : 
    3883         9088 :   tree pointee_size_tree = size_in_bytes (pointee_type);
    3884              :   /* We give up if the type size is not known at compile-time or the
    3885              :      type size is always compatible regardless of the buffer size.  */
    3886         9088 :   if (TREE_CODE (pointee_size_tree) != INTEGER_CST
    3887         9001 :       || integer_zerop (pointee_size_tree)
    3888        18076 :       || integer_onep (pointee_size_tree))
    3889              :     return;
    3890              : 
    3891         6068 :   const region *rhs_reg = deref_rvalue (rhs_sval, NULL_TREE, ctxt, false);
    3892         6068 :   const svalue *capacity = get_capacity (rhs_reg);
    3893         6068 :   switch (capacity->get_kind ())
    3894              :     {
    3895         1688 :     case svalue_kind::SK_CONSTANT:
    3896         1688 :       {
    3897         1688 :         const constant_svalue *cst_cap_sval
    3898         1688 :           = as_a <const constant_svalue *> (capacity);
    3899         1688 :         tree cst_cap = cst_cap_sval->get_constant ();
    3900         1688 :         if (TREE_CODE (cst_cap) == INTEGER_CST
    3901         1688 :             && !capacity_compatible_with_type (cst_cap, pointee_size_tree,
    3902              :                                                is_struct))
    3903           66 :           ctxt->warn
    3904          132 :             (std::make_unique <dubious_allocation_size> (lhs_reg, rhs_reg,
    3905              :                                                          capacity, cst_cap,
    3906          132 :                                                          ctxt->get_stmt ()));
    3907              :       }
    3908         1688 :       break;
    3909         4380 :     default:
    3910         4380 :       {
    3911         4380 :         if (!is_struct)
    3912              :           {
    3913         3312 :             if (is_dubious_capacity (pointee_size_tree,
    3914              :                                      capacity,
    3915         3312 :                                      m_constraints))
    3916              :               {
    3917           56 :                 tree expr = get_representative_tree (capacity);
    3918           56 :                 ctxt->warn
    3919          112 :                   (std::make_unique <dubious_allocation_size> (lhs_reg,
    3920              :                                                                rhs_reg,
    3921              :                                                                capacity, expr,
    3922          112 :                                                                ctxt->get_stmt ()));
    3923              :               }
    3924              :           }
    3925              :       break;
    3926              :       }
    3927              :     }
    3928              : }
    3929              : 
    3930              : /* Write BIT_VEC to the memory starting at MEM_OFFSET.
    3931              :    If non-null, complain to CTXT about any problems that occur.  */
    3932              : 
    3933              : void
    3934       282565 : region_model::
    3935              : write_to_memory_offset (const symbolic::memory_offset &mem_offset,
    3936              :                         const symbolic::bit_vector &bv,
    3937              :                         region_model_context *ctxt)
    3938              : {
    3939       282565 :   symbolic::memory_range mem_range
    3940              :     (mem_offset.get_base_region (),
    3941       282565 :      symbolic_bit_range (mem_offset.get_bit_offset (),
    3942       282565 :                          bv.get_size ()));
    3943       282565 :   const svalue *sval_hint = nullptr;
    3944       282565 :   if (auto *bv_sval = bv.dyn_cast_bit_vector_from_svalue ())
    3945       168408 :     sval_hint = &bv_sval->get_svalue ();
    3946       282565 :   if (check_memory_range_access (mem_range,
    3947              :                                  access_direction::write,
    3948              :                                  sval_hint,
    3949              :                                  ctxt))
    3950              :     /* Bail out if any part of the access is invalid.  */
    3951          374 :     return;
    3952       483924 :   m_store.set_bits (mem_range, bv,
    3953       201733 :                     ctxt ? ctxt->get_uncertainty () : nullptr,
    3954              :                     *this);
    3955              : }
    3956              : 
    3957              : /* Set the value of the region given by LHS_REG to the value given
    3958              :    by RHS_SVAL.
    3959              :    Use CTXT to report any warnings associated with writing to LHS_REG.  */
    3960              : 
    3961              : void
    3962       278520 : region_model::set_value (const region *lhs_reg, const svalue *rhs_sval,
    3963              :                          region_model_context *ctxt)
    3964              : {
    3965       278520 :   gcc_assert (lhs_reg);
    3966       278520 :   gcc_assert (rhs_sval);
    3967              : 
    3968              :   /* Setting the value of an empty region is a no-op.  */
    3969       278520 :   if (lhs_reg->empty_p (*m_mgr))
    3970              :     return;
    3971              : 
    3972       278520 :   check_region_size (lhs_reg, rhs_sval, ctxt);
    3973              : 
    3974       278520 :   auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
    3975       278520 :   auto &bv = bv_mgr.get_bit_vector_from_svalue (*rhs_sval);
    3976              : 
    3977       278520 :   symbolic::memory_offset mem_offset = lhs_reg->get_memory_offset (*m_mgr);
    3978       278520 :   write_to_memory_offset (mem_offset, bv, ctxt);
    3979              : }
    3980              : 
    3981              : /* Set the value of the region given by LHS to the value given by RHS.  */
    3982              : 
    3983              : void
    3984           84 : region_model::set_value (tree lhs, tree rhs, region_model_context *ctxt)
    3985              : {
    3986           84 :   const region *lhs_reg = get_lvalue (lhs, ctxt);
    3987           84 :   const svalue *rhs_sval = get_rvalue (rhs, ctxt);
    3988           84 :   gcc_assert (lhs_reg);
    3989           84 :   gcc_assert (rhs_sval);
    3990           84 :   set_value (lhs_reg, rhs_sval, ctxt);
    3991           84 : }
    3992              : 
    3993              : /* Issue a note specifying that a particular function parameter is expected
    3994              :    to be a valid null-terminated string.  */
    3995              : 
    3996              : static void
    3997          175 : inform_about_expected_null_terminated_string_arg (const call_arg_details &ad)
    3998              : {
    3999              :   // TODO: ideally we'd underline the param here
    4000          175 :   inform (DECL_SOURCE_LOCATION (ad.m_called_fndecl),
    4001              :           "argument %d of %qD must be a pointer to a null-terminated string",
    4002          175 :           ad.m_arg_idx + 1, ad.m_called_fndecl);
    4003          175 : }
    4004              : 
    4005              : static tree
    4006          325 : get_tree_for_byte_offset (tree ptr_expr, concrete_byte_offset byte_offset)
    4007              : {
    4008          325 :   gcc_assert (ptr_expr);
    4009          325 :   tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
    4010          325 :   return fold_build2
    4011              :     (MEM_REF,
    4012              :      char_type_node,
    4013              :      ptr_expr,
    4014              :      make_integer_cst_from_integer (ptype, byte_offset.get_integer (), true));
    4015              : }
    4016              : 
    4017              : /* Simulate a series of reads of REG until we find a 0 byte
    4018              :    (equivalent to calling strlen).
    4019              : 
    4020              :    Complain to CTXT and return NULL if:
    4021              :    - the buffer pointed to isn't null-terminated
    4022              :    - the buffer pointed to has any uninitialized bytes before any 0-terminator
    4023              :    - any of the reads aren't within the bounds of the underlying base region
    4024              : 
    4025              :    Otherwise, return a svalue for the number of bytes read (strlen + 1),
    4026              :    and, if OUT_BV is non-NULL, write to *OUT_BV with a bit_vector
    4027              :    representing the content of REG up to and including the terminator.  */
    4028              : 
    4029              : const svalue *
    4030         6359 : region_model::
    4031              : scan_for_null_terminator_1 (const region *reg,
    4032              :                             tree expr,
    4033              :                             const symbolic::bit_vector **out_bv,
    4034              :                             region_model_context *ctxt) const
    4035              : {
    4036         6359 :   logger *logger = ctxt ? ctxt->get_logger () : nullptr;
    4037              : 
    4038         6359 :   auto sym_ptr = reg->get_pointer (*m_mgr);
    4039         6359 :   auto &bc = m_store.get_bit_contents (sym_ptr.get_base_region (),
    4040              :                                        get_baseline_state ());
    4041              : 
    4042         6359 :   auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
    4043              : 
    4044         6359 :   integer_with_unit<units::byte> conc_offset;
    4045         6359 :   if (!concrete_from_symbolic (sym_ptr.get_byte_offset (), &conc_offset))
    4046              :     {
    4047           47 :       if (out_bv)
    4048            0 :         *out_bv = &bv_mgr.get_unknown_bits ();
    4049           47 :       if (logger)
    4050            0 :         logger->log ("offset is symbolic");
    4051           47 :       return m_mgr->get_or_create_unknown_svalue (size_type_node);
    4052              :     }
    4053         6312 :   string_scan scan = bc.scan_for_first_zero_byte (conc_offset);
    4054              : 
    4055         6312 :   if (scan.m_state == string_scan::state::cannot_scan)
    4056              :     {
    4057         2780 :       if (out_bv)
    4058          279 :         *out_bv = &bv_mgr.get_unknown_bits ();
    4059         2780 :       return m_mgr->get_or_create_unknown_svalue (size_type_node);
    4060              :     }
    4061              : 
    4062         3532 :   auto &byte_mgr = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
    4063              : 
    4064              :   /* If we ran into a problem, then don't trust the bit_vector or the
    4065              :      bytes read: provide "unknown" for both.  */
    4066         3532 :   if (scan.m_state == string_scan::state::found_poison)
    4067              :     {
    4068              :       /* Simulate reading from the bad byte to trigger a warning,
    4069              :          then give up.  */
    4070          333 :       symbolic::pointer bad_byte_ptr (sym_ptr.get_base_region (),
    4071          333 :                                       symbolic_from_concrete (scan.m_byte_offset,
    4072          333 :                                                               byte_mgr));
    4073          333 :       tree bad_byte_expr
    4074              :         = (expr
    4075          983 :            ? get_tree_for_byte_offset (expr, scan.m_byte_offset)
    4076              :            : NULL_TREE);
    4077          666 :       read_bytes (bad_byte_ptr,
    4078              :                   bad_byte_expr,
    4079          333 :                   byte_mgr.get_concrete (1_byte),
    4080              :                   ctxt);
    4081          333 :       if (out_bv)
    4082           47 :         *out_bv = &bv_mgr.get_unknown_bits ();
    4083          333 :       return m_mgr->get_or_create_unknown_svalue (size_type_node);
    4084              :     }
    4085              : 
    4086              :   /* Simulate accessing the bytes read, which ought to trigger
    4087              :      any warnings (out-of-bounds, uninit, etc).  */
    4088              :   // number of bytes read == offset of last byte read + 1:
    4089         3199 :   concrete_byte_size num_bytes_read = scan.m_byte_offset + 1_byte - conc_offset;
    4090         3199 :   auto &bv = read_bytes (sym_ptr, expr,
    4091         3199 :                          byte_mgr.get_concrete (num_bytes_read),
    4092              :                          ctxt);
    4093         3199 :   if (out_bv)
    4094          360 :     *out_bv = &bv;
    4095              : 
    4096         3199 :   return m_mgr->get_or_create_int_cst (size_type_node,
    4097         3199 :                                        num_bytes_read.as_unsigned_long ());
    4098         9511 : }
    4099              : 
    4100              : /* Like region_model::scan_for_null_terminator_1, but add logging.  */
    4101              : 
    4102              : const svalue *
    4103         6359 : region_model::
    4104              : scan_for_null_terminator (const region *reg,
    4105              :                           tree expr,
    4106              :                           const symbolic::bit_vector **out_bv,
    4107              :                           region_model_context *ctxt) const
    4108              : {
    4109         6359 :   logger *logger = ctxt ? ctxt->get_logger () : nullptr;
    4110         6359 :   LOG_SCOPE (logger);
    4111         6359 :   if (logger)
    4112              :     {
    4113            2 :       pretty_printer *pp = logger->get_printer ();
    4114            2 :       logger->start_log_line ();
    4115            2 :       logger->log_partial ("region: ");
    4116            2 :       reg->dump_to_pp (pp, true);
    4117            2 :       logger->end_log_line ();
    4118              :     }
    4119         6359 :   if (out_bv)
    4120          686 :     *out_bv = nullptr;
    4121         6359 :   const svalue *sval
    4122         6359 :     = scan_for_null_terminator_1 (reg, expr, out_bv, ctxt);
    4123         6359 :   if (sval && out_bv)
    4124          686 :     gcc_assert (*out_bv);
    4125         6359 :   if (logger)
    4126              :     {
    4127            2 :       pretty_printer *pp = logger->get_printer ();
    4128            2 :       logger->start_log_line ();
    4129            2 :       logger->log_partial ("length result: ");
    4130            2 :       if (sval)
    4131            2 :         sval->dump_to_pp (pp, true);
    4132              :       else
    4133            0 :         pp_printf (pp, "NULL");
    4134            2 :       logger->end_log_line ();
    4135            2 :       if (out_bv)
    4136              :         {
    4137            2 :           logger->start_log_line ();
    4138            2 :           logger->log_partial ("content result: ");
    4139            2 :           if (*out_bv)
    4140            2 :             (*out_bv)->dump_to_pp (pp);
    4141              :           else
    4142            0 :             pp_printf (pp, "NULL");
    4143            2 :           logger->end_log_line ();
    4144              :         }
    4145              :     }
    4146        12718 :   return sval;
    4147         6359 : }
    4148              : 
    4149              : /* Check that argument ARG_IDX (0-based) to the call described by CD
    4150              :    is a pointer to a valid null-terminated string.
    4151              : 
    4152              :    Simulate scanning through the buffer, reading until we find a 0 byte
    4153              :    (equivalent to calling strlen).
    4154              : 
    4155              :    Complain and return nullptr if:
    4156              :    - the buffer pointed to isn't null-terminated
    4157              :    - the buffer pointed to has any uninitialized bytes before any 0-terminator
    4158              :    - any of the reads aren't within the bounds of the underlying base region
    4159              : 
    4160              :    Otherwise, return a svalue for strlen of the buffer (*not* including
    4161              :    the null terminator).
    4162              : 
    4163              :    TODO: we should also complain if:
    4164              :    - the pointer is NULL (or could be).  */
    4165              : 
    4166              : const svalue *
    4167          221 : region_model::check_for_null_terminated_string_arg (const call_details &cd,
    4168              :                                                     unsigned arg_idx) const
    4169              : {
    4170          221 :   return check_for_null_terminated_string_arg (cd,
    4171              :                                                arg_idx,
    4172              :                                                false, /* include_terminator */
    4173          221 :                                                nullptr); // out_sval
    4174              : }
    4175              : 
    4176              : 
    4177              : /* Check that argument ARG_IDX (0-based) to the call described by CD
    4178              :    is a pointer to a valid null-terminated string.
    4179              : 
    4180              :    Simulate scanning through the buffer, reading until we find a 0 byte
    4181              :    (equivalent to calling strlen).
    4182              : 
    4183              :    Complain and return nullptr if:
    4184              :    - the buffer pointed to isn't null-terminated
    4185              :    - the buffer pointed to has any uninitialized bytes before any 0-terminator
    4186              :    - any of the reads aren't within the bounds of the underlying base region
    4187              : 
    4188              :    Otherwise, return a svalue.  This will be the number of bytes read
    4189              :    (including the null terminator) if INCLUDE_TERMINATOR is true, or strlen
    4190              :    of the buffer (not including the null terminator) if it is false.
    4191              : 
    4192              :    Also, when returning an svalue, if OUT_BV is non-nullptr, write to
    4193              :    *OUT_BV with a bit_vector representing the content of the buffer up to
    4194              :    and including the terminator.
    4195              : 
    4196              :    TODO: we should also complain if:
    4197              :    - the pointer is NULL (or could be).  */
    4198              : 
    4199              : const svalue *
    4200         6000 : region_model::
    4201              : check_for_null_terminated_string_arg (const call_details &cd,
    4202              :                                       unsigned arg_idx,
    4203              :                                       bool include_terminator,
    4204              :                                       const symbolic::bit_vector **out_bv)
    4205              :   const
    4206              : {
    4207            0 :   class null_terminator_check_event : public custom_event
    4208              :   {
    4209              :   public:
    4210          187 :     null_terminator_check_event (const event_loc_info &loc_info,
    4211              :                                  const call_arg_details &arg_details)
    4212              :     : custom_event (loc_info),
    4213          187 :       m_arg_details (arg_details)
    4214              :     {
    4215              :     }
    4216              : 
    4217          356 :     void print_desc (pretty_printer &pp) const final override
    4218              :     {
    4219          356 :       if (m_arg_details.m_arg_expr)
    4220          356 :         pp_printf (&pp,
    4221              :                    "while looking for null terminator"
    4222              :                    " for argument %i (%qE) of %qD...",
    4223          356 :                    m_arg_details.m_arg_idx + 1,
    4224              :                    m_arg_details.m_arg_expr,
    4225          356 :                    m_arg_details.m_called_fndecl);
    4226              :       else
    4227            0 :         pp_printf (&pp,
    4228              :                    "while looking for null terminator"
    4229              :                    " for argument %i of %qD...",
    4230            0 :                    m_arg_details.m_arg_idx + 1,
    4231            0 :                    m_arg_details.m_called_fndecl);
    4232          356 :     }
    4233              : 
    4234              :   private:
    4235              :     const call_arg_details m_arg_details;
    4236              :   };
    4237              : 
    4238            0 :   class null_terminator_check_decl_note
    4239              :     : public pending_note_subclass<null_terminator_check_decl_note>
    4240              :   {
    4241              :   public:
    4242          187 :     null_terminator_check_decl_note (const call_arg_details &arg_details)
    4243          187 :     : m_arg_details (arg_details)
    4244              :     {
    4245              :     }
    4246              : 
    4247         1634 :     const char *get_kind () const final override
    4248              :     {
    4249         1634 :       return "null_terminator_check_decl_note";
    4250              :     }
    4251              : 
    4252          175 :     void emit () const final override
    4253              :     {
    4254          175 :       inform_about_expected_null_terminated_string_arg (m_arg_details);
    4255          175 :     }
    4256              : 
    4257          817 :     bool operator== (const null_terminator_check_decl_note &other) const
    4258              :     {
    4259          817 :       return m_arg_details == other.m_arg_details;
    4260              :     }
    4261              : 
    4262              :   private:
    4263              :     const call_arg_details m_arg_details;
    4264              :   };
    4265              : 
    4266              :   /* Subclass of decorated_region_model_context that
    4267              :      adds the above event and note to any saved diagnostics.  */
    4268         6000 :   class annotating_ctxt : public annotating_context
    4269              :   {
    4270              :   public:
    4271         6000 :     annotating_ctxt (const call_details &cd,
    4272              :                      unsigned arg_idx)
    4273              :     : annotating_context (cd.get_ctxt ()),
    4274         6000 :       m_cd (cd),
    4275         6000 :       m_arg_idx (arg_idx)
    4276              :     {
    4277              :     }
    4278          187 :     void add_annotations () final override
    4279              :     {
    4280          187 :       call_arg_details arg_details (m_cd, m_arg_idx);
    4281          374 :       event_loc_info loc_info (m_cd.get_location (),
    4282          187 :                                m_cd.get_model ()->get_current_function ()->decl,
    4283          374 :                                m_cd.get_model ()->get_stack_depth ());
    4284              : 
    4285          187 :       add_event
    4286          187 :         (std::make_unique<null_terminator_check_event> (loc_info,
    4287              :                                                         arg_details));
    4288          187 :       add_note
    4289          187 :         (std::make_unique <null_terminator_check_decl_note> (arg_details));
    4290          187 :     }
    4291              :   private:
    4292              :     const call_details &m_cd;
    4293              :     unsigned m_arg_idx;
    4294              :   };
    4295              : 
    4296              :   /* Use this ctxt below so that any diagnostics that get added
    4297              :      get annotated.  */
    4298         6000 :   annotating_ctxt my_ctxt (cd, arg_idx);
    4299              : 
    4300         6000 :   const svalue *arg_sval = cd.get_arg_svalue (arg_idx);
    4301         6000 :   const region *buf_reg
    4302         6000 :     = deref_rvalue (arg_sval, cd.get_arg_tree (arg_idx), &my_ctxt);
    4303              : 
    4304        12000 :   if (const svalue *num_bytes_read_sval
    4305         6000 :       = scan_for_null_terminator (buf_reg,
    4306              :                                   cd.get_arg_tree (arg_idx),
    4307              :                                   out_bv,
    4308              :                                   &my_ctxt))
    4309              :     {
    4310         6000 :       if (out_bv)
    4311          686 :         gcc_assert (*out_bv);
    4312         6000 :       if (include_terminator)
    4313              :         return num_bytes_read_sval;
    4314              :       else
    4315              :         {
    4316              :           /* strlen is (bytes_read - 1).  */
    4317         5314 :           const svalue *one = m_mgr->get_or_create_int_cst (size_type_node, 1);
    4318         5314 :           return m_mgr->get_or_create_binop (size_type_node,
    4319              :                                              MINUS_EXPR,
    4320              :                                              num_bytes_read_sval,
    4321         5314 :                                              one);
    4322              :         }
    4323              :     }
    4324              :   else
    4325              :     return nullptr;
    4326              : }
    4327              : 
    4328              : /* Remove all bindings overlapping REG within the store.  */
    4329              : 
    4330              : void
    4331         7380 : region_model::clobber_region (const region *reg)
    4332              : {
    4333         7380 :   m_store.clobber_region (reg, get_baseline_state (), *m_mgr);
    4334         7380 : }
    4335              : 
    4336              : /* Remove any bindings for REG within the store.  */
    4337              : 
    4338              : void
    4339       173547 : region_model::purge_region (const region *reg)
    4340              : {
    4341       173547 :   m_store.purge_region (reg);
    4342       173547 : }
    4343              : 
    4344              : /* Zero-fill REG.
    4345              :    Use CTXT to report any warnings associated with the write
    4346              :    (e.g. out-of-bounds).  */
    4347              : 
    4348              : void
    4349         1454 : region_model::zero_fill_region (const region *reg,
    4350              :                                 region_model_context *ctxt)
    4351              : {
    4352         1454 :   auto mem_range = reg->get_memory_range (*m_mgr);
    4353         1454 :   if (mem_range.get_size ().is_zero_p ())
    4354         1454 :     return;
    4355         1428 :   auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
    4356         1428 :   auto &all_zeros = bv_mgr.get_all_zeros (mem_range.get_size ());
    4357         1428 :   write_to_memory_offset
    4358         1428 :     (symbolic::memory_offset (mem_range.get_base_region (),
    4359         1428 :                               mem_range.get_start_offset ()),
    4360              :      all_zeros,
    4361              :      ctxt);
    4362              : }
    4363              : 
    4364              : /* Copy BYTES to DEST_SYM_PTR.
    4365              :    Use CTXT to report any warnings associated with the copy
    4366              :    (e.g. out-of-bounds writes).  */
    4367              : 
    4368              : void
    4369         1926 : region_model::write_bytes (symbolic::pointer dest_sym_ptr,
    4370              :                            const symbolic::bit_vector &bytes,
    4371              :                            region_model_context *ctxt)
    4372              : {
    4373         1926 :   symbolic::memory_offset mem_offset (dest_sym_ptr.get_base_region (),
    4374         1926 :                                       bits_from_bytes (dest_sym_ptr.get_byte_offset ()));
    4375         1926 :   write_to_memory_offset (mem_offset, bytes, ctxt);
    4376         1926 : }
    4377              : 
    4378              : /* Read NUM_BYTES bytes from SRC_SYM_PTR.
    4379              :    Use CTXT to report any warnings associated with the copy
    4380              :    (e.g. out-of-bounds reads, copying of uninitialized values, etc).  */
    4381              : 
    4382              : const symbolic::bit_vector &
    4383         4888 : region_model::read_bytes (symbolic::pointer src_sym_ptr,
    4384              :                           tree src_ptr_expr,
    4385              :                           const symbolic_byte_size &num_bytes,
    4386              :                           region_model_context *ctxt) const
    4387              : {
    4388         4888 :   auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
    4389         4888 :   if (auto *from_val = num_bytes.dyn_cast_scalar_from_svalue ())
    4390              :     {
    4391          720 :       if (from_val->get_svalue ().get_kind () == SK_UNKNOWN)
    4392          289 :         return bv_mgr.get_unknown_bytes (num_bytes);
    4393              :     }
    4394         4599 :   symbolic::memory_range src_mem_range (src_sym_ptr, num_bytes);
    4395         4599 :   auto &bytes = get_store_bits (src_mem_range, ctxt);
    4396         4599 :   check_bytes_for_poison (bytes, src_sym_ptr, src_ptr_expr, ctxt);
    4397         4599 :   return bytes;
    4398              : }
    4399              : 
    4400              : /* Copy NUM_BYTES_SVAL bytes from SRC_REG to DEST_REG.
    4401              :    Use CTXT to report any warnings associated with the copy
    4402              :    (e.g. out-of-bounds reads/writes, copying of uninitialized values,
    4403              :    etc).  */
    4404              : 
    4405              : void
    4406          682 : region_model::copy_bytes (symbolic::pointer dest_sym_ptr,
    4407              :                           symbolic::pointer src_sym_ptr,
    4408              :                           tree src_ptr_expr,
    4409              :                           const symbolic_byte_size &num_bytes,
    4410              :                           region_model_context *ctxt)
    4411              : {
    4412          682 :   if (num_bytes.is_zero_p ())
    4413              :     return;
    4414          672 :   auto &bytes = read_bytes (src_sym_ptr, src_ptr_expr, num_bytes, ctxt);
    4415          672 :   write_bytes (dest_sym_ptr, bytes, ctxt);
    4416              : }
    4417              : 
    4418              : /* Mark REG as having unknown content.  */
    4419              : 
    4420              : void
    4421          552 : region_model::mark_region_as_unknown (const region *reg,
    4422              :                                       uncertainty_t *uncertainty)
    4423              : {
    4424          552 :   m_store.mark_region_as_unknown (reg, uncertainty, *this);
    4425          552 : }
    4426              : 
    4427              : /* Conjure a new new bit_contents for the effect of STMT on BASE_REG
    4428              :    and update the region in the store accordingly.  */
    4429              : 
    4430              : void
    4431          528 : region_model::mark_region_as_conjured (const region &base_reg,
    4432              :                                        const gimple &stmt,
    4433              :                                        region_model_context *ctxt)
    4434              : {
    4435          528 :   m_store.mark_region_as_conjured (base_reg,
    4436              :                                    get_baseline_state (),
    4437              :                                    stmt,
    4438          528 :                                    conjured_purge (this, ctxt));
    4439          528 : }
    4440              : 
    4441              : bool
    4442       163369 : equal_bit_vectors_p (const svalue &lhs,
    4443              :                      const svalue &rhs,
    4444              :                      const region_model_manager &rmm)
    4445              : {
    4446       163369 :   auto &bv_mgr = rmm.get_node_manager ().get_bit_vector_manager ();
    4447       163369 :   auto &lhs_bv = bv_mgr.get_bit_vector_from_svalue (lhs);
    4448       163369 :   auto &rhs_bv = bv_mgr.get_bit_vector_from_svalue (rhs);
    4449              : 
    4450              :   // TODO: not necessarily true e.g. if contains unknown bits
    4451       163369 :   return &lhs_bv == &rhs_bv;
    4452              : }
    4453              : 
    4454              : const svalue *
    4455       501575 : region_model::canonicalize_svalue_for_constraint (const svalue *sval) const
    4456              : {
    4457              :   /* Unwrap any unmergeable values.  */
    4458       501575 :   sval = sval->unwrap_any_unmergeable ();
    4459              : 
    4460              :   // Canonicalize pointers involved in constraints to use (void *)
    4461       501575 :   if (sval->get_type () && POINTER_TYPE_P (sval->get_type ()))
    4462       141057 :     sval = get_manager ()->get_or_create_cast (ptr_type_node, sval);
    4463       501575 :   if (auto *sym_ptr = sval->maybe_get_symbolic_pointer ())
    4464        26104 :     sval = get_manager ()->get_ptr_svalue (ptr_type_node, *sym_ptr);
    4465              : 
    4466       501575 :   return sval;
    4467              : }
    4468              : 
    4469              : /* Predicate for guarding against infinite recursion in eval_condition,
    4470              :    preventing a case where we cycle between canonicalization that adds
    4471              :    a cast and folding that tries to remove the cast.  */
    4472              : 
    4473              : bool
    4474         6559 : region_model::
    4475              : can_recurse_eval_condition_p (const unaryop_svalue *unary_op) const
    4476              : {
    4477         6559 :   return (canonicalize_svalue_for_constraint (unary_op->get_arg ())
    4478         6559 :           != unary_op);
    4479              : }
    4480              : 
    4481              : /* Determine what is known about the condition "LHS_SVAL OP RHS_SVAL" within
    4482              :    this model.  */
    4483              : 
    4484              : tristate
    4485       175846 : region_model::eval_condition (const svalue *lhs,
    4486              :                                enum tree_code op,
    4487              :                                const svalue *rhs) const
    4488              : {
    4489       175846 :   gcc_assert (lhs);
    4490       175846 :   gcc_assert (rhs);
    4491              : 
    4492              :   /* For now, make no attempt to capture constraints on floating-point
    4493              :      values.  */
    4494       175846 :   if ((lhs->get_type () && FLOAT_TYPE_P (lhs->get_type ()))
    4495       351620 :       || (rhs->get_type () && FLOAT_TYPE_P (rhs->get_type ())))
    4496           72 :     return tristate::unknown ();
    4497              : 
    4498              :   /* See what we know based on the values.  */
    4499              : 
    4500       175774 :   lhs = canonicalize_svalue_for_constraint (lhs);
    4501       175774 :   rhs = canonicalize_svalue_for_constraint (rhs);
    4502              : 
    4503       175774 :   if (lhs == rhs
    4504       175774 :       || equal_bit_vectors_p (*lhs, *rhs, *get_manager ()))
    4505              :     {
    4506              :       /* If we have the same svalue, then we have equality
    4507              :          (apart from NaN-handling).
    4508              :          TODO: should this definitely be the case for poisoned values?  */
    4509              :       /* Poisoned and unknown values are "unknowable".  */
    4510        13514 :       if (lhs->get_kind () == SK_POISONED
    4511        13514 :           || lhs->get_kind () == SK_UNKNOWN)
    4512          956 :         return tristate::TS_UNKNOWN;
    4513              : 
    4514        12558 :       switch (op)
    4515              :         {
    4516         9500 :         case EQ_EXPR:
    4517         9500 :         case GE_EXPR:
    4518         9500 :         case LE_EXPR:
    4519         9500 :           return tristate::TS_TRUE;
    4520              : 
    4521         3058 :         case NE_EXPR:
    4522         3058 :         case GT_EXPR:
    4523         3058 :         case LT_EXPR:
    4524         3058 :           return tristate::TS_FALSE;
    4525              : 
    4526              :         default:
    4527              :           /* For other ops, use the logic below.  */
    4528              :           break;
    4529              :         }
    4530              :     }
    4531              : 
    4532              :   /* If we have a pair of pointer_svalues, compare them.  */
    4533       162260 :   if (auto *lhs_sym_ptr = lhs->maybe_get_symbolic_pointer ())
    4534        13372 :     if (auto *rhs_sym_ptr = rhs->maybe_get_symbolic_pointer ())
    4535              :       {
    4536          923 :         tristate res = symbolic::pointer::eval_condition (*lhs_sym_ptr,
    4537              :                                                           op,
    4538              :                                                           *rhs_sym_ptr,
    4539              :                                                           *this);
    4540          923 :         if (res.is_known ())
    4541          603 :           return res;
    4542              :         /* Otherwise, only known through constraints.  */
    4543              :       }
    4544              : 
    4545       161657 :   if (const constant_svalue *cst_lhs = lhs->dyn_cast_constant_svalue ())
    4546              :     {
    4547              :       /* If we have a pair of constants, compare them.  */
    4548        43423 :       if (const constant_svalue *cst_rhs = rhs->dyn_cast_constant_svalue ())
    4549        11227 :         return constant_svalue::eval_condition (cst_lhs, op, cst_rhs);
    4550              :       else
    4551              :         {
    4552              :           /* When we have one constant, put it on the RHS.  */
    4553        32196 :           std::swap (lhs, rhs);
    4554        32196 :           op = swap_tree_comparison (op);
    4555              :         }
    4556              :     }
    4557       150430 :   gcc_assert (lhs->get_kind () != SK_CONSTANT);
    4558              : 
    4559              :   /* Handle comparison against zero.  */
    4560       150430 :   if (const constant_svalue *cst_rhs = rhs->dyn_cast_constant_svalue ())
    4561       123595 :     if (zerop (cst_rhs->get_constant ()))
    4562              :       {
    4563        72521 :         if (const pointer_svalue *ptr = lhs->dyn_cast_pointer_svalue ())
    4564              :           {
    4565        12351 :             if (ptr->non_null_p ())
    4566              :               {
    4567         4060 :                 switch (op)
    4568              :                   {
    4569            0 :                   default:
    4570            0 :                     gcc_unreachable ();
    4571              : 
    4572          325 :                   case EQ_EXPR:
    4573          325 :                   case GE_EXPR:
    4574          325 :                   case LE_EXPR:
    4575          325 :                     return tristate::TS_FALSE;
    4576              : 
    4577         3735 :                   case NE_EXPR:
    4578         3735 :                   case GT_EXPR:
    4579         3735 :                   case LT_EXPR:
    4580         3735 :                     return tristate::TS_TRUE;
    4581              :                   }
    4582              :               }
    4583              :           }
    4584        60170 :         else if (const binop_svalue *binop = lhs->dyn_cast_binop_svalue ())
    4585              :           {
    4586              :             /* Treat offsets from a non-NULL pointer as being non-NULL.  This
    4587              :                isn't strictly true, in that eventually ptr++ will wrap
    4588              :                around and be NULL, but it won't occur in practise and thus
    4589              :                can be used to suppress effectively false positives that we
    4590              :                shouldn't warn for.  */
    4591         8075 :             if (binop->get_op () == POINTER_PLUS_EXPR)
    4592              :               {
    4593         2000 :                 tristate lhs_ts = eval_condition (binop->get_arg0 (), op, rhs);
    4594         2000 :                 if (lhs_ts.is_known ())
    4595         1321 :                   return lhs_ts;
    4596              :               }
    4597              :           }
    4598       104190 :         else if (const unaryop_svalue *unaryop
    4599        52095 :                    = lhs->dyn_cast_unaryop_svalue ())
    4600              :           {
    4601         2293 :             if (unaryop->get_op () == NEGATE_EXPR)
    4602              :               {
    4603              :                 /* e.g. "-X <= 0" is equivalent to X >= 0".  */
    4604           51 :                 tristate lhs_ts = eval_condition (unaryop->get_arg (),
    4605              :                                                   swap_tree_comparison (op),
    4606              :                                                   rhs);
    4607           51 :                 if (lhs_ts.is_known ())
    4608           48 :                   return lhs_ts;
    4609              :               }
    4610              :           }
    4611              :       }
    4612              : 
    4613              :   /* Handle rejection of equality for comparisons of the initial values of
    4614              :      "external" values (such as params) with the address of locals.  */
    4615       145001 :   if (const initial_svalue *init_lhs = lhs->dyn_cast_initial_svalue ())
    4616        32149 :     if (auto *sym_ptr = rhs->maybe_get_symbolic_pointer ())
    4617              :       {
    4618          138 :         tristate res = compare_initial_and_pointer (init_lhs, *sym_ptr);
    4619          138 :         if (res.is_known ())
    4620           72 :           return res;
    4621              :       }
    4622       144929 :   if (const initial_svalue *init_rhs = rhs->dyn_cast_initial_svalue ())
    4623         4933 :     if (auto *sym_ptr = lhs->maybe_get_symbolic_pointer ())
    4624              :       {
    4625          132 :         tristate res = compare_initial_and_pointer (init_rhs, *sym_ptr);
    4626          132 :         if (res.is_known ())
    4627            0 :           return res;
    4628              :       }
    4629              : 
    4630       144929 :   if (const widening_svalue *widen_lhs = lhs->dyn_cast_widening_svalue ())
    4631         5102 :     if (tree rhs_cst = rhs->maybe_get_constant ())
    4632              :       {
    4633         2572 :         tristate res = widen_lhs->eval_condition_without_cm (op, rhs_cst);
    4634         2572 :         if (res.is_known ())
    4635           49 :           return res;
    4636              :       }
    4637              : 
    4638              :   /* Handle comparisons between two svalues with more than one operand.  */
    4639       144880 :   if (const binop_svalue *binop = lhs->dyn_cast_binop_svalue ())
    4640              :     {
    4641        23332 :       switch (op)
    4642              :         {
    4643              :         default:
    4644              :           break;
    4645         2521 :         case EQ_EXPR:
    4646         2521 :           {
    4647              :             /* TODO: binops can be equal even if they are not structurally
    4648              :                      equal in case of commutative operators.  */
    4649         2521 :             tristate res = structural_equality (lhs, rhs);
    4650         2521 :             if (res.is_true ())
    4651           44 :               return res;
    4652              :           }
    4653         2477 :           break;
    4654          754 :         case LE_EXPR:
    4655          754 :           {
    4656          754 :             tristate res = structural_equality (lhs, rhs);
    4657          754 :             if (res.is_true ())
    4658            0 :               return res;
    4659              :           }
    4660          754 :           break;
    4661         6603 :         case GE_EXPR:
    4662         6603 :           {
    4663         6603 :             tristate res = structural_equality (lhs, rhs);
    4664         6603 :             if (res.is_true ())
    4665           42 :               return res;
    4666         6561 :             res = symbolic_greater_than (binop, rhs);
    4667         6561 :             if (res.is_true ())
    4668           56 :               return res;
    4669              :           }
    4670              :           break;
    4671         8073 :         case GT_EXPR:
    4672         8073 :           {
    4673         8073 :             tristate res = symbolic_greater_than (binop, rhs);
    4674         8073 :             if (res.is_true ())
    4675          171 :               return res;
    4676              :           }
    4677         7902 :           break;
    4678              :         }
    4679              :     }
    4680              : 
    4681              :   /* Try range_op, but avoid cases where we have been sloppy about types.  */
    4682       144567 :   if (lhs->get_type ()
    4683       144567 :       && rhs->get_type ()
    4684       289134 :       && range_compatible_p (lhs->get_type (), rhs->get_type ()))
    4685              :     {
    4686       137055 :       value_range lhs_vr, rhs_vr;
    4687       137055 :       if (lhs->maybe_get_value_range (lhs_vr))
    4688        59781 :         if (rhs->maybe_get_value_range (rhs_vr))
    4689              :           {
    4690        47432 :             range_op_handler handler (op);
    4691        47432 :             if (handler)
    4692              :               {
    4693        47432 :                 int_range_max out;
    4694        47432 :                 if (handler.fold_range (out, boolean_type_node, lhs_vr, rhs_vr))
    4695              :                   {
    4696        47432 :                     if (out.zero_p ())
    4697          294 :                       return tristate::TS_FALSE;
    4698        47138 :                     if (!out.contains_zero_p ())
    4699          208 :                       return tristate::TS_TRUE;
    4700              :                   }
    4701        47432 :               }
    4702              :           }
    4703       137055 :     }
    4704              : 
    4705              :   /* Attempt to unwrap cast if there is one, and the types match.
    4706              :      Don't do it if the cast is due to the canonicalization above.  */
    4707       144065 :   tree lhs_type = lhs->get_type ();
    4708       144065 :   tree rhs_type = rhs->get_type ();
    4709       144065 :   if (lhs_type && rhs_type)
    4710              :   {
    4711       144065 :     const bool types_match_p = types_compatible_p (lhs_type, rhs_type);
    4712       144065 :     const unaryop_svalue *lhs_un_op = dyn_cast <const unaryop_svalue *> (lhs);
    4713       144065 :     const unaryop_svalue *rhs_un_op = dyn_cast <const unaryop_svalue *> (rhs);
    4714         6949 :     if (lhs_un_op && CONVERT_EXPR_CODE_P (lhs_un_op->get_op ())
    4715         6624 :         && rhs_un_op && CONVERT_EXPR_CODE_P (rhs_un_op->get_op ())
    4716          153 :         && types_match_p
    4717       144218 :         && (can_recurse_eval_condition_p (lhs_un_op)
    4718            0 :             || can_recurse_eval_condition_p (rhs_un_op)))
    4719              :       {
    4720          153 :         tristate res = eval_condition (lhs_un_op->get_arg (),
    4721              :                                        op,
    4722              :                                        rhs_un_op->get_arg ());
    4723          153 :         if (res.is_known ())
    4724            7 :           return res;
    4725              :       }
    4726         6796 :     else if (lhs_un_op && CONVERT_EXPR_CODE_P (lhs_un_op->get_op ())
    4727         6471 :              && types_match_p
    4728       149702 :              && can_recurse_eval_condition_p (lhs_un_op))
    4729              :       {
    4730         5782 :         tristate res = eval_condition (lhs_un_op->get_arg (), op, rhs);
    4731         5782 :         if (res.is_known ())
    4732          236 :           return res;
    4733              :       }
    4734          768 :     else if (rhs_un_op && CONVERT_EXPR_CODE_P (rhs_un_op->get_op ())
    4735          768 :              && types_match_p
    4736       138746 :              && can_recurse_eval_condition_p (rhs_un_op))
    4737              :       {
    4738          616 :         tristate res = eval_condition (lhs, op, rhs_un_op->get_arg ());
    4739          616 :         if (res.is_known ())
    4740            0 :           return res;
    4741              :       }
    4742              :   }
    4743              : 
    4744              :   /* Otherwise, try constraints.
    4745              :      Cast to const to ensure we don't change the constraint_manager as we
    4746              :      do this (e.g. by creating equivalence classes).  */
    4747       143822 :   const constraint_manager *constraints = m_constraints;
    4748       143822 :   return constraints->eval_condition (lhs, op, rhs);
    4749              : }
    4750              : 
    4751              : /* Subroutine of region_model::eval_condition, for rejecting
    4752              :    equality of INIT_VAL(PARM) with &LOCAL.  */
    4753              : 
    4754              : tristate
    4755          270 : region_model::compare_initial_and_pointer (const initial_svalue *init,
    4756              :                                            const symbolic::pointer &ptr) const
    4757              : {
    4758              :   /* If we have a pointer to something within a stack frame, it can't be the
    4759              :      initial value of a param.  */
    4760          270 :   if (ptr.get_base_region ().maybe_get_frame_region ())
    4761           72 :     if (init->initial_value_of_param_p ())
    4762           72 :       return tristate::TS_FALSE;
    4763              : 
    4764          198 :   return tristate::TS_UNKNOWN;
    4765              : }
    4766              : 
    4767              : /* Return true if SVAL is definitely positive.  */
    4768              : 
    4769              : static bool
    4770        13909 : is_positive_svalue (const svalue *sval)
    4771              : {
    4772        13909 :   if (tree cst = sval->maybe_get_constant ())
    4773        13415 :     return !zerop (cst) && get_range_pos_neg (cst) == 1;
    4774          494 :   tree type = sval->get_type ();
    4775          494 :   if (!type)
    4776              :     return false;
    4777              :   /* Consider a binary operation size_t + int.  The analyzer wraps the int in
    4778              :      an unaryop_svalue, converting it to a size_t, but in the dynamic execution
    4779              :      the result is smaller than the first operand.  Thus, we have to look if
    4780              :      the argument of the unaryop_svalue is also positive.  */
    4781          494 :   if (const unaryop_svalue *un_op = dyn_cast <const unaryop_svalue *> (sval))
    4782          102 :     return CONVERT_EXPR_CODE_P (un_op->get_op ()) && TYPE_UNSIGNED (type)
    4783          196 :            && is_positive_svalue (un_op->get_arg ());
    4784              : 
    4785          392 :   if (const binop_svalue *bin_op = dyn_cast <const binop_svalue *> (sval))
    4786          178 :     if (bin_op->get_op () == MULT_EXPR)
    4787              :       /* (definitely +ve * definitely +ve) == definitely +ve.  */
    4788           32 :       return (is_positive_svalue (bin_op->get_arg0 ())
    4789           32 :               && is_positive_svalue (bin_op->get_arg1 ()));
    4790              : 
    4791          360 :   return TYPE_UNSIGNED (type);
    4792              : }
    4793              : 
    4794              : /* Return true if A is definitely larger than B.
    4795              : 
    4796              :    Limitation: does not account for integer overflows and does not try to
    4797              :                return false, so it can not be used negated.  */
    4798              : 
    4799              : tristate
    4800        14634 : region_model::symbolic_greater_than (const binop_svalue *bin_a,
    4801              :                                      const svalue *b) const
    4802              : {
    4803        14634 :   if (bin_a->get_op () == PLUS_EXPR || bin_a->get_op () == MULT_EXPR)
    4804              :     {
    4805              :       /* Eliminate the right-hand side of both svalues.  */
    4806        13819 :       if (const binop_svalue *bin_b = dyn_cast <const binop_svalue *> (b))
    4807         1647 :         if (bin_a->get_op () == bin_b->get_op ()
    4808          990 :             && eval_condition (bin_a->get_arg1 (),
    4809              :                                GT_EXPR,
    4810          990 :                                bin_b->get_arg1 ()).is_true ()
    4811         2637 :             && eval_condition (bin_a->get_arg0 (),
    4812              :                                GE_EXPR,
    4813           45 :                                bin_b->get_arg0 ()).is_true ())
    4814           40 :           return tristate (tristate::TS_TRUE);
    4815              : 
    4816              :       /* Otherwise, try to remove a positive offset or factor from BIN_A.  */
    4817        13779 :       if (is_positive_svalue (bin_a->get_arg1 ())
    4818        13779 :           && eval_condition (bin_a->get_arg0 (),
    4819        12843 :                              GE_EXPR, b).is_true ())
    4820          187 :           return tristate (tristate::TS_TRUE);
    4821              :     }
    4822        14407 :   return tristate::unknown ();
    4823              : }
    4824              : 
    4825              : /* Return true if A and B are equal structurally.
    4826              : 
    4827              :    Structural equality means that A and B are equal if the svalues A and B have
    4828              :    the same nodes at the same positions in the tree and the leafs are equal.
    4829              :    Equality for conjured_svalues and initial_svalues is determined by comparing
    4830              :    the pointers while constants are compared by value.  That behavior is useful
    4831              :    to check for binaryop_svlaues that evaluate to the same concrete value but
    4832              :    might use one operand with a different type but the same constant value.
    4833              : 
    4834              :    For example,
    4835              :      binop_svalue (mult_expr,
    4836              :        initial_svalue (‘size_t’, decl_region (..., 'some_var')),
    4837              :        constant_svalue (‘size_t’, 4))
    4838              :    and
    4839              :      binop_svalue (mult_expr,
    4840              :        initial_svalue (‘size_t’, decl_region (..., 'some_var'),
    4841              :        constant_svalue (‘sizetype’, 4))
    4842              :    are structurally equal.  A concrete C code example, where this occurs, can
    4843              :    be found in test7 of out-of-bounds-5.c.  */
    4844              : 
    4845              : tristate
    4846        11753 : region_model::structural_equality (const svalue *a, const svalue *b) const
    4847              : {
    4848              :   /* If A and B are referentially equal, they are also structurally equal.  */
    4849        11753 :   if (a == b)
    4850          378 :     return tristate (tristate::TS_TRUE);
    4851              : 
    4852        11375 :   switch (a->get_kind ())
    4853              :     {
    4854          680 :     default:
    4855          680 :       return tristate::unknown ();
    4856              :     /* SK_CONJURED and SK_INITIAL are already handled
    4857              :        by the referential equality above.  */
    4858          531 :     case SK_CONSTANT:
    4859          531 :       {
    4860          531 :         tree a_cst = a->maybe_get_constant ();
    4861          531 :         tree b_cst = b->maybe_get_constant ();
    4862          531 :         if (a_cst && b_cst)
    4863          898 :           return tristate (tree_int_cst_equal (a_cst, b_cst));
    4864              :       }
    4865           66 :       return tristate (tristate::TS_FALSE);
    4866          239 :     case SK_UNARYOP:
    4867          239 :       {
    4868          239 :         const unaryop_svalue *un_a = as_a <const unaryop_svalue *> (a);
    4869          239 :         if (const unaryop_svalue *un_b = dyn_cast <const unaryop_svalue *> (b))
    4870          169 :           return tristate (pending_diagnostic::same_tree_p (un_a->get_type (),
    4871              :                                                             un_b->get_type ())
    4872          173 :                            && un_a->get_op () == un_b->get_op ()
    4873              :                            && structural_equality (un_a->get_arg (),
    4874          338 :                                                    un_b->get_arg ()));
    4875              :       }
    4876           70 :       return tristate (tristate::TS_FALSE);
    4877         9925 :     case SK_BINOP:
    4878         9925 :       {
    4879         9925 :         const binop_svalue *bin_a = as_a <const binop_svalue *> (a);
    4880         9925 :         if (const binop_svalue *bin_b = dyn_cast <const binop_svalue *> (b))
    4881         1284 :           return tristate (bin_a->get_op () == bin_b->get_op ()
    4882              :                            && structural_equality (bin_a->get_arg0 (),
    4883         1706 :                                                    bin_b->get_arg0 ())
    4884              :                            && structural_equality (bin_a->get_arg1 (),
    4885         1706 :                                                    bin_b->get_arg1 ()));
    4886              :       }
    4887         9072 :       return tristate (tristate::TS_FALSE);
    4888              :     }
    4889              : }
    4890              : 
    4891              : /* Handle various constraints of the form:
    4892              :      LHS: ((bool)INNER_LHS INNER_OP INNER_RHS))
    4893              :      OP : == or !=
    4894              :      RHS: zero
    4895              :    and (with a cast):
    4896              :      LHS: CAST([long]int, ((bool)INNER_LHS INNER_OP INNER_RHS))
    4897              :      OP : == or !=
    4898              :      RHS: zero
    4899              :    by adding constraints for INNER_LHS INNEROP INNER_RHS.
    4900              : 
    4901              :    Return true if this function can fully handle the constraint; if
    4902              :    so, add the implied constraint(s) and write true to *OUT if they
    4903              :    are consistent with existing constraints, or write false to *OUT
    4904              :    if they contradicts existing constraints.
    4905              : 
    4906              :    Return false for cases that this function doeesn't know how to handle.
    4907              : 
    4908              :    For example, if we're checking a stored conditional, we'll have
    4909              :    something like:
    4910              :      LHS: CAST(long int, (&HEAP_ALLOCATED_REGION(8)!=(int *)0B))
    4911              :      OP : NE_EXPR
    4912              :      RHS: zero
    4913              :    which this function can turn into an add_constraint of:
    4914              :      (&HEAP_ALLOCATED_REGION(8) != (int *)0B)
    4915              : 
    4916              :    Similarly, optimized && and || conditionals lead to e.g.
    4917              :      if (p && q)
    4918              :    becoming gimple like this:
    4919              :      _1 = p_6 == 0B;
    4920              :      _2 = q_8 == 0B
    4921              :      _3 = _1 | _2
    4922              :    On the "_3 is false" branch we can have constraints of the form:
    4923              :      ((&HEAP_ALLOCATED_REGION(8)!=(int *)0B)
    4924              :       | (&HEAP_ALLOCATED_REGION(10)!=(int *)0B))
    4925              :      == 0
    4926              :    which implies that both _1 and _2 are false,
    4927              :    which this function can turn into a pair of add_constraints of
    4928              :      (&HEAP_ALLOCATED_REGION(8)!=(int *)0B)
    4929              :    and:
    4930              :      (&HEAP_ALLOCATED_REGION(10)!=(int *)0B).  */
    4931              : 
    4932              : bool
    4933        48408 : region_model::add_constraints_from_binop (const svalue *outer_lhs,
    4934              :                                           enum tree_code outer_op,
    4935              :                                           const svalue *outer_rhs,
    4936              :                                           bool *out,
    4937              :                                           region_model_context *ctxt)
    4938              : {
    4939        49466 :   while (const svalue *cast = outer_lhs->maybe_undo_cast ())
    4940              :     outer_lhs = cast;
    4941        48408 :   const binop_svalue *binop_sval = outer_lhs->dyn_cast_binop_svalue ();
    4942        48408 :   if (!binop_sval)
    4943              :     return false;
    4944         5960 :   if (!outer_rhs->all_zeroes_p ())
    4945              :     return false;
    4946              : 
    4947         4325 :   const svalue *inner_lhs = binop_sval->get_arg0 ();
    4948         4325 :   enum tree_code inner_op = binop_sval->get_op ();
    4949         4325 :   const svalue *inner_rhs = binop_sval->get_arg1 ();
    4950              : 
    4951         4325 :   if (outer_op != NE_EXPR && outer_op != EQ_EXPR)
    4952              :     return false;
    4953              : 
    4954              :   /* We have either
    4955              :      - "OUTER_LHS != false" (i.e. OUTER is true), or
    4956              :      - "OUTER_LHS == false" (i.e. OUTER is false).  */
    4957         3824 :   bool is_true = outer_op == NE_EXPR;
    4958              : 
    4959         3824 :   switch (inner_op)
    4960              :     {
    4961              :     default:
    4962              :       return false;
    4963              : 
    4964         2594 :     case EQ_EXPR:
    4965         2594 :     case NE_EXPR:
    4966         2594 :     case GE_EXPR:
    4967         2594 :     case GT_EXPR:
    4968         2594 :     case LE_EXPR:
    4969         2594 :     case LT_EXPR:
    4970         2594 :       {
    4971              :         /* ...and "(inner_lhs OP inner_rhs) == 0"
    4972              :            then (inner_lhs OP inner_rhs) must have the same
    4973              :            logical value as LHS.  */
    4974         2594 :         if (!is_true)
    4975         1226 :           inner_op = invert_tree_comparison (inner_op, false /* honor_nans */);
    4976         2594 :         *out = add_constraint (inner_lhs, inner_op, inner_rhs, ctxt);
    4977         2594 :         return true;
    4978              :       }
    4979          479 :       break;
    4980              : 
    4981          479 :     case BIT_AND_EXPR:
    4982          479 :       if (is_true)
    4983              :         {
    4984              :           /* ...and "(inner_lhs & inner_rhs) != 0"
    4985              :              then both inner_lhs and inner_rhs must be true.  */
    4986          256 :           const svalue *false_sval
    4987          256 :             = m_mgr->get_or_create_constant_svalue (boolean_false_node);
    4988          256 :           bool sat1 = add_constraint (inner_lhs, NE_EXPR, false_sval, ctxt);
    4989          256 :           bool sat2 = add_constraint (inner_rhs, NE_EXPR, false_sval, ctxt);
    4990          256 :           *out = sat1 && sat2;
    4991          256 :           return true;
    4992              :         }
    4993              :       return false;
    4994              : 
    4995          136 :     case BIT_IOR_EXPR:
    4996          136 :       if (!is_true)
    4997              :         {
    4998              :           /* ...and "(inner_lhs | inner_rhs) == 0"
    4999              :              i.e. "(inner_lhs | inner_rhs)" is false
    5000              :              then both inner_lhs and inner_rhs must be false.  */
    5001           74 :           const svalue *false_sval
    5002           74 :             = m_mgr->get_or_create_constant_svalue (boolean_false_node);
    5003           74 :           bool sat1 = add_constraint (inner_lhs, EQ_EXPR, false_sval, ctxt);
    5004           74 :           bool sat2 = add_constraint (inner_rhs, EQ_EXPR, false_sval, ctxt);
    5005           74 :           *out = sat1 && sat2;
    5006           74 :           return true;
    5007              :         }
    5008              :       return false;
    5009              :     }
    5010              : }
    5011              : 
    5012              : /* Attempt to add the constraint "LHS OP RHS" to this region_model.
    5013              :    If it is consistent with existing constraints, add it, and return true.
    5014              :    Return false if it contradicts existing constraints.
    5015              :    Use CTXT for reporting any diagnostics associated with the accesses.  */
    5016              : 
    5017              : bool
    5018        63771 : region_model::add_constraint (tree lhs, enum tree_code op, tree rhs,
    5019              :                               region_model_context *ctxt)
    5020              : {
    5021              :   /* For now, make no attempt to capture constraints on floating-point
    5022              :      values.  */
    5023        63771 :   if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
    5024              :     return true;
    5025              : 
    5026        63437 :   const svalue *lhs_sval = get_rvalue (lhs, ctxt);
    5027        63437 :   const svalue *rhs_sval = get_rvalue (rhs, ctxt);
    5028              : 
    5029        63437 :   return add_constraint (lhs_sval, op, rhs_sval, ctxt);
    5030              : }
    5031              : 
    5032              : static bool
    5033        11564 : unusable_in_infinite_loop_constraint_p (const svalue *sval)
    5034              : {
    5035        11175 :   if (sval->get_kind () == SK_WIDENING)
    5036            0 :     return true;
    5037              :   return false;
    5038              : }
    5039              : 
    5040              : /* Attempt to add the constraint "LHS OP RHS" to this region_model.
    5041              :    If it is consistent with existing constraints, add it, and return true.
    5042              :    Return false if it contradicts existing constraints.
    5043              :    Use CTXT for reporting any diagnostics associated with the accesses.  */
    5044              : 
    5045              : bool
    5046        71970 : region_model::add_constraint (const svalue *lhs,
    5047              :                               enum tree_code op,
    5048              :                               const svalue *rhs,
    5049              :                               region_model_context *ctxt)
    5050              : {
    5051        71970 :   const bool checking_for_infinite_loop
    5052        71970 :     = ctxt ? ctxt->checking_for_infinite_loop_p () : false;
    5053              : 
    5054         5500 :   if (checking_for_infinite_loop)
    5055              :     {
    5056        10767 :       if (unusable_in_infinite_loop_constraint_p (lhs)
    5057        71970 :           || unusable_in_infinite_loop_constraint_p (rhs))
    5058              :         {
    5059          236 :           gcc_assert (ctxt);
    5060          236 :           ctxt->on_unusable_in_infinite_loop ();
    5061          236 :           return false;
    5062              :         }
    5063              :     }
    5064              : 
    5065        71734 :   lhs = canonicalize_svalue_for_constraint (lhs);
    5066        71734 :   rhs = canonicalize_svalue_for_constraint (rhs);
    5067              : 
    5068        71734 :   tristate t_cond = eval_condition (lhs, op, rhs);
    5069              : 
    5070              :   /* If we already have the condition, do nothing.  */
    5071        71734 :   if (t_cond.is_true ())
    5072              :     return true;
    5073              : 
    5074              :   /* Reject a constraint that would contradict existing knowledge, as
    5075              :      unsatisfiable.  */
    5076        59952 :   if (t_cond.is_false ())
    5077              :     return false;
    5078              : 
    5079        51684 :   if (checking_for_infinite_loop)
    5080              :     {
    5081              :       /* Here, we don't have a definite true/false value, so bail out
    5082              :          when checking for infinite loops.  */
    5083         3276 :       gcc_assert (ctxt);
    5084         3276 :       ctxt->on_unusable_in_infinite_loop ();
    5085         3276 :       return false;
    5086              :     }
    5087              : 
    5088        48408 :   bool out;
    5089        48408 :   if (add_constraints_from_binop (lhs, op, rhs, &out, ctxt))
    5090         2924 :     return out;
    5091              : 
    5092              :   /* Attempt to store the constraint.  */
    5093        45484 :   if (!m_constraints->add_constraint (lhs, op, rhs))
    5094              :     return false;
    5095              : 
    5096              :   /* Notify the context, if any.  This exists so that the state machines
    5097              :      in a program_state can be notified about the condition, and so can
    5098              :      set sm-state for e.g. unchecked->checked, both for cfg-edges, and
    5099              :      when synthesizing constraints as above.  */
    5100        45396 :   if (ctxt)
    5101        30856 :     ctxt->on_condition (lhs, op, rhs);
    5102              : 
    5103              :   /* If we have &REGION == NULL, then drop dynamic extents for REGION (for
    5104              :      the case where REGION is heap-allocated and thus could be NULL).  */
    5105        45396 :   if (tree rhs_cst = rhs->maybe_get_constant ())
    5106        38083 :     if (op == EQ_EXPR && zerop (rhs_cst))
    5107        11044 :       if (auto *sym_ptr = lhs->maybe_get_symbolic_pointer ())
    5108         2099 :         unset_dynamic_extents (&sym_ptr->get_base_region ());
    5109              : 
    5110              :   return true;
    5111              : }
    5112              : 
    5113              : /* As above, but when returning false, if OUT is non-NULL, write a
    5114              :    new rejected_constraint to *OUT.  */
    5115              : 
    5116              : bool
    5117        62627 : region_model::add_constraint (tree lhs, enum tree_code op, tree rhs,
    5118              :                               region_model_context *ctxt,
    5119              :                               std::unique_ptr<rejected_constraint> *out)
    5120              : {
    5121        62627 :   bool sat = add_constraint (lhs, op, rhs, ctxt);
    5122        62627 :   if (!sat && out)
    5123              :     {
    5124         1611 :       const svalue *lhs_sval = get_rvalue (lhs, nullptr);
    5125         1611 :       const svalue *rhs_sval = get_rvalue (rhs, nullptr);
    5126         3222 :       *out = std::make_unique <rejected_op_constraint> (*this,
    5127         1611 :                                                         lhs_sval, op, rhs_sval);
    5128              :     }
    5129        62627 :   return sat;
    5130              : }
    5131              : 
    5132              : /* Determine what is known about the condition "LHS OP RHS" within
    5133              :    this model.
    5134              :    Use CTXT for reporting any diagnostics associated with the accesses.  */
    5135              : 
    5136              : tristate
    5137        27820 : region_model::eval_condition (tree lhs,
    5138              :                               enum tree_code op,
    5139              :                               tree rhs,
    5140              :                               region_model_context *ctxt) const
    5141              : {
    5142              :   /* For now, make no attempt to model constraints on floating-point
    5143              :      values.  */
    5144        27820 :   if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
    5145           16 :     return tristate::unknown ();
    5146              : 
    5147        27804 :   return eval_condition (get_rvalue (lhs, ctxt), op, get_rvalue (rhs, ctxt));
    5148              : }
    5149              : 
    5150              : /* Convert EXPR to ORIG_TYPE.
    5151              : 
    5152              :    If EXPR is of RECORD_TYPE, then detect the case where the initial field
    5153              :    is of ORIG_TYPE (or we have a chain of such initial fields ending in
    5154              :    ORIG_TYPE), and return a COMPONENT_REF accessing the field.
    5155              : 
    5156              :    Otherwise, return a NOP_EXPR for a cast.  */
    5157              : 
    5158              : static tree
    5159          378 : convert_to_type (tree orig_type, tree expr)
    5160              : {
    5161          378 :   for (tree iter_expr = expr;
    5162          400 :        TREE_CODE (TREE_TYPE (iter_expr)) == RECORD_TYPE;
    5163              :        )
    5164              :     {
    5165           84 :       tree initial_field = TYPE_FIELDS (TREE_TYPE (iter_expr));
    5166           84 :       iter_expr = build3 (COMPONENT_REF,
    5167           84 :                           TREE_TYPE (initial_field),
    5168              :                           iter_expr, initial_field, NULL_TREE);
    5169           84 :       if (types_compatible_p (TREE_TYPE (iter_expr), orig_type))
    5170              :         return iter_expr;
    5171              :     }
    5172          316 :   return build1 (NOP_EXPR, orig_type, expr);
    5173              : }
    5174              : 
    5175              : /* Implementation of region_model::get_representative_path_var.
    5176              :    Attempt to return a path_var that represents SVAL, or return NULL_TREE.
    5177              :    Use VISITED to prevent infinite mutual recursion with the overload for
    5178              :    regions.  */
    5179              : 
    5180              : path_var
    5181        12105 : region_model::get_representative_path_var_1 (const svalue *sval,
    5182              :                                              value_set *visited,
    5183              :                                              logger *logger) const
    5184              : {
    5185        12105 :   gcc_assert (sval);
    5186              : 
    5187              :   /* Prevent infinite recursion.  */
    5188        12105 :   if (visited->contains (sval))
    5189              :     {
    5190           42 :       if (sval->get_kind () == SK_CONSTANT)
    5191           10 :         return path_var (sval->maybe_get_constant (), 0);
    5192              :       else
    5193           32 :         return path_var (NULL_TREE, 0);
    5194              :     }
    5195        12063 :   visited->add (sval);
    5196              : 
    5197              :   /* Gather candidates.  */
    5198        12063 :   auto_vec<path_var> pvs;
    5199              : 
    5200              :   /* Consider casts.  */
    5201        12063 :   if (const svalue *cast_sval = sval->maybe_undo_cast ())
    5202              :     {
    5203          402 :       path_var result = get_representative_path_var (cast_sval, visited,
    5204              :                                                      logger);
    5205          402 :       tree orig_type = sval->get_type ();
    5206              :       /* If necessary, wrap the result in a cast, or in a field lookup.  */
    5207          402 :       if (result.m_tree && orig_type)
    5208          378 :         result.m_tree = convert_to_type (orig_type, result.m_tree);
    5209          402 :       if (result)
    5210          378 :         pvs.safe_push (result);
    5211              :     }
    5212              : 
    5213        12063 :   m_store.get_representative_path_vars (this, visited, sval, logger, &pvs);
    5214              : 
    5215        12063 :   if (tree cst = sval->maybe_get_constant ())
    5216         2036 :     pvs.safe_push (path_var (cst, 0));
    5217              : 
    5218              :   /* Handle string literals and various other pointers.  */
    5219        12063 :   if (auto *sym_ptr = sval->maybe_get_symbolic_pointer ())
    5220         4607 :     if (sym_ptr->zero_offset_p ())
    5221              :       {
    5222         4597 :         auto &reg = sym_ptr->get_base_region ();
    5223         4597 :         if (path_var pv = get_representative_path_var (&reg, visited, logger))
    5224           48 :           pvs.safe_push (path_var (build1 (ADDR_EXPR,
    5225              :                                            sval->get_type (),
    5226              :                                            pv.m_tree),
    5227           48 :                                    pv.m_stack_depth));
    5228              :       }
    5229              : 
    5230              : 
    5231              :   /* Handle binops.  */
    5232        12063 :   if (const binop_svalue *binop_sval = sval->dyn_cast_binop_svalue ())
    5233          416 :     if (path_var lhs_pv
    5234          416 :         = get_representative_path_var (binop_sval->get_arg0 (), visited,
    5235          416 :                                        logger))
    5236          379 :       if (path_var rhs_pv
    5237          379 :           = get_representative_path_var (binop_sval->get_arg1 (), visited,
    5238          379 :                                          logger))
    5239          378 :         pvs.safe_push (path_var (build2 (binop_sval->get_op (),
    5240              :                                          sval->get_type (),
    5241              :                                          lhs_pv.m_tree, rhs_pv.m_tree),
    5242          378 :                                  lhs_pv.m_stack_depth));
    5243              : 
    5244              :   /* Handle bit vectors.  */
    5245        12063 :   if (const auto *bv_sval = sval->dyn_cast_svalue_from_bit_vector ())
    5246              :     {
    5247         2282 :       const auto &bv = bv_sval->get_bit_vector ();
    5248         2282 :       if (const auto *sval_bv = bv.dyn_cast_bit_vector_from_svalue ())
    5249              :         {
    5250            0 :           path_var result
    5251            0 :             = get_representative_path_var (&sval_bv->get_svalue (),
    5252              :                                            visited,
    5253              :                                            logger);
    5254            0 :           tree orig_type = sval->get_type ();
    5255              :           /* If necessary, wrap the result in a cast.  */
    5256            0 :           if (result.m_tree && orig_type)
    5257            0 :             result.m_tree = build1 (NOP_EXPR, orig_type, result.m_tree);
    5258            0 :           if (result)
    5259            0 :             pvs.safe_push (result);
    5260              :         }
    5261         2282 :       if (const auto *cropped_bv = bv.dyn_cast_cropped_bit_vector ())
    5262              :         {
    5263           56 :           auto &uncropped_bv = cropped_bv->get_uncropped_bit_vector ();
    5264           56 :           if (auto *from_sval = uncropped_bv.dyn_cast_bit_vector_from_svalue ())
    5265           56 :             if (auto *init_sval = from_sval->get_svalue ().dyn_cast_initial_svalue ())
    5266              :               {
    5267           56 :                 symbolic_bit_range uncropped_bit_range
    5268           56 :                   = cropped_bv->get_uncropped_bits_to_use ();
    5269           56 :                 if (const region *reg
    5270           56 :                     = maybe_get_subregion_for_symbolic_bit_range (*init_sval->get_region (),
    5271              :                                                                   sval->get_type (),
    5272              :                                                                   uncropped_bit_range))
    5273           56 :                   if (path_var result = get_representative_path_var (reg,
    5274              :                                                                      visited,
    5275           56 :                                                                      logger))
    5276           56 :                     pvs.safe_push (result);
    5277              :               }
    5278              :         }
    5279         2282 :       if (const auto *bv_from_ubc = bv.dyn_cast_bit_vector_from_ubc ())
    5280          356 :         if (auto *baseline_bc
    5281          356 :               = bv_from_ubc->get_bit_contents ().dyn_cast_baseline_bit_contents ())
    5282              :           {
    5283              :             /* Are the bits implicitly live due to the region
    5284              :                being untouched?  */
    5285          229 :             const cluster_region *cluster_reg
    5286          229 :               = baseline_bc->get_baseline_key ().m_cluster_reg;
    5287          229 :             symbolic::memory_range mem_range (*cluster_reg,
    5288          229 :                                               bv_from_ubc->get_bit_range ());
    5289          229 :             if (&m_store.get_bits (mem_range, get_baseline_state ())
    5290              :                 == bv_from_ubc)
    5291          206 :                 if (const region *reg
    5292              :                       = maybe_get_subregion_for_symbolic_bit_range
    5293          206 :                           (*cluster_reg,
    5294              :                            sval->get_type (),
    5295          206 :                            bv_from_ubc->get_bit_range ()))
    5296          206 :                   if (path_var result = get_representative_path_var (reg,
    5297              :                                                                      visited,
    5298          206 :                                                                      logger))
    5299           72 :                     pvs.safe_push (result);
    5300              :           }
    5301              :     }
    5302              : 
    5303        12063 :   if (pvs.length () < 1)
    5304         1043 :     return path_var (NULL_TREE, 0);
    5305              : 
    5306        11020 :   pvs.qsort (readability_comparator);
    5307        11020 :   return pvs[0];
    5308        12063 : }
    5309              : 
    5310              : /* Attempt to return a path_var that represents SVAL, or return NULL_TREE.
    5311              :    Use VISITED to prevent infinite mutual recursion with the overload for
    5312              :    regions
    5313              : 
    5314              :    This function defers to get_representative_path_var_1 to do the work;
    5315              :    it adds verification that get_representative_path_var_1 returned a tree
    5316              :    of the correct type.  */
    5317              : 
    5318              : path_var
    5319        18111 : region_model::get_representative_path_var (const svalue *sval,
    5320              :                                            value_set *visited,
    5321              :                                            logger *logger) const
    5322              : {
    5323        18111 :   if (sval == nullptr)
    5324         6006 :     return path_var (NULL_TREE, 0);
    5325              : 
    5326        12105 :   LOG_SCOPE (logger);
    5327        12105 :   if (logger)
    5328              :     {
    5329            0 :       logger->start_log_line ();
    5330            0 :       logger->log_partial ("sval: ");
    5331            0 :       sval->dump_to_pp (logger->get_printer (), true);
    5332            0 :       logger->end_log_line ();
    5333              :     }
    5334              : 
    5335        12105 :   tree orig_type = sval->get_type ();
    5336              : 
    5337        12105 :   path_var result = get_representative_path_var_1 (sval, visited, logger);
    5338              : 
    5339              :   /* Verify that the result has compatible type with SVAL, if any.  */
    5340        12105 :   if (result.m_tree && orig_type)
    5341         9495 :     gcc_assert (types_compatible_p (TREE_TYPE (result.m_tree), orig_type));
    5342              : 
    5343        12105 :   if (logger)
    5344              :     {
    5345            0 :       logger->start_log_line ();
    5346            0 :       logger->log_partial ("sval: ");
    5347            0 :       sval->dump_to_pp (logger->get_printer (), true);
    5348            0 :       logger->end_log_line ();
    5349              : 
    5350            0 :       if (result.m_tree)
    5351            0 :         logger->log ("tree: %qE", result.m_tree);
    5352              :       else
    5353            0 :         logger->log ("tree: NULL");
    5354              :     }
    5355              : 
    5356        12105 :   return result;
    5357        12105 : }
    5358              : 
    5359              : /* Attempt to return a tree that represents SVAL, or return NULL_TREE.
    5360              : 
    5361              :    Strip off any top-level cast, to avoid messages like
    5362              :      double-free of '(void *)ptr'
    5363              :    from analyzer diagnostics.  */
    5364              : 
    5365              : tree
    5366        15085 : region_model::get_representative_tree (const svalue *sval, logger *logger) const
    5367              : {
    5368        15085 :   value_set visited;
    5369        15085 :   tree expr = get_representative_path_var (sval, &visited, logger).m_tree;
    5370              : 
    5371              :   /* Strip off any top-level casts.  */
    5372        17415 :   while (expr && TREE_CODE (expr) == NOP_EXPR)
    5373         2330 :     expr = TREE_OPERAND (expr, 0);
    5374              : 
    5375        15085 :   expr = fixup_tree_for_diagnostic (expr);
    5376              : 
    5377              :   /* The fixup can add a cast; strip it too.  */
    5378        30171 :   while (expr && TREE_CODE (expr) == NOP_EXPR)
    5379            1 :     expr = TREE_OPERAND (expr, 0);
    5380              : 
    5381        15085 :   return expr;
    5382        15085 : }
    5383              : 
    5384              : tree
    5385          933 : region_model::get_representative_tree (const region *reg, logger *logger) const
    5386              : {
    5387          933 :   value_set visited;
    5388          933 :   tree expr = get_representative_path_var (reg, &visited, logger).m_tree;
    5389              : 
    5390              :   /* Strip off any top-level cast.  */
    5391          933 :   if (expr && TREE_CODE (expr) == NOP_EXPR)
    5392            5 :     expr = TREE_OPERAND (expr, 0);
    5393              : 
    5394          933 :   return fixup_tree_for_diagnostic (expr);
    5395          933 : }
    5396              : 
    5397              : const region *
    5398       664108 : region_model::
    5399              : maybe_get_region_for_mem_range (const symbolic::memory_range &mem_range,
    5400              :                                 tree desired_type,
    5401              :                                 logger *) const
    5402              : {
    5403       664108 :   return maybe_get_subregion_for_symbolic_bit_range
    5404       664108 :     (mem_range.get_base_region (),
    5405              :      desired_type,
    5406       664108 :      mem_range.get_bit_range ());
    5407              : }
    5408              : 
    5409              : const region *
    5410       669936 : region_model::
    5411              : maybe_get_subregion_for_symbolic_bit_range (const region &reg,
    5412              :                                             tree desired_type,
    5413              :                                             symbolic_bit_range bit_range) const
    5414              : {
    5415       669936 :   concrete_bit_range conc_bit_range;
    5416       669936 :   if (concrete_from_symbolic (bit_range, &conc_bit_range))
    5417      1311648 :     return maybe_get_subregion_for_concrete_bit_range (reg,
    5418              :                                                        desired_type,
    5419              :                                                        conc_bit_range);
    5420              : 
    5421              :   /* Symbolic case.  */
    5422        14112 :   if (reg.get_type ())
    5423        12246 :     switch (TREE_CODE (reg.get_type ()))
    5424              :       {
    5425              :       default:
    5426              :         break;
    5427              : 
    5428         4153 :       case ARRAY_TYPE:
    5429         8306 :         if (auto *result
    5430         4153 :               = maybe_get_subregion_for_symbolic_bit_range_in_array (reg,
    5431              :                                                                      desired_type,
    5432              :                                                                      bit_range))
    5433              :           return result;
    5434              :         break;
    5435              : 
    5436         1562 :       case RECORD_TYPE:
    5437         3124 :         if (auto *result
    5438         1562 :               = maybe_get_subregion_for_symbolic_bit_range_in_record (reg,
    5439              :                                                                       desired_type,
    5440              :                                                                       bit_range))
    5441              :           return result;
    5442              :         break;
    5443              :       }
    5444              : 
    5445              :   /* Fallback: see if we can express this using offset_region and
    5446              :      sized_region.  */
    5447        10503 :   if (auto *byte_size = maybe_bytes_from_bits (bit_range.get_size ()))
    5448         9796 :     if (auto *byte_offset
    5449         9796 :           = maybe_bytes_from_bits (bit_range.get_start_offset ()))
    5450              :       {
    5451         6075 :         auto *byte_offset_sval
    5452         6075 :           = m_mgr->get_svalue_from_scalar<concrete_byte_offset>
    5453         6075 :               (ptrdiff_type_node, *byte_offset);
    5454         6075 :         auto *offset_reg = m_mgr->get_offset_region (&reg,
    5455              :                                                      NULL_TREE,
    5456              :                                                      byte_offset_sval);
    5457         6075 :         auto *byte_size_sval
    5458         6075 :           = m_mgr->get_svalue_from_scalar<concrete_byte_size> (size_type_node,
    5459              :                                                                *byte_size);
    5460         6075 :         return m_mgr->get_sized_region (offset_reg, desired_type,
    5461         6075 :                                         byte_size_sval);
    5462              :       }
    5463              : 
    5464              :   return nullptr;
    5465       669936 : }
    5466              : 
    5467              : /* Subroutine of maybe_get_subregion_for_symbolic_bit_range for the
    5468              :    purely concrete case; we shouldn't need this region_model.  */
    5469              : 
    5470              : const region *
    5471       655824 : region_model::
    5472              : maybe_get_subregion_for_concrete_bit_range (const region &reg,
    5473              :                                             tree desired_type,
    5474              :                                             concrete_bit_range conc_bit_range) const
    5475              : {
    5476       655824 :   auto_vec<const region *> regions;
    5477       655824 :   reg.get_subregions_for_bit_range (m_mgr, conc_bit_range,
    5478              :                                     desired_type,
    5479              :                                     &regions);
    5480       655824 :   if (regions.length () < 1)
    5481              :     {
    5482              :       /* Fallback: see if we can express this using offset_region and
    5483              :          sized_region.  */
    5484        15687 :       concrete_byte_size conc_byte_size;
    5485        15687 :       if (maybe_bytes_from_bits (conc_bit_range.get_size (),
    5486              :                                  &conc_byte_size))
    5487              :         {
    5488        15569 :           concrete_byte_offset conc_byte_offset;
    5489        15569 :           if (maybe_bytes_from_bits (conc_bit_range.get_start_offset (),
    5490              :                                      &conc_byte_offset))
    5491              :             {
    5492        15569 :               auto &byte_mgr
    5493        15569 :                 = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
    5494        15569 :               auto *byte_offset_sval
    5495              :                 = m_mgr->get_svalue_from_scalar<concrete_byte_offset>
    5496        15569 :                 (ptrdiff_type_node,
    5497        15569 :                  byte_mgr.get_concrete (conc_byte_offset));
    5498        15569 :               auto *offset_reg
    5499        15569 :                 = m_mgr->get_offset_region (&reg,
    5500              :                                             NULL_TREE,
    5501              :                                             byte_offset_sval);
    5502        15569 :               auto *byte_size_sval
    5503        15569 :                 = m_mgr->get_svalue_from_scalar<concrete_byte_size>
    5504        15569 :                 (size_type_node,
    5505        15569 :                  byte_mgr.get_concrete (conc_byte_size));
    5506        15569 :               return m_mgr->get_sized_region (offset_reg, desired_type,
    5507              :                                               byte_size_sval);
    5508              :             }
    5509        15569 :         }
    5510              :       return nullptr;
    5511        15687 :     }
    5512       640137 :   return regions[0]; // TODO: sort by readability?
    5513       655824 : }
    5514              : 
    5515              : /* Subroutine for ARRAY_TYPE case of
    5516              :    region_model::maybe_get_subregion_for_symbolic_bit_range
    5517              :    for getting a type for the index of an element_region.  */
    5518              : 
    5519              : template <typename ConcreteValueType>
    5520              : static tree
    5521         4152 : get_underlying_index_type (const symbolic::scalar<ConcreteValueType> &sym_offset)
    5522              : {
    5523              :   /* Try to preserve the type of an underlying integral svalue.  */
    5524         4152 :   if (auto *from_sval
    5525         4152 :       = sym_offset.dyn_cast_scalar_from_svalue ())
    5526              :     {
    5527         1741 :       auto &sval = from_sval->get_svalue ();
    5528         1741 :       if (sval.get_type ()
    5529         1741 :           && TREE_CODE (sval.get_type ()) == INTEGER_TYPE)
    5530              :         return sval.get_type ();
    5531              :     }
    5532              : 
    5533         2413 :   return integer_type_node;
    5534              : }
    5535              : 
    5536              : namespace {
    5537              : 
    5538              : /* Support code for maybe_get_subregion_for_symbolic_bit_range_in_array
    5539              :    for reconstructing array indices from bit/byte offsets.  */
    5540              : 
    5541              : /* Result of splitting an expression into (quotient * divisor) + residual.  */
    5542              : 
    5543              : template <typename ConcreteValueType>
    5544              : struct quotient_and_residual
    5545              : {
    5546         7361 :   quotient_and_residual (const symbolic::scalar<integer> *quotient,
    5547              :                          const symbolic::scalar<ConcreteValueType> *residual)
    5548         7361 :    : m_quotient (quotient),
    5549         7361 :      m_residual (residual)
    5550              :   {
    5551         7361 :     gcc_assert (quotient);
    5552         7361 :     gcc_assert (residual);
    5553         7361 :   }
    5554              : 
    5555              :   quotient_and_residual &
    5556          870 :   operator+= (const quotient_and_residual &other)
    5557              :   {
    5558          870 :     m_quotient = &(*m_quotient + *other.m_quotient);
    5559          870 :     m_residual = &(*m_residual + *other.m_residual);
    5560          870 :     return *this;
    5561              :   }
    5562              : 
    5563              :   DEBUG_FUNCTION void
    5564            0 :   dump () const
    5565              :   {
    5566            0 :     symbolic::dump_node_tree_to_stderr<quotient_and_residual> (*this);
    5567            0 :   }
    5568              : 
    5569              :   std::unique_ptr<text_art::tree_widget>
    5570            0 :   make_dump_widget (symbolic::node_dump_state &nds) const
    5571              :   {
    5572              :     using text_art::tree_widget;
    5573            0 :     std::unique_ptr<tree_widget> w
    5574              :       (tree_widget::from_fmt (nds, nullptr, "quotient_and_residual"));
    5575            0 :     w->add_child (m_quotient->make_dump_widget (nds));
    5576            0 :     w->add_child (m_residual->make_dump_widget (nds));
    5577            0 :     return w;
    5578              :   }
    5579              : 
    5580              :   const symbolic::scalar<integer> *m_quotient;
    5581              :   const symbolic::scalar<ConcreteValueType> *m_residual;
    5582              : };
    5583              : 
    5584              : template <typename ConcreteValueType>
    5585              : quotient_and_residual<ConcreteValueType>
    5586              : handle_bits_from_bytes (const symbolic::scalar<ConcreteValueType> &scalar,
    5587              :                         ConcreteValueType divisor);
    5588              : 
    5589              : /* Try to split SCALAR into the form
    5590              :      (quotient * DIVISOR) + residual
    5591              :    This is always possible with quotient == 0 and residual == SCALAR,
    5592              :    but we want it in a form that will help when trying to reconstruct
    5593              :    an array index from a bit offset.  */
    5594              : 
    5595              : template <typename ConcreteValueType>
    5596              : quotient_and_residual<ConcreteValueType>
    5597         7361 : try_split_exact_multiple (const symbolic::scalar<ConcreteValueType> &scalar,
    5598              :                           ConcreteValueType divisor)
    5599              : {
    5600         7361 :   auto &unit_mgr = scalar.get_mgr ();
    5601         7361 :   auto &unitless_mgr = unit_mgr.get_unitless_manager ();
    5602              : 
    5603         7361 :   auto &zero_quotient = unitless_mgr.get_concrete (0);
    5604         7361 :   auto &zero_units = unit_mgr.get_concrete (ConcreteValueType (0));
    5605              : 
    5606         7361 :   switch (scalar.get_kind ())
    5607              :     {
    5608            0 :     default:
    5609            0 :       gcc_unreachable ();
    5610              : 
    5611          503 :     case symbolic::scalar<ConcreteValueType>::kind::concrete:
    5612              :       {
    5613          503 :         auto &concrete
    5614              :           = static_cast<const symbolic::concrete_scalar<ConcreteValueType> &> (scalar);
    5615          503 :         auto &conc_val = concrete.get_concrete ();
    5616              :         return quotient_and_residual<ConcreteValueType>
    5617          503 :           {&unitless_mgr.get_concrete (conc_val.floor_div (divisor)),
    5618          503 :            &unit_mgr.get_concrete (conc_val.floor_mod (divisor))};
    5619              :       }
    5620              :       break;
    5621              : 
    5622          424 :     case symbolic::scalar<ConcreteValueType>::kind::sum:
    5623              :       {
    5624          424 :         auto &sum
    5625              :           = static_cast<const symbolic::sum<ConcreteValueType> &> (scalar);
    5626          424 :         quotient_and_residual<ConcreteValueType> result {&zero_quotient, &zero_units};
    5627          897 :         for (size_t i = 0; i < sum.get_num_symbolic_addends (); ++i)
    5628              :           {
    5629          473 :             auto result_for_term
    5630          473 :               = try_split_exact_multiple (sum.get_symbolic_addend (i),
    5631              :                                           divisor);
    5632          473 :             result += result_for_term;
    5633              :           }
    5634          424 :         if (auto *conc = sum.get_any_concrete_addend ())
    5635          397 :           result += try_split_exact_multiple (*conc, divisor);
    5636          424 :         return result;
    5637              :       }
    5638              :       break;
    5639              : 
    5640         1494 :     case symbolic::scalar<ConcreteValueType>::kind::product:
    5641              :       {
    5642         1494 :         auto &product
    5643              :           = static_cast<const symbolic::product<ConcreteValueType> &> (scalar);
    5644              :         // Does factor == divisor?
    5645         1494 :         ConcreteValueType conc_lhs;
    5646         1494 :         if (concrete_from_symbolic (product.get_lhs (), &conc_lhs)
    5647         1494 :             && conc_lhs == divisor)
    5648         1334 :           return quotient_and_residual<ConcreteValueType> {&product.get_rhs (),
    5649         1334 :                                                            &zero_units};
    5650         1334 :       }
    5651          160 :       break;
    5652              : 
    5653         2596 :     case symbolic::scalar<ConcreteValueType>::kind::from_svalue:
    5654         2596 :       if (divisor.is_one_p ())
    5655              :         {
    5656          407 :           auto &from_sval
    5657              :             = static_cast<const symbolic::scalar_from_svalue<ConcreteValueType> &> (scalar);
    5658              :           return quotient_and_residual<ConcreteValueType>
    5659          407 :             {&unitless_mgr.get_scalar_from_svalue (from_sval.get_svalue ()),
    5660          407 :              &zero_units};
    5661              :         }
    5662              :       break;
    5663              : 
    5664              :     case symbolic::scalar<ConcreteValueType>::kind::named_test:
    5665              :       break;
    5666              : 
    5667         2344 :     case symbolic::scalar<ConcreteValueType>::kind::bits_from_bytes:
    5668         2344 :       return handle_bits_from_bytes (scalar, divisor);
    5669              :     }
    5670              : 
    5671              :   // Can't split:
    5672         2349 :   return quotient_and_residual<ConcreteValueType> {&zero_quotient, &scalar};
    5673              : }
    5674              : 
    5675              : template <>
    5676              : quotient_and_residual<concrete_bit_offset>
    5677         2344 : handle_bits_from_bytes (const symbolic::scalar<concrete_bit_offset> &scalar,
    5678              :                         concrete_bit_offset divisor)
    5679              : {
    5680         2344 :   auto &unit_mgr = scalar.get_mgr ();
    5681         2344 :   auto &unitless_mgr = unit_mgr.get_unitless_manager ();
    5682              : 
    5683         2344 :   auto &zero_quotient = unitless_mgr.get_concrete (0);
    5684              : 
    5685         2344 :   auto *bits_from_bytes
    5686         2344 :     = scalar.dyn_cast_bits_from_bytes_scalar ();
    5687         2344 :   gcc_assert (bits_from_bytes);
    5688              : 
    5689         4688 :   if (divisor.get_integer ().floor_mod (BITS_PER_UNIT) == 0)
    5690              :     {
    5691         2339 :       concrete_byte_offset divisor_as_bytes
    5692         2339 :         (divisor.get_integer ().floor_div (BITS_PER_UNIT));
    5693         2339 :       auto &bytes = bits_from_bytes->get_bytes ();
    5694         2339 :       auto bytes_result
    5695         2339 :         = try_split_exact_multiple<concrete_byte_offset> (bytes, divisor_as_bytes);
    5696         4678 :       return quotient_and_residual<concrete_bit_offset>
    5697              :         {bytes_result.m_quotient,
    5698         2339 :          &unit_mgr.get_bits_from_bytes (*bytes_result.m_residual)};
    5699         2339 :     }
    5700              : 
    5701              :   // Can't split:
    5702            5 :   return quotient_and_residual<concrete_bit_offset> {&zero_quotient, &scalar};
    5703              : }
    5704              : 
    5705              : template <>
    5706              : quotient_and_residual<concrete_byte_offset>
    5707            0 : handle_bits_from_bytes (const symbolic::scalar<concrete_byte_offset> &,
    5708              :                         concrete_byte_offset)
    5709              : {
    5710            0 :   gcc_unreachable ();
    5711              : }
    5712              : 
    5713              : } // anonymous namespace
    5714              : 
    5715              : /* Subroutine of maybe_get_subregion_for_symbolic_bit_range for the
    5716              :    case where ARRAY_REG is of ARRAY_TYPE.  */
    5717              : 
    5718              : const region *
    5719         4153 : region_model::
    5720              : maybe_get_subregion_for_symbolic_bit_range_in_array (const region &array_reg,
    5721              :                                                      tree desired_type,
    5722              :                                                      symbolic_bit_range bit_range) const
    5723              : {
    5724         4153 :   gcc_assert (TREE_CODE (array_reg.get_type ()) == ARRAY_TYPE);
    5725              : 
    5726         4153 :   tree element_type = TREE_TYPE (array_reg.get_type ());
    5727         4153 :   concrete_bit_size element_size;
    5728         4153 :   if (!get_type_size (element_type, &element_size))
    5729              :     return nullptr;
    5730              : 
    5731         4152 :   auto split = try_split_exact_multiple<concrete_bit_offset>
    5732         4152 :     (bit_range.get_start_offset (),
    5733              :      element_size);
    5734              : 
    5735         4152 :   tree index_type = get_underlying_index_type (*split.m_quotient);
    5736         4152 :   auto *index_sval = m_mgr->get_svalue_from_scalar<integer>
    5737         4152 :     (index_type, *split.m_quotient);
    5738              : 
    5739         4152 :   auto *element_reg = m_mgr->get_element_region (&array_reg,
    5740              :                                                  element_type,
    5741              :                                                  index_sval);
    5742         4152 :   symbolic_bit_range relative_bit_range (*split.m_residual,
    5743         4152 :                                          bit_range.get_size ());
    5744         4152 :   return maybe_get_subregion_for_symbolic_bit_range
    5745         4152 :     (*element_reg, desired_type, relative_bit_range);
    5746         4153 : }
    5747              : 
    5748              : const region *
    5749         1562 : region_model::
    5750              : maybe_get_subregion_for_symbolic_bit_range_in_record (const region &record_reg,
    5751              :                                                       tree desired_type,
    5752              :                                                       symbolic_bit_range bit_range) const
    5753              : {
    5754         1562 :   auto &start_offset = bit_range.get_start_offset ();
    5755              : 
    5756              :   /* Determine if we have sum(X, concrete), possibly of bytes.  */
    5757         1562 :   concrete_bit_offset conc_bit_offset;
    5758         1562 :   if (auto *bits_from_bytes_scalar = start_offset.dyn_cast_bits_from_bytes_scalar ())
    5759              :     {
    5760         1210 :       if (auto *byte_sum = bits_from_bytes_scalar->get_bytes ().dyn_cast_sum ())
    5761          567 :         if (auto *conc_byte_addend = byte_sum->get_any_concrete_addend_value ())
    5762          564 :           conc_bit_offset = bits_from_bytes (*conc_byte_addend);
    5763              :     }
    5764          352 :   else if (auto *bit_sum = start_offset.dyn_cast_sum ())
    5765            0 :     if (auto *conc_bit_addend = bit_sum->get_any_concrete_addend_value ())
    5766            0 :       conc_bit_offset = *conc_bit_addend;
    5767              : 
    5768              :   /* If we have sum(X, concrete), then offset into the struct
    5769              :      and do something with that... */
    5770         1562 :   {
    5771              :       /* Determine where the concrete addend is within the record.  */
    5772              :       // TODO: amortize this?
    5773         1562 :       record_layout layout (record_reg.get_type ());
    5774         1562 :       if (auto *item = layout.get_item_at (conc_bit_offset))
    5775              :         {
    5776         1414 :           auto *field_reg
    5777         2828 :             = m_mgr->get_field_region (&record_reg,
    5778         1414 :                                        const_cast<tree> (item->m_field));
    5779         1414 :           symbolic_bit_range relative_bit_range
    5780         2828 :             (bit_range.get_start_offset () - item->get_start_offset (),
    5781         1414 :              bit_range.get_size ());
    5782         1414 :           return maybe_get_subregion_for_symbolic_bit_range
    5783         1414 :             (*field_reg, desired_type, relative_bit_range);
    5784              :         }
    5785         1414 :     }
    5786              : 
    5787          148 :   return nullptr;
    5788         1562 : }
    5789              : 
    5790              : /* Implementation of region_model::get_representative_path_var.
    5791              : 
    5792              :    Attempt to return a path_var that represents REG, or return
    5793              :    the NULL path_var.
    5794              :    For example, a region for a field of a local would be a path_var
    5795              :    wrapping a COMPONENT_REF.
    5796              :    Use VISITED to prevent infinite mutual recursion with the overload for
    5797              :    svalues.  */
    5798              : 
    5799              : path_var
    5800        18451 : region_model::get_representative_path_var_1 (const region *reg,
    5801              :                                              value_set *visited,
    5802              :                                              logger *logger) const
    5803              : {
    5804        18451 :   switch (reg->get_kind ())
    5805              :     {
    5806            0 :     default:
    5807            0 :       gcc_unreachable ();
    5808              : 
    5809            0 :     case RK_FRAME:
    5810            0 :     case RK_MEMORY_SPACE:
    5811            0 :     case RK_ROOT:
    5812              :        /* Regions that represent memory spaces are not expressible as trees.  */
    5813            0 :       return path_var (NULL_TREE, 0);
    5814              : 
    5815            4 :     case RK_FUNCTION:
    5816            4 :       {
    5817            4 :         const function_region *function_reg
    5818            4 :           = as_a <const function_region *> (reg);
    5819            4 :         return path_var (function_reg->get_fndecl (), 0);
    5820              :       }
    5821            4 :     case RK_LABEL:
    5822            4 :       {
    5823            4 :         const label_region *label_reg = as_a <const label_region *> (reg);
    5824            4 :         return path_var (label_reg->get_label (), 0);
    5825              :       }
    5826              : 
    5827          316 :     case RK_SYMBOLIC:
    5828          316 :       {
    5829          316 :         const symbolic_region *symbolic_reg
    5830          316 :           = as_a <const symbolic_region *> (reg);
    5831          316 :         const svalue *pointer = symbolic_reg->get_pointer ();
    5832          316 :         path_var pointer_pv = get_representative_path_var (pointer, visited,
    5833              :                                                            logger);
    5834          316 :         if (!pointer_pv)
    5835           48 :           return path_var (NULL_TREE, 0);
    5836          268 :         tree offset = build_int_cst (pointer->get_type (), 0);
    5837          268 :         return path_var (build2 (MEM_REF,
    5838              :                                  reg->get_type (),
    5839              :                                  pointer_pv.m_tree,
    5840              :                                  offset),
    5841          268 :                          pointer_pv.m_stack_depth);
    5842              :       }
    5843        10682 :     case RK_DECL:
    5844        10682 :       {
    5845        10682 :         const decl_region *decl_reg = as_a <const decl_region *> (reg);
    5846        10682 :         return path_var (decl_reg->get_decl (), decl_reg->get_stack_depth ());
    5847              :       }
    5848         2045 :     case RK_FIELD:
    5849         2045 :       {
    5850         2045 :         const field_region *field_reg = as_a <const field_region *> (reg);
    5851         2045 :         path_var parent_pv
    5852         2045 :           = get_representative_path_var (reg->get_parent_region (), visited,
    5853              :                                          logger);
    5854         2045 :         if (!parent_pv)
    5855           16 :           return path_var (NULL_TREE, 0);
    5856         2029 :         return path_var (build3 (COMPONENT_REF,
    5857              :                                  reg->get_type (),
    5858              :                                  parent_pv.m_tree,
    5859              :                                  field_reg->get_field (),
    5860              :                                  NULL_TREE),
    5861         2029 :                          parent_pv.m_stack_depth);
    5862              :       }
    5863              : 
    5864          235 :     case RK_ELEMENT:
    5865          235 :       {
    5866          235 :         const element_region *element_reg
    5867          235 :           = as_a <const element_region *> (reg);
    5868          235 :         path_var parent_pv
    5869          235 :           = get_representative_path_var (reg->get_parent_region (), visited,
    5870              :                                          logger);
    5871          235 :         if (!parent_pv)
    5872            0 :           return path_var (NULL_TREE, 0);
    5873          235 :         path_var index_pv
    5874          235 :           = get_representative_path_var (element_reg->get_index (), visited,
    5875              :                                          logger);
    5876          235 :         if (!index_pv)
    5877            0 :           return path_var (NULL_TREE, 0);
    5878          235 :         return path_var (build4 (ARRAY_REF,
    5879              :                                  reg->get_type (),
    5880              :                                  parent_pv.m_tree, index_pv.m_tree,
    5881              :                                  NULL_TREE, NULL_TREE),
    5882          235 :                          parent_pv.m_stack_depth);
    5883              :       }
    5884              : 
    5885            0 :     case RK_OFFSET:
    5886            0 :       {
    5887            0 :         const offset_region *offset_reg
    5888            0 :           = as_a <const offset_region *> (reg);
    5889            0 :         path_var parent_pv
    5890            0 :           = get_representative_path_var (reg->get_parent_region (), visited,
    5891              :                                          logger);
    5892            0 :         if (!parent_pv)
    5893            0 :           return path_var (NULL_TREE, 0);
    5894            0 :         path_var offset_pv
    5895            0 :           = get_representative_path_var (offset_reg->get_byte_offset (),
    5896              :                                          visited, logger);
    5897            0 :         if (!offset_pv || TREE_CODE (offset_pv.m_tree) != INTEGER_CST)
    5898            0 :           return path_var (NULL_TREE, 0);
    5899            0 :         tree addr_parent = build1 (ADDR_EXPR,
    5900              :                                    build_pointer_type (reg->get_type ()),
    5901              :                                    parent_pv.m_tree);
    5902            0 :         tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode,
    5903              :                                                   true);
    5904            0 :         return path_var (build2 (MEM_REF, reg->get_type (), addr_parent,
    5905              :                                  fold_convert (ptype, offset_pv.m_tree)),
    5906            0 :                          parent_pv.m_stack_depth);
    5907              :       }
    5908              : 
    5909          170 :     case RK_SIZED:
    5910          170 :       return path_var (NULL_TREE, 0);
    5911              : 
    5912          224 :     case RK_CAST:
    5913          224 :       {
    5914          224 :         path_var parent_pv
    5915          224 :           = get_representative_path_var (reg->get_parent_region (), visited,
    5916              :                                          logger);
    5917          224 :         if (!parent_pv)
    5918            1 :           return path_var (NULL_TREE, 0);
    5919          223 :         return path_var (build1 (NOP_EXPR,
    5920              :                                  reg->get_type (),
    5921              :                                  parent_pv.m_tree),
    5922          223 :                          parent_pv.m_stack_depth);
    5923              :       }
    5924              : 
    5925         4758 :     case RK_HEAP_ALLOCATED:
    5926         4758 :     case RK_ALLOCA:
    5927              :       /* No good way to express heap-allocated/alloca regions as trees.  */
    5928         4758 :       return path_var (NULL_TREE, 0);
    5929              : 
    5930           13 :     case RK_STRING:
    5931           13 :       {
    5932           13 :         const string_region *string_reg = as_a <const string_region *> (reg);
    5933           13 :         return path_var (string_reg->get_string_cst (), 0);
    5934              :       }
    5935              : 
    5936            0 :     case RK_VAR_ARG:
    5937            0 :     case RK_ERRNO:
    5938            0 :     case RK_UNKNOWN:
    5939            0 :     case RK_PRIVATE:
    5940            0 :       return path_var (NULL_TREE, 0);
    5941              :     }
    5942              : }
    5943              : 
    5944              : /* Attempt to return a path_var that represents REG, or return
    5945              :    the NULL path_var.
    5946              :    For example, a region for a field of a local would be a path_var
    5947              :    wrapping a COMPONENT_REF.
    5948              :    Use VISITED to prevent infinite mutual recursion with the overload for
    5949              :    svalues.
    5950              : 
    5951              :    This function defers to get_representative_path_var_1 to do the work;
    5952              :    it adds verification that get_representative_path_var_1 returned a tree
    5953              :    of the correct type.  */
    5954              : 
    5955              : path_var
    5956        18451 : region_model::get_representative_path_var (const region *reg,
    5957              :                                            value_set *visited,
    5958              :                                            logger *logger) const
    5959              : {
    5960        18451 :   LOG_SCOPE (logger);
    5961        18451 :   if (logger)
    5962              :     {
    5963            0 :       logger->start_log_line ();
    5964            0 :       logger->log_partial ("reg: ");
    5965            0 :       reg->dump_to_pp (logger->get_printer (), true);
    5966            0 :       logger->end_log_line ();
    5967              :     }
    5968              : 
    5969        18451 :   path_var result = get_representative_path_var_1 (reg, visited, logger);
    5970              : 
    5971              :   /* Verify that the result has the same type as REG, if any.  */
    5972        18451 :   if (result.m_tree && reg->get_type ())
    5973        13379 :     gcc_assert (TREE_TYPE (result.m_tree) == reg->get_type ());
    5974              : 
    5975        18451 :   if (logger)
    5976              :     {
    5977            0 :       logger->start_log_line ();
    5978            0 :       logger->log_partial ("reg: ");
    5979            0 :       reg->dump_to_pp (logger->get_printer (), true);
    5980            0 :       logger->end_log_line ();
    5981              : 
    5982            0 :       if (result.m_tree)
    5983            0 :         logger->log ("tree: %qE", result.m_tree);
    5984              :       else
    5985            0 :         logger->log ("tree: NULL");
    5986              :     }
    5987              : 
    5988        36902 :   return result;
    5989        18451 : }
    5990              : 
    5991              : /* Push a new frame_region on to the stack region.
    5992              :    Populate the frame_region with child regions for the function call's
    5993              :    parameters, using values from the arguments at the callsite in the
    5994              :    caller's frame.  */
    5995              : 
    5996              : void
    5997        14818 : region_model::update_for_gcall (const gcall &call_stmt,
    5998              :                                 region_model_context *ctxt,
    5999              :                                 function *callee)
    6000              : {
    6001              :   /* Build a vec of argument svalues, using the current top
    6002              :      frame for resolving tree expressions.  */
    6003        14818 :   auto_vec<const svalue *> arg_svals (gimple_call_num_args (&call_stmt));
    6004              : 
    6005        47024 :   for (unsigned i = 0; i < gimple_call_num_args (&call_stmt); i++)
    6006              :     {
    6007        17388 :       tree arg = gimple_call_arg (&call_stmt, i);
    6008        17388 :       arg_svals.quick_push (get_rvalue (arg, ctxt));
    6009              :     }
    6010              : 
    6011        14818 :   if(!callee)
    6012              :   {
    6013              :     /* Get the function * from the gcall.  */
    6014            0 :     tree fn_decl = get_fndecl_for_call (call_stmt, ctxt);
    6015            0 :     callee = DECL_STRUCT_FUNCTION (fn_decl);
    6016              :   }
    6017              : 
    6018            0 :   gcc_assert (callee);
    6019        14818 :   push_frame (*callee, &call_stmt, &arg_svals, ctxt);
    6020        14818 : }
    6021              : 
    6022              : /* Pop the top-most frame_region from the stack, and copy the return
    6023              :    region's values (if any) into the region for the lvalue of the LHS of
    6024              :    the call (if any).  */
    6025              : 
    6026              : void
    6027        11064 : region_model::update_for_return_gcall (const gcall &call_stmt,
    6028              :                                        region_model_context *ctxt)
    6029              : {
    6030              :   /* Get the lvalue for the result of the call, passing it to pop_frame,
    6031              :      so that pop_frame can determine the region with respect to the
    6032              :      *caller* frame.  */
    6033        11064 :   tree lhs = gimple_call_lhs (&call_stmt);
    6034        11064 :   pop_frame (lhs, nullptr, ctxt, &call_stmt);
    6035        11064 : }
    6036              : 
    6037              : /* Attempt to use R to replay SUMMARY into this object.
    6038              :    Return true if it is possible.  */
    6039              : 
    6040              : bool
    6041          677 : region_model::replay_call_summary (call_summary_replay &r,
    6042              :                                    const region_model &summary)
    6043              : {
    6044          677 :   gcc_assert (summary.get_stack_depth () == 1);
    6045              : 
    6046          677 :   if (!m_store.replay_call_summary (r, summary.m_store))
    6047              :     return false;
    6048              : 
    6049          507 :   if (r.get_ctxt ())
    6050          465 :     r.get_ctxt ()->maybe_did_work ();
    6051              : 
    6052          507 :   if (!m_constraints->replay_call_summary (r, *summary.m_constraints))
    6053              :     return false;
    6054              : 
    6055          528 :   for (auto kv : summary.m_dynamic_extents)
    6056              :     {
    6057           72 :       const region *summary_reg = kv.first;
    6058           72 :       const region *caller_reg = r.convert_region_from_summary (summary_reg);
    6059           72 :       if (!caller_reg)
    6060            2 :         continue;
    6061           70 :       const svalue *summary_sval = kv.second;
    6062           70 :       const svalue *caller_sval = r.convert_svalue_from_summary (summary_sval);
    6063           70 :       if (!caller_sval)
    6064            0 :         continue;
    6065           70 :       m_dynamic_extents.put (caller_reg, caller_sval);
    6066              :     }
    6067              : 
    6068          456 :   return true;
    6069              : }
    6070              : 
    6071              : /* For use with push_frame when handling a top-level call within the analysis.
    6072              :    PARAM has a defined but unknown initial value.
    6073              :    Anything it points to has escaped, since the calling context "knows"
    6074              :    the pointer, and thus calls to unknown functions could read/write into
    6075              :    the region.
    6076              :    If NONNULL is true, then assume that PARAM must be non-NULL.  */
    6077              : 
    6078              : void
    6079        23880 : region_model::on_top_level_param (tree param,
    6080              :                                   bool nonnull,
    6081              :                                   region_model_context *ctxt)
    6082              : {
    6083        23880 :   if (POINTER_TYPE_P (TREE_TYPE (param)))
    6084              :     {
    6085        11506 :       const region *param_reg = get_lvalue (param, ctxt);
    6086        11506 :       const svalue *init_ptr_sval
    6087        11506 :         = m_mgr->get_or_create_initial_value (param_reg);
    6088        11506 :       const region *pointee_reg = m_mgr->get_symbolic_region (init_ptr_sval);
    6089        11506 :       m_store.mark_as_escaped (pointee_reg, get_baseline_state ());
    6090        11506 :       if (nonnull)
    6091              :         {
    6092         1125 :           const svalue *null_ptr_sval
    6093         1125 :             = m_mgr->get_or_create_null_ptr (TREE_TYPE (param));
    6094         1125 :           add_constraint (init_ptr_sval, NE_EXPR, null_ptr_sval, ctxt);
    6095              :         }
    6096              :     }
    6097        23880 : }
    6098              : 
    6099              : /* Update this region_model to reflect pushing a frame onto the stack
    6100              :    for a call to FUN.
    6101              : 
    6102              :    If CALL_STMT is non-NULL, this is for the interprocedural case where
    6103              :    we already have an execution path into the caller.  It can be NULL for
    6104              :    top-level entrypoints into the analysis, or in selftests.
    6105              : 
    6106              :    If ARG_SVALS is non-NULL, use it to populate the parameters
    6107              :    in the new frame.
    6108              :    Otherwise, the params have their initial_svalues.
    6109              : 
    6110              :    Return the frame_region for the new frame.  */
    6111              : 
    6112              : const region *
    6113        41340 : region_model::push_frame (const function &fun,
    6114              :                           const gcall *call_stmt,
    6115              :                           const vec<const svalue *> *arg_svals,
    6116              :                           region_model_context *ctxt)
    6117              : {
    6118        41340 :   tree fndecl = fun.decl;
    6119        41340 :   if (arg_svals)
    6120              :     {
    6121              :       /* If the result of the callee is DECL_BY_REFERENCE, then
    6122              :          we'll need to store a reference to the caller's lhs of
    6123              :          CALL_STMT within callee's result.
    6124              :          If so, determine the region of CALL_STMT's lhs within
    6125              :          the caller's frame before updating m_current_frame.  */
    6126        14818 :       const region *caller_return_by_reference_reg = nullptr;
    6127        14818 :       if (tree result = DECL_RESULT (fndecl))
    6128        14818 :         if (DECL_BY_REFERENCE (result))
    6129              :           {
    6130           55 :             gcc_assert (call_stmt);
    6131           55 :             tree lhs = gimple_call_lhs (call_stmt);
    6132           55 :             gcc_assert (lhs);
    6133           55 :             caller_return_by_reference_reg = get_lvalue (lhs, ctxt);
    6134              :           }
    6135              : 
    6136              :       /* Update m_current_frame.  */
    6137        14818 :       m_current_frame = m_mgr->get_frame_region (m_current_frame, fun);
    6138              : 
    6139              :       /* Arguments supplied from a caller frame.  */
    6140        14818 :       unsigned idx = 0;
    6141        31730 :       for (tree iter_parm = DECL_ARGUMENTS (fndecl); iter_parm;
    6142        16912 :            iter_parm = DECL_CHAIN (iter_parm), ++idx)
    6143              :         {
    6144              :           /* If there's a mismatching declaration, the call stmt might
    6145              :              not have enough args.  Handle this case by leaving the
    6146              :              rest of the params as uninitialized.  */
    6147        16916 :           if (idx >= arg_svals->length ())
    6148              :             break;
    6149        16912 :           tree parm_lval = iter_parm;
    6150        16912 :           if (tree parm_default_ssa = get_ssa_default_def (fun, iter_parm))
    6151        15474 :             parm_lval = parm_default_ssa;
    6152        16912 :           const region *parm_reg = get_lvalue (parm_lval, ctxt);
    6153        16912 :           const svalue *arg_sval = (*arg_svals)[idx];
    6154        16912 :           set_value (parm_reg, arg_sval, ctxt);
    6155              :         }
    6156              : 
    6157              :       /* Handle any variadic args.  */
    6158        15294 :       unsigned va_arg_idx = 0;
    6159        15294 :       for (; idx < arg_svals->length (); idx++, va_arg_idx++)
    6160              :         {
    6161          476 :           const svalue *arg_sval = (*arg_svals)[idx];
    6162              :           /* Try to preserve the type of arg_sval in the store,
    6163              :              by wrapping it in an "unmergeable" decorator.  */
    6164          476 :           if (arg_sval->get_kind () == SK_CONSTANT)
    6165          278 :             arg_sval = m_mgr->get_or_create_unmergeable (arg_sval);
    6166          476 :           const region *var_arg_reg
    6167          476 :             = m_mgr->get_var_arg_region (m_current_frame,
    6168              :                                          va_arg_idx);
    6169          476 :           set_value (var_arg_reg, arg_sval, ctxt);
    6170              :         }
    6171              : 
    6172              :       /* If the result of the callee is DECL_BY_REFERENCE, then above
    6173              :          we should have determined the region within the
    6174              :          caller's frame that the callee will be writing back to.
    6175              :          Use this now to initialize the reference in callee's frame.  */
    6176        14818 :       if (tree result = DECL_RESULT (fndecl))
    6177        14818 :         if (DECL_BY_REFERENCE (result))
    6178              :           {
    6179              :             /* Get reference to the caller lhs.  */
    6180           55 :             gcc_assert (caller_return_by_reference_reg);
    6181           55 :             const svalue *ref_sval
    6182           55 :               = m_mgr->get_ptr_svalue (TREE_TYPE (result),
    6183              :                                        caller_return_by_reference_reg);
    6184              : 
    6185              :             /* Get region for default val of DECL_RESULT within the
    6186              :                callee.  */
    6187           55 :             if (tree result_default_ssa = get_ssa_default_def (fun, result))
    6188              :               {
    6189           52 :                 const region *callee_result_reg
    6190           52 :                   = get_lvalue (result_default_ssa, ctxt);
    6191              : 
    6192              :                 /* Set the callee's reference to refer to the caller's lhs.  */
    6193           52 :                 set_value (callee_result_reg, ref_sval, ctxt);
    6194              :               }
    6195              :           }
    6196              :     }
    6197              :   else
    6198              :     {
    6199              :       /* Otherwise we have a top-level call within the analysis.  The params
    6200              :          have defined but unknown initial values.
    6201              :          Anything they point to has escaped.  */
    6202              : 
    6203              :       /* Update m_current_frame.  */
    6204        26522 :       m_current_frame = m_mgr->get_frame_region (m_current_frame, fun);
    6205              : 
    6206              :       /* Handle "__attribute__((nonnull))".   */
    6207        26522 :       tree fntype = TREE_TYPE (fndecl);
    6208        26522 :       bitmap nonnull_args = get_nonnull_args (fntype);
    6209              : 
    6210        26522 :       unsigned parm_idx = 0;
    6211        50402 :       for (tree iter_parm = DECL_ARGUMENTS (fndecl); iter_parm;
    6212        23880 :            iter_parm = DECL_CHAIN (iter_parm))
    6213              :         {
    6214        23880 :           bool non_null = (nonnull_args
    6215        23880 :                            ? (bitmap_empty_p (nonnull_args)
    6216         1515 :                               || bitmap_bit_p (nonnull_args, parm_idx))
    6217        23880 :                            : false);
    6218        23880 :           if (tree parm_default_ssa = get_ssa_default_def (fun, iter_parm))
    6219        20411 :             on_top_level_param (parm_default_ssa, non_null, ctxt);
    6220              :           else
    6221         3469 :             on_top_level_param (iter_parm, non_null, ctxt);
    6222        23880 :           parm_idx++;
    6223              :         }
    6224              : 
    6225        26522 :       BITMAP_FREE (nonnull_args);
    6226              :     }
    6227              : 
    6228        41340 :   return m_current_frame;
    6229              : }
    6230              : 
    6231              : /* Get the function of the top-most frame in this region_model's stack.
    6232              :    There must be such a frame.  */
    6233              : 
    6234              : const function *
    6235         1213 : region_model::get_current_function () const
    6236              : {
    6237         1213 :   const frame_region *frame = get_current_frame ();
    6238         1213 :   gcc_assert (frame);
    6239         1213 :   return &frame->get_function ();
    6240              : }
    6241              : 
    6242              : /* Custom region_model_context for the assignment to the result
    6243              :    at a call statement when popping a frame (PR analyzer/106203).  */
    6244              : 
    6245              : class caller_context : public region_model_context_decorator
    6246              : {
    6247              : public:
    6248         5782 :   caller_context (region_model_context *inner,
    6249              :                   const gcall *call_stmt,
    6250              :                   const frame_region &caller_frame)
    6251              :     : region_model_context_decorator (inner),
    6252         5782 :       m_call_stmt (call_stmt),
    6253         5782 :       m_caller_frame (caller_frame)
    6254              :   {}
    6255              : 
    6256              :   pending_location
    6257            9 :   get_pending_location_for_diag () const override
    6258              :   {
    6259            9 :     pending_location ploc
    6260            9 :       = region_model_context_decorator::get_pending_location_for_diag ();
    6261              : 
    6262            9 :     ploc.m_event_loc_info
    6263            9 :       = event_loc_info (m_call_stmt->location,
    6264            9 :                         m_caller_frame.get_fndecl (),
    6265            9 :                         m_caller_frame.get_stack_depth ());
    6266              : 
    6267            9 :     return ploc;
    6268              :   }
    6269              : 
    6270        11573 :   const gimple *get_stmt () const override
    6271              :   {
    6272        11573 :     return m_call_stmt;
    6273              :   };
    6274              : 
    6275              : private:
    6276              :   const gcall *m_call_stmt;
    6277              :   const frame_region &m_caller_frame;
    6278              : };
    6279              : 
    6280              : 
    6281              : /* Pop the topmost frame_region from this region_model's stack;
    6282              : 
    6283              :    If RESULT_LVALUE is non-null, copy any return value from the frame
    6284              :    into the corresponding region (evaluated with respect to the *caller*
    6285              :    frame, rather than the called frame).
    6286              :    If OUT_RESULT is non-null, copy any return value from the frame
    6287              :    into *OUT_RESULT.
    6288              : 
    6289              :    If non-null, use CALL_STMT as the location when complaining about
    6290              :    assignment of the return value to RESULT_LVALUE.
    6291              : 
    6292              :    If EVAL_RETURN_SVALUE is false, then don't evaluate the return value.
    6293              :    This is for use when unwinding frames e.g. due to longjmp, to suppress
    6294              :    erroneously reporting uninitialized return values.
    6295              : 
    6296              :    Purge the frame region and all its descendent regions.
    6297              :    Convert any pointers that point into such regions into
    6298              :    poison_kind::popped_stack svalues.  */
    6299              : 
    6300              : void
    6301        30110 : region_model::pop_frame (tree result_lvalue,
    6302              :                          const svalue **out_result,
    6303              :                          region_model_context *ctxt,
    6304              :                          const gcall *call_stmt,
    6305              :                          bool eval_return_svalue)
    6306              : {
    6307        30110 :   gcc_assert (m_current_frame);
    6308              : 
    6309        30110 :   const region_model pre_popped_model = *this;
    6310        30110 :   const frame_region *frame_reg = m_current_frame;
    6311              : 
    6312              :   /* Notify state machines.  */
    6313        30110 :   if (ctxt)
    6314        27482 :     ctxt->on_pop_frame (frame_reg);
    6315              : 
    6316              :   /* Evaluate the result, within the callee frame.  */
    6317        30110 :   tree fndecl = m_current_frame->get_function ().decl;
    6318        30110 :   tree result = DECL_RESULT (fndecl);
    6319        30110 :   const svalue *retval = nullptr;
    6320        30110 :   if (result
    6321        30102 :       && TREE_TYPE (result) != void_type_node
    6322        43899 :       && eval_return_svalue)
    6323              :     {
    6324        11501 :       retval = get_rvalue (result, ctxt);
    6325        11501 :       if (out_result)
    6326         5318 :         *out_result = retval;
    6327              :     }
    6328              : 
    6329              :   /* Pop the frame.  */
    6330        30110 :   m_current_frame = m_current_frame->get_calling_frame ();
    6331              : 
    6332        30110 :   if (result_lvalue
    6333        30110 :       && retval
    6334              :       /* Don't write back for DECL_BY_REFERENCE; the writes
    6335              :          should have happened within the callee already.  */
    6336        30110 :       && !DECL_BY_REFERENCE (result))
    6337              :     {
    6338         5782 :       gcc_assert (eval_return_svalue);
    6339              : 
    6340              :       /* Compute result_dst_reg using RESULT_LVALUE *after* popping
    6341              :          the frame, but before poisoning pointers into the old frame.  */
    6342         5782 :       const region *result_dst_reg = get_lvalue (result_lvalue, ctxt);
    6343              : 
    6344              :       /* Assign retval to result_dst_reg, using caller_context
    6345              :          to set the call_stmt and the popped_frame for any diagnostics
    6346              :          due to the assignment.  */
    6347         5782 :       gcc_assert (m_current_frame);
    6348         5782 :       caller_context caller_ctxt (ctxt, call_stmt, *m_current_frame);
    6349        11564 :       set_value (result_dst_reg, retval, call_stmt ? &caller_ctxt : ctxt);
    6350              :     }
    6351              : 
    6352        30110 :   unbind_region_and_descendents (frame_reg,poison_kind::popped_stack);
    6353              : 
    6354        30110 :   if (auto chan = g->get_channels ().analyzer_events_channel.get_if_active ())
    6355              :     {
    6356          227 :       gcc::topics::analyzer_events::on_frame_popped msg
    6357          227 :         {this, &pre_popped_model, retval, ctxt};
    6358          227 :       chan->publish (msg);
    6359              :     }
    6360        30110 : }
    6361              : 
    6362              : /* Get the number of frames in this region_model's stack.  */
    6363              : 
    6364              : int
    6365      4985666 : region_model::get_stack_depth () const
    6366              : {
    6367      4985666 :   const frame_region *frame = get_current_frame ();
    6368      4985666 :   if (frame)
    6369      4967694 :     return frame->get_stack_depth ();
    6370              :   else
    6371              :     return 0;
    6372              : }
    6373              : 
    6374              : /* Get the frame_region with the given index within the stack.
    6375              :    The frame_region must exist.  */
    6376              : 
    6377              : const frame_region *
    6378      4694696 : region_model::get_frame_at_index (int index) const
    6379              : {
    6380      4694696 :   const frame_region *frame = get_current_frame ();
    6381      4694696 :   gcc_assert (frame);
    6382      4694696 :   gcc_assert (index >= 0);
    6383      4694696 :   gcc_assert (index <= frame->get_index ());
    6384      7347206 :   while (index != frame->get_index ())
    6385              :     {
    6386      2652510 :       frame = frame->get_calling_frame ();
    6387      2652510 :       gcc_assert (frame);
    6388              :     }
    6389      4694696 :   return frame;
    6390              : }
    6391              : 
    6392              : /* Unbind svalues for any regions in REG and below.
    6393              :    Find any pointers to such regions; convert them to
    6394              :    poisoned values of kind PKIND.
    6395              :    Also purge any dynamic extents.  */
    6396              : 
    6397              : void
    6398        41145 : region_model::unbind_region_and_descendents (const region *reg,
    6399              :                                              enum poison_kind pkind)
    6400              : {
    6401              :   /* Gather a set of base regions to be unbound.  */
    6402        41145 :   hash_set<const region *> base_regs;
    6403       198897 :   for (store::cluster_map_t::iterator iter = m_store.begin ();
    6404       198897 :        iter != m_store.end (); ++iter)
    6405              :     {
    6406       157752 :       const region *iter_base_reg = (*iter).first;
    6407       157752 :       if (iter_base_reg->descendent_of_p (reg))
    6408        31832 :         base_regs.add (iter_base_reg);
    6409              :     }
    6410        72977 :   for (hash_set<const region *>::iterator iter = base_regs.begin ();
    6411        72977 :        iter != base_regs.end (); ++iter)
    6412        31832 :     m_store.purge_cluster (*iter);
    6413              : 
    6414              :   /* Find any pointers to REG or its descendents; convert to poisoned.  */
    6415        41145 :   poison_any_pointers_to_descendents (reg, pkind);
    6416              : 
    6417              :   /* Purge dynamic extents of any base regions in REG and below
    6418              :      (e.g. VLAs and alloca stack regions).  */
    6419        97283 :   for (auto iter : m_dynamic_extents)
    6420              :     {
    6421        14993 :       const region *iter_reg = iter.first;
    6422        14993 :       if (iter_reg->descendent_of_p (reg))
    6423         6437 :         unset_dynamic_extents (iter_reg);
    6424              :     }
    6425        41145 : }
    6426              : 
    6427              : /* Find any pointers to REG or its descendents; convert them to
    6428              :    poisoned values of kind PKIND.  */
    6429              : 
    6430              : void
    6431        41145 : region_model::poison_any_pointers_to_descendents (const region *reg,
    6432              :                                                   enum poison_kind pkind)
    6433              : {
    6434       167065 :   for (const auto &cluster_iter : m_store)
    6435              :     {
    6436       125920 :       binding_cluster *cluster = cluster_iter.second;
    6437       125920 :       cluster->poison_any_pointers_to_descendents (reg, pkind);
    6438              :     }
    6439        41145 : }
    6440              : 
    6441              : /* Attempt to merge THIS with OTHER_MODEL, writing the result
    6442              :    to OUT_MODEL.  Use POINT to distinguish values created as a
    6443              :    result of merging.  */
    6444              : 
    6445              : bool
    6446        65300 : region_model::can_merge_with_p (const region_model &other_model,
    6447              :                                 const program_point &point,
    6448              :                                 region_model *out_model,
    6449              :                                 const extrinsic_state *ext_state,
    6450              :                                 const program_state *state_a,
    6451              :                                 const program_state *state_b) const
    6452              : {
    6453        65300 :   gcc_assert (out_model);
    6454        65300 :   gcc_assert (m_mgr == other_model.m_mgr);
    6455        65300 :   gcc_assert (m_mgr == out_model->m_mgr);
    6456              : 
    6457        65300 :   if (m_current_frame != other_model.m_current_frame)
    6458              :     return false;
    6459        65300 :   out_model->m_current_frame = m_current_frame;
    6460              : 
    6461        65300 :   model_merger m (this, &other_model, point, out_model,
    6462        65300 :                   ext_state, state_a, state_b);
    6463              : 
    6464        65300 :   if (!store::can_merge_p (&m_store, &other_model.m_store,
    6465              :                            &out_model->m_store,
    6466              :                            &m))
    6467              :     return false;
    6468              : 
    6469        47349 :   if (!m_dynamic_extents.can_merge_with_p (other_model.m_dynamic_extents,
    6470              :                                            &out_model->m_dynamic_extents))
    6471              :     return false;
    6472              : 
    6473              :   /* Merge constraints.  */
    6474        42252 :   constraint_manager::merge (*m_constraints,
    6475        42252 :                               *other_model.m_constraints,
    6476              :                               out_model->m_constraints);
    6477              : 
    6478        43133 :   for (auto iter : m.m_svals_changing_meaning)
    6479          881 :     out_model->m_constraints->purge_state_involving (*iter);
    6480              : 
    6481        42252 :   if (m_thrown_exceptions_stack != other_model.m_thrown_exceptions_stack)
    6482              :     return false;
    6483        38370 :   out_model->m_thrown_exceptions_stack = m_thrown_exceptions_stack;
    6484              : 
    6485        38370 :   if (m_caught_exceptions_stack != other_model.m_caught_exceptions_stack)
    6486              :     return false;
    6487        37653 :   out_model->m_caught_exceptions_stack = m_caught_exceptions_stack;
    6488              : 
    6489        37653 :   return true;
    6490        65300 : }
    6491              : 
    6492              : /* Recover the vtable OBJ's vptr (for OBJ_TYPE) actually points to, plus the
    6493              :    byte offset into it, so callers can recover the most-derived type from the
    6494              :    vtable's DECL_CONTEXT and BINFO.
    6495              : 
    6496              :    Only recognizes the shape we model for a vptr store, "vptr_field =
    6497              :    &vtable_decl + offset", i.e. a POINTER_PLUS_EXPR binop_svalue of a
    6498              :    region_svalue for the _ZTV* decl and a constant offset.  The offset is
    6499              :    nonzero when this vptr slot belongs to a non-primary base's own sub-vtable
    6500              :    group within the same decl; we return it via OUT for callers that need to
    6501              :    index into the vtable (e.g. gimple_get_virt_method_for_vtable).  */
    6502              : 
    6503              : tree
    6504         2130 : region_model::get_vtable_from_obj (tree obj, tree obj_type,
    6505              :                                    region_model_manager *mgr,
    6506              :                                    region_model_context *ctxt,
    6507              :                                    unsigned HOST_WIDE_INT *out) const
    6508              : {
    6509         2130 :   if (!obj_type)
    6510              :     return NULL_TREE;
    6511         2130 :   tree vfield = TYPE_VFIELD (obj_type);
    6512         2130 :   if (!vfield)
    6513              :     return NULL_TREE;
    6514              : 
    6515         2130 :   const svalue *obj_sval = get_rvalue (obj, ctxt);
    6516         2130 :   const region *obj_reg = deref_rvalue (obj_sval, obj, ctxt);
    6517         2130 :   const region *vptr_reg = mgr->get_field_region (obj_reg, vfield);
    6518              : 
    6519         2130 :   const svalue *vptr_sval = get_store_value (vptr_reg, ctxt);
    6520         2130 :   auto *sym_ptr = vptr_sval->maybe_get_symbolic_pointer ();
    6521         2130 :   if (!sym_ptr)
    6522              :     return NULL_TREE;
    6523          261 :   concrete_byte_offset conc_byte_offset;
    6524          261 :   if (!concrete_from_symbolic (sym_ptr->get_byte_offset (), &conc_byte_offset))
    6525              :     return NULL_TREE;
    6526          261 :   if (out)
    6527          261 :     *out = conc_byte_offset.get_integer ().as_unsigned_long ();
    6528          261 :   tree vtable = sym_ptr->get_base_region ().maybe_get_decl ();
    6529          261 :   return vtable;
    6530          261 : }
    6531              : 
    6532              : /* Attempt to get the fndecl for a virtual call via OBJ_TYPE_REF, or
    6533              :    NULL_TREE if it can't be resolved.
    6534              : 
    6535              :    A virtual call's callee is a GIMPLE OBJ_TYPE_REF:
    6536              :      OBJ_TYPE_REF(EXPR; (TYPE)OBJECT->TOKEN)
    6537              :    EXPR is the function pointer actually loaded and called; OBJECT, TYPE and
    6538              :    TOKEN are devirtualization metadata, not needed to perform the call itself.
    6539              :    OBJECT is the "this" pointer, TYPE its static type, TOKEN the vtable slot
    6540              :    index.  We ignore EXPR and instead resolve TOKEN against OBJECT's modeled
    6541              :    dynamic type rather than its static TYPE.
    6542              : 
    6543              :    Reads the value bound to the object's vptr field (OBJ_TYPE_REF_OBJECT's
    6544              :    vfield).
    6545              :    If that value has the form "&vtable_decl + constant" (a region_svalue for a
    6546              :    _ZTV* decl plus a byte offset), recover the vtable decl and offset and use
    6547              :    gimple_get_virt_method_for_vtable, together with OBJ_TYPE_REF_TOKEN, to look
    6548              :    up the concrete fndecl in the vtable's initializer.
    6549              : 
    6550              :    Relies on the store having bound the vptr field to the _ZTV* instance, so no
    6551              :    separate modeling of the object's dynamic type is needed.  */
    6552              : 
    6553              : tree
    6554         2031 : region_model::get_fndecl_for_virtual_call (const_tree obj_type_ref,
    6555              :                                            region_model_context *ctxt)
    6556              : {
    6557         2031 :   tree obj = OBJ_TYPE_REF_OBJECT (obj_type_ref);
    6558         2031 :   tree obj_type = obj_type_ref_class (obj_type_ref);
    6559              : 
    6560         2031 :   unsigned HOST_WIDE_INT offset;
    6561         2031 :   tree vtable = get_vtable_from_obj (obj, obj_type, m_mgr, ctxt, &offset);
    6562         2031 :   if (!vtable)
    6563              :     return NULL_TREE;
    6564              : 
    6565          165 :   unsigned HOST_WIDE_INT token
    6566          165 :     = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (obj_type_ref));
    6567          165 :   bool can_refer;
    6568          165 :   tree vptr_fn
    6569          165 :     = gimple_get_virt_method_for_vtable (token, vtable, offset, &can_refer);
    6570          165 :   if (!vptr_fn || !can_refer)
    6571              :     return NULL_TREE;
    6572              : 
    6573          165 :   if (cgraph_node *node = cgraph_node::get_create (vptr_fn))
    6574          165 :     if (const cgraph_node *ultimate = node->ultimate_alias_target ())
    6575          165 :       return ultimate->decl;
    6576              : 
    6577              :   return NULL_TREE;
    6578              : }
    6579              : 
    6580              : /* Attempt to get the fndecl used at CALL, if known, or NULL_TREE
    6581              :    otherwise.  */
    6582              : 
    6583              : tree
    6584       941623 : region_model::get_fndecl_for_call (const gcall &call,
    6585              :                                    region_model_context *ctxt)
    6586              : {
    6587       941623 :   tree fn_ptr = gimple_call_fn (&call);
    6588       941623 :   if (fn_ptr == NULL_TREE)
    6589              :     return NULL_TREE;
    6590              : 
    6591              :   /* Handle OBJ_TYPE_REF so that we can try to find the definition for a virtual
    6592              :      call and treat it like any other call.  */
    6593       897985 :   if (TREE_CODE (fn_ptr) == OBJ_TYPE_REF)
    6594         2031 :     return get_fndecl_for_virtual_call (fn_ptr, ctxt);
    6595              : 
    6596       895954 :   const svalue *fn_ptr_sval = get_rvalue (fn_ptr, ctxt);
    6597       895954 :   if (auto sym_ptr = fn_ptr_sval->maybe_get_symbolic_pointer ())
    6598       891546 :     if (sym_ptr->zero_offset_p ())
    6599              :       {
    6600       891546 :         const region &reg = sym_ptr->get_base_region ();
    6601       891546 :         if (const function_region *fn_reg = reg.dyn_cast_function_region ())
    6602              :           {
    6603       891490 :             tree fn_decl = fn_reg->get_fndecl ();
    6604       891490 :             cgraph_node *node = cgraph_node::get (fn_decl);
    6605       891490 :             if (!node)
    6606              :               return NULL_TREE;
    6607       891420 :             const cgraph_node *ultimate_node = node->ultimate_alias_target ();
    6608       891420 :             if (ultimate_node)
    6609       891420 :               return ultimate_node->decl;
    6610              :         }
    6611              :       }
    6612              : 
    6613              :   return NULL_TREE;
    6614              : }
    6615              : 
    6616              : /* Would be much simpler to use a lambda here, if it were supported.  */
    6617              : 
    6618              : struct append_regions_cb_data
    6619              : {
    6620              :   const region_model *model;
    6621              :   auto_vec<const decl_region *> *out;
    6622              : };
    6623              : 
    6624              : /* Populate *OUT with all decl_regions in the current
    6625              :    frame that have clusters within the store.  */
    6626              : 
    6627              : void
    6628       374044 : region_model::
    6629              : get_regions_for_current_frame (auto_vec<const decl_region *> *out) const
    6630              : {
    6631       374044 :   append_regions_cb_data data;
    6632       374044 :   data.model = this;
    6633       374044 :   data.out = out;
    6634       374044 :   m_store.for_each_cluster (append_regions_cb, &data);
    6635       374044 : }
    6636              : 
    6637              : /* Implementation detail of get_regions_for_current_frame.  */
    6638              : 
    6639              : void
    6640      1965078 : region_model::append_regions_cb (const cluster_region &cluster_reg,
    6641              :                                  append_regions_cb_data *cb_data)
    6642              : {
    6643      1965078 :   if (cluster_reg.get_parent_region () != cb_data->model->m_current_frame)
    6644              :     return;
    6645       934201 :   if (const decl_region *decl_reg = cluster_reg.dyn_cast_decl_region ())
    6646       915870 :     cb_data->out->safe_push (decl_reg);
    6647              : }
    6648              : 
    6649              : 
    6650              : /* Abstract class for diagnostics related to the use of
    6651              :    floating-point arithmetic where precision is needed.  */
    6652              : 
    6653           25 : class imprecise_floating_point_arithmetic : public pending_diagnostic
    6654              : {
    6655              : public:
    6656           50 :   int get_controlling_option () const final override
    6657              :   {
    6658           50 :     return OPT_Wanalyzer_imprecise_fp_arithmetic;
    6659              :   }
    6660              : };
    6661              : 
    6662              : /* Concrete diagnostic to complain about uses of floating-point arithmetic
    6663              :    in the size argument of malloc etc.  */
    6664              : 
    6665              : class float_as_size_arg : public imprecise_floating_point_arithmetic
    6666              : {
    6667              : public:
    6668           25 :   float_as_size_arg (tree arg) : m_arg (arg)
    6669              :   {}
    6670              : 
    6671          305 :   const char *get_kind () const final override
    6672              :   {
    6673          305 :     return "float_as_size_arg_diagnostic";
    6674              :   }
    6675              : 
    6676           25 :   bool subclass_equal_p (const pending_diagnostic &other) const final override
    6677              :   {
    6678           25 :     return same_tree_p (m_arg, ((const float_as_size_arg &) other).m_arg);
    6679              :   }
    6680              : 
    6681           25 :   bool emit (diagnostic_emission_context &ctxt) final override
    6682              :   {
    6683           25 :     bool warned = ctxt.warn ("use of floating-point arithmetic here might"
    6684              :                              " yield unexpected results");
    6685           25 :     if (warned)
    6686           25 :       inform (ctxt.get_location (),
    6687              :               "only use operands of an integer type"
    6688              :               " inside the size argument");
    6689           25 :     return warned;
    6690              :   }
    6691              : 
    6692              :   bool
    6693           50 :   describe_final_event (pretty_printer &pp,
    6694              :                         const evdesc::final_event &) final override
    6695              :   {
    6696           50 :     if (m_arg)
    6697           50 :       pp_printf (&pp,
    6698              :                  "operand %qE is of type %qT",
    6699           50 :                  m_arg, TREE_TYPE (m_arg));
    6700              :     else
    6701            0 :       pp_printf (&pp,
    6702              :                  "at least one operand of the size argument is"
    6703              :                  " of a floating-point type");
    6704           50 :     return true;
    6705              :   }
    6706              : 
    6707              : private:
    6708              :   tree m_arg;
    6709              : };
    6710              : 
    6711              : /* Visitor to find uses of floating-point variables/constants in an svalue.  */
    6712              : 
    6713              : class contains_floating_point_visitor : public visitor
    6714              : {
    6715              : public:
    6716         8035 :   contains_floating_point_visitor (const svalue *root_sval) : m_result (nullptr)
    6717              :   {
    6718         8035 :     root_sval->accept (this);
    6719              :   }
    6720              : 
    6721         8035 :   const svalue *get_svalue_to_report ()
    6722              :   {
    6723         8035 :     return m_result;
    6724              :   }
    6725              : 
    6726         7449 :   void visit_constant_svalue (const constant_svalue *sval) final override
    6727              :   {
    6728              :     /* At the point the analyzer runs, constant integer operands in a floating
    6729              :        point expression are already implicitly converted to floating-points.
    6730              :        Thus, we do prefer to report non-constants such that the diagnostic
    6731              :        always reports a floating-point operand.  */
    6732         7449 :     tree type = sval->get_type ();
    6733         7449 :     if (type && FLOAT_TYPE_P (type) && !m_result)
    6734            9 :       m_result = sval;
    6735         7449 :   }
    6736              : 
    6737          749 :   void visit_initial_svalue (const initial_svalue *sval) final override
    6738              :   {
    6739          749 :     tree type = sval->get_type ();
    6740          749 :     if (type && FLOAT_TYPE_P (type))
    6741           16 :       m_result = sval;
    6742          749 :   }
    6743              : 
    6744              : private:
    6745              :   /* Non-null if at least one floating-point operand was found.  */
    6746              :   const svalue *m_result;
    6747              : };
    6748              : 
    6749              : /* May complain about uses of floating-point operands in SIZE_IN_BYTES.  */
    6750              : 
    6751              : void
    6752         8035 : region_model::check_dynamic_size_for_floats (const svalue *size_in_bytes,
    6753              :                                              region_model_context *ctxt) const
    6754              : {
    6755         8035 :   gcc_assert (ctxt);
    6756              : 
    6757         8035 :   contains_floating_point_visitor v (size_in_bytes);
    6758         8035 :   if (const svalue *float_sval = v.get_svalue_to_report ())
    6759              :         {
    6760           25 :           tree diag_arg = get_representative_tree (float_sval);
    6761           25 :           ctxt->warn (std::make_unique<float_as_size_arg> (diag_arg));
    6762              :         }
    6763         8035 : }
    6764              : 
    6765              : /* Return a region describing a heap-allocated block of memory.
    6766              :    Use CTXT to complain about tainted sizes.
    6767              : 
    6768              :    Reuse an existing heap_allocated_region if it's not being referenced by
    6769              :    this region_model; otherwise create a new one.
    6770              : 
    6771              :    Optionally (update_state_machine) transitions the pointer pointing to the
    6772              :    heap_allocated_region from start to assumed non-null.  */
    6773              : 
    6774              : const region *
    6775        18916 : region_model::get_or_create_region_for_heap_alloc (const svalue *size_in_bytes,
    6776              :        region_model_context *ctxt,
    6777              :        bool update_state_machine,
    6778              :        const call_details *cd)
    6779              : {
    6780              :   /* Determine which regions are referenced in this region_model, so that
    6781              :      we can reuse an existing heap_allocated_region if it's not in use on
    6782              :      this path.  */
    6783        18916 :   auto_bitmap base_regs_in_use;
    6784        18916 :   get_referenced_base_regions (base_regs_in_use);
    6785              : 
    6786              :   /* Don't reuse regions that are marked as TOUCHED.  */
    6787        90907 :   for (store::cluster_map_t::iterator iter = m_store.begin ();
    6788        90907 :        iter != m_store.end (); ++iter)
    6789        71991 :     if ((*iter).second->touched_p ())
    6790              :       {
    6791         3271 :         const region *base_reg = (*iter).first;
    6792         3271 :         bitmap_set_bit (base_regs_in_use, base_reg->get_id ());
    6793              :       }
    6794              : 
    6795        18916 :   const region *reg
    6796        18916 :     = m_mgr->get_or_create_region_for_heap_alloc (base_regs_in_use);
    6797        18916 :   if (size_in_bytes)
    6798        13305 :     if (compat_types_p (size_in_bytes->get_type (), size_type_node))
    6799        13305 :       set_dynamic_extents (reg, size_in_bytes, ctxt);
    6800              : 
    6801        18916 :         if (update_state_machine && cd)
    6802              :                 {
    6803            0 :                   const svalue *ptr_sval
    6804            0 :                     = m_mgr->get_ptr_svalue (cd->get_lhs_type (), reg);
    6805            0 :                   transition_ptr_sval_non_null (ctxt, ptr_sval);
    6806              :                 }
    6807              : 
    6808        18916 :   return reg;
    6809        18916 : }
    6810              : 
    6811              : /* Populate OUT_IDS with the set of IDs of those base regions which are
    6812              :    reachable in this region_model.  */
    6813              : 
    6814              : void
    6815        19052 : region_model::get_referenced_base_regions (auto_bitmap &out_ids) const
    6816              : {
    6817        19052 :   reachable_regions reachable_regs (const_cast<region_model *> (this));
    6818        19052 :   m_store.for_each_cluster (reachable_regions::init_cluster_cb,
    6819              :                             &reachable_regs);
    6820              :   /* Get regions for locals that have explicitly bound values.  */
    6821        91457 :   for (store::cluster_map_t::iterator iter = m_store.begin ();
    6822        91457 :        iter != m_store.end (); ++iter)
    6823              :     {
    6824        72405 :       const region *base_reg = (*iter).first;
    6825        72405 :       if (const region *parent = base_reg->get_parent_region ())
    6826        72405 :         if (parent->get_kind () == RK_FRAME)
    6827        57452 :           reachable_regs.add (base_reg, false);
    6828              :     }
    6829              : 
    6830        19056 :   for (auto &eh_node : m_thrown_exceptions_stack)
    6831            4 :     eh_node.add_to_reachable_regions (reachable_regs);
    6832        19118 :   for (auto &eh_node : m_caught_exceptions_stack)
    6833           66 :     eh_node.add_to_reachable_regions (reachable_regs);
    6834              : 
    6835              : 
    6836        19052 :   bitmap_clear (out_ids);
    6837        95394 :   for (auto iter_reg : reachable_regs)
    6838        76342 :     bitmap_set_bit (out_ids, iter_reg->get_id ());
    6839        19052 : }
    6840              : 
    6841              : /* Return a new region describing a block of memory allocated within the
    6842              :    current frame.
    6843              :    Use CTXT to complain about tainted sizes.  */
    6844              : 
    6845              : const region *
    6846          535 : region_model::create_region_for_alloca (const svalue *size_in_bytes,
    6847              :                                         region_model_context *ctxt)
    6848              : {
    6849          535 :   const region *reg = m_mgr->create_region_for_alloca (m_current_frame);
    6850          535 :   if (compat_types_p (size_in_bytes->get_type (), size_type_node))
    6851          534 :     set_dynamic_extents (reg, size_in_bytes, ctxt);
    6852          535 :   return reg;
    6853              : }
    6854              : 
    6855              : /* Record that the size of REG is SIZE_IN_BYTES.
    6856              :    Use CTXT to complain about tainted sizes.  */
    6857              : 
    6858              : void
    6859        14304 : region_model::set_dynamic_extents (const region *reg,
    6860              :                                    const svalue *size_in_bytes,
    6861              :                                    region_model_context *ctxt)
    6862              : {
    6863        14304 :   assert_compat_types (size_in_bytes->get_type (), size_type_node);
    6864        14304 :   if (ctxt)
    6865              :     {
    6866         8035 :       check_dynamic_size_for_taint (reg->get_memory_space (), size_in_bytes,
    6867              :                                     ctxt);
    6868         8035 :       check_dynamic_size_for_floats (size_in_bytes, ctxt);
    6869              :     }
    6870        14304 :   m_dynamic_extents.put (reg, size_in_bytes);
    6871        14304 : }
    6872              : 
    6873              : /* Get the recording of REG in bytes, or nullptr if no dynamic size was
    6874              :    recorded.  */
    6875              : 
    6876              : const svalue *
    6877        91983 : region_model::get_dynamic_extents (const region *reg) const
    6878              : {
    6879        91983 :   if (const svalue * const *slot = m_dynamic_extents.get (reg))
    6880        15231 :     return *slot;
    6881              :   return nullptr;
    6882              : }
    6883              : 
    6884              : /* Unset any recorded dynamic size of REG.  */
    6885              : 
    6886              : void
    6887        49761 : region_model::unset_dynamic_extents (const region *reg)
    6888              : {
    6889        49761 :   m_dynamic_extents.remove (reg);
    6890        49761 : }
    6891              : 
    6892              : /* Visitor that counts the number of uninitialized bites seen
    6893              :    in bit_vectors.  */
    6894              : 
    6895           25 : struct uninit_bit_counter : public symbolic::node_visitor
    6896              : {
    6897           25 :   uninit_bit_counter (symbolic::scalar_manager<concrete_bit_size> &mgr)
    6898           25 :   : m_num_uninit_bits (&mgr.get_concrete (0_bits))
    6899              :   {
    6900           25 :   }
    6901              : 
    6902              :   bool
    6903           78 :   visit_svalue (const svalue &sval) final override
    6904              :   {
    6905           78 :     return symbolic::node_visitor::visit_svalue (sval);
    6906              :   }
    6907              : 
    6908              :   bool
    6909           94 :   visit_bit_vector (const symbolic::bit_vector &bv) final override
    6910              :   {
    6911           94 :     if (!symbolic::node_visitor::visit_bit_vector (bv))
    6912              :       return false;
    6913           94 :     if (auto *p = bv.dyn_cast_poisoned_bit_vector ())
    6914           28 :       if (p->get_poison_kind () == poison_kind::uninit)
    6915           28 :         m_num_uninit_bits = &(*m_num_uninit_bits + bv.get_size ());
    6916              :     return true;
    6917              :   }
    6918              : 
    6919              :   const symbolic_bit_size *m_num_uninit_bits;
    6920              : };
    6921              : 
    6922              : /* A subclass of pending_diagnostic for complaining about uninitialized data
    6923              :    being copied across a trust boundary to an untrusted output
    6924              :    (e.g. copy_to_user infoleaks in the Linux kernel).  */
    6925              : 
    6926              : class exposure_through_uninit_copy
    6927              :   : public pending_diagnostic_subclass<exposure_through_uninit_copy>
    6928              : {
    6929              : public:
    6930           26 :   exposure_through_uninit_copy (const region *src_region,
    6931              :                                 const region *dest_region,
    6932              :                                 const svalue *copied_sval,
    6933              :                                 symbolic::node_manager &node_mgr)
    6934           26 :   : m_src_region (src_region),
    6935           26 :     m_dest_region (dest_region),
    6936           26 :     m_copied_sval (copied_sval),
    6937           26 :     m_node_mgr (node_mgr)
    6938              :   {
    6939              :   }
    6940              : 
    6941          294 :   const char *get_kind () const final override
    6942              :   {
    6943          294 :     return "exposure_through_uninit_copy";
    6944              :   }
    6945              : 
    6946           26 :   bool operator== (const exposure_through_uninit_copy &other) const
    6947              :   {
    6948           26 :     return (m_src_region == other.m_src_region
    6949           26 :             && m_dest_region == other.m_dest_region
    6950           52 :             && m_copied_sval == other.m_copied_sval);
    6951              :   }
    6952              : 
    6953           51 :   int get_controlling_option () const final override
    6954              :   {
    6955           51 :     return OPT_Wanalyzer_exposure_through_uninit_copy;
    6956              :   }
    6957              : 
    6958           25 :   bool emit (diagnostic_emission_context &ctxt) final override
    6959              :   {
    6960              :     /* CWE-200: Exposure of Sensitive Information to an Unauthorized Actor.  */
    6961           25 :     ctxt.add_cwe (200);
    6962           51 :     memory_space mem_space = get_src_memory_space ();
    6963           25 :     bool warned;
    6964           25 :     switch (mem_space)
    6965              :       {
    6966            1 :       default:
    6967            1 :         warned = ctxt.warn ("potential exposure of sensitive information"
    6968              :                             " by copying uninitialized data"
    6969              :                             " across trust boundary");
    6970            1 :         break;
    6971           24 :       case memory_space::stack:
    6972           24 :         warned = ctxt.warn ("potential exposure of sensitive information"
    6973              :                             " by copying uninitialized data from stack"
    6974              :                             " across trust boundary");
    6975           24 :         break;
    6976            0 :       case memory_space::heap:
    6977            0 :         warned = ctxt.warn ("potential exposure of sensitive information"
    6978              :                             " by copying uninitialized data from heap"
    6979              :                             " across trust boundary");
    6980            0 :         break;
    6981              :       }
    6982           25 :     if (warned)
    6983              :       {
    6984           25 :         const location_t loc = ctxt.get_location ();
    6985           25 :         inform_number_of_uninit_bits (loc);
    6986           25 :         complain_about_uninit_ranges (loc);
    6987              : 
    6988           25 :         if (mem_space == memory_space::stack)
    6989           24 :           maybe_emit_fixit_hint ();
    6990              :       }
    6991           25 :     return warned;
    6992              :   }
    6993              : 
    6994              :   bool
    6995           50 :   describe_final_event (pretty_printer &pp,
    6996              :                         const evdesc::final_event &) final override
    6997              :   {
    6998          102 :     memory_space mem_space = get_src_memory_space ();
    6999           50 :     switch (mem_space)
    7000              :       {
    7001            2 :       default:
    7002            2 :         pp_string (&pp, "uninitialized data copied here");
    7003            2 :         return true;
    7004              : 
    7005           48 :       case memory_space::stack:
    7006           48 :         pp_string (&pp, "uninitialized data copied from stack here");
    7007           48 :         return true;
    7008              : 
    7009            0 :       case memory_space::heap:
    7010            0 :         pp_string (&pp, "uninitialized data copied from heap here");
    7011            0 :         return true;
    7012              :       }
    7013              :   }
    7014              : 
    7015           50 :   void mark_interesting_stuff (interesting_t *interest) final override
    7016              :   {
    7017           50 :     if (m_src_region)
    7018           50 :       interest->add_region_creation (m_src_region);
    7019           50 :   }
    7020              : 
    7021              :   void
    7022            0 :   maybe_add_sarif_properties (diagnostics::sarif_object &result_obj)
    7023              :     const final override
    7024              :   {
    7025            0 :     auto &props = result_obj.get_or_create_properties ();
    7026              : #define PROPERTY_PREFIX "gcc/-Wanalyzer-exposure-through-uninit-copy/"
    7027            0 :     props.set (PROPERTY_PREFIX "src_region", m_src_region->to_json ());
    7028            0 :     props.set (PROPERTY_PREFIX "dest_region", m_dest_region->to_json ());
    7029            0 :     props.set (PROPERTY_PREFIX "copied_sval", m_copied_sval->to_json ());
    7030              : #undef PROPERTY_PREFIX
    7031            0 :   }
    7032              : 
    7033              : private:
    7034              :   memory_space
    7035           75 :   get_src_memory_space () const
    7036              :   {
    7037           75 :     return (m_src_region
    7038           75 :             ? m_src_region->get_memory_space ()
    7039              :             : memory_space::unknown);
    7040              :   }
    7041              : 
    7042              :   const symbolic_bit_size &
    7043           25 :   calc_num_uninit_bits () const
    7044              :   {
    7045           25 :     auto &bit_mgr = m_node_mgr.get_scalars ().get_bits ();
    7046           25 :     uninit_bit_counter v (bit_mgr);
    7047           25 :     m_copied_sval->accept_node_visitor (v);
    7048           25 :     return *v.m_num_uninit_bits;
    7049           25 :   }
    7050              : 
    7051           25 :   void inform_number_of_uninit_bits (location_t loc) const
    7052              :   {
    7053           25 :     auto &num_uninit_bits = calc_num_uninit_bits ();
    7054           25 :     concrete_bit_size conc_num_uninit_bits;
    7055           25 :     if (!concrete_from_symbolic (num_uninit_bits, &conc_num_uninit_bits))
    7056            0 :       return;
    7057           25 :     concrete_byte_size conc_num_uninit_bytes;
    7058           25 :     if (maybe_bytes_from_bits (conc_num_uninit_bits, &conc_num_uninit_bytes))
    7059              :       {
    7060              :         /* Express in bytes.  */
    7061           25 :         if (conc_num_uninit_bytes == 1_byte)
    7062            3 :           inform (loc, "1 byte is uninitialized");
    7063              :         else
    7064              :           {
    7065           22 :             pp_element_integer e_num_bytes
    7066           22 :               (conc_num_uninit_bytes.get_integer ());
    7067           22 :             inform (loc,
    7068              :                     "%e bytes are uninitialized", &e_num_bytes);
    7069           22 :           }
    7070              :       }
    7071              :     else
    7072              :       {
    7073              :         /* Express in bits.  */
    7074            0 :         if (conc_num_uninit_bits == 1_bit)
    7075            0 :           inform (loc, "1 bit is uninitialized");
    7076              :         else
    7077              :           {
    7078            0 :             pp_element_integer e_num_bits
    7079            0 :               (conc_num_uninit_bits.get_integer ());
    7080            0 :             inform (loc,
    7081              :                     "%e bits are uninitialized", &e_num_bits);
    7082            0 :           }
    7083              :       }
    7084           25 :   }
    7085              : 
    7086              :   bool
    7087           25 :   get_uninit_ranges (std::vector<concrete_bit_range> *out) const
    7088              :   {
    7089           25 :     auto *sval_from_bv = m_copied_sval->dyn_cast_svalue_from_bit_vector ();
    7090           25 :     if (!sval_from_bv)
    7091              :       return false;
    7092           25 :     auto &bv = sval_from_bv->get_bit_vector ();
    7093              :     /* Find keys for uninit svals.  */
    7094           25 :     if (auto *p = bv.dyn_cast_poisoned_bit_vector ())
    7095              :       {
    7096            4 :         if (p->get_poison_kind () == poison_kind::uninit)
    7097              :           {
    7098            4 :             concrete_bit_size bit_size;
    7099            4 :             if (!concrete_from_symbolic (p->get_size (), &bit_size))
    7100              :               return false;
    7101           12 :             out->push_back (concrete_bit_range (0_bits, bit_size));
    7102            4 :             return true;
    7103            4 :           }
    7104              :       }
    7105           21 :     else if (auto *concat = bv.dyn_cast_concat_bit_vector ())
    7106              :       {
    7107           20 :         concrete_bit_offset start_offset (0_bits);
    7108           73 :         for (auto iter : *concat)
    7109              :           {
    7110           53 :             concrete_bit_size bit_size;
    7111           53 :             if (!concrete_from_symbolic (iter->get_size (), &bit_size))
    7112            0 :               return false;
    7113           53 :             if (auto *p = iter->dyn_cast_poisoned_bit_vector ())
    7114           23 :               if (p->get_poison_kind () == poison_kind::uninit)
    7115           69 :                 out->push_back (concrete_bit_range (start_offset, bit_size));
    7116           53 :             start_offset += bit_size;
    7117           53 :           }
    7118              :         return true;
    7119           20 :       }
    7120              :     return false;
    7121              :   }
    7122              : 
    7123           25 :   void complain_about_uninit_ranges (location_t loc) const
    7124              :   {
    7125           25 :     std::vector<concrete_bit_range> uninit_bit_ranges;
    7126           25 :     if (!get_uninit_ranges (&uninit_bit_ranges))
    7127            1 :       return;
    7128              : 
    7129           24 :     std::unique_ptr<record_layout> layout;
    7130              : 
    7131           24 :     tree type = m_copied_sval->get_type ();
    7132           24 :     if (type && TREE_CODE (type) == RECORD_TYPE)
    7133              :       {
    7134           19 :         layout = std::make_unique<record_layout> (type);
    7135              : 
    7136           19 :         if (0)
    7137              :           layout->dump ();
    7138              :       }
    7139              : 
    7140           51 :     for (auto &bits : uninit_bit_ranges)
    7141              :       {
    7142           27 :         concrete_bit_offset start_bit = bits.get_start_offset ();
    7143           27 :         concrete_bit_offset next_bit = bits.get_next_offset ();
    7144           27 :         complain_about_uninit_range (loc, start_bit, next_bit,
    7145           27 :                                      layout.get ());
    7146           27 :       }
    7147           25 :   }
    7148              : 
    7149           27 :   void complain_about_uninit_range (location_t loc,
    7150              :                                     concrete_bit_offset start_bit,
    7151              :                                     concrete_bit_offset next_bit,
    7152              :                                     const record_layout *layout) const
    7153              :   {
    7154           27 :     if (layout)
    7155              :       {
    7156           79 :         while (start_bit < next_bit)
    7157              :           {
    7158          171 :             if (const record_layout::item *item
    7159           57 :                   = layout->get_item_at (start_bit))
    7160              :               {
    7161           57 :                 gcc_assert (start_bit >= item->get_start_offset ());
    7162           57 :                 gcc_assert (start_bit < item->get_next_offset ());
    7163           57 :                 if (item->get_start_offset () == start_bit
    7164          167 :                     && item->get_next_offset () <= next_bit)
    7165           55 :                   complain_about_fully_uninit_item (*item);
    7166              :                 else
    7167            2 :                   complain_about_partially_uninit_item (*item);
    7168           57 :                 start_bit = item->get_next_offset ();
    7169           57 :                 continue;
    7170              :               }
    7171              :             else
    7172              :               break;
    7173              :           }
    7174              :       }
    7175              : 
    7176           27 :     if (start_bit >= next_bit)
    7177           22 :       return;
    7178              : 
    7179            5 :     concrete_byte_offset start_byte;
    7180            5 :     concrete_byte_offset next_byte;
    7181           10 :     if (maybe_bytes_from_bits (start_bit, &start_byte)
    7182           20 :         && maybe_bytes_from_bits (next_bit, &next_byte))
    7183              :       {
    7184              :         /* Express in bytes.  */
    7185            5 :         concrete_byte_offset last_byte = next_byte - 1_byte;
    7186            5 :         pp_element_integer e_start_byte (start_byte.get_integer ());
    7187            5 :         pp_element_integer e_last_byte (last_byte.get_integer ());
    7188            5 :         if (last_byte == start_byte)
    7189            1 :           inform (loc,
    7190              :                   "byte %e is uninitialized",
    7191              :                   &e_start_byte);
    7192              :         else
    7193            4 :           inform (loc,
    7194              :                   "bytes %e - %e are uninitialized",
    7195              :                   &e_start_byte, &e_last_byte);
    7196            5 :       }
    7197              :     else
    7198              :       {
    7199              :         /* Express in bits.  */
    7200            0 :         concrete_bit_offset last_bit = next_bit - 1_bit;
    7201            0 :         pp_element_integer e_start_bit (start_bit.get_integer ());
    7202            0 :         pp_element_integer e_last_bit (last_bit.get_integer ());
    7203            0 :         if (last_bit == start_bit)
    7204            0 :           inform (loc,
    7205              :                   "bit %e is uninitialized",
    7206              :                   &e_start_bit);
    7207              :         else
    7208            0 :           inform (loc,
    7209              :                   "bits %e - %e are uninitialized",
    7210              :                   &e_start_bit, &e_last_bit);
    7211            0 :       }
    7212            5 :   }
    7213              : 
    7214              :   static void
    7215           55 :   complain_about_fully_uninit_item (const record_layout::item &item)
    7216              :   {
    7217           55 :     const_tree field = item.m_field;
    7218           55 :     concrete_bit_size num_bits = item.m_bit_range.get_size ();
    7219           55 :     if (item.m_is_padding)
    7220              :       {
    7221           10 :         concrete_byte_size num_bytes;
    7222           10 :         if (maybe_bytes_from_bits (num_bits, &num_bytes))
    7223              :           {
    7224              :             /* Express in bytes.  */
    7225            8 :             if (num_bytes == 1_byte)
    7226            2 :               inform (DECL_SOURCE_LOCATION (field),
    7227              :                       "padding after field %qD is uninitialized (1 byte)",
    7228              :                       field);
    7229              :             else
    7230              :               {
    7231            6 :                 pp_element_integer e_num_bytes (num_bytes.get_integer ());
    7232            6 :                 inform (DECL_SOURCE_LOCATION (field),
    7233              :                         "padding after field %qD is uninitialized (%e bytes)",
    7234              :                         field, &e_num_bytes);
    7235            6 :               }
    7236              :           }
    7237              :         else
    7238              :           {
    7239              :             /* Express in bits.  */
    7240            2 :             if (num_bits == 1_bit)
    7241            0 :               inform (DECL_SOURCE_LOCATION (field),
    7242              :                       "padding after field %qD is uninitialized (1 bit)",
    7243              :                       field);
    7244              :             else
    7245              :               {
    7246            2 :                 pp_element_integer e_num_bits (num_bits.get_integer ());
    7247            2 :                 inform (DECL_SOURCE_LOCATION (field),
    7248              :                         "padding after field %qD is uninitialized (%e bits)",
    7249              :                         field, &e_num_bits);
    7250            2 :               }
    7251              :           }
    7252           10 :       }
    7253              :     else
    7254              :       {
    7255           45 :         concrete_byte_size num_bytes;
    7256           45 :         if (maybe_bytes_from_bits (num_bits, &num_bytes))
    7257              :           {
    7258              :             /* Express in bytes.  */
    7259           35 :             if (num_bytes == 1_byte)
    7260            1 :               inform (DECL_SOURCE_LOCATION (field),
    7261              :                       "field %qD is uninitialized (1 byte)", field);
    7262              :             else
    7263              :               {
    7264           34 :                 pp_element_integer e_num_bytes (num_bytes.get_integer ());
    7265           34 :                 inform (DECL_SOURCE_LOCATION (field),
    7266              :                         "field %qD is uninitialized (%e bytes)",
    7267              :                         field, &e_num_bytes);
    7268           34 :               }
    7269              :           }
    7270              :         else
    7271              :           {
    7272              :             /* Express in bits.  */
    7273           10 :             if (num_bits == 1_bit)
    7274            9 :               inform (DECL_SOURCE_LOCATION (field),
    7275              :                       "field %qD is uninitialized (1 bit)", field);
    7276              :             else
    7277              :               {
    7278            1 :                 pp_element_integer e_num_bits (num_bits.get_integer ());
    7279            1 :                 inform (DECL_SOURCE_LOCATION (field),
    7280              :                         "field %qD is uninitialized (%e bits)",
    7281              :                         field, &e_num_bits);
    7282            1 :               }
    7283              :           }
    7284           45 :       }
    7285           55 :   }
    7286              : 
    7287              :   static void
    7288            2 :   complain_about_partially_uninit_item (const record_layout::item &item)
    7289              :   {
    7290            2 :     const_tree field = item.m_field;
    7291            2 :     if (item.m_is_padding)
    7292            0 :       inform (DECL_SOURCE_LOCATION (field),
    7293              :               "padding after field %qD is partially uninitialized",
    7294              :               field);
    7295              :     else
    7296            2 :       inform (DECL_SOURCE_LOCATION (field),
    7297              :               "field %qD is partially uninitialized",
    7298              :               field);
    7299              :     /* TODO: ideally we'd describe what parts are uninitialized.  */
    7300            2 :   }
    7301              : 
    7302           24 :   void maybe_emit_fixit_hint () const
    7303              :   {
    7304           24 :     if (tree decl = m_src_region->maybe_get_decl ())
    7305              :       {
    7306           24 :         gcc_rich_location hint_richloc (DECL_SOURCE_LOCATION (decl));
    7307           24 :         hint_richloc.add_fixit_insert_after (" = {0}");
    7308           24 :         inform (&hint_richloc,
    7309              :                 "suggest forcing zero-initialization by"
    7310              :                 " providing a %<{0}%> initializer");
    7311           24 :       }
    7312           24 :   }
    7313              : 
    7314              : private:
    7315              :   const region *m_src_region;
    7316              :   const region *m_dest_region;
    7317              :   const svalue *m_copied_sval;
    7318              :   symbolic::node_manager &m_node_mgr;
    7319              : };
    7320              : 
    7321              : /* Return true if any part of SVAL is uninitialized.  */
    7322              : 
    7323              : static bool
    7324           78 : contains_uninit_p (const svalue *sval)
    7325              : {
    7326           78 :   poison_finder v;
    7327           78 :   sval->accept_node_visitor (v);
    7328           78 :   if (!v.m_found_poison)
    7329              :     return false;
    7330           26 :   return v.m_pkind == poison_kind::uninit;
    7331           78 : }
    7332              : 
    7333              : /* Function for use by plugins when simulating writing data through a
    7334              :    pointer to an "untrusted" region DST_REG (and thus crossing a security
    7335              :    boundary), such as copying data to user space in an OS kernel.
    7336              : 
    7337              :    Check that COPIED_SVAL is fully initialized.  If not, complain about
    7338              :    an infoleak to CTXT.
    7339              : 
    7340              :    SRC_REG can be nullptr; if non-NULL it is used as a hint in the diagnostic
    7341              :    as to where COPIED_SVAL came from.  */
    7342              : 
    7343              : void
    7344           78 : region_model::maybe_complain_about_infoleak (const region *dst_reg,
    7345              :                                              const svalue *copied_sval,
    7346              :                                              const region *src_reg,
    7347              :                                              region_model_context *ctxt)
    7348              : {
    7349              :   /* Check for exposure.  */
    7350           78 :   if (contains_uninit_p (copied_sval))
    7351              :     {
    7352           26 :       auto &node_mgr = get_manager ()->get_node_manager ();
    7353           26 :       ctxt->warn
    7354           26 :         (std::make_unique<exposure_through_uninit_copy> (src_reg,
    7355              :                                                          dst_reg,
    7356              :                                                          copied_sval,
    7357              :                                                          node_mgr));
    7358              :     }
    7359           78 : }
    7360              : 
    7361              : /* Set errno to a positive symbolic int, as if some error has occurred.  */
    7362              : 
    7363              : void
    7364          451 : region_model::set_errno (const call_details &cd)
    7365              : {
    7366          451 :   const region *errno_reg = m_mgr->get_errno_region ();
    7367          451 :   conjured_purge p (this, cd.get_ctxt ());
    7368          451 :   const svalue *new_errno_sval
    7369          451 :     = m_mgr->get_or_create_conjured_svalue (integer_type_node,
    7370          451 :                                             &cd.get_call_stmt (),
    7371              :                                             errno_reg, p);
    7372          451 :   const svalue *zero
    7373          451 :     = m_mgr->get_or_create_int_cst (integer_type_node, 0);
    7374          451 :   add_constraint (new_errno_sval, GT_EXPR, zero, cd.get_ctxt ());
    7375          451 :   set_value (errno_reg, new_errno_sval, cd.get_ctxt ());
    7376          451 : }
    7377              : 
    7378              : // class region_model_context
    7379              : 
    7380              : bool
    7381         4149 : region_model_context::
    7382              : warn (std::unique_ptr<pending_diagnostic> d,
    7383              :       std::unique_ptr<pending_location::fixer_for_epath> ploc_fixer)
    7384              : {
    7385         4149 :   pending_location ploc (get_pending_location_for_diag ());
    7386         4149 :   ploc.m_fixer_for_epath = std::move (ploc_fixer);
    7387         4149 :   return warn_at (std::move (d), std::move (ploc));
    7388         4149 : }
    7389              : 
    7390              : /* class noop_region_model_context : public region_model_context.  */
    7391              : 
    7392              : void
    7393            0 : noop_region_model_context::add_note (std::unique_ptr<pending_note>)
    7394              : {
    7395            0 : }
    7396              : 
    7397              : void
    7398            0 : noop_region_model_context::add_event (std::unique_ptr<checker_event>)
    7399              : {
    7400            0 : }
    7401              : 
    7402              : void
    7403           75 : noop_region_model_context::bifurcate (std::unique_ptr<custom_edge_info>)
    7404              : {
    7405           75 : }
    7406              : 
    7407              : void
    7408            0 : noop_region_model_context::terminate_path ()
    7409              : {
    7410            0 : }
    7411              : 
    7412              : /* class region_model_context_decorator : public region_model_context.  */
    7413              : 
    7414              : void
    7415          195 : region_model_context_decorator::add_event (std::unique_ptr<checker_event> event)
    7416              : {
    7417          195 :   if (m_inner)
    7418          195 :     m_inner->add_event (std::move (event));
    7419          195 : }
    7420              : 
    7421              : /* struct model_merger.  */
    7422              : 
    7423              : /* Return true if it's OK to merge SVAL with other svalues.  */
    7424              : 
    7425              : bool
    7426       159525 : model_merger::mergeable_svalue_p (const svalue *sval) const
    7427              : {
    7428       159525 :   if (m_ext_state)
    7429              :     {
    7430              :       /* Reject merging svalues that have non-purgeable sm-state,
    7431              :          to avoid falsely reporting memory leaks by merging them
    7432              :          with something else.  For example, given a local var "p",
    7433              :          reject the merger of a:
    7434              :            store_a mapping "p" to a malloc-ed ptr
    7435              :          with:
    7436              :            store_b mapping "p" to a NULL ptr.  */
    7437       159437 :       if (m_state_a)
    7438       159437 :         if (!m_state_a->can_purge_p (*m_ext_state, sval))
    7439              :           return false;
    7440       157706 :       if (m_state_b)
    7441       157706 :         if (!m_state_b->can_purge_p (*m_ext_state, sval))
    7442              :           return false;
    7443              :     }
    7444              :   return true;
    7445              : }
    7446              : 
    7447              : /* Return true if it's OK to merge BV with other bit vectors.  */
    7448              : 
    7449              : bool
    7450       128908 : model_merger::mergeable_bit_vector_p (const symbolic::bit_vector &bv) const
    7451              : {
    7452       128908 :   if (auto *from_sval = bv.dyn_cast_bit_vector_from_svalue ())
    7453        59117 :     return mergeable_svalue_p (&from_sval->get_svalue ());
    7454              : 
    7455              :   return true;
    7456              : }
    7457              : 
    7458              : /* Mark WIDENING_SVAL as changing meaning during the merge.  */
    7459              : 
    7460              : void
    7461          966 : model_merger::on_widening_reuse (const widening_svalue *widening_sval)
    7462              : {
    7463          966 :   m_svals_changing_meaning.add (widening_sval);
    7464          966 : }
    7465              : 
    7466              : } // namespace ana
    7467              : 
    7468              : // class rejected_constraint
    7469              : 
    7470              : std::unique_ptr<json::object>
    7471            0 : rejected_constraint::make_base_json (const char *kind) const
    7472              : {
    7473            0 :   auto obj = std::make_unique<json::object> ();
    7474            0 :   obj->set_string ("kind", kind);
    7475            0 :   obj->set<json::object> ("region_model", m_model.to_json ());
    7476            0 :   return obj;
    7477              : }
    7478              : 
    7479              : /* class rejected_op_constraint : public rejected_constraint.  */
    7480              : 
    7481              : void
    7482            0 : rejected_op_constraint::dump_to_pp (pretty_printer *pp) const
    7483              : {
    7484            0 :   region_model m (m_model);
    7485            0 :   m_lhs->dump_to_pp (pp, true);
    7486            0 :   pp_printf (pp, " %s ", op_symbol_code (m_op));
    7487            0 :   m_rhs->dump_to_pp (pp, true);
    7488            0 : }
    7489              : 
    7490              : std::unique_ptr<json::object>
    7491            0 : rejected_op_constraint::to_json () const
    7492              : {
    7493            0 :   auto obj = rejected_constraint::make_base_json ("rejected_op_constraint");
    7494            0 :   obj->set<json::value> ("lhs", m_lhs->to_json ());
    7495            0 :   obj->set_string ("op", op_symbol_code (m_op));
    7496            0 :   obj->set<json::value> ("rhs", m_rhs->to_json ());
    7497            0 :   return obj;
    7498              : }
    7499              : 
    7500              : /* class rejected_default_case : public rejected_constraint.  */
    7501              : 
    7502              : void
    7503            0 : rejected_default_case::dump_to_pp (pretty_printer *pp) const
    7504              : {
    7505            0 :   pp_string (pp, "implicit default for enum");
    7506            0 : }
    7507              : 
    7508              : std::unique_ptr<json::object>
    7509            0 : rejected_default_case::to_json () const
    7510              : {
    7511            0 :   return rejected_constraint::make_base_json ("rejected_default_case");
    7512              : }
    7513              : 
    7514              : /* class rejected_ranges_constraint : public rejected_constraint.  */
    7515              : 
    7516              : void
    7517            0 : rejected_ranges_constraint::dump_to_pp (pretty_printer *pp) const
    7518              : {
    7519            0 :   region_model m (m_model);
    7520            0 :   const svalue *sval = m.get_rvalue (m_expr, nullptr);
    7521            0 :   sval->dump_to_pp (pp, true);
    7522            0 :   pp_string (pp, " in ");
    7523            0 :   m_ranges->dump_to_pp (pp, true);
    7524            0 : }
    7525              : 
    7526              : std::unique_ptr<json::object>
    7527            0 : rejected_ranges_constraint::to_json () const
    7528              : {
    7529            0 :   auto obj = rejected_constraint::make_base_json ("rejected_ranges_constraint");
    7530            0 :   if (m_expr)
    7531            0 :     obj->set ("expr", tree_to_json (m_expr));
    7532            0 :   obj->set<json::value> ("ranges", m_ranges->to_json ());
    7533            0 :   return obj;
    7534              : }
    7535              : 
    7536              : /* class engine.  */
    7537              : 
    7538              : /* engine's ctor.  */
    7539              : 
    7540         3679 : engine::engine (symbolic::node_manager &node_mgr,
    7541              :                 const supergraph *sg)
    7542         3679 : : m_node_mgr (node_mgr),
    7543         3679 :   m_sg (sg)
    7544              : {
    7545         3679 : }
    7546              : 
    7547              : /* Dump the managed objects by class to LOGGER, and the per-class totals.  */
    7548              : 
    7549              : void
    7550            5 : engine::log_stats (logger *logger) const
    7551              : {
    7552            5 :   m_node_mgr.log_stats (logger, true);
    7553            5 : }
    7554              : 
    7555              : namespace ana {
    7556              : 
    7557              : #if CHECKING_P
    7558              : 
    7559              : namespace selftest {
    7560              : 
    7561              : /* Build a constant tree of the given type from STR.  */
    7562              : 
    7563              : static tree
    7564           64 : build_real_cst_from_string (tree type, const char *str)
    7565              : {
    7566           64 :   REAL_VALUE_TYPE real;
    7567           64 :   real_from_string (&real, str);
    7568           64 :   return build_real (type, real);
    7569              : }
    7570              : 
    7571              : /* Append various "interesting" constants to OUT (e.g. NaN).  */
    7572              : 
    7573              : static void
    7574            8 : append_interesting_constants (auto_vec<tree> *out)
    7575              : {
    7576            8 :   out->safe_push (integer_zero_node);
    7577            8 :   out->safe_push (build_int_cst (integer_type_node, 42));
    7578            8 :   out->safe_push (build_int_cst (unsigned_type_node, 0));
    7579            8 :   out->safe_push (build_int_cst (unsigned_type_node, 42));
    7580            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "QNaN"));
    7581            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "-QNaN"));
    7582            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "SNaN"));
    7583            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "-SNaN"));
    7584            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "0.0"));
    7585            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "-0.0"));
    7586            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "Inf"));
    7587            8 :   out->safe_push (build_real_cst_from_string (float_type_node, "-Inf"));
    7588            8 : }
    7589              : 
    7590              : /* Verify that tree_cmp is a well-behaved comparator for qsort, even
    7591              :    if the underlying constants aren't comparable.  */
    7592              : 
    7593              : static void
    7594            4 : test_tree_cmp_on_constants ()
    7595              : {
    7596            4 :   auto_vec<tree> csts;
    7597            4 :   append_interesting_constants (&csts);
    7598              : 
    7599              :   /* Try sorting every triple. */
    7600            4 :   const unsigned num = csts.length ();
    7601           52 :   for (unsigned i = 0; i < num; i++)
    7602          624 :     for (unsigned j = 0; j < num; j++)
    7603         7488 :       for (unsigned k = 0; k < num; k++)
    7604              :         {
    7605         6912 :           auto_vec<tree> v (3);
    7606         6912 :           v.quick_push (csts[i]);
    7607         6912 :           v.quick_push (csts[j]);
    7608         6912 :           v.quick_push (csts[k]);
    7609         6912 :           v.qsort (tree_cmp);
    7610         6912 :         }
    7611            4 : }
    7612              : 
    7613              : /* Implementation detail of the ASSERT_CONDITION_* macros.  */
    7614              : 
    7615              : void
    7616            8 : assert_condition (const location &loc,
    7617              :                   region_model &model,
    7618              :                   const svalue *lhs, tree_code op, const svalue *rhs,
    7619              :                   tristate expected)
    7620              : {
    7621            8 :   tristate actual = model.eval_condition (lhs, op, rhs);
    7622            8 :   ASSERT_EQ_AT (loc, actual, expected);
    7623            8 : }
    7624              : 
    7625              : /* Implementation detail of the ASSERT_CONDITION_* macros.  */
    7626              : 
    7627              : void
    7628         3084 : assert_condition (const location &loc,
    7629              :                   region_model &model,
    7630              :                   tree lhs, tree_code op, tree rhs,
    7631              :                   tristate expected)
    7632              : {
    7633         3084 :   tristate actual = model.eval_condition (lhs, op, rhs, nullptr);
    7634         3084 :   ASSERT_EQ_AT (loc, actual, expected);
    7635         3084 : }
    7636              : 
    7637              : /* Implementation detail of ASSERT_DUMP_TREE_EQ.  */
    7638              : 
    7639              : static void
    7640           24 : assert_dump_tree_eq (const location &loc, tree t, const char *expected)
    7641              : {
    7642           24 :   auto_fix_quotes sentinel;
    7643           24 :   pretty_printer pp;
    7644           24 :   pp_format_decoder (&pp) = default_tree_printer;
    7645           24 :   dump_tree (&pp, t);
    7646           24 :   ASSERT_STREQ_AT (loc, pp_formatted_text (&pp), expected);
    7647           24 : }
    7648              : 
    7649              : /* Assert that dump_tree (T) is EXPECTED.  */
    7650              : 
    7651              : #define ASSERT_DUMP_TREE_EQ(T, EXPECTED) \
    7652              :   SELFTEST_BEGIN_STMT                                                   \
    7653              :   assert_dump_tree_eq ((SELFTEST_LOCATION), (T), (EXPECTED)); \
    7654              :   SELFTEST_END_STMT
    7655              : 
    7656              : /* Smoketest for region_model::dump_to_pp.  */
    7657              : 
    7658              : static void
    7659            4 : test_dump ()
    7660              : {
    7661            4 :   symbolic::node_manager node_mgr;
    7662            4 :   region_model model (node_mgr);
    7663              : 
    7664            4 :   text_art::ascii_theme theme;
    7665            4 :   pretty_printer pp;
    7666            4 :   symbolic::dump_node_tree_to_pp<region_model> (model, &theme, &pp,
    7667              :                                                 false, false);
    7668            4 :   ASSERT_STREQ ("Region Model\n"
    7669              :                 "`- Store\n"
    7670              :                 "   `- m_called_unknown_fn: false\n",
    7671              :                 pp_formatted_text (&pp));
    7672            4 : }
    7673              : 
    7674              : /* Verify usage of a struct.  */
    7675              : 
    7676              : static void
    7677            4 : test_struct ()
    7678              : {
    7679            4 :   coord_test ct;
    7680              : 
    7681            4 :   tree c = build_global_decl ("c", ct.m_coord_type);
    7682            4 :   tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
    7683              :                      c, ct.m_x_field, NULL_TREE);
    7684            4 :   tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    7685              :                      c, ct.m_y_field, NULL_TREE);
    7686              : 
    7687            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    7688            4 :   tree int_m3 = build_int_cst (integer_type_node, -3);
    7689              : 
    7690            4 :   symbolic::node_manager node_mgr;
    7691            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    7692            4 :   auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
    7693            4 :   region_model model (node_mgr);
    7694              :   /* Set fields in order y, then x.  */
    7695            4 :   model.set_value (c_y, int_m3, nullptr);
    7696            4 :   model.set_value (c_x, int_17, nullptr);
    7697              : 
    7698            4 :   const region *c_reg = model.get_lvalue (c, nullptr);
    7699              : 
    7700            4 :   diagnostics::markup::lowering_options opts;
    7701            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_reg, opts, "c");
    7702              : 
    7703            4 :   auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
    7704            4 :   auto int_size_bytes = concrete_byte_size (INT_TYPE_SIZE / BITS_PER_UNIT);
    7705              : 
    7706              :   /* Verify offsets/pointers for "c.x".  */
    7707            4 :   {
    7708            4 :     const region *c_x_reg = model.get_lvalue (c_x, nullptr);
    7709              : 
    7710            4 :     ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_x_reg, opts, "c.x");
    7711              : 
    7712            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7713              :       (c_x_reg->maybe_get_bit_offset_relative_to_parent (mgr),
    7714              :        &node_mgr.get_scalars ().get_bits ().get_concrete (0_bits));
    7715              : 
    7716            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7717              :       (c_x_reg->maybe_get_byte_offset_relative_to_parent (mgr),
    7718              :        &node_mgr.get_scalars ().get_bytes ().get_concrete (0_bytes));
    7719              : 
    7720            4 :     auto sym_ptr = c_x_reg->get_pointer (mgr);
    7721            4 :     ASSERT_SAME_SYMBOLIC_NODE (sym_ptr.get_base_region (),
    7722              :                         *c_reg);
    7723            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7724              :       (sym_ptr.get_byte_offset (),
    7725              :        node_mgr.get_scalars ().get_bytes ().get_concrete (0_bytes));
    7726              : 
    7727            8 :     ASSERT_EQ (c_reg->get_pointer (mgr), c_x_reg->get_pointer (mgr));
    7728              : 
    7729            4 :     auto mem_range = c_x_reg->get_memory_range (mgr);
    7730            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_base_region (), *c_reg);
    7731           16 :     ASSERT_EQ
    7732              :       (mem_range.get_bit_range (),
    7733              :        symbolic_from_concrete (concrete_bit_range (0_bits, int_size_bits),
    7734              :                                bit_mgr));
    7735            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7736              :       (model.maybe_get_region_for_mem_range (mem_range, TREE_TYPE (c_x)),
    7737              :        c_x_reg);
    7738              :   }
    7739              : 
    7740              :   /* Verify offsets/pointers for "c.y".  */
    7741            4 :   {
    7742            4 :     const region *c_y_reg = model.get_lvalue (c_y, nullptr);
    7743              : 
    7744            4 :     ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_y_reg, opts, "c.y");
    7745              : 
    7746            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7747              :       (c_y_reg->maybe_get_bit_offset_relative_to_parent (mgr),
    7748              :        &node_mgr.get_scalars ().get_bits ().get_concrete (int_size_bits));
    7749              : 
    7750            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7751              :       (c_y_reg->maybe_get_byte_offset_relative_to_parent (mgr),
    7752              :        &node_mgr.get_scalars ().get_bytes ().get_concrete (int_size_bytes));
    7753              : 
    7754            4 :     auto sym_ptr = c_y_reg->get_pointer (mgr);
    7755            4 :     ASSERT_SAME_SYMBOLIC_NODE (sym_ptr.get_base_region (),
    7756              :                                *c_reg);
    7757            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7758              :       (sym_ptr.get_byte_offset (),
    7759              :        node_mgr.get_scalars ().get_bytes ().get_concrete (int_size_bytes));
    7760              : 
    7761            8 :     ASSERT_NE (c_reg->get_pointer (mgr), c_y_reg->get_pointer (mgr));
    7762              : 
    7763            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7764              :       (model.maybe_get_region_for_mem_range (c_y_reg->get_memory_range (mgr),
    7765              :                                              TREE_TYPE (c_x)),
    7766              :        c_y_reg);
    7767              : 
    7768            4 :     auto mem_range = c_y_reg->get_memory_range (mgr);
    7769            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_base_region (), *c_reg);
    7770           16 :     ASSERT_EQ
    7771              :       (mem_range.get_bit_range (),
    7772              :        symbolic_from_concrete (concrete_bit_range (int_size_bits,
    7773              :                                                    int_size_bits),
    7774              :                                bit_mgr));
    7775            4 :     ASSERT_SAME_SYMBOLIC_NODE
    7776              :       (model.maybe_get_region_for_mem_range (mem_range, TREE_TYPE (c_y)),
    7777              :        c_y_reg);
    7778              :   }
    7779            4 : }
    7780              : 
    7781              : /* Verify usage of an array element.  */
    7782              : 
    7783              : static void
    7784            4 : test_array_1 ()
    7785              : {
    7786            4 :   tree tlen = size_int (10);
    7787            4 :   tree arr_type = build_array_type (char_type_node, build_index_type (tlen));
    7788              : 
    7789            4 :   tree a = build_global_decl ("a", arr_type);
    7790              : 
    7791            4 :   symbolic::node_manager node_mgr;
    7792            4 :   region_model model (node_mgr);
    7793            4 :   tree int_0 = integer_zero_node;
    7794            4 :   tree a_0 = build4 (ARRAY_REF, char_type_node,
    7795              :                      a, int_0, NULL_TREE, NULL_TREE);
    7796            4 :   tree char_A = build_int_cst (char_type_node, 'A');
    7797            4 :   model.set_value (a_0, char_A, nullptr);
    7798              : 
    7799            4 :   diagnostics::markup::lowering_options opts;
    7800            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*model.get_lvalue (a_0, nullptr),
    7801              :                                        opts,
    7802              :                                        "a[0]");
    7803            4 : }
    7804              : 
    7805              : /* Verify that region_model::get_representative_tree works as expected.  */
    7806              : 
    7807              : static void
    7808            4 : test_get_representative_tree ()
    7809              : {
    7810            4 :   symbolic::node_manager node_mgr;
    7811              : 
    7812              :   /* STRING_CST.  */
    7813            4 :   {
    7814            4 :     tree string_cst = build_string (4, "foo");
    7815            4 :     region_model m (node_mgr);
    7816            4 :     const svalue *str_sval = m.get_rvalue (string_cst, nullptr);
    7817            4 :     tree rep = m.get_representative_tree (str_sval);
    7818            4 :     ASSERT_EQ (rep, string_cst);
    7819            4 :   }
    7820              : 
    7821              :   /* String literal.  */
    7822            4 :   {
    7823            4 :     tree string_cst_ptr = build_string_literal (4, "foo");
    7824            4 :     region_model m (node_mgr);
    7825            4 :     const svalue *str_sval = m.get_rvalue (string_cst_ptr, nullptr);
    7826            4 :     tree rep = m.get_representative_tree (str_sval);
    7827            4 :     ASSERT_DUMP_TREE_EQ (rep, "\"foo\"");
    7828            4 :   }
    7829              : 
    7830              :   /* Value of an element within an array.  */
    7831            4 :   {
    7832            4 :     tree tlen = size_int (10);
    7833            4 :     tree arr_type = build_array_type (char_type_node, build_index_type (tlen));
    7834            4 :     tree a = build_global_decl ("a", arr_type);
    7835            4 :     placeholder_svalue test_sval (node_mgr.alloc_node_id (),
    7836            4 :                                   char_type_node, "test value");
    7837              : 
    7838              :     /* Value of a[3].  */
    7839            4 :     {
    7840            4 :       test_region_model_context ctxt;
    7841            4 :       region_model model (node_mgr);
    7842            4 :       tree int_3 = build_int_cst (integer_type_node, 3);
    7843            4 :       tree a_3 = build4 (ARRAY_REF, char_type_node,
    7844              :                          a, int_3, NULL_TREE, NULL_TREE);
    7845            4 :       const region *a_3_reg = model.get_lvalue (a_3, &ctxt);
    7846            4 :       model.set_value (a_3_reg, &test_sval, &ctxt);
    7847            4 :       tree rep = model.get_representative_tree (&test_sval);
    7848            4 :       ASSERT_DUMP_TREE_EQ (rep, "a[3]");
    7849            4 :     }
    7850              : 
    7851              :     /* Value of a[0].  */
    7852            4 :     {
    7853            4 :       test_region_model_context ctxt;
    7854            4 :       region_model model (node_mgr);
    7855            4 :       tree idx = integer_zero_node;
    7856            4 :       tree a_0 = build4 (ARRAY_REF, char_type_node,
    7857              :                          a, idx, NULL_TREE, NULL_TREE);
    7858            4 :       const region *a_0_reg = model.get_lvalue (a_0, &ctxt);
    7859            4 :       model.set_value (a_0_reg, &test_sval, &ctxt);
    7860            4 :       tree rep = model.get_representative_tree (&test_sval);
    7861            4 :       ASSERT_DUMP_TREE_EQ (rep, "a[0]");
    7862            4 :     }
    7863            4 :   }
    7864              : 
    7865              :   /* Value of a field within a struct.  */
    7866            4 :   {
    7867            4 :     coord_test ct;
    7868              : 
    7869            4 :     tree c = build_global_decl ("c", ct.m_coord_type);
    7870            4 :     tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
    7871              :                        c, ct.m_x_field, NULL_TREE);
    7872            4 :     tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    7873              :                        c, ct.m_y_field, NULL_TREE);
    7874              : 
    7875            4 :     test_region_model_context ctxt;
    7876              : 
    7877              :     /* Value of initial field.  */
    7878            4 :     {
    7879            4 :       region_model m (node_mgr);
    7880            4 :       const region *c_x_reg = m.get_lvalue (c_x, &ctxt);
    7881            4 :       placeholder_svalue test_sval_x (node_mgr.alloc_node_id (),
    7882            4 :                                       integer_type_node, "test x val");
    7883            4 :       m.set_value (c_x_reg, &test_sval_x, &ctxt);
    7884            4 :       tree rep = m.get_representative_tree (&test_sval_x);
    7885            4 :       ASSERT_DUMP_TREE_EQ (rep, "c.x");
    7886            4 :     }
    7887              : 
    7888              :     /* Value of non-initial field.  */
    7889            4 :     {
    7890            4 :       region_model m (node_mgr);
    7891            4 :       const region *c_y_reg = m.get_lvalue (c_y, &ctxt);
    7892            4 :       placeholder_svalue test_sval_y (node_mgr.alloc_node_id (),
    7893            4 :                                       integer_type_node, "test y val");
    7894            4 :       m.set_value (c_y_reg, &test_sval_y, &ctxt);
    7895            4 :       tree rep = m.get_representative_tree (&test_sval_y);
    7896            4 :       ASSERT_DUMP_TREE_EQ (rep, "c.y");
    7897            4 :     }
    7898            4 :   }
    7899              : 
    7900              :   /* Value of a single field within a struct,
    7901              :      so sizeof(field) == sizeof(struct).
    7902              :   */
    7903            4 :   {
    7904              :     /* Consider:
    7905              :        | struct foo {
    7906              :        |   void *ptr;
    7907              :        | };
    7908              :        | c.ptr = VAL;
    7909              :     */
    7910            4 :     tree t_field_ptr = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
    7911              :                                    get_identifier ("ptr"), ptr_type_node);
    7912            4 :     tree t_struct_foo_type = make_test_compound_type ("foo", true, {t_field_ptr});
    7913            4 :     tree c = build_global_decl ("c", t_struct_foo_type);
    7914            4 :     tree c_ptr = build3 (COMPONENT_REF, TREE_TYPE (t_field_ptr),
    7915              :                          c, t_field_ptr, NULL_TREE);
    7916              : 
    7917            4 :     test_region_model_context ctxt;
    7918              : 
    7919              :     /* Value of single field.  */
    7920            4 :     region_model m (node_mgr);
    7921            4 :     const region *c_ptr_reg = m.get_lvalue (c_ptr, &ctxt);
    7922            4 :     placeholder_svalue test_val (node_mgr.alloc_node_id (),
    7923            4 :                                  ptr_type_node, "test val");
    7924            4 :     m.set_value (c_ptr_reg, &test_val, &ctxt);
    7925            4 :     tree rep = m.get_representative_tree (&test_val);
    7926            4 :     ASSERT_DUMP_TREE_EQ (rep, "c.ptr");
    7927            4 :   }
    7928            4 : }
    7929              : 
    7930              : /* Verify that calling region_model::get_rvalue repeatedly on the same
    7931              :    tree constant retrieves the same svalue *.  */
    7932              : 
    7933              : static void
    7934            4 : test_unique_constants ()
    7935              : {
    7936            4 :   tree int_0 = integer_zero_node;
    7937            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    7938              : 
    7939            4 :   test_region_model_context ctxt;
    7940            4 :   symbolic::node_manager node_mgr;
    7941            4 :   region_model model (node_mgr);
    7942            4 :   ASSERT_EQ (model.get_rvalue (int_0, &ctxt), model.get_rvalue (int_0, &ctxt));
    7943            4 :   ASSERT_EQ (model.get_rvalue (int_42, &ctxt),
    7944              :              model.get_rvalue (int_42, &ctxt));
    7945            4 :   ASSERT_NE (model.get_rvalue (int_0, &ctxt), model.get_rvalue (int_42, &ctxt));
    7946            4 :   ASSERT_EQ (ctxt.get_num_diagnostics (), 0);
    7947              : 
    7948            4 :   diagnostics::markup::lowering_options opts;
    7949            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*model.get_rvalue (int_42, &ctxt),
    7950              :                                        opts,
    7951              :                                        "42");
    7952              : 
    7953              :   /* A "(const int)42" will be a different tree from "(int)42)"...  */
    7954            4 :   tree const_int_type_node
    7955            4 :     = build_qualified_type (integer_type_node, TYPE_QUAL_CONST);
    7956            4 :   tree const_int_42 = build_int_cst (const_int_type_node, 42);
    7957            4 :   ASSERT_NE (int_42, const_int_42);
    7958              :   /* It should have a different const_svalue.  */
    7959            4 :   const svalue *int_42_sval = model.get_rvalue (int_42, &ctxt);
    7960            4 :   const svalue *const_int_42_sval = model.get_rvalue (const_int_42, &ctxt);
    7961            4 :   ASSERT_NE (int_42_sval, const_int_42_sval);
    7962              :   /* But they should compare as equal.  */
    7963            4 :   ASSERT_CONDITION_TRUE (model, int_42_sval, EQ_EXPR, const_int_42_sval);
    7964            4 :   ASSERT_CONDITION_FALSE (model, int_42_sval, NE_EXPR, const_int_42_sval);
    7965            4 : }
    7966              : 
    7967              : /* Verify that each type gets its own singleton unknown_svalue within a
    7968              :    region_model_manager, and that NULL_TREE gets its own singleton.  */
    7969              : 
    7970              : static void
    7971            4 : test_unique_unknowns ()
    7972              : {
    7973            4 :   symbolic::node_manager node_mgr;
    7974            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    7975            4 :   const svalue *unknown_int
    7976            4 :     = mgr.get_or_create_unknown_svalue (integer_type_node);
    7977              :   /* Repeated calls with the same type should get the same "unknown"
    7978              :      svalue.  */
    7979            4 :   const svalue *unknown_int_2
    7980            4 :     = mgr.get_or_create_unknown_svalue (integer_type_node);
    7981            4 :   ASSERT_EQ (unknown_int, unknown_int_2);
    7982              : 
    7983              :   /* Different types (or the NULL type) should have different
    7984              :      unknown_svalues.  */
    7985            4 :   const svalue *unknown_NULL_type = mgr.get_or_create_unknown_svalue (nullptr);
    7986            4 :   ASSERT_NE (unknown_NULL_type, unknown_int);
    7987              : 
    7988              :   /* Repeated calls with NULL for the type should get the same "unknown"
    7989              :      svalue.  */
    7990            4 :   const svalue *unknown_NULL_type_2 = mgr.get_or_create_unknown_svalue (nullptr);
    7991            4 :   ASSERT_EQ (unknown_NULL_type, unknown_NULL_type_2);
    7992              : 
    7993            4 :   diagnostics::markup::lowering_options opts;
    7994            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*unknown_int, opts, "unknown");
    7995            4 : }
    7996              : 
    7997              : /* Verify that initial_svalue are handled as expected.  */
    7998              : 
    7999              : static void
    8000            4 : test_initial_svalue_folding ()
    8001              : {
    8002            4 :   symbolic::node_manager node_mgr;
    8003            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8004            4 :   tree x = build_global_decl ("x", integer_type_node);
    8005            4 :   tree y = build_global_decl ("y", integer_type_node);
    8006              : 
    8007            4 :   test_region_model_context ctxt;
    8008            4 :   region_model model (node_mgr);
    8009            4 :   const svalue *x_init = model.get_rvalue (x, &ctxt);
    8010            4 :   const svalue *y_init = model.get_rvalue (y, &ctxt);
    8011            4 :   ASSERT_NE (x_init, y_init);
    8012            4 :   const region *x_reg = model.get_lvalue (x, &ctxt);
    8013            4 :   ASSERT_SAME_SYMBOLIC_NODE (x_init,
    8014              :                              mgr.get_or_create_initial_value (x_reg));
    8015              : 
    8016            4 :   diagnostics::markup::lowering_options opts;
    8017            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*x_init, opts, "x");
    8018            4 : }
    8019              : 
    8020              : /* Verify that unary ops are folded as expected.  */
    8021              : 
    8022              : static void
    8023            4 : test_unaryop_svalue_folding ()
    8024              : {
    8025            4 :   symbolic::node_manager node_mgr;
    8026            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8027              : 
    8028            4 :   tree x = build_global_decl ("x", integer_type_node);
    8029            4 :   tree y = build_global_decl ("y", integer_type_node);
    8030              : 
    8031            4 :   test_region_model_context ctxt;
    8032            4 :   region_model model (node_mgr);
    8033            4 :   const svalue *x_init = model.get_rvalue (x, &ctxt);
    8034            4 :   const svalue *y_init = model.get_rvalue (y, &ctxt);
    8035            4 :   const region *x_reg = model.get_lvalue (x, &ctxt);
    8036            4 :   ASSERT_SAME_SYMBOLIC_NODE (x_init,
    8037              :                              mgr.get_or_create_initial_value (x_reg));
    8038              : 
    8039              :   /* "(int)x" -> "x".  */
    8040            4 :   ASSERT_EQ (x_init, mgr.get_or_create_cast (integer_type_node, x_init));
    8041              : 
    8042              :   /* "(void *)x" -> something other than "x".  */
    8043            4 :   ASSERT_NE (x_init, mgr.get_or_create_cast (ptr_type_node, x_init));
    8044              : 
    8045              :   /* "!(x == y)" -> "x != y".  */
    8046            4 :   ASSERT_EQ (mgr.get_or_create_unaryop
    8047              :                (boolean_type_node, TRUTH_NOT_EXPR,
    8048              :                 mgr.get_or_create_binop (boolean_type_node, EQ_EXPR,
    8049              :                                          x_init, y_init)),
    8050              :              mgr.get_or_create_binop (boolean_type_node, NE_EXPR,
    8051              :                                       x_init, y_init));
    8052              :   /* "!(x > y)" -> "x <= y".  */
    8053            4 :   ASSERT_EQ (mgr.get_or_create_unaryop
    8054              :                (boolean_type_node, TRUTH_NOT_EXPR,
    8055              :                 mgr.get_or_create_binop (boolean_type_node, GT_EXPR,
    8056              :                                          x_init, y_init)),
    8057              :              mgr.get_or_create_binop (boolean_type_node, LE_EXPR,
    8058              :                                       x_init, y_init));
    8059            4 : }
    8060              : 
    8061              : /* Verify that binops on constant svalues are folded.  */
    8062              : 
    8063              : static void
    8064            4 : test_binop_svalue_folding ()
    8065              : {
    8066              : #define NUM_CSTS 10
    8067            4 :   tree cst_int[NUM_CSTS];
    8068            4 :   symbolic::node_manager node_mgr;
    8069            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8070            4 :   const svalue *cst_sval[NUM_CSTS];
    8071           44 :   for (int i = 0; i < NUM_CSTS; i++)
    8072              :     {
    8073           40 :       cst_int[i] = build_int_cst (integer_type_node, i);
    8074           40 :       cst_sval[i] = mgr.get_or_create_constant_svalue (cst_int[i]);
    8075           40 :       ASSERT_EQ (cst_sval[i]->get_kind (), SK_CONSTANT);
    8076           40 :       ASSERT_EQ (cst_sval[i]->maybe_get_constant (), cst_int[i]);
    8077              :     }
    8078              : 
    8079           44 :   for (int i = 0; i < NUM_CSTS; i++)
    8080          440 :     for (int j = 0; j < NUM_CSTS; j++)
    8081              :       {
    8082          400 :         if (i != j)
    8083          360 :           ASSERT_NE (cst_sval[i], cst_sval[j]);
    8084          400 :         if (i + j < NUM_CSTS)
    8085              :           {
    8086          220 :             const svalue *sum
    8087          220 :               = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8088              :                                          cst_sval[i], cst_sval[j]);
    8089          220 :             ASSERT_EQ (sum, cst_sval[i + j]);
    8090              :           }
    8091          400 :         if (i - j >= 0)
    8092              :           {
    8093          220 :             const svalue *difference
    8094          220 :               = mgr.get_or_create_binop (integer_type_node, MINUS_EXPR,
    8095              :                                          cst_sval[i], cst_sval[j]);
    8096          220 :             ASSERT_EQ (difference, cst_sval[i - j]);
    8097              :           }
    8098          400 :         if (i * j < NUM_CSTS)
    8099              :           {
    8100          168 :             const svalue *product
    8101          168 :               = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8102              :                                          cst_sval[i], cst_sval[j]);
    8103          168 :             ASSERT_EQ (product, cst_sval[i * j]);
    8104              :           }
    8105          400 :         const svalue *eq = mgr.get_or_create_binop (integer_type_node, EQ_EXPR,
    8106              :                                                cst_sval[i], cst_sval[j]);
    8107          400 :         ASSERT_EQ (eq, i == j ? cst_sval[1] : cst_sval [0]);
    8108          400 :         const svalue *neq = mgr.get_or_create_binop (integer_type_node, NE_EXPR,
    8109              :                                                 cst_sval[i], cst_sval[j]);
    8110          400 :         ASSERT_EQ (neq, i != j ? cst_sval[1] : cst_sval [0]);
    8111              :         // etc
    8112              :       }
    8113              : 
    8114            4 :   tree x = build_global_decl ("x", integer_type_node);
    8115              : 
    8116            4 :   test_region_model_context ctxt;
    8117            4 :   region_model model (node_mgr);
    8118            4 :   const svalue *x_init = model.get_rvalue (x, &ctxt);
    8119              : 
    8120              :   /* PLUS_EXPR folding.  */
    8121            4 :   const svalue *x_init_plus_zero
    8122            4 :     = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8123              :                                x_init, cst_sval[0]);
    8124            4 :   ASSERT_EQ (x_init_plus_zero, x_init);
    8125            4 :   const svalue *zero_plus_x_init
    8126            4 :     = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8127              :                                cst_sval[0], x_init);
    8128            4 :   ASSERT_EQ (zero_plus_x_init, x_init);
    8129              : 
    8130              :   /* MULT_EXPR folding.  */
    8131            4 :   const svalue *x_init_times_zero
    8132            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8133              :                                x_init, cst_sval[0]);
    8134            4 :   ASSERT_EQ (x_init_times_zero, cst_sval[0]);
    8135            4 :   const svalue *zero_times_x_init
    8136            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8137              :                                cst_sval[0], x_init);
    8138            4 :   ASSERT_EQ (zero_times_x_init, cst_sval[0]);
    8139              : 
    8140            4 :   const svalue *x_init_times_one
    8141            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8142              :                                x_init, cst_sval[1]);
    8143            4 :   ASSERT_EQ (x_init_times_one, x_init);
    8144            4 :   const svalue *one_times_x_init
    8145            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8146              :                                cst_sval[1], x_init);
    8147            4 :   ASSERT_EQ (one_times_x_init, x_init);
    8148              : 
    8149              :   // etc
    8150              :   // TODO: do we want to use the match-and-simplify DSL for this?
    8151              : 
    8152              :   /* Verify that binops put any constants on the RHS.  */
    8153            4 :   const svalue *four_times_x_init
    8154            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8155              :                                cst_sval[4], x_init);
    8156            4 :   const svalue *x_init_times_four
    8157            4 :     = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
    8158              :                                x_init, cst_sval[4]);
    8159            4 :   ASSERT_EQ (four_times_x_init, x_init_times_four);
    8160            4 :   const binop_svalue *binop = four_times_x_init->dyn_cast_binop_svalue ();
    8161            4 :   ASSERT_EQ (binop->get_op (), MULT_EXPR);
    8162            4 :   ASSERT_EQ (binop->get_arg0 (), x_init);
    8163            4 :   ASSERT_EQ (binop->get_arg1 (), cst_sval[4]);
    8164              : 
    8165              :   /* Verify that ((x + 1) + 1) == (x + 2).  */
    8166            4 :   const svalue *x_init_plus_one
    8167            4 :     = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8168              :                                x_init, cst_sval[1]);
    8169            4 :   const svalue *x_init_plus_two
    8170            4 :     = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8171              :                                x_init, cst_sval[2]);
    8172            4 :   const svalue *x_init_plus_one_plus_one
    8173            4 :     = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
    8174              :                                x_init_plus_one, cst_sval[1]);
    8175            4 :   ASSERT_EQ (x_init_plus_one_plus_one, x_init_plus_two);
    8176              : 
    8177            4 :   diagnostics::markup::lowering_options opts;
    8178            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*x_init_plus_one, opts, "x + 1");
    8179              : 
    8180              :   /* Verify various binops on booleans.  */
    8181            4 :   {
    8182            4 :     const svalue *sval_true = mgr.get_or_create_int_cst (boolean_type_node, 1);
    8183            4 :     const svalue *sval_false = mgr.get_or_create_int_cst (boolean_type_node, 0);
    8184            4 :     const svalue *sval_unknown
    8185            4 :       = mgr.get_or_create_unknown_svalue (boolean_type_node);
    8186            4 :     const placeholder_svalue sval_placeholder (mgr.alloc_node_id (),
    8187            4 :                                                boolean_type_node, "v");
    8188           12 :     for (auto op : {BIT_IOR_EXPR, TRUTH_OR_EXPR})
    8189              :       {
    8190            8 :         ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
    8191              :                                             sval_true, sval_unknown),
    8192              :                    sval_true);
    8193            8 :         ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
    8194              :                                             sval_false, sval_unknown),
    8195              :                    sval_unknown);
    8196            8 :         ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
    8197              :                                             sval_false, &sval_placeholder),
    8198              :                    &sval_placeholder);
    8199              :       }
    8200           12 :     for (auto op : {BIT_AND_EXPR, TRUTH_AND_EXPR})
    8201              :       {
    8202            8 :         ASSERT_SAME_SYMBOLIC_NODE
    8203              :           (mgr.get_or_create_binop (boolean_type_node, op,
    8204              :                                     sval_false, sval_unknown),
    8205              :            sval_false);
    8206            8 :         ASSERT_SAME_SYMBOLIC_NODE
    8207              :           (mgr.get_or_create_binop (boolean_type_node, op,
    8208              :                                     sval_true, sval_unknown),
    8209              :            sval_unknown);
    8210              :       }
    8211            4 :   }
    8212            4 : }
    8213              : 
    8214              : /* Test that region::descendent_of_p works as expected.  */
    8215              : 
    8216              : static void
    8217            4 : test_descendent_of_p ()
    8218              : {
    8219            4 :   symbolic::node_manager node_mgr;
    8220            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8221            4 :   const region *stack = mgr.get_stack_region ();
    8222            4 :   const region *heap = mgr.get_heap_region ();
    8223            4 :   const region *code = mgr.get_code_region ();
    8224            4 :   const region *globals = mgr.get_globals_region ();
    8225              : 
    8226              :   /* descendent_of_p should return true when used on the region itself.  */
    8227            4 :   ASSERT_TRUE (stack->descendent_of_p (stack));
    8228            4 :   ASSERT_FALSE (stack->descendent_of_p (heap));
    8229            4 :   ASSERT_FALSE (stack->descendent_of_p (code));
    8230            4 :   ASSERT_FALSE (stack->descendent_of_p (globals));
    8231              : 
    8232            4 :   tree x = build_global_decl ("x", integer_type_node);
    8233            4 :   const region *x_reg = mgr.get_region_for_global (x);
    8234            4 :   ASSERT_TRUE (x_reg->descendent_of_p (globals));
    8235              : 
    8236              :   /* A cast_region should be a descendent of the original region.  */
    8237            4 :   const region *cast_reg = mgr.get_cast_region (x_reg, ptr_type_node);
    8238            4 :   ASSERT_TRUE (cast_reg->descendent_of_p (x_reg));
    8239            4 : }
    8240              : 
    8241              : /* Verify that bit_range_region works as expected.  */
    8242              : 
    8243              : static void
    8244            4 : test_bit_range_regions ()
    8245              : {
    8246            4 :   tree x = build_global_decl ("x", integer_type_node);
    8247            4 :   symbolic::node_manager node_mgr;
    8248            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8249            4 :   const region *x_reg = mgr.get_region_for_global (x);
    8250            4 :   const region *byte0
    8251            4 :     = mgr.get_bit_range (x_reg, char_type_node,
    8252           12 :                          concrete_bit_range (0_bits, 8_bits));
    8253            4 :   const region *byte1
    8254            4 :     = mgr.get_bit_range (x_reg, char_type_node,
    8255           12 :                          concrete_bit_range (8_bits, 8_bits));
    8256            4 :   ASSERT_TRUE (byte0->descendent_of_p (x_reg));
    8257            4 :   ASSERT_TRUE (byte1->descendent_of_p (x_reg));
    8258            4 :   ASSERT_NE (byte0, byte1);
    8259              : 
    8260            4 :   diagnostics::markup::lowering_options opts;
    8261            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*byte1, opts,
    8262              :                                        "bit_range_region (x, bits=[8, 16))");
    8263            4 : }
    8264              : 
    8265              : /* Verify that simple assignments work as expected.  */
    8266              : 
    8267              : static void
    8268            4 : test_assignment ()
    8269              : {
    8270            4 :   tree int_0 = integer_zero_node;
    8271            4 :   tree x = build_global_decl ("x", integer_type_node);
    8272            4 :   tree y = build_global_decl ("y", integer_type_node);
    8273              : 
    8274              :   /* "x == 0", then use of y, then "y = 0;".  */
    8275            4 :   symbolic::node_manager node_mgr;
    8276            4 :   region_model model (node_mgr);
    8277            4 :   ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0);
    8278            4 :   ASSERT_CONDITION_UNKNOWN (model, y, EQ_EXPR, int_0);
    8279            4 :   model.set_value (model.get_lvalue (y, nullptr),
    8280              :                    model.get_rvalue (int_0, nullptr),
    8281              :                    nullptr);
    8282            4 :   ASSERT_CONDITION_TRUE (model, y, EQ_EXPR, int_0);
    8283            4 :   ASSERT_CONDITION_TRUE (model, y, EQ_EXPR, x);
    8284            4 : }
    8285              : 
    8286              : /* Verify that compound assignments work as expected.  */
    8287              : 
    8288              : static void
    8289            4 : test_compound_assignment ()
    8290              : {
    8291            4 :   coord_test ct;
    8292              : 
    8293            4 :   tree c = build_global_decl ("c", ct.m_coord_type);
    8294            4 :   tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
    8295              :                      c, ct.m_x_field, NULL_TREE);
    8296            4 :   tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    8297              :                      c, ct.m_y_field, NULL_TREE);
    8298            4 :   tree d = build_global_decl ("d", ct.m_coord_type);
    8299            4 :   tree d_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
    8300              :                      d, ct.m_x_field, NULL_TREE);
    8301            4 :   tree d_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    8302              :                      d, ct.m_y_field, NULL_TREE);
    8303              : 
    8304            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    8305            4 :   tree int_m3 = build_int_cst (integer_type_node, -3);
    8306              : 
    8307            4 :   symbolic::node_manager node_mgr;
    8308            4 :   region_model model (node_mgr);
    8309            4 :   model.set_value (c_x, int_17, nullptr);
    8310            4 :   model.set_value (c_y, int_m3, nullptr);
    8311              : 
    8312              :   /* Copy c to d.  */
    8313            4 :   const svalue *sval = model.get_rvalue (c, nullptr);
    8314            4 :   model.set_value (model.get_lvalue (d, nullptr), sval, nullptr);
    8315              : 
    8316              :   /* Check that the fields have the same svalues.  */
    8317            4 :   ASSERT_EQ (model.get_rvalue (c_x, nullptr), model.get_rvalue (d_x, nullptr));
    8318            4 :   ASSERT_EQ (model.get_rvalue (c_y, nullptr), model.get_rvalue (d_y, nullptr));
    8319            4 : }
    8320              : 
    8321              : /* Verify the details of pushing and popping stack frames.  */
    8322              : 
    8323              : static void
    8324            4 : test_stack_frames ()
    8325              : {
    8326            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    8327            4 :   tree int_10 = build_int_cst (integer_type_node, 10);
    8328            4 :   tree int_5 = build_int_cst (integer_type_node, 5);
    8329            4 :   tree int_0 = integer_zero_node;
    8330              : 
    8331            4 :   auto_vec <tree> param_types;
    8332            4 :   tree parent_fndecl = make_fndecl (integer_type_node,
    8333              :                                     "parent_fn",
    8334              :                                     param_types);
    8335            4 :   allocate_struct_function (parent_fndecl, true);
    8336              : 
    8337            4 :   tree child_fndecl = make_fndecl (integer_type_node,
    8338              :                                    "child_fn",
    8339              :                                    param_types);
    8340            4 :   allocate_struct_function (child_fndecl, true);
    8341              : 
    8342              :   /* "a" and "b" in the parent frame.  */
    8343            4 :   tree a = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8344              :                        get_identifier ("a"),
    8345              :                        integer_type_node);
    8346            4 :   DECL_CONTEXT (a) = parent_fndecl;
    8347            4 :   tree b = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8348              :                        get_identifier ("b"),
    8349              :                        integer_type_node);
    8350            4 :   DECL_CONTEXT (b) = parent_fndecl;
    8351              :   /* "x" and "y" in a child frame.  */
    8352            4 :   tree x = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8353              :                        get_identifier ("x"),
    8354              :                        integer_type_node);
    8355            4 :   DECL_CONTEXT (x) = child_fndecl;
    8356            4 :   tree y = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8357              :                        get_identifier ("y"),
    8358              :                        integer_type_node);
    8359            4 :   DECL_CONTEXT (y) = child_fndecl;
    8360              : 
    8361              :   /* "p" global.  */
    8362            4 :   tree p = build_global_decl ("p", ptr_type_node);
    8363              : 
    8364              :   /* "q" global.  */
    8365            4 :   tree q = build_global_decl ("q", ptr_type_node);
    8366              : 
    8367            4 :   symbolic::node_manager node_mgr;
    8368            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8369            4 :   test_region_model_context ctxt;
    8370            4 :   region_model model (node_mgr);
    8371              : 
    8372              :   /* Push stack frame for "parent_fn".  */
    8373            4 :   const region *parent_frame_reg
    8374            4 :     = model.push_frame (*DECL_STRUCT_FUNCTION (parent_fndecl),
    8375              :                         nullptr, nullptr, &ctxt);
    8376            4 :   ASSERT_EQ (model.get_current_frame (), parent_frame_reg);
    8377            4 :   ASSERT_TRUE (model.region_exists_p (parent_frame_reg));
    8378            4 :   const region *a_in_parent_reg = model.get_lvalue (a, &ctxt);
    8379            4 :   model.set_value (a_in_parent_reg,
    8380              :                    model.get_rvalue (int_42, &ctxt),
    8381              :                    &ctxt);
    8382            4 :   ASSERT_EQ (a_in_parent_reg->maybe_get_frame_region (), parent_frame_reg);
    8383              : 
    8384            4 :   model.add_constraint (b, LT_EXPR, int_10, &ctxt);
    8385            4 :   ASSERT_EQ (model.eval_condition (b, LT_EXPR, int_10, &ctxt),
    8386              :              tristate (tristate::TS_TRUE));
    8387              : 
    8388              :   /* Push stack frame for "child_fn".  */
    8389            4 :   const region *child_frame_reg
    8390            4 :     = model.push_frame (*DECL_STRUCT_FUNCTION (child_fndecl),
    8391              :                         nullptr, nullptr, &ctxt);
    8392            4 :   ASSERT_EQ (model.get_current_frame (), child_frame_reg);
    8393            4 :   ASSERT_TRUE (model.region_exists_p (child_frame_reg));
    8394            4 :   const region *x_in_child_reg = model.get_lvalue (x, &ctxt);
    8395            4 :   model.set_value (x_in_child_reg,
    8396              :                    model.get_rvalue (int_0, &ctxt),
    8397              :                    &ctxt);
    8398            4 :   ASSERT_EQ (x_in_child_reg->maybe_get_frame_region (), child_frame_reg);
    8399              : 
    8400            4 :   model.add_constraint (y, NE_EXPR, int_5, &ctxt);
    8401            4 :   ASSERT_EQ (model.eval_condition (y, NE_EXPR, int_5, &ctxt),
    8402              :              tristate (tristate::TS_TRUE));
    8403              : 
    8404              :   /* Point a global pointer at a local in the child frame:  p = &x.  */
    8405            4 :   const region *p_in_globals_reg = model.get_lvalue (p, &ctxt);
    8406            4 :   model.set_value (p_in_globals_reg,
    8407              :                    mgr.get_ptr_svalue (ptr_type_node, x_in_child_reg),
    8408              :                    &ctxt);
    8409            4 :   ASSERT_EQ (p_in_globals_reg->maybe_get_frame_region (), nullptr);
    8410              : 
    8411              :   /* Point another global pointer at p: q = &p.  */
    8412            4 :   const region *q_in_globals_reg = model.get_lvalue (q, &ctxt);
    8413            4 :   model.set_value (q_in_globals_reg,
    8414              :                    mgr.get_ptr_svalue (ptr_type_node, p_in_globals_reg),
    8415              :                    &ctxt);
    8416              : 
    8417              :   /* Test region::descendent_of_p.  */
    8418            4 :   ASSERT_TRUE (child_frame_reg->descendent_of_p (child_frame_reg));
    8419            4 :   ASSERT_TRUE (x_in_child_reg->descendent_of_p (child_frame_reg));
    8420            4 :   ASSERT_FALSE (a_in_parent_reg->descendent_of_p (child_frame_reg));
    8421              : 
    8422              :   /* Pop the "child_fn" frame from the stack.  */
    8423            4 :   model.pop_frame (nullptr, nullptr, &ctxt, nullptr);
    8424            4 :   ASSERT_FALSE (model.region_exists_p (child_frame_reg));
    8425            4 :   ASSERT_TRUE (model.region_exists_p (parent_frame_reg));
    8426              : 
    8427              :   /* Verify that p (which was pointing at the local "x" in the popped
    8428              :      frame) has been poisoned.  */
    8429            4 :   const svalue *new_p_sval = model.get_rvalue (p, nullptr);
    8430            4 :   ASSERT_EQ (new_p_sval->get_kind (), SK_BIT_VECTOR);
    8431            4 :   auto &new_p_bv
    8432            4 :     = new_p_sval->dyn_cast_svalue_from_bit_vector ()->get_bit_vector ();
    8433            4 :   ASSERT_EQ (new_p_bv.get_kind (), symbolic::bit_vector::kind::poisoned);
    8434            4 :   ASSERT_EQ (new_p_bv.dyn_cast_poisoned_bit_vector ()->get_poison_kind (),
    8435              :              poison_kind::popped_stack);
    8436              : 
    8437              :   /* Verify that q still points to p, in spite of the region
    8438              :      renumbering.  */
    8439            4 :   const svalue *new_q_sval = model.get_rvalue (q, &ctxt);
    8440            4 :   ASSERT_EQ (new_q_sval->get_kind (), SK_POINTER);
    8441            4 :   ASSERT_SAME_SYMBOLIC_NODE
    8442              :     (new_q_sval->maybe_get_symbolic_pointer ()->get_base_region (),
    8443              :      *model.get_lvalue (p, &ctxt));
    8444              : 
    8445              :   /* Verify that top of stack has been updated.  */
    8446            4 :   ASSERT_EQ (model.get_current_frame (), parent_frame_reg);
    8447              : 
    8448              :   /* Verify locals in parent frame.  */
    8449              :   /* Verify "a" still has its value.  */
    8450            4 :   const svalue *new_a_sval = model.get_rvalue (a, &ctxt);
    8451            4 :   ASSERT_EQ (new_a_sval->get_kind (), SK_CONSTANT);
    8452            4 :   ASSERT_EQ (new_a_sval->dyn_cast_constant_svalue ()->get_constant (),
    8453              :              int_42);
    8454              :   /* Verify "b" still has its constraint.  */
    8455            4 :   ASSERT_EQ (model.eval_condition (b, LT_EXPR, int_10, &ctxt),
    8456              :              tristate (tristate::TS_TRUE));
    8457            4 : }
    8458              : 
    8459              : /* Verify that get_representative_path_var works as expected, that
    8460              :    we can map from regions to parms and back within a recursive call
    8461              :    stack.  */
    8462              : 
    8463              : static void
    8464            4 : test_get_representative_path_var ()
    8465              : {
    8466            4 :   auto_vec <tree> param_types;
    8467            4 :   tree fndecl = make_fndecl (integer_type_node,
    8468              :                              "factorial",
    8469              :                              param_types);
    8470            4 :   allocate_struct_function (fndecl, true);
    8471              : 
    8472              :   /* Parm "n".  */
    8473            4 :   tree n = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8474              :                        get_identifier ("n"),
    8475              :                        integer_type_node);
    8476            4 :   DECL_CONTEXT (n) = fndecl;
    8477              : 
    8478            4 :   symbolic::node_manager node_mgr;
    8479            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8480            4 :   test_region_model_context ctxt;
    8481            4 :   region_model model (node_mgr);
    8482              : 
    8483              :   /* Push 5 stack frames for "factorial", each with a param  */
    8484            4 :   auto_vec<const region *> parm_regs;
    8485            4 :   auto_vec<const svalue *> parm_svals;
    8486           24 :   for (int depth = 0; depth < 5; depth++)
    8487              :     {
    8488           20 :       const region *frame_n_reg
    8489           20 :         = model.push_frame (*DECL_STRUCT_FUNCTION (fndecl),
    8490              :                             nullptr, nullptr, &ctxt);
    8491           20 :       const region *parm_n_reg = model.get_lvalue (path_var (n, depth), &ctxt);
    8492           20 :       parm_regs.safe_push (parm_n_reg);
    8493              : 
    8494           20 :       ASSERT_EQ (parm_n_reg->get_parent_region (), frame_n_reg);
    8495           20 :       const svalue *sval_n = mgr.get_or_create_initial_value (parm_n_reg);
    8496           20 :       parm_svals.safe_push (sval_n);
    8497              :     }
    8498              : 
    8499              :   /* Verify that we can recognize that the regions are the parms,
    8500              :      at every depth.  */
    8501           24 :   for (int depth = 0; depth < 5; depth++)
    8502              :     {
    8503           20 :       {
    8504           20 :         value_set visited;
    8505           40 :         ASSERT_EQ (model.get_representative_path_var (parm_regs[depth],
    8506              :                                                       &visited,
    8507              :                                                       nullptr),
    8508              :                    path_var (n, depth + 1));
    8509           20 :       }
    8510              :       /* ...and that we can lookup lvalues for locals for all frames,
    8511              :          not just the top.  */
    8512           20 :       ASSERT_EQ (model.get_lvalue (path_var (n, depth), nullptr),
    8513              :                  parm_regs[depth]);
    8514              :       /* ...and that we can locate the svalues.  */
    8515           20 :       {
    8516           20 :         value_set visited;
    8517           40 :         ASSERT_EQ (model.get_representative_path_var (parm_svals[depth],
    8518              :                                                       &visited,
    8519              :                                                       nullptr),
    8520              :                    path_var (n, depth + 1));
    8521           20 :       }
    8522              :     }
    8523            4 : }
    8524              : 
    8525              : /* Ensure that region_model::operator== works as expected.  */
    8526              : 
    8527              : static void
    8528            4 : test_equality_1 ()
    8529              : {
    8530            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    8531            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    8532              : 
    8533              : /* Verify that "empty" region_model instances are equal to each other.  */
    8534            4 :   symbolic::node_manager node_mgr;
    8535            4 :   region_model model0 (node_mgr);
    8536            4 :   region_model model1 (node_mgr);
    8537            4 :   ASSERT_EQ (model0, model1);
    8538              : 
    8539              :   /* Verify that setting state in model1 makes the models non-equal.  */
    8540            4 :   tree x = build_global_decl ("x", integer_type_node);
    8541            4 :   model0.set_value (x, int_42, nullptr);
    8542            4 :   ASSERT_EQ (model0.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
    8543            4 :   ASSERT_NE (model0, model1);
    8544              : 
    8545              :   /* Verify the copy-ctor.  */
    8546            4 :   region_model model2 (model0);
    8547            4 :   ASSERT_EQ (model0, model2);
    8548            4 :   ASSERT_EQ (model2.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
    8549            4 :   ASSERT_NE (model1, model2);
    8550              : 
    8551              :   /* Verify that models obtained from copy-ctor are independently editable
    8552              :      w/o affecting the original model.  */
    8553            4 :   model2.set_value (x, int_17, nullptr);
    8554            4 :   ASSERT_NE (model0, model2);
    8555            4 :   ASSERT_EQ (model2.get_rvalue (x, nullptr)->maybe_get_constant (), int_17);
    8556            4 :   ASSERT_EQ (model0.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
    8557            4 : }
    8558              : 
    8559              : /* Verify that region models for
    8560              :       x = 42; y = 113;
    8561              :    and
    8562              :       y = 113; x = 42;
    8563              :    are equal.  */
    8564              : 
    8565              : static void
    8566            4 : test_canonicalization_2 ()
    8567              : {
    8568            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    8569            4 :   tree int_113 = build_int_cst (integer_type_node, 113);
    8570            4 :   tree x = build_global_decl ("x", integer_type_node);
    8571            4 :   tree y = build_global_decl ("y", integer_type_node);
    8572              : 
    8573            4 :   symbolic::node_manager node_mgr;
    8574            4 :   region_model model0 (node_mgr);
    8575            4 :   model0.set_value (model0.get_lvalue (x, nullptr),
    8576              :                     model0.get_rvalue (int_42, nullptr),
    8577              :                     nullptr);
    8578            4 :   model0.set_value (model0.get_lvalue (y, nullptr),
    8579              :                     model0.get_rvalue (int_113, nullptr),
    8580              :                     nullptr);
    8581              : 
    8582            4 :   region_model model1 (node_mgr);
    8583            4 :   model1.set_value (model1.get_lvalue (y, nullptr),
    8584              :                     model1.get_rvalue (int_113, nullptr),
    8585              :                     nullptr);
    8586            4 :   model1.set_value (model1.get_lvalue (x, nullptr),
    8587              :                     model1.get_rvalue (int_42, nullptr),
    8588              :                     nullptr);
    8589              : 
    8590            4 :   ASSERT_EQ (model0, model1);
    8591            4 : }
    8592              : 
    8593              : /* Verify that constraints for
    8594              :      x > 3 && y > 42
    8595              :    and
    8596              :      y > 42 && x > 3
    8597              :    are equal after canonicalization.  */
    8598              : 
    8599              : static void
    8600            4 : test_canonicalization_3 ()
    8601              : {
    8602            4 :   tree int_3 = build_int_cst (integer_type_node, 3);
    8603            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    8604            4 :   tree x = build_global_decl ("x", integer_type_node);
    8605            4 :   tree y = build_global_decl ("y", integer_type_node);
    8606              : 
    8607            4 :   symbolic::node_manager node_mgr;
    8608            4 :   region_model model0 (node_mgr);
    8609            4 :   model0.add_constraint (x, GT_EXPR, int_3, nullptr);
    8610            4 :   model0.add_constraint (y, GT_EXPR, int_42, nullptr);
    8611              : 
    8612            4 :   region_model model1 (node_mgr);
    8613            4 :   model1.add_constraint (y, GT_EXPR, int_42, nullptr);
    8614            4 :   model1.add_constraint (x, GT_EXPR, int_3, nullptr);
    8615              : 
    8616            4 :   model0.canonicalize ();
    8617            4 :   model1.canonicalize ();
    8618            4 :   ASSERT_EQ (model0, model1);
    8619            4 : }
    8620              : 
    8621              : /* Verify that we can canonicalize a model containing NaN and other real
    8622              :    constants.  */
    8623              : 
    8624              : static void
    8625            4 : test_canonicalization_4 ()
    8626              : {
    8627            4 :   auto_vec<tree> csts;
    8628            4 :   append_interesting_constants (&csts);
    8629              : 
    8630            4 :   symbolic::node_manager node_mgr;
    8631            4 :   region_model model (node_mgr);
    8632              : 
    8633           60 :   for (tree cst : csts)
    8634           48 :     model.get_rvalue (cst, nullptr);
    8635              : 
    8636            4 :   model.canonicalize ();
    8637            4 : }
    8638              : 
    8639              : /* Assert that if we have two region_model instances
    8640              :    with values VAL_A and VAL_B for EXPR that they are
    8641              :    mergeable.  Write the merged model to *OUT_MERGED_MODEL,
    8642              :    and the merged svalue ptr to *OUT_MERGED_SVALUE.
    8643              :    If VAL_A or VAL_B are nullptr_TREE, don't populate EXPR
    8644              :    for that region_model.  */
    8645              : 
    8646              : static void
    8647           20 : assert_region_models_merge (tree expr, tree val_a, tree val_b,
    8648              :                             region_model *out_merged_model,
    8649              :                             const svalue **out_merged_svalue)
    8650              : {
    8651           20 :   region_model_manager *mgr = out_merged_model->get_manager ();
    8652           20 :   auto &node_mgr = mgr->get_node_manager ();
    8653           20 :   program_point point (program_point::origin (*mgr));
    8654           20 :   test_region_model_context ctxt;
    8655           20 :   region_model model0 (node_mgr);
    8656           20 :   region_model model1 (node_mgr);
    8657           20 :   if (val_a)
    8658           16 :     model0.set_value (model0.get_lvalue (expr, &ctxt),
    8659              :                       model0.get_rvalue (val_a, &ctxt),
    8660              :                       &ctxt);
    8661           20 :   if (val_b)
    8662           16 :     model1.set_value (model1.get_lvalue (expr, &ctxt),
    8663              :                       model1.get_rvalue (val_b, &ctxt),
    8664              :                       &ctxt);
    8665              : 
    8666              :   /* They should be mergeable.  */
    8667           20 :   ASSERT_TRUE (model0.can_merge_with_p (model1, point, out_merged_model));
    8668           20 :   *out_merged_svalue = out_merged_model->get_rvalue (expr, &ctxt);
    8669           20 : }
    8670              : 
    8671              : /* Verify that we can merge region_model instances.  */
    8672              : 
    8673              : static void
    8674            4 : test_state_merging ()
    8675              : {
    8676            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    8677            4 :   tree int_113 = build_int_cst (integer_type_node, 113);
    8678            4 :   tree x = build_global_decl ("x", integer_type_node);
    8679            4 :   tree y = build_global_decl ("y", integer_type_node);
    8680            4 :   tree z = build_global_decl ("z", integer_type_node);
    8681            4 :   tree p = build_global_decl ("p", ptr_type_node);
    8682              : 
    8683            4 :   tree addr_of_y = build1 (ADDR_EXPR, ptr_type_node, y);
    8684            4 :   tree addr_of_z = build1 (ADDR_EXPR, ptr_type_node, z);
    8685              : 
    8686            4 :   auto_vec <tree> param_types;
    8687            4 :   tree test_fndecl = make_fndecl (integer_type_node, "test_fn", param_types);
    8688            4 :   allocate_struct_function (test_fndecl, true);
    8689              : 
    8690              :   /* Param "a".  */
    8691            4 :   tree a = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8692              :                        get_identifier ("a"),
    8693              :                        integer_type_node);
    8694            4 :   DECL_CONTEXT (a) = test_fndecl;
    8695            4 :   tree addr_of_a = build1 (ADDR_EXPR, ptr_type_node, a);
    8696              : 
    8697              :   /* Param "q", a pointer.  */
    8698            4 :   tree q = build_decl (UNKNOWN_LOCATION, PARM_DECL,
    8699              :                        get_identifier ("q"),
    8700              :                        ptr_type_node);
    8701            4 :   DECL_CONTEXT (q) = test_fndecl;
    8702              : 
    8703            4 :   symbolic::node_manager node_mgr;
    8704            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    8705            4 :   program_point point (program_point::origin (mgr));
    8706              : 
    8707            4 :   {
    8708            4 :     region_model model0 (node_mgr);
    8709            4 :     region_model model1 (node_mgr);
    8710            4 :     region_model merged (node_mgr);
    8711              :     /* Verify empty models can be merged.  */
    8712            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8713            4 :     ASSERT_EQ (model0, merged);
    8714            4 :   }
    8715              : 
    8716              :   /* Verify that we can merge two contradictory constraints on the
    8717              :      value for a global.  */
    8718              :   /* TODO: verify that the merged model doesn't have a value for
    8719              :      the global  */
    8720            4 :   {
    8721            4 :     region_model model0 (node_mgr);
    8722            4 :     region_model model1 (node_mgr);
    8723            4 :     region_model merged (node_mgr);
    8724            4 :     test_region_model_context ctxt;
    8725            4 :     model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
    8726            4 :     model1.add_constraint (x, EQ_EXPR, int_113, &ctxt);
    8727            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8728            4 :     ASSERT_NE (model0, merged);
    8729            4 :     ASSERT_NE (model1, merged);
    8730            4 :   }
    8731              : 
    8732              :   /* Verify handling of a PARM_DECL.  */
    8733            4 :   {
    8734            4 :     test_region_model_context ctxt;
    8735            4 :     region_model model0 (node_mgr);
    8736            4 :     region_model model1 (node_mgr);
    8737            4 :     ASSERT_EQ (model0.get_stack_depth (), 0);
    8738            4 :     model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    8739              :                        nullptr, nullptr, &ctxt);
    8740            4 :     ASSERT_EQ (model0.get_stack_depth (), 1);
    8741            4 :     model1.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    8742              :                        nullptr, nullptr, &ctxt);
    8743              : 
    8744            4 :     placeholder_svalue test_sval (mgr.alloc_node_id (),
    8745            4 :                                   integer_type_node, "test sval");
    8746            4 :     model0.set_value (model0.get_lvalue (a, &ctxt), &test_sval, &ctxt);
    8747            4 :     model1.set_value (model1.get_lvalue (a, &ctxt), &test_sval, &ctxt);
    8748            4 :     ASSERT_EQ (model0, model1);
    8749              : 
    8750              :     /* They should be mergeable, and the result should be the same.  */
    8751            4 :     region_model merged (node_mgr);
    8752            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8753            4 :     ASSERT_EQ (model0, merged);
    8754              :     /* In particular, "a" should have the placeholder value.  */
    8755            4 :     ASSERT_EQ (merged.get_rvalue (a, &ctxt), &test_sval);
    8756            4 :   }
    8757              : 
    8758              :   /* Verify handling of a global.  */
    8759            4 :   {
    8760            4 :     test_region_model_context ctxt;
    8761            4 :     region_model model0 (node_mgr);
    8762            4 :     region_model model1 (node_mgr);
    8763              : 
    8764            4 :     placeholder_svalue test_sval (mgr.alloc_node_id (),
    8765            4 :                                   integer_type_node, "test sval");
    8766            4 :     model0.set_value (model0.get_lvalue (x, &ctxt), &test_sval, &ctxt);
    8767            4 :     model1.set_value (model1.get_lvalue (x, &ctxt), &test_sval, &ctxt);
    8768            4 :     ASSERT_EQ (model0, model1);
    8769              : 
    8770              :     /* They should be mergeable, and the result should be the same.  */
    8771            4 :     region_model merged (node_mgr);
    8772            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8773            4 :     ASSERT_EQ (model0, merged);
    8774              :     /* In particular, "x" should have the placeholder value.  */
    8775            4 :     ASSERT_EQ (merged.get_rvalue (x, &ctxt), &test_sval);
    8776            4 :   }
    8777              : 
    8778              :   /* Use global-handling to verify various combinations of values.  */
    8779              : 
    8780              :   /* Two equal constant values.  */
    8781            4 :   {
    8782            4 :     region_model merged (node_mgr);
    8783            4 :     const svalue *merged_x_sval;
    8784            4 :     assert_region_models_merge (x, int_42, int_42, &merged, &merged_x_sval);
    8785              : 
    8786              :     /* In particular, there should be a constant value for "x".  */
    8787            4 :     ASSERT_EQ (merged_x_sval->get_kind (), SK_CONSTANT);
    8788            4 :     ASSERT_EQ (merged_x_sval->dyn_cast_constant_svalue ()->get_constant (),
    8789              :                int_42);
    8790            4 :   }
    8791              : 
    8792              :   /* Two non-equal constant values.  */
    8793            4 :   {
    8794            4 :     region_model merged (node_mgr);
    8795            4 :     const svalue *merged_x_sval;
    8796            4 :     assert_region_models_merge (x, int_42, int_113, &merged, &merged_x_sval);
    8797              : 
    8798              :     /* In particular, there should be a "widening" value for "x".  */
    8799            4 :     ASSERT_EQ (merged_x_sval->get_kind (), SK_WIDENING);
    8800            4 :   }
    8801              : 
    8802              :   /* Initial and constant.  */
    8803            4 :   {
    8804            4 :     region_model merged (node_mgr);
    8805            4 :     const svalue *merged_x_sval;
    8806            4 :     assert_region_models_merge (x, NULL_TREE, int_113, &merged, &merged_x_sval);
    8807              : 
    8808              :     /* In particular, there should be an unknown value for "x".  */
    8809            4 :     ASSERT_EQ (merged_x_sval->get_kind (), SK_UNKNOWN);
    8810            4 :   }
    8811              : 
    8812              :   /* Constant and initial.  */
    8813            4 :   {
    8814            4 :     region_model merged (node_mgr);
    8815            4 :     const svalue *merged_x_sval;
    8816            4 :     assert_region_models_merge (x, int_42, NULL_TREE, &merged, &merged_x_sval);
    8817              : 
    8818              :     /* In particular, there should be an unknown value for "x".  */
    8819            4 :     ASSERT_EQ (merged_x_sval->get_kind (), SK_UNKNOWN);
    8820            4 :   }
    8821              : 
    8822              :   /* Unknown and constant.  */
    8823              :   // TODO
    8824              : 
    8825              :   /* Pointers: NULL and NULL.  */
    8826              :   // TODO
    8827              : 
    8828              :   /* Pointers: NULL and non-NULL.  */
    8829              :   // TODO
    8830              : 
    8831              :   /* Pointers: non-NULL and non-NULL: ptr to a local.  */
    8832            4 :   {
    8833            4 :     region_model model0 (node_mgr);
    8834            4 :     model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    8835              :                        nullptr, nullptr, nullptr);
    8836            4 :     model0.set_value (model0.get_lvalue (p, nullptr),
    8837              :                       model0.get_rvalue (addr_of_a, nullptr), nullptr);
    8838              : 
    8839            4 :     region_model model1 (model0);
    8840            4 :     ASSERT_EQ (model0, model1);
    8841              : 
    8842              :     /* They should be mergeable, and the result should be the same.  */
    8843            4 :     region_model merged (node_mgr);
    8844            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8845            4 :     ASSERT_EQ (model0, merged);
    8846            4 :   }
    8847              : 
    8848              :   /* Pointers: non-NULL and non-NULL: ptr to a global.  */
    8849            4 :   {
    8850            4 :     region_model merged (node_mgr);
    8851              :     /* p == &y in both input models.  */
    8852            4 :     const svalue *merged_p_sval;
    8853            4 :     assert_region_models_merge (p, addr_of_y, addr_of_y, &merged,
    8854              :                                 &merged_p_sval);
    8855              : 
    8856              :     /* We should get p == &y in the merged model.  */
    8857            4 :     auto *sym_ptr = merged_p_sval->maybe_get_symbolic_pointer ();
    8858            4 :     ASSERT_NE (sym_ptr, nullptr);
    8859            4 :     ASSERT_SAME_SYMBOLIC_NODE (sym_ptr->get_base_region (),
    8860              :                                *merged.get_lvalue (y, nullptr));
    8861            4 :     ASSERT_TRUE (sym_ptr->get_byte_offset ().is_zero_p ());
    8862            4 :   }
    8863              : 
    8864              :   /* Pointers: non-NULL ptrs to different globals should not merge;
    8865              :      see e.g. gcc.dg/analyzer/torture/uninit-pr108725.c  */
    8866            4 :   {
    8867            4 :     region_model merged_model (node_mgr);
    8868            4 :     program_point point (program_point::origin (mgr));
    8869            4 :     test_region_model_context ctxt;
    8870              :     /* p == &y vs p == &z in the input models.  */
    8871            4 :     region_model model0 (node_mgr);
    8872            4 :     region_model model1 (node_mgr);
    8873            4 :     model0.set_value (model0.get_lvalue (p, &ctxt),
    8874              :                       model0.get_rvalue (addr_of_y, &ctxt),
    8875              :                       &ctxt);
    8876            4 :     model1.set_value (model1.get_lvalue (p, &ctxt),
    8877              :                       model1.get_rvalue (addr_of_z, &ctxt),
    8878              :                       &ctxt);
    8879              :     /* They should not be mergeable.  */
    8880            4 :     ASSERT_FALSE (model0.can_merge_with_p (model1, point, &merged_model));
    8881            4 :   }
    8882              : 
    8883              :   /* Pointers: non-NULL and non-NULL: ptr to a heap region.  */
    8884            4 :   {
    8885            4 :     test_region_model_context ctxt;
    8886            4 :     region_model model0 (node_mgr);
    8887            4 :     tree size = build_int_cst (size_type_node, 1024);
    8888            4 :     const svalue *size_sval = mgr.get_or_create_constant_svalue (size);
    8889            4 :     const region *new_reg
    8890            4 :       = model0.get_or_create_region_for_heap_alloc (size_sval, &ctxt);
    8891            4 :     const svalue *ptr_sval = mgr.get_ptr_svalue (ptr_type_node, new_reg);
    8892            4 :     model0.set_value (model0.get_lvalue (p, &ctxt),
    8893              :                       ptr_sval, &ctxt);
    8894              : 
    8895            4 :     region_model model1 (model0);
    8896              : 
    8897            4 :     ASSERT_EQ (model0, model1);
    8898              : 
    8899            4 :     region_model merged (node_mgr);
    8900            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8901              : 
    8902              :     /* The merged model ought to be identical.  */
    8903            4 :     ASSERT_EQ (model0, merged);
    8904            4 :   }
    8905              : 
    8906              :   /* Two regions sharing the same placeholder svalue should continue sharing
    8907              :      it after self-merger.  */
    8908            4 :   {
    8909            4 :     test_region_model_context ctxt;
    8910            4 :     region_model model0 (node_mgr);
    8911            4 :     placeholder_svalue placeholder_sval (mgr.alloc_node_id (),
    8912            4 :                                          integer_type_node, "test");
    8913            4 :     model0.set_value (model0.get_lvalue (x, &ctxt),
    8914              :                       &placeholder_sval, &ctxt);
    8915            4 :     model0.set_value (model0.get_lvalue (y, &ctxt), &placeholder_sval, &ctxt);
    8916            4 :     region_model model1 (model0);
    8917              : 
    8918              :     /* They should be mergeable, and the result should be the same.  */
    8919            4 :     region_model merged (node_mgr);
    8920            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8921            4 :     ASSERT_EQ (model0, merged);
    8922              : 
    8923              :     /* In particular, we should have x == y.  */
    8924            4 :     ASSERT_EQ (merged.eval_condition (x, EQ_EXPR, y, &ctxt),
    8925              :                tristate (tristate::TS_TRUE));
    8926            4 :   }
    8927              : 
    8928            4 :   {
    8929            4 :     region_model model0 (node_mgr);
    8930            4 :     region_model model1 (node_mgr);
    8931            4 :     test_region_model_context ctxt;
    8932            4 :     model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
    8933            4 :     model1.add_constraint (x, NE_EXPR, int_42, &ctxt);
    8934            4 :     region_model merged (node_mgr);
    8935            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8936            4 :   }
    8937              : 
    8938            4 :   {
    8939            4 :     region_model model0 (node_mgr);
    8940            4 :     region_model model1 (node_mgr);
    8941            4 :     test_region_model_context ctxt;
    8942            4 :     model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
    8943            4 :     model1.add_constraint (x, NE_EXPR, int_42, &ctxt);
    8944            4 :     model1.add_constraint (x, EQ_EXPR, int_113, &ctxt);
    8945            4 :     region_model merged (node_mgr);
    8946            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8947            4 :   }
    8948              : 
    8949              :   // TODO: what can't we merge? need at least one such test
    8950              : 
    8951              :   /* TODO: various things
    8952              :      - heap regions
    8953              :      - value merging:
    8954              :        - every combination, but in particular
    8955              :            - pairs of regions
    8956              :    */
    8957              : 
    8958              :   /* Views.  */
    8959            4 :   {
    8960            4 :     test_region_model_context ctxt;
    8961            4 :     region_model model0 (node_mgr);
    8962              : 
    8963            4 :     const region *x_reg = model0.get_lvalue (x, &ctxt);
    8964            4 :     const region *x_as_ptr = mgr.get_cast_region (x_reg, ptr_type_node);
    8965            4 :     model0.set_value (x_as_ptr, model0.get_rvalue (addr_of_y, &ctxt), &ctxt);
    8966              : 
    8967            4 :     region_model model1 (model0);
    8968            4 :     ASSERT_EQ (model1, model0);
    8969              : 
    8970              :     /* They should be mergeable, and the result should be the same.  */
    8971            4 :     region_model merged (node_mgr);
    8972            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    8973            4 :   }
    8974              : 
    8975              :   /* Verify that we can merge a model in which a local in an older stack
    8976              :      frame points to a local in a more recent stack frame.  */
    8977            4 :   {
    8978            4 :     region_model model0 (node_mgr);
    8979            4 :     model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    8980              :                        nullptr, nullptr, nullptr);
    8981            4 :     const region *q_in_first_frame = model0.get_lvalue (q, nullptr);
    8982              : 
    8983              :     /* Push a second frame.  */
    8984            4 :     const region *reg_2nd_frame
    8985            4 :       = model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    8986              :                            nullptr, nullptr, nullptr);
    8987              : 
    8988              :     /* Have a pointer in the older frame point to a local in the
    8989              :        more recent frame.  */
    8990            4 :     const svalue *sval_ptr = model0.get_rvalue (addr_of_a, nullptr);
    8991            4 :     model0.set_value (q_in_first_frame, sval_ptr, nullptr);
    8992              : 
    8993              :     /* Verify that it's pointing at the newer frame.  */
    8994            4 :     auto *sym_ptr = sval_ptr->maybe_get_symbolic_pointer ();
    8995            4 :     ASSERT_NE (sym_ptr, nullptr);
    8996            4 :     ASSERT_SAME_SYMBOLIC_NODE
    8997              :       (*sym_ptr->get_base_region ().get_parent_region (),
    8998              :        *reg_2nd_frame);
    8999            4 :     ASSERT_TRUE (sym_ptr->get_byte_offset ().is_zero_p ());
    9000            4 :     model0.canonicalize ();
    9001              : 
    9002            4 :     region_model model1 (model0);
    9003            4 :     ASSERT_EQ (model0, model1);
    9004              : 
    9005              :     /* They should be mergeable, and the result should be the same
    9006              :        (after canonicalization, at least).  */
    9007            4 :     region_model merged (node_mgr);
    9008            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    9009            4 :     merged.canonicalize ();
    9010            4 :     ASSERT_EQ (model0, merged);
    9011            4 :   }
    9012              : 
    9013              :   /* Verify that we can merge a model in which a local points to a global.  */
    9014            4 :   {
    9015            4 :     region_model model0 (node_mgr);
    9016            4 :     model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
    9017              :                        nullptr, nullptr, nullptr);
    9018            4 :     model0.set_value (model0.get_lvalue (q, nullptr),
    9019              :                       model0.get_rvalue (addr_of_y, nullptr), nullptr);
    9020              : 
    9021            4 :     region_model model1 (model0);
    9022            4 :     ASSERT_EQ (model0, model1);
    9023              : 
    9024              :     /* They should be mergeable, and the result should be the same
    9025              :        (after canonicalization, at least).  */
    9026            4 :     region_model merged (node_mgr);
    9027            4 :     ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    9028            4 :     ASSERT_EQ (model0, merged);
    9029            4 :   }
    9030            4 : }
    9031              : 
    9032              : /* Verify that constraints are correctly merged when merging region_model
    9033              :    instances.  */
    9034              : 
    9035              : static void
    9036            4 : test_constraint_merging ()
    9037              : {
    9038            4 :   tree int_0 = integer_zero_node;
    9039            4 :   tree int_5 = build_int_cst (integer_type_node, 5);
    9040            4 :   tree x = build_global_decl ("x", integer_type_node);
    9041            4 :   tree y = build_global_decl ("y", integer_type_node);
    9042            4 :   tree z = build_global_decl ("z", integer_type_node);
    9043            4 :   tree n = build_global_decl ("n", integer_type_node);
    9044              : 
    9045            4 :   symbolic::node_manager node_mgr;
    9046            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9047            4 :   test_region_model_context ctxt;
    9048              : 
    9049              :   /* model0: 0 <= (x == y) < n.  */
    9050            4 :   region_model model0 (node_mgr);
    9051            4 :   model0.add_constraint (x, EQ_EXPR, y, &ctxt);
    9052            4 :   model0.add_constraint (x, GE_EXPR, int_0, nullptr);
    9053            4 :   model0.add_constraint (x, LT_EXPR, n, nullptr);
    9054              : 
    9055              :   /* model1: z != 5 && (0 <= x < n).  */
    9056            4 :   region_model model1 (node_mgr);
    9057            4 :   model1.add_constraint (z, NE_EXPR, int_5, nullptr);
    9058            4 :   model1.add_constraint (x, GE_EXPR, int_0, nullptr);
    9059            4 :   model1.add_constraint (x, LT_EXPR, n, nullptr);
    9060              : 
    9061              :   /* They should be mergeable; the merged constraints should
    9062              :      be: (0 <= x < n).  */
    9063            4 :   program_point point (program_point::origin (mgr));
    9064            4 :   region_model merged (node_mgr);
    9065            4 :   ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
    9066              : 
    9067            4 :   ASSERT_EQ (merged.eval_condition (x, GE_EXPR, int_0, &ctxt),
    9068              :              tristate (tristate::TS_TRUE));
    9069            4 :   ASSERT_EQ (merged.eval_condition (x, LT_EXPR, n, &ctxt),
    9070              :              tristate (tristate::TS_TRUE));
    9071              : 
    9072            4 :   ASSERT_EQ (merged.eval_condition (z, NE_EXPR, int_5, &ctxt),
    9073              :              tristate (tristate::TS_UNKNOWN));
    9074            4 :   ASSERT_EQ (merged.eval_condition (x, LT_EXPR, y, &ctxt),
    9075              :              tristate (tristate::TS_UNKNOWN));
    9076            4 : }
    9077              : 
    9078              : /* Verify that widening_svalue::eval_condition_without_cm works as
    9079              :    expected.  */
    9080              : 
    9081              : static void
    9082            4 : test_widening_constraints ()
    9083              : {
    9084            4 :   symbolic::node_manager node_mgr;
    9085            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9086            4 :   const supernode *snode = nullptr;
    9087            4 :   tree int_0 = integer_zero_node;
    9088            4 :   tree int_m1 = build_int_cst (integer_type_node, -1);
    9089            4 :   tree int_1 = integer_one_node;
    9090            4 :   tree int_256 = build_int_cst (integer_type_node, 256);
    9091            4 :   test_region_model_context ctxt;
    9092            4 :   const svalue *int_0_sval = mgr.get_or_create_constant_svalue (int_0);
    9093            4 :   const svalue *int_1_sval = mgr.get_or_create_constant_svalue (int_1);
    9094            4 :   const svalue *w_zero_then_one_sval
    9095            4 :     = mgr.get_or_create_widening_svalue (integer_type_node, snode,
    9096              :                                           int_0_sval, int_1_sval);
    9097            4 :   const widening_svalue *w_zero_then_one
    9098            4 :     = w_zero_then_one_sval->dyn_cast_widening_svalue ();
    9099            4 :   ASSERT_EQ (w_zero_then_one->get_direction (),
    9100              :              widening_svalue::DIR_ASCENDING);
    9101            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_m1),
    9102              :              tristate::TS_FALSE);
    9103            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_0),
    9104              :              tristate::TS_FALSE);
    9105            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_1),
    9106              :              tristate::TS_UNKNOWN);
    9107            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_256),
    9108              :              tristate::TS_UNKNOWN);
    9109              : 
    9110            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_m1),
    9111              :              tristate::TS_FALSE);
    9112            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_0),
    9113              :              tristate::TS_UNKNOWN);
    9114            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_1),
    9115              :              tristate::TS_UNKNOWN);
    9116            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_256),
    9117              :              tristate::TS_UNKNOWN);
    9118              : 
    9119            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_m1),
    9120              :              tristate::TS_TRUE);
    9121            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_0),
    9122              :              tristate::TS_UNKNOWN);
    9123            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_1),
    9124              :              tristate::TS_UNKNOWN);
    9125            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_256),
    9126              :              tristate::TS_UNKNOWN);
    9127              : 
    9128            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_m1),
    9129              :              tristate::TS_TRUE);
    9130            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_0),
    9131              :              tristate::TS_TRUE);
    9132            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_1),
    9133              :              tristate::TS_UNKNOWN);
    9134            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_256),
    9135              :              tristate::TS_UNKNOWN);
    9136              : 
    9137            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_m1),
    9138              :              tristate::TS_FALSE);
    9139            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_0),
    9140              :              tristate::TS_UNKNOWN);
    9141            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_1),
    9142              :              tristate::TS_UNKNOWN);
    9143            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_256),
    9144              :              tristate::TS_UNKNOWN);
    9145              : 
    9146            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_m1),
    9147              :              tristate::TS_TRUE);
    9148            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_0),
    9149              :              tristate::TS_UNKNOWN);
    9150            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_1),
    9151              :              tristate::TS_UNKNOWN);
    9152            4 :   ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_256),
    9153              :              tristate::TS_UNKNOWN);
    9154            4 : }
    9155              : 
    9156              : /* Verify merging constraints for states simulating successive iterations
    9157              :    of a loop.
    9158              :    Simulate:
    9159              :      for (i = 0; i < 256; i++)
    9160              :        [...body...]
    9161              :    i.e. this gimple:.
    9162              :      i_15 = 0;
    9163              :      goto <bb 4>;
    9164              : 
    9165              :    <bb 4> :
    9166              :      i_11 = PHI <i_15(2), i_23(3)>
    9167              :      if (i_11 <= 255)
    9168              :        goto <bb 3>;
    9169              :      else
    9170              :        goto [AFTER LOOP]
    9171              : 
    9172              :    <bb 3> :
    9173              :      [LOOP BODY]
    9174              :      i_23 = i_11 + 1;
    9175              : 
    9176              :    and thus these ops (and resultant states):
    9177              :      i_11 = PHI()
    9178              :        {i_11: 0}
    9179              :      add_constraint (i_11 <= 255) [for the true edge]
    9180              :        {i_11: 0}  [constraint was a no-op]
    9181              :      i_23 = i_11 + 1;
    9182              :        {i_22: 1}
    9183              :      i_11 = PHI()
    9184              :        {i_11: WIDENED (at phi, 0, 1)}
    9185              :      add_constraint (i_11 <= 255) [for the true edge]
    9186              :        {i_11: WIDENED (at phi, 0, 1); WIDENED <= 255}
    9187              :      i_23 = i_11 + 1;
    9188              :        {i_23: (WIDENED (at phi, 0, 1) + 1); WIDENED <= 255}
    9189              :      i_11 = PHI(); merge with state at phi above
    9190              :        {i_11: WIDENED (at phi, 0, 1); WIDENED <= 256}
    9191              :          [changing meaning of "WIDENED" here]
    9192              :      if (i_11 <= 255)
    9193              :         T: {i_11: WIDENED (at phi, 0, 1); WIDENED <= 255}; cache hit
    9194              :         F: {i_11: 256}
    9195              :  */
    9196              : 
    9197              : static void
    9198            4 : test_iteration_1 ()
    9199              : {
    9200            4 :   symbolic::node_manager node_mgr;
    9201            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9202            4 :   program_point point (program_point::origin (mgr));
    9203              : 
    9204            4 :   tree int_0 = integer_zero_node;
    9205            4 :   tree int_1 = integer_one_node;
    9206            4 :   tree int_256 = build_int_cst (integer_type_node, 256);
    9207            4 :   tree i = build_global_decl ("i", integer_type_node);
    9208              : 
    9209            4 :   test_region_model_context ctxt;
    9210              : 
    9211              :   /* model0: i: 0.  */
    9212            4 :   region_model model0 (node_mgr);
    9213            4 :   model0.set_value (i, int_0, &ctxt);
    9214              : 
    9215              :   /* model1: i: 1.  */
    9216            4 :   region_model model1 (node_mgr);
    9217            4 :   model1.set_value (i, int_1, &ctxt);
    9218              : 
    9219              :   /* Should merge "i" to a widened value.  */
    9220            4 :   region_model model2 (node_mgr);
    9221            4 :   ASSERT_TRUE (model1.can_merge_with_p (model0, point, &model2));
    9222            4 :   const svalue *merged_i = model2.get_rvalue (i, &ctxt);
    9223            4 :   ASSERT_EQ (merged_i->get_kind (), SK_WIDENING);
    9224            4 :   const widening_svalue *w = merged_i->dyn_cast_widening_svalue ();
    9225            4 :   ASSERT_EQ (w->get_direction (), widening_svalue::DIR_ASCENDING);
    9226              : 
    9227              :   /* Add constraint: i < 256  */
    9228            4 :   model2.add_constraint (i, LT_EXPR, int_256, &ctxt);
    9229            4 :   ASSERT_EQ (model2.eval_condition (i, LT_EXPR, int_256, &ctxt),
    9230              :              tristate (tristate::TS_TRUE));
    9231            4 :   ASSERT_EQ (model2.eval_condition (i, GE_EXPR, int_0, &ctxt),
    9232              :              tristate (tristate::TS_TRUE));
    9233              : 
    9234              :   /* Try merging with the initial state.  */
    9235            4 :   region_model model3 (node_mgr);
    9236            4 :   ASSERT_TRUE (model2.can_merge_with_p (model0, point, &model3));
    9237              :   /* Merging the merged value with the initial value should be idempotent,
    9238              :      so that the analysis converges.  */
    9239            4 :   ASSERT_EQ (model3.get_rvalue (i, &ctxt), merged_i);
    9240              :   /* Merger of 0 and a widening value with constraint < CST
    9241              :      should retain the constraint, even though it was implicit
    9242              :      for the 0 case.  */
    9243            4 :   ASSERT_EQ (model3.eval_condition (i, LT_EXPR, int_256, &ctxt),
    9244              :              tristate (tristate::TS_TRUE));
    9245              :   /* ...and we should have equality: the analysis should have converged.  */
    9246            4 :   ASSERT_EQ (model3, model2);
    9247              : 
    9248              :   /* "i_23 = i_11 + 1;"  */
    9249            4 :   region_model model4 (model3);
    9250            4 :   ASSERT_EQ (model4, model2);
    9251            4 :   model4.set_value (i, build2 (PLUS_EXPR, integer_type_node, i, int_1), &ctxt);
    9252            4 :   const svalue *plus_one = model4.get_rvalue (i, &ctxt);
    9253            4 :   ASSERT_EQ (plus_one->get_kind (), SK_BINOP);
    9254              : 
    9255              :   /* Try merging with the "i: 1" state.  */
    9256            4 :   region_model model5 (node_mgr);
    9257            4 :   ASSERT_TRUE (model4.can_merge_with_p (model1, point, &model5));
    9258            4 :   ASSERT_EQ (model5.get_rvalue (i, &ctxt), plus_one);
    9259            4 :   ASSERT_EQ (model5, model4);
    9260              : 
    9261              :   /* "i_11 = PHI();" merge with state at phi above.
    9262              :      For i, we should have a merger of WIDENING with WIDENING + 1,
    9263              :      and this should be WIDENING again.  */
    9264            4 :   region_model model6 (node_mgr);
    9265            4 :   ASSERT_TRUE (model5.can_merge_with_p (model2, point, &model6));
    9266            4 :   const svalue *merged_widening = model6.get_rvalue (i, &ctxt);
    9267            4 :   ASSERT_EQ (merged_widening->get_kind (), SK_WIDENING);
    9268            4 : }
    9269              : 
    9270              : /* Verify that if we mark a pointer to a malloc-ed region as non-NULL,
    9271              :    all cast pointers to that region are also known to be non-NULL.  */
    9272              : 
    9273              : static void
    9274            4 : test_malloc_constraints ()
    9275              : {
    9276            4 :   symbolic::node_manager node_mgr;
    9277            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9278            4 :   region_model model (node_mgr);
    9279            4 :   tree p = build_global_decl ("p", ptr_type_node);
    9280            4 :   tree char_star = build_pointer_type (char_type_node);
    9281            4 :   tree q = build_global_decl ("q", char_star);
    9282            4 :   tree null_ptr = build_int_cst (ptr_type_node, 0);
    9283              : 
    9284            4 :   const svalue *size_in_bytes
    9285            4 :     = mgr.get_or_create_unknown_svalue (size_type_node);
    9286            4 :   const region *reg
    9287            4 :     = model.get_or_create_region_for_heap_alloc (size_in_bytes, nullptr);
    9288            4 :   const svalue *sval = mgr.get_ptr_svalue (ptr_type_node, reg);
    9289            4 :   model.set_value (model.get_lvalue (p, nullptr), sval, nullptr);
    9290            4 :   model.set_value (q, p, nullptr);
    9291              : 
    9292            4 :   ASSERT_CONDITION_UNKNOWN (model, p, NE_EXPR, null_ptr);
    9293            4 :   ASSERT_CONDITION_UNKNOWN (model, p, EQ_EXPR, null_ptr);
    9294            4 :   ASSERT_CONDITION_UNKNOWN (model, q, NE_EXPR, null_ptr);
    9295            4 :   ASSERT_CONDITION_UNKNOWN (model, q, EQ_EXPR, null_ptr);
    9296              : 
    9297            4 :   model.add_constraint (p, NE_EXPR, null_ptr, nullptr);
    9298              : 
    9299            4 :   ASSERT_CONDITION_TRUE (model, p, NE_EXPR, null_ptr);
    9300            4 :   ASSERT_CONDITION_FALSE (model, p, EQ_EXPR, null_ptr);
    9301            4 :   ASSERT_CONDITION_TRUE (model, q, NE_EXPR, null_ptr);
    9302            4 :   ASSERT_CONDITION_FALSE (model, q, EQ_EXPR, null_ptr);
    9303            4 : }
    9304              : 
    9305              : /* Smoketest of getting and setting the value of a variable.  */
    9306              : 
    9307              : static void
    9308            4 : test_var ()
    9309              : {
    9310              :   /* "int i;"  */
    9311            4 :   tree i = build_global_decl ("i", integer_type_node);
    9312              : 
    9313            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    9314            4 :   tree int_m3 = build_int_cst (integer_type_node, -3);
    9315              : 
    9316            4 :   symbolic::node_manager node_mgr;
    9317            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9318            4 :   region_model model (node_mgr);
    9319              : 
    9320            4 :   const region *i_reg = model.get_lvalue (i, nullptr);
    9321            4 :   ASSERT_EQ (i_reg->get_kind (), RK_DECL);
    9322              : 
    9323              :   /* Reading "i" should give a symbolic "initial value".  */
    9324            4 :   const svalue *sval_init = model.get_rvalue (i, nullptr);
    9325            4 :   ASSERT_EQ (sval_init->get_kind (), SK_INITIAL);
    9326            4 :   ASSERT_EQ (sval_init->dyn_cast_initial_svalue ()->get_region (), i_reg);
    9327              :   /* ..and doing it again should give the same "initial value".  */
    9328            4 :   ASSERT_EQ (model.get_rvalue (i, nullptr), sval_init);
    9329              : 
    9330              :   /* "i = 17;".  */
    9331            4 :   model.set_value (i, int_17, nullptr);
    9332            4 :   ASSERT_EQ (model.get_rvalue (i, nullptr),
    9333              :              model.get_rvalue (int_17, nullptr));
    9334              : 
    9335              :   /* "i = -3;".  */
    9336            4 :   model.set_value (i, int_m3, nullptr);
    9337            4 :   ASSERT_EQ (model.get_rvalue (i, nullptr),
    9338              :              model.get_rvalue (int_m3, nullptr));
    9339              : 
    9340              :   /* Verify get_memory_range for "i".  */
    9341            4 :   {
    9342            4 :     auto mem_range = i_reg->get_memory_range (mgr);
    9343            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9344              :       (mem_range.get_base_region (),
    9345              :        *i_reg);
    9346            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9347              :       (mem_range.get_start_offset (),
    9348              :        node_mgr.get_scalars ().get_bits ().get_concrete (0_bits));
    9349              :   }
    9350            4 : }
    9351              : 
    9352              : static void
    9353            4 : test_array_2 ()
    9354              : {
    9355              :   /* "int arr[10];"  */
    9356            4 :   tree tlen = size_int (10);
    9357            4 :   tree arr_type
    9358            4 :     = build_array_type (integer_type_node, build_index_type (tlen));
    9359            4 :   tree arr = build_global_decl ("arr", arr_type);
    9360              : 
    9361              :   /* "int i;"  */
    9362            4 :   tree i = build_global_decl ("i", integer_type_node);
    9363              : 
    9364            4 :   tree int_0 = integer_zero_node;
    9365            4 :   tree int_1 = integer_one_node;
    9366              : 
    9367            4 :   tree arr_0 = build4 (ARRAY_REF, integer_type_node,
    9368              :                        arr, int_0, NULL_TREE, NULL_TREE);
    9369            4 :   tree arr_1 = build4 (ARRAY_REF, integer_type_node,
    9370              :                        arr, int_1, NULL_TREE, NULL_TREE);
    9371            4 :   tree arr_i = build4 (ARRAY_REF, integer_type_node,
    9372              :                        arr, i, NULL_TREE, NULL_TREE);
    9373              : 
    9374            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    9375            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    9376            4 :   tree int_m3 = build_int_cst (integer_type_node, -3);
    9377              : 
    9378            4 :   symbolic::node_manager node_mgr;
    9379            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9380            4 :   auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
    9381            4 :   auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
    9382            4 :   region_model model (node_mgr);
    9383              :   /* "arr[0] = 17;".  */
    9384            4 :   model.set_value (arr_0, int_17, nullptr);
    9385              :   /* "arr[1] = -3;".  */
    9386            4 :   model.set_value (arr_1, int_m3, nullptr);
    9387              : 
    9388            4 :   ASSERT_EQ (model.get_rvalue (arr_0, nullptr),
    9389              :              model.get_rvalue (int_17, nullptr));
    9390            4 :   ASSERT_EQ (model.get_rvalue (arr_1, nullptr),
    9391              :              model.get_rvalue (int_m3, nullptr));
    9392              : 
    9393              :   /* Overwrite a pre-existing binding: "arr[1] = 42;".  */
    9394            4 :   model.set_value (arr_1, int_42, nullptr);
    9395            4 :   ASSERT_EQ (model.get_rvalue (arr_1, nullptr),
    9396              :              model.get_rvalue (int_42, nullptr));
    9397              : 
    9398              :   /* Verify get_memory_offset for "arr[0]".  */
    9399            4 :   {
    9400            4 :     const region *arr_0_reg = model.get_lvalue (arr_0, nullptr);
    9401            4 :     auto mem_offset = arr_0_reg->get_memory_offset (mgr);
    9402            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_base_region (),
    9403              :                                *model.get_lvalue (arr, nullptr));
    9404            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_bit_offset (),
    9405              :                                bit_mgr.get_concrete (0_bits));
    9406            4 :     auto mem_range = arr_0_reg->get_memory_range (mgr);
    9407           16 :     ASSERT_EQ
    9408              :       (mem_range.get_bit_range (),
    9409              :        symbolic_from_concrete (concrete_bit_range (0_bits, int_size_bits),
    9410              :                                bit_mgr));
    9411            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9412              :       (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
    9413              :        arr_0_reg);
    9414              :   }
    9415              : 
    9416              :   /* Verify get_memory_offset for "arr[1]".  */
    9417            4 :   {
    9418            4 :     const region *arr_1_reg = model.get_lvalue (arr_1, nullptr);
    9419            4 :     auto mem_offset = arr_1_reg->get_memory_offset (mgr);
    9420            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9421              :       (mem_offset.get_base_region (),
    9422              :        *model.get_lvalue (arr, nullptr));
    9423            4 :     auto mem_range = arr_1_reg->get_memory_range (mgr);
    9424           16 :     ASSERT_EQ
    9425              :       (mem_range.get_bit_range (),
    9426              :        symbolic_from_concrete (concrete_bit_range (int_size_bits, int_size_bits),
    9427              :                                bit_mgr));
    9428            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9429              :       (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
    9430              :        arr_1_reg);
    9431              :   }
    9432              : 
    9433              :   /* Verify get_memory_offset for "arr[i]".  */
    9434            4 :   {
    9435            4 :     const region *arr_i_reg = model.get_lvalue (arr_i, nullptr);
    9436            4 :     auto mem_offset = arr_i_reg->get_memory_offset (mgr);
    9437            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_base_region (),
    9438              :                                *model.get_lvalue (arr, nullptr));
    9439            4 :     auto mem_range = arr_i_reg->get_memory_range (mgr);
    9440            8 :     ASSERT_EQ
    9441              :       (mem_range.get_bit_range (),
    9442              :        symbolic_bit_range (mem_offset.get_bit_offset (),
    9443              :                            bit_mgr.get_concrete (int_size_bits)));
    9444            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9445              :       (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
    9446              :        arr_i_reg);
    9447              :   }
    9448              : 
    9449              :   /* "arr[i] = i;" - this should remove the earlier bindings.  */
    9450            4 :   model.set_value (arr_i, i, nullptr);
    9451            4 :   ASSERT_EQ (model.get_rvalue (arr_i, nullptr), model.get_rvalue (i, nullptr));
    9452            4 :   ASSERT_EQ (model.get_rvalue (arr_0, nullptr)->get_kind (), SK_UNKNOWN);
    9453              : 
    9454              :   /* "arr[0] = 17;" - this should remove the arr[i] binding.  */
    9455            4 :   model.set_value (arr_0, int_17, nullptr);
    9456            4 :   ASSERT_EQ (model.get_rvalue (arr_0, nullptr),
    9457              :              model.get_rvalue (int_17, nullptr));
    9458            4 :   ASSERT_EQ (model.get_rvalue (arr_i, nullptr)->get_kind (), SK_UNKNOWN);
    9459            4 : }
    9460              : 
    9461              : /* Smoketest of dereferencing a pointer via MEM_REF.  */
    9462              : 
    9463              : static void
    9464            4 : test_mem_ref ()
    9465              : {
    9466              :   /*
    9467              :     x = 17;
    9468              :     p = &x;
    9469              :     *p;
    9470              :    */
    9471            4 :   tree x = build_global_decl ("x", integer_type_node);
    9472            4 :   tree int_star = build_pointer_type (integer_type_node);
    9473            4 :   tree p = build_global_decl ("p", int_star);
    9474              : 
    9475            4 :   tree int_17 = build_int_cst (integer_type_node, 17);
    9476            4 :   tree addr_of_x = build1 (ADDR_EXPR, int_star, x);
    9477            4 :   tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
    9478            4 :   tree offset_0 = build_int_cst (ptype, 0);
    9479            4 :   tree star_p = build2 (MEM_REF, integer_type_node, p, offset_0);
    9480              : 
    9481            4 :   symbolic::node_manager node_mgr;
    9482            4 :   region_model model (node_mgr);
    9483              : 
    9484              :   /* "x = 17;".  */
    9485            4 :   model.set_value (x, int_17, nullptr);
    9486              : 
    9487              :   /* "p = &x;".  */
    9488            4 :   model.set_value (p, addr_of_x, nullptr);
    9489              : 
    9490            4 :   const svalue *sval = model.get_rvalue (star_p, nullptr);
    9491            4 :   ASSERT_EQ (sval->maybe_get_constant (), int_17);
    9492            4 : }
    9493              : 
    9494              : /* Test for a POINTER_PLUS_EXPR followed by a MEM_REF.
    9495              :    Analogous to this code:
    9496              :      void test_6 (int a[10])
    9497              :      {
    9498              :        __analyzer_eval (a[3] == 42); [should be UNKNOWN]
    9499              :        a[3] = 42;
    9500              :        __analyzer_eval (a[3] == 42); [should be TRUE]
    9501              :      }
    9502              :    from data-model-1.c, which looks like this at the gimple level:
    9503              :        # __analyzer_eval (a[3] == 42); [should be UNKNOWN]
    9504              :        int *_1 = a_10(D) + 12;   # POINTER_PLUS_EXPR
    9505              :        int _2 = *_1;             # MEM_REF
    9506              :        _Bool _3 = _2 == 42;
    9507              :        int _4 = (int) _3;
    9508              :        __analyzer_eval (_4);
    9509              : 
    9510              :        # a[3] = 42;
    9511              :        int *_5 = a_10(D) + 12;   # POINTER_PLUS_EXPR
    9512              :        *_5 = 42;                 # MEM_REF
    9513              : 
    9514              :        # __analyzer_eval (a[3] == 42); [should be TRUE]
    9515              :        int *_6 = a_10(D) + 12;   # POINTER_PLUS_EXPR
    9516              :        int _7 = *_6;             # MEM_REF
    9517              :        _Bool _8 = _7 == 42;
    9518              :        int _9 = (int) _8;
    9519              :        __analyzer_eval (_9);  */
    9520              : 
    9521              : static void
    9522            4 : test_POINTER_PLUS_EXPR_then_MEM_REF ()
    9523              : {
    9524            4 :   tree int_star = build_pointer_type (integer_type_node);
    9525            4 :   tree a = build_global_decl ("a", int_star);
    9526            4 :   tree offset_12 = build_int_cst (size_type_node, 12);
    9527            4 :   tree pointer_plus_expr = build2 (POINTER_PLUS_EXPR, int_star, a, offset_12);
    9528            4 :   tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
    9529            4 :   tree offset_0 = build_int_cst (ptype, 0);
    9530            4 :   tree mem_ref = build2 (MEM_REF, integer_type_node,
    9531              :                          pointer_plus_expr, offset_0);
    9532            4 :   symbolic::node_manager node_mgr;
    9533            4 :   region_model m (node_mgr);
    9534              : 
    9535            4 :   tree int_42 = build_int_cst (integer_type_node, 42);
    9536            4 :   m.set_value (mem_ref, int_42, nullptr);
    9537            4 :   ASSERT_EQ (m.get_rvalue (mem_ref, nullptr)->maybe_get_constant (), int_42);
    9538            4 : }
    9539              : 
    9540              : /* Verify that malloc works.  */
    9541              : 
    9542              : static void
    9543            4 : test_malloc ()
    9544              : {
    9545            4 :   tree int_star = build_pointer_type (integer_type_node);
    9546            4 :   tree p = build_global_decl ("p", int_star);
    9547            4 :   tree n = build_global_decl ("n", integer_type_node);
    9548            4 :   tree n_times_4 = build2 (MULT_EXPR, size_type_node,
    9549              :                            n, build_int_cst (size_type_node, 4));
    9550              : 
    9551            4 :   symbolic::node_manager node_mgr;
    9552            4 :   test_region_model_context ctxt;
    9553            4 :   region_model model (node_mgr);
    9554              : 
    9555              :   /* "p = malloc (n * 4);".  */
    9556            4 :   const svalue *size_sval = model.get_rvalue (n_times_4, &ctxt);
    9557            4 :   const region *reg
    9558            4 :     = model.get_or_create_region_for_heap_alloc (size_sval, &ctxt);
    9559            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9560            4 :   const svalue *ptr = mgr.get_ptr_svalue (int_star, reg);
    9561            4 :   model.set_value (model.get_lvalue (p, &ctxt), ptr, &ctxt);
    9562            4 :   ASSERT_EQ (model.get_capacity (reg), size_sval);
    9563            4 : }
    9564              : 
    9565              : /* Verify that alloca works.  */
    9566              : 
    9567              : static void
    9568            4 : test_alloca ()
    9569              : {
    9570            4 :   auto_vec <tree> param_types;
    9571            4 :   tree fndecl = make_fndecl (integer_type_node,
    9572              :                              "test_fn",
    9573              :                              param_types);
    9574            4 :   allocate_struct_function (fndecl, true);
    9575              : 
    9576              : 
    9577            4 :   tree int_star = build_pointer_type (integer_type_node);
    9578            4 :   tree p = build_global_decl ("p", int_star);
    9579            4 :   tree n = build_global_decl ("n", integer_type_node);
    9580            4 :   tree n_times_4 = build2 (MULT_EXPR, size_type_node,
    9581              :                            n, build_int_cst (size_type_node, 4));
    9582              : 
    9583            4 :   symbolic::node_manager node_mgr;
    9584            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9585            4 :   test_region_model_context ctxt;
    9586            4 :   region_model model (node_mgr);
    9587              : 
    9588              :   /* Push stack frame.  */
    9589            4 :   const region *frame_reg
    9590            4 :     = model.push_frame (*DECL_STRUCT_FUNCTION (fndecl),
    9591              :                         nullptr, nullptr, &ctxt);
    9592              :   /* "p = alloca (n * 4);".  */
    9593            4 :   const svalue *size_sval = model.get_rvalue (n_times_4, &ctxt);
    9594            4 :   const region *reg = model.create_region_for_alloca (size_sval, &ctxt);
    9595            4 :   ASSERT_EQ (reg->get_parent_region (), frame_reg);
    9596            4 :   const svalue *ptr = mgr.get_ptr_svalue (int_star, reg);
    9597            4 :   model.set_value (model.get_lvalue (p, &ctxt), ptr, &ctxt);
    9598            4 :   ASSERT_EQ (model.get_capacity (reg), size_sval);
    9599              : 
    9600              :   /* Verify that the pointers to the alloca region are replaced by
    9601              :      poisoned values when the frame is popped.  */
    9602            4 :   model.pop_frame (nullptr, nullptr, &ctxt, nullptr);
    9603            4 :   auto *sval = model.get_rvalue (p, nullptr);
    9604            4 :   auto *sval_from_bv = sval->dyn_cast_svalue_from_bit_vector ();
    9605            4 :   ASSERT_NE (sval_from_bv, nullptr);
    9606            4 :   auto *poisoned_bv
    9607            4 :     = sval_from_bv->get_bit_vector ().dyn_cast_poisoned_bit_vector ();
    9608            4 :   ASSERT_NE (poisoned_bv, nullptr);
    9609            4 :   ASSERT_EQ (poisoned_bv->get_poison_kind (), poison_kind::popped_stack);
    9610            4 : }
    9611              : 
    9612              : /* Verify that svalue::involves_p works.  */
    9613              : 
    9614              : static void
    9615            4 : test_involves_p ()
    9616              : {
    9617            4 :   symbolic::node_manager node_mgr;
    9618            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9619              : 
    9620            4 :   tree int_star = build_pointer_type (integer_type_node);
    9621            4 :   tree p = build_global_decl ("p", int_star);
    9622            4 :   tree q = build_global_decl ("q", int_star);
    9623              : 
    9624            4 :   test_region_model_context ctxt;
    9625            4 :   region_model model (node_mgr);
    9626            4 :   const svalue *p_init = model.get_rvalue (p, &ctxt);
    9627            4 :   const svalue *q_init = model.get_rvalue (q, &ctxt);
    9628              : 
    9629            4 :   ASSERT_TRUE (p_init->involves_p (*p_init));
    9630            4 :   ASSERT_FALSE (p_init->involves_p (*q_init));
    9631              : 
    9632            4 :   const region *star_p_reg = mgr.get_symbolic_region (p_init);
    9633            4 :   const region *star_q_reg = mgr.get_symbolic_region (q_init);
    9634              : 
    9635            4 :   const svalue *init_star_p = mgr.get_or_create_initial_value (star_p_reg);
    9636            4 :   const svalue *init_star_q = mgr.get_or_create_initial_value (star_q_reg);
    9637              : 
    9638            4 :   ASSERT_TRUE (init_star_p->involves_p (*p_init));
    9639            4 :   ASSERT_FALSE (p_init->involves_p (*init_star_p));
    9640            4 :   ASSERT_FALSE (init_star_p->involves_p (*q_init));
    9641            4 :   ASSERT_TRUE (init_star_q->involves_p (*q_init));
    9642            4 :   ASSERT_FALSE (init_star_q->involves_p (*p_init));
    9643            4 : }
    9644              : 
    9645              : /* Simulate:
    9646              : 
    9647              :    | struct quad {
    9648              :    |   int m_i;
    9649              :    |   // padding, potentially //
    9650              :    |   struct coord m_vertex[4];
    9651              :    | } q;
    9652              : 
    9653              :    Verify that we can roundtrip between regions and memory_range
    9654              :    for "q.m_coord[q.m_i].m_x" and "q.m_coord[q.m_i].m_y"
    9655              :    (which have symbolic start offsets).  */
    9656              : 
    9657              : static void
    9658            4 : test_array_in_struct ()
    9659              : {
    9660            4 :   coord_test ct;
    9661              : 
    9662            4 :   tree quad_i_field = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
    9663              :                                get_identifier ("m_i"), integer_type_node);
    9664            4 :   tree vert_arr_type = build_array_type_nelts (ct.m_coord_type, 3);
    9665            4 :   tree quad_vertex_field
    9666            4 :     = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
    9667              :                   get_identifier ("m_vertex"), vert_arr_type);
    9668            4 :   tree quad_type = make_test_compound_type ("quad", true,
    9669              :                                             {quad_i_field, quad_vertex_field});
    9670              : 
    9671            4 :   tree q = build_global_decl ("q", quad_type);
    9672              :   // "q.m_i":
    9673            4 :   tree q_i = build3 (COMPONENT_REF, TREE_TYPE (quad_i_field),
    9674              :                      q, quad_i_field, NULL_TREE);
    9675              :   // "q.m_vertex":
    9676            4 :   tree q_vertex = build3 (COMPONENT_REF, TREE_TYPE (quad_vertex_field),
    9677              :                           q, quad_vertex_field, NULL_TREE);
    9678              : 
    9679              :   // "q.m_vertex[q.m_i]":
    9680            4 :   tree q_vertex_q_i = build4 (ARRAY_REF, TREE_TYPE (ct.m_coord_type),
    9681              :                               q_vertex, q_i, NULL_TREE, NULL_TREE);
    9682              :   // "q.m_vertex[q.m_i].m_x":
    9683            4 :   tree q_vertex_q_i_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    9684              :                                 q_vertex_q_i, ct.m_x_field, NULL_TREE);
    9685              :   // "q.m_vertex[q.m_i].m_y":
    9686            4 :   tree q_vertex_q_i_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
    9687              :                                 q_vertex_q_i, ct.m_y_field, NULL_TREE);
    9688              : 
    9689            4 :   symbolic::node_manager node_mgr;
    9690            4 :   auto &mgr = node_mgr.get_region_model_manager ();
    9691            4 :   auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
    9692            4 :   region_model model (node_mgr);
    9693              : 
    9694            4 :   auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
    9695              : 
    9696            4 :   const region *q_reg = model.get_lvalue (q, nullptr);
    9697            4 :   diagnostics::markup::lowering_options opts;
    9698            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*q_reg, opts, "q");
    9699              : 
    9700            4 :   const region *vertex_reg = model.get_lvalue (q_vertex, nullptr);
    9701            4 :   ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*vertex_reg, opts, "q.m_vertex");
    9702              : 
    9703            4 :   const region *x_reg = model.get_lvalue (q_vertex_q_i_x, nullptr);
    9704            4 :   const region *y_reg = model.get_lvalue (q_vertex_q_i_y, nullptr);
    9705              : 
    9706              :   /* Verify memory range for the access of "q.m_vertex[q.m_i].m_x".  */
    9707            4 :   {
    9708            4 :     auto mem_range = x_reg->get_memory_range (mgr);
    9709            4 :     ASSERT_SAME_SYMBOLIC_NODE (&mem_range.get_base_region (), q_reg);
    9710              : 
    9711            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_size (),
    9712              :                                bit_mgr.get_concrete (int_size_bits));
    9713              : 
    9714            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9715              :       (model.maybe_get_region_for_mem_range (mem_range, NULL_TREE),
    9716              :        x_reg);
    9717              :   }
    9718              : 
    9719              :   /* Verify memory range for the access of "q.m_vertex[q.m_i].m_y".  */
    9720            4 :   {
    9721            4 :     auto mem_range = y_reg->get_memory_range (mgr);
    9722            4 :     ASSERT_SAME_SYMBOLIC_NODE (&mem_range.get_base_region (), q_reg);
    9723              : 
    9724            4 :     ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_size (),
    9725              :                                bit_mgr.get_concrete (int_size_bits));
    9726              : 
    9727              :     /* Verify that we can get the region back from the symbolic
    9728              :        memory range, even without a type.  */
    9729            4 :     ASSERT_SAME_SYMBOLIC_NODE
    9730              :       (model.maybe_get_region_for_mem_range (mem_range, NULL_TREE),
    9731              :        y_reg);
    9732              :   }
    9733            4 : }
    9734              : 
    9735              : /* Check that we can construct a region from an awkward memory_range.  */
    9736              : 
    9737              : static void
    9738            4 : test_maybe_get_region_for_mem_range ()
    9739              : {
    9740            4 :   coord_test ct;
    9741            4 :   tree c = build_global_decl ("c", ct.m_coord_type);
    9742              : 
    9743            4 :   symbolic::node_manager node_mgr;
    9744            4 :   auto &rmm = node_mgr.get_region_model_manager ();
    9745            4 :   auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
    9746            4 :   auto &byte_mgr = node_mgr.get_scalars ().get_bytes ();
    9747            4 :   region_model model (node_mgr);
    9748              : 
    9749            4 :   const region *reg = model.get_lvalue (c, nullptr);
    9750            4 :   const cluster_region *cluster_reg = reg->get_cluster_region ();
    9751            4 :   ASSERT_SAME_SYMBOLIC_NODE (reg, cluster_reg);
    9752              : 
    9753              :   // Fully concrete case
    9754            4 :   {
    9755            4 :     symbolic::memory_range mem_range
    9756              :       (*cluster_reg,
    9757            8 :        symbolic_from_concrete (concrete_bit_range (16_bits, 8_bits),
    9758            4 :                                bit_mgr));
    9759            4 :     auto *subreg = model.maybe_get_region_for_mem_range (mem_range, NULL_TREE);
    9760            4 :     ASSERT_NE (subreg, nullptr);
    9761              :     /* Check that the memory range roundtrips.  */
    9762            8 :     ASSERT_EQ (subreg->get_memory_range (rmm),
    9763              :                mem_range);
    9764              :   }
    9765              : 
    9766              :   // Symbolic start offset
    9767            4 :   {
    9768            4 :     placeholder_svalue sval
    9769            4 :       (node_mgr.alloc_node_id (), size_type_node, "sval");
    9770            4 :     auto &num_bytes = byte_mgr.get_scalar_from_svalue (sval);
    9771            4 :     symbolic::memory_range mem_range
    9772              :       (*cluster_reg,
    9773            4 :        symbolic_bit_range (bits_from_bytes (num_bytes),
    9774            4 :                            bit_mgr.get_concrete (8_bits)));
    9775            4 :     auto *subreg = model.maybe_get_region_for_mem_range (mem_range, NULL_TREE);
    9776            4 :     ASSERT_NE (subreg, nullptr);
    9777            4 :   }
    9778            4 : }
    9779              : 
    9780              : /* Run all of the selftests within this file.  */
    9781              : 
    9782              : void
    9783            4 : analyzer_region_model_cc_tests ()
    9784              : {
    9785            4 :   test_tree_cmp_on_constants ();
    9786            4 :   test_dump ();
    9787            4 :   test_struct ();
    9788            4 :   test_array_1 ();
    9789            4 :   test_get_representative_tree ();
    9790            4 :   test_unique_constants ();
    9791            4 :   test_unique_unknowns ();
    9792            4 :   test_initial_svalue_folding ();
    9793            4 :   test_unaryop_svalue_folding ();
    9794            4 :   test_binop_svalue_folding ();
    9795            4 :   test_descendent_of_p ();
    9796            4 :   test_bit_range_regions ();
    9797            4 :   test_assignment ();
    9798            4 :   test_compound_assignment ();
    9799            4 :   test_stack_frames ();
    9800            4 :   test_get_representative_path_var ();
    9801            4 :   test_equality_1 ();
    9802            4 :   test_canonicalization_2 ();
    9803            4 :   test_canonicalization_3 ();
    9804            4 :   test_canonicalization_4 ();
    9805            4 :   test_state_merging ();
    9806            4 :   test_constraint_merging ();
    9807            4 :   test_widening_constraints ();
    9808            4 :   test_iteration_1 ();
    9809            4 :   test_malloc_constraints ();
    9810            4 :   test_var ();
    9811            4 :   test_array_2 ();
    9812            4 :   test_mem_ref ();
    9813            4 :   test_POINTER_PLUS_EXPR_then_MEM_REF ();
    9814            4 :   test_malloc ();
    9815            4 :   test_alloca ();
    9816            4 :   test_involves_p ();
    9817            4 :   test_array_in_struct ();
    9818            4 :   test_maybe_get_region_for_mem_range ();
    9819            4 : }
    9820              : 
    9821              : } // namespace selftest
    9822              : 
    9823              : #endif /* CHECKING_P */
    9824              : 
    9825              : } // namespace ana
    9826              : 
    9827              : #endif /* #if ENABLE_ANALYZER */
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.