gimple.h: Remove all includes.
[platform/upstream/gcc.git] / gcc / trans-mem.c
1 /* Passes for transactional memory support.
2    Copyright (C) 2008-2013 Free Software Foundation, Inc.
3
4    This file is part of GCC.
5
6    GCC is free software; you can redistribute it and/or modify it under
7    the terms of the GNU General Public License as published by the Free
8    Software Foundation; either version 3, or (at your option) any later
9    version.
10
11    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12    WARRANTY; without even the implied warranty of MERCHANTABILITY or
13    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14    for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GCC; see the file COPYING3.  If not see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hash-table.h"
24 #include "tree.h"
25 #include "basic-block.h"
26 #include "tree-ssa-alias.h"
27 #include "internal-fn.h"
28 #include "tree-eh.h"
29 #include "gimple-expr.h"
30 #include "is-a.h"
31 #include "gimple.h"
32 #include "calls.h"
33 #include "function.h"
34 #include "rtl.h"
35 #include "emit-rtl.h"
36 #include "gimplify.h"
37 #include "gimple-iterator.h"
38 #include "gimplify-me.h"
39 #include "gimple-walk.h"
40 #include "gimple-ssa.h"
41 #include "cgraph.h"
42 #include "tree-cfg.h"
43 #include "stringpool.h"
44 #include "tree-ssanames.h"
45 #include "tree-into-ssa.h"
46 #include "tree-pass.h"
47 #include "tree-inline.h"
48 #include "diagnostic-core.h"
49 #include "demangle.h"
50 #include "output.h"
51 #include "trans-mem.h"
52 #include "params.h"
53 #include "target.h"
54 #include "langhooks.h"
55 #include "gimple-pretty-print.h"
56 #include "cfgloop.h"
57 #include "tree-ssa-address.h"
58
59
60 #define PROB_VERY_UNLIKELY      (REG_BR_PROB_BASE / 2000 - 1)
61 #define PROB_VERY_LIKELY        (PROB_ALWAYS - PROB_VERY_UNLIKELY)
62 #define PROB_UNLIKELY           (REG_BR_PROB_BASE / 5 - 1)
63 #define PROB_LIKELY             (PROB_ALWAYS - PROB_VERY_LIKELY)
64 #define PROB_ALWAYS             (REG_BR_PROB_BASE)
65
66 #define A_RUNINSTRUMENTEDCODE   0x0001
67 #define A_RUNUNINSTRUMENTEDCODE 0x0002
68 #define A_SAVELIVEVARIABLES     0x0004
69 #define A_RESTORELIVEVARIABLES  0x0008
70 #define A_ABORTTRANSACTION      0x0010
71
72 #define AR_USERABORT            0x0001
73 #define AR_USERRETRY            0x0002
74 #define AR_TMCONFLICT           0x0004
75 #define AR_EXCEPTIONBLOCKABORT  0x0008
76 #define AR_OUTERABORT           0x0010
77
78 #define MODE_SERIALIRREVOCABLE  0x0000
79
80
81 /* The representation of a transaction changes several times during the
82    lowering process.  In the beginning, in the front-end we have the
83    GENERIC tree TRANSACTION_EXPR.  For example,
84
85         __transaction {
86           local++;
87           if (++global == 10)
88             __tm_abort;
89         }
90
91   During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
92   trivially replaced with a GIMPLE_TRANSACTION node.
93
94   During pass_lower_tm, we examine the body of transactions looking
95   for aborts.  Transactions that do not contain an abort may be
96   merged into an outer transaction.  We also add a TRY-FINALLY node
97   to arrange for the transaction to be committed on any exit.
98
99   [??? Think about how this arrangement affects throw-with-commit
100   and throw-with-abort operations.  In this case we want the TRY to
101   handle gotos, but not to catch any exceptions because the transaction
102   will already be closed.]
103
104         GIMPLE_TRANSACTION [label=NULL] {
105           try {
106             local = local + 1;
107             t0 = global;
108             t1 = t0 + 1;
109             global = t1;
110             if (t1 == 10)
111               __builtin___tm_abort ();
112           } finally {
113             __builtin___tm_commit ();
114           }
115         }
116
117   During pass_lower_eh, we create EH regions for the transactions,
118   intermixed with the regular EH stuff.  This gives us a nice persistent
119   mapping (all the way through rtl) from transactional memory operation
120   back to the transaction, which allows us to get the abnormal edges
121   correct to model transaction aborts and restarts:
122
123         GIMPLE_TRANSACTION [label=over]
124         local = local + 1;
125         t0 = global;
126         t1 = t0 + 1;
127         global = t1;
128         if (t1 == 10)
129           __builtin___tm_abort ();
130         __builtin___tm_commit ();
131         over:
132
133   This is the end of all_lowering_passes, and so is what is present
134   during the IPA passes, and through all of the optimization passes.
135
136   During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
137   functions and mark functions for cloning.
138
139   At the end of gimple optimization, before exiting SSA form,
140   pass_tm_edges replaces statements that perform transactional
141   memory operations with the appropriate TM builtins, and swap
142   out function calls with their transactional clones.  At this
143   point we introduce the abnormal transaction restart edges and
144   complete lowering of the GIMPLE_TRANSACTION node.
145
146         x = __builtin___tm_start (MAY_ABORT);
147         eh_label:
148         if (x & abort_transaction)
149           goto over;
150         local = local + 1;
151         t0 = __builtin___tm_load (global);
152         t1 = t0 + 1;
153         __builtin___tm_store (&global, t1);
154         if (t1 == 10)
155           __builtin___tm_abort ();
156         __builtin___tm_commit ();
157         over:
158 */
159
160 static void *expand_regions (struct tm_region *,
161                              void *(*callback)(struct tm_region *, void *),
162                              void *, bool);
163
164 \f
165 /* Return the attributes we want to examine for X, or NULL if it's not
166    something we examine.  We look at function types, but allow pointers
167    to function types and function decls and peek through.  */
168
169 static tree
170 get_attrs_for (const_tree x)
171 {
172   switch (TREE_CODE (x))
173     {
174     case FUNCTION_DECL:
175       return TYPE_ATTRIBUTES (TREE_TYPE (x));
176       break;
177
178     default:
179       if (TYPE_P (x))
180         return NULL;
181       x = TREE_TYPE (x);
182       if (TREE_CODE (x) != POINTER_TYPE)
183         return NULL;
184       /* FALLTHRU */
185
186     case POINTER_TYPE:
187       x = TREE_TYPE (x);
188       if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
189         return NULL;
190       /* FALLTHRU */
191
192     case FUNCTION_TYPE:
193     case METHOD_TYPE:
194       return TYPE_ATTRIBUTES (x);
195     }
196 }
197
198 /* Return true if X has been marked TM_PURE.  */
199
200 bool
201 is_tm_pure (const_tree x)
202 {
203   unsigned flags;
204
205   switch (TREE_CODE (x))
206     {
207     case FUNCTION_DECL:
208     case FUNCTION_TYPE:
209     case METHOD_TYPE:
210       break;
211
212     default:
213       if (TYPE_P (x))
214         return false;
215       x = TREE_TYPE (x);
216       if (TREE_CODE (x) != POINTER_TYPE)
217         return false;
218       /* FALLTHRU */
219
220     case POINTER_TYPE:
221       x = TREE_TYPE (x);
222       if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
223         return false;
224       break;
225     }
226
227   flags = flags_from_decl_or_type (x);
228   return (flags & ECF_TM_PURE) != 0;
229 }
230
231 /* Return true if X has been marked TM_IRREVOCABLE.  */
232
233 static bool
234 is_tm_irrevocable (tree x)
235 {
236   tree attrs = get_attrs_for (x);
237
238   if (attrs && lookup_attribute ("transaction_unsafe", attrs))
239     return true;
240
241   /* A call to the irrevocable builtin is by definition,
242      irrevocable.  */
243   if (TREE_CODE (x) == ADDR_EXPR)
244     x = TREE_OPERAND (x, 0);
245   if (TREE_CODE (x) == FUNCTION_DECL
246       && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
247       && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
248     return true;
249
250   return false;
251 }
252
253 /* Return true if X has been marked TM_SAFE.  */
254
255 bool
256 is_tm_safe (const_tree x)
257 {
258   if (flag_tm)
259     {
260       tree attrs = get_attrs_for (x);
261       if (attrs)
262         {
263           if (lookup_attribute ("transaction_safe", attrs))
264             return true;
265           if (lookup_attribute ("transaction_may_cancel_outer", attrs))
266             return true;
267         }
268     }
269   return false;
270 }
271
272 /* Return true if CALL is const, or tm_pure.  */
273
274 static bool
275 is_tm_pure_call (gimple call)
276 {
277   tree fn = gimple_call_fn (call);
278
279   if (TREE_CODE (fn) == ADDR_EXPR)
280     {
281       fn = TREE_OPERAND (fn, 0);
282       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
283     }
284   else
285     fn = TREE_TYPE (fn);
286
287   return is_tm_pure (fn);
288 }
289
290 /* Return true if X has been marked TM_CALLABLE.  */
291
292 static bool
293 is_tm_callable (tree x)
294 {
295   tree attrs = get_attrs_for (x);
296   if (attrs)
297     {
298       if (lookup_attribute ("transaction_callable", attrs))
299         return true;
300       if (lookup_attribute ("transaction_safe", attrs))
301         return true;
302       if (lookup_attribute ("transaction_may_cancel_outer", attrs))
303         return true;
304     }
305   return false;
306 }
307
308 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER.  */
309
310 bool
311 is_tm_may_cancel_outer (tree x)
312 {
313   tree attrs = get_attrs_for (x);
314   if (attrs)
315     return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
316   return false;
317 }
318
319 /* Return true for built in functions that "end" a transaction.   */
320
321 bool
322 is_tm_ending_fndecl (tree fndecl)
323 {
324   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
325     switch (DECL_FUNCTION_CODE (fndecl))
326       {
327       case BUILT_IN_TM_COMMIT:
328       case BUILT_IN_TM_COMMIT_EH:
329       case BUILT_IN_TM_ABORT:
330       case BUILT_IN_TM_IRREVOCABLE:
331         return true;
332       default:
333         break;
334       }
335
336   return false;
337 }
338
339 /* Return true if STMT is a built in function call that "ends" a
340    transaction.  */
341
342 bool
343 is_tm_ending (gimple stmt)
344 {
345   tree fndecl;
346
347   if (gimple_code (stmt) != GIMPLE_CALL)
348     return false;
349
350   fndecl = gimple_call_fndecl (stmt);
351   return (fndecl != NULL_TREE
352           && is_tm_ending_fndecl (fndecl));
353 }
354
355 /* Return true if STMT is a TM load.  */
356
357 static bool
358 is_tm_load (gimple stmt)
359 {
360   tree fndecl;
361
362   if (gimple_code (stmt) != GIMPLE_CALL)
363     return false;
364
365   fndecl = gimple_call_fndecl (stmt);
366   return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
367           && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
368 }
369
370 /* Same as above, but for simple TM loads, that is, not the
371    after-write, after-read, etc optimized variants.  */
372
373 static bool
374 is_tm_simple_load (gimple stmt)
375 {
376   tree fndecl;
377
378   if (gimple_code (stmt) != GIMPLE_CALL)
379     return false;
380
381   fndecl = gimple_call_fndecl (stmt);
382   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
383     {
384       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
385       return (fcode == BUILT_IN_TM_LOAD_1
386               || fcode == BUILT_IN_TM_LOAD_2
387               || fcode == BUILT_IN_TM_LOAD_4
388               || fcode == BUILT_IN_TM_LOAD_8
389               || fcode == BUILT_IN_TM_LOAD_FLOAT
390               || fcode == BUILT_IN_TM_LOAD_DOUBLE
391               || fcode == BUILT_IN_TM_LOAD_LDOUBLE
392               || fcode == BUILT_IN_TM_LOAD_M64
393               || fcode == BUILT_IN_TM_LOAD_M128
394               || fcode == BUILT_IN_TM_LOAD_M256);
395     }
396   return false;
397 }
398
399 /* Return true if STMT is a TM store.  */
400
401 static bool
402 is_tm_store (gimple stmt)
403 {
404   tree fndecl;
405
406   if (gimple_code (stmt) != GIMPLE_CALL)
407     return false;
408
409   fndecl = gimple_call_fndecl (stmt);
410   return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
411           && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
412 }
413
414 /* Same as above, but for simple TM stores, that is, not the
415    after-write, after-read, etc optimized variants.  */
416
417 static bool
418 is_tm_simple_store (gimple stmt)
419 {
420   tree fndecl;
421
422   if (gimple_code (stmt) != GIMPLE_CALL)
423     return false;
424
425   fndecl = gimple_call_fndecl (stmt);
426   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
427     {
428       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
429       return (fcode == BUILT_IN_TM_STORE_1
430               || fcode == BUILT_IN_TM_STORE_2
431               || fcode == BUILT_IN_TM_STORE_4
432               || fcode == BUILT_IN_TM_STORE_8
433               || fcode == BUILT_IN_TM_STORE_FLOAT
434               || fcode == BUILT_IN_TM_STORE_DOUBLE
435               || fcode == BUILT_IN_TM_STORE_LDOUBLE
436               || fcode == BUILT_IN_TM_STORE_M64
437               || fcode == BUILT_IN_TM_STORE_M128
438               || fcode == BUILT_IN_TM_STORE_M256);
439     }
440   return false;
441 }
442
443 /* Return true if FNDECL is BUILT_IN_TM_ABORT.  */
444
445 static bool
446 is_tm_abort (tree fndecl)
447 {
448   return (fndecl
449           && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
450           && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
451 }
452
453 /* Build a GENERIC tree for a user abort.  This is called by front ends
454    while transforming the __tm_abort statement.  */
455
456 tree
457 build_tm_abort_call (location_t loc, bool is_outer)
458 {
459   return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
460                               build_int_cst (integer_type_node,
461                                              AR_USERABORT
462                                              | (is_outer ? AR_OUTERABORT : 0)));
463 }
464
465 /* Common gateing function for several of the TM passes.  */
466
467 static bool
468 gate_tm (void)
469 {
470   return flag_tm;
471 }
472 \f
473 /* Map for aribtrary function replacement under TM, as created
474    by the tm_wrap attribute.  */
475
476 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
477      htab_t tm_wrap_map;
478
479 void
480 record_tm_replacement (tree from, tree to)
481 {
482   struct tree_map **slot, *h;
483
484   /* Do not inline wrapper functions that will get replaced in the TM
485      pass.
486
487      Suppose you have foo() that will get replaced into tmfoo().  Make
488      sure the inliner doesn't try to outsmart us and inline foo()
489      before we get a chance to do the TM replacement.  */
490   DECL_UNINLINABLE (from) = 1;
491
492   if (tm_wrap_map == NULL)
493     tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
494
495   h = ggc_alloc_tree_map ();
496   h->hash = htab_hash_pointer (from);
497   h->base.from = from;
498   h->to = to;
499
500   slot = (struct tree_map **)
501     htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
502   *slot = h;
503 }
504
505 /* Return a TM-aware replacement function for DECL.  */
506
507 static tree
508 find_tm_replacement_function (tree fndecl)
509 {
510   if (tm_wrap_map)
511     {
512       struct tree_map *h, in;
513
514       in.base.from = fndecl;
515       in.hash = htab_hash_pointer (fndecl);
516       h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
517       if (h)
518         return h->to;
519     }
520
521   /* ??? We may well want TM versions of most of the common <string.h>
522      functions.  For now, we've already these two defined.  */
523   /* Adjust expand_call_tm() attributes as necessary for the cases
524      handled here:  */
525   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
526     switch (DECL_FUNCTION_CODE (fndecl))
527       {
528       case BUILT_IN_MEMCPY:
529         return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
530       case BUILT_IN_MEMMOVE:
531         return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
532       case BUILT_IN_MEMSET:
533         return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
534       default:
535         return NULL;
536       }
537
538   return NULL;
539 }
540
541 /* When appropriate, record TM replacement for memory allocation functions.
542
543    FROM is the FNDECL to wrap.  */
544 void
545 tm_malloc_replacement (tree from)
546 {
547   const char *str;
548   tree to;
549
550   if (TREE_CODE (from) != FUNCTION_DECL)
551     return;
552
553   /* If we have a previous replacement, the user must be explicitly
554      wrapping malloc/calloc/free.  They better know what they're
555      doing... */
556   if (find_tm_replacement_function (from))
557     return;
558
559   str = IDENTIFIER_POINTER (DECL_NAME (from));
560
561   if (!strcmp (str, "malloc"))
562     to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
563   else if (!strcmp (str, "calloc"))
564     to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
565   else if (!strcmp (str, "free"))
566     to = builtin_decl_explicit (BUILT_IN_TM_FREE);
567   else
568     return;
569
570   TREE_NOTHROW (to) = 0;
571
572   record_tm_replacement (from, to);
573 }
574 \f
575 /* Diagnostics for tm_safe functions/regions.  Called by the front end
576    once we've lowered the function to high-gimple.  */
577
578 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
579    Process exactly one statement.  WI->INFO is set to non-null when in
580    the context of a tm_safe function, and null for a __transaction block.  */
581
582 #define DIAG_TM_OUTER           1
583 #define DIAG_TM_SAFE            2
584 #define DIAG_TM_RELAXED         4
585
586 struct diagnose_tm
587 {
588   unsigned int summary_flags : 8;
589   unsigned int block_flags : 8;
590   unsigned int func_flags : 8;
591   unsigned int saw_volatile : 1;
592   gimple stmt;
593 };
594
595 /* Return true if T is a volatile variable of some kind.  */
596
597 static bool
598 volatile_var_p (tree t)
599 {
600   return (SSA_VAR_P (t)
601           && TREE_THIS_VOLATILE (TREE_TYPE (t)));
602 }
603
604 /* Tree callback function for diagnose_tm pass.  */
605
606 static tree
607 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
608                   void *data)
609 {
610   struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
611   struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
612
613   if (volatile_var_p (*tp)
614       && d->block_flags & DIAG_TM_SAFE
615       && !d->saw_volatile)
616     {
617       d->saw_volatile = 1;
618       error_at (gimple_location (d->stmt),
619                 "invalid volatile use of %qD inside transaction",
620                 *tp);
621     }
622
623   return NULL_TREE;
624 }
625
626 static inline bool
627 is_tm_safe_or_pure (const_tree x)
628 {
629   return is_tm_safe (x) || is_tm_pure (x);
630 }
631
632 static tree
633 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
634                     struct walk_stmt_info *wi)
635 {
636   gimple stmt = gsi_stmt (*gsi);
637   struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
638
639   /* Save stmt for use in leaf analysis.  */
640   d->stmt = stmt;
641
642   switch (gimple_code (stmt))
643     {
644     case GIMPLE_CALL:
645       {
646         tree fn = gimple_call_fn (stmt);
647
648         if ((d->summary_flags & DIAG_TM_OUTER) == 0
649             && is_tm_may_cancel_outer (fn))
650           error_at (gimple_location (stmt),
651                     "%<transaction_may_cancel_outer%> function call not within"
652                     " outer transaction or %<transaction_may_cancel_outer%>");
653
654         if (d->summary_flags & DIAG_TM_SAFE)
655           {
656             bool is_safe, direct_call_p;
657             tree replacement;
658
659             if (TREE_CODE (fn) == ADDR_EXPR
660                 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
661               {
662                 direct_call_p = true;
663                 replacement = TREE_OPERAND (fn, 0);
664                 replacement = find_tm_replacement_function (replacement);
665                 if (replacement)
666                   fn = replacement;
667               }
668             else
669               {
670                 direct_call_p = false;
671                 replacement = NULL_TREE;
672               }
673
674             if (is_tm_safe_or_pure (fn))
675               is_safe = true;
676             else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
677               {
678                 /* A function explicitly marked transaction_callable as
679                    opposed to transaction_safe is being defined to be
680                    unsafe as part of its ABI, regardless of its contents.  */
681                 is_safe = false;
682               }
683             else if (direct_call_p)
684               {
685                 if (flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
686                   is_safe = true;
687                 else if (replacement)
688                   {
689                     /* ??? At present we've been considering replacements
690                        merely transaction_callable, and therefore might
691                        enter irrevocable.  The tm_wrap attribute has not
692                        yet made it into the new language spec.  */
693                     is_safe = false;
694                   }
695                 else
696                   {
697                     /* ??? Diagnostics for unmarked direct calls moved into
698                        the IPA pass.  Section 3.2 of the spec details how
699                        functions not marked should be considered "implicitly
700                        safe" based on having examined the function body.  */
701                     is_safe = true;
702                   }
703               }
704             else
705               {
706                 /* An unmarked indirect call.  Consider it unsafe even
707                    though optimization may yet figure out how to inline.  */
708                 is_safe = false;
709               }
710
711             if (!is_safe)
712               {
713                 if (TREE_CODE (fn) == ADDR_EXPR)
714                   fn = TREE_OPERAND (fn, 0);
715                 if (d->block_flags & DIAG_TM_SAFE)
716                   {
717                     if (direct_call_p)
718                       error_at (gimple_location (stmt),
719                                 "unsafe function call %qD within "
720                                 "atomic transaction", fn);
721                     else
722                       {
723                         if (!DECL_P (fn) || DECL_NAME (fn))
724                           error_at (gimple_location (stmt),
725                                     "unsafe function call %qE within "
726                                     "atomic transaction", fn);
727                         else
728                           error_at (gimple_location (stmt),
729                                     "unsafe indirect function call within "
730                                     "atomic transaction");
731                       }
732                   }
733                 else
734                   {
735                     if (direct_call_p)
736                       error_at (gimple_location (stmt),
737                                 "unsafe function call %qD within "
738                                 "%<transaction_safe%> function", fn);
739                     else
740                       {
741                         if (!DECL_P (fn) || DECL_NAME (fn))
742                           error_at (gimple_location (stmt),
743                                     "unsafe function call %qE within "
744                                     "%<transaction_safe%> function", fn);
745                         else
746                           error_at (gimple_location (stmt),
747                                     "unsafe indirect function call within "
748                                     "%<transaction_safe%> function");
749                       }
750                   }
751               }
752           }
753       }
754       break;
755
756     case GIMPLE_ASM:
757       /* ??? We ought to come up with a way to add attributes to
758          asm statements, and then add "transaction_safe" to it.
759          Either that or get the language spec to resurrect __tm_waiver.  */
760       if (d->block_flags & DIAG_TM_SAFE)
761         error_at (gimple_location (stmt),
762                   "asm not allowed in atomic transaction");
763       else if (d->func_flags & DIAG_TM_SAFE)
764         error_at (gimple_location (stmt),
765                   "asm not allowed in %<transaction_safe%> function");
766       break;
767
768     case GIMPLE_TRANSACTION:
769       {
770         unsigned char inner_flags = DIAG_TM_SAFE;
771
772         if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
773           {
774             if (d->block_flags & DIAG_TM_SAFE)
775               error_at (gimple_location (stmt),
776                         "relaxed transaction in atomic transaction");
777             else if (d->func_flags & DIAG_TM_SAFE)
778               error_at (gimple_location (stmt),
779                         "relaxed transaction in %<transaction_safe%> function");
780             inner_flags = DIAG_TM_RELAXED;
781           }
782         else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
783           {
784             if (d->block_flags)
785               error_at (gimple_location (stmt),
786                         "outer transaction in transaction");
787             else if (d->func_flags & DIAG_TM_OUTER)
788               error_at (gimple_location (stmt),
789                         "outer transaction in "
790                         "%<transaction_may_cancel_outer%> function");
791             else if (d->func_flags & DIAG_TM_SAFE)
792               error_at (gimple_location (stmt),
793                         "outer transaction in %<transaction_safe%> function");
794             inner_flags |= DIAG_TM_OUTER;
795           }
796
797         *handled_ops_p = true;
798         if (gimple_transaction_body (stmt))
799           {
800             struct walk_stmt_info wi_inner;
801             struct diagnose_tm d_inner;
802
803             memset (&d_inner, 0, sizeof (d_inner));
804             d_inner.func_flags = d->func_flags;
805             d_inner.block_flags = d->block_flags | inner_flags;
806             d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
807
808             memset (&wi_inner, 0, sizeof (wi_inner));
809             wi_inner.info = &d_inner;
810
811             walk_gimple_seq (gimple_transaction_body (stmt),
812                              diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
813           }
814       }
815       break;
816
817     default:
818       break;
819     }
820
821   return NULL_TREE;
822 }
823
824 static unsigned int
825 diagnose_tm_blocks (void)
826 {
827   struct walk_stmt_info wi;
828   struct diagnose_tm d;
829
830   memset (&d, 0, sizeof (d));
831   if (is_tm_may_cancel_outer (current_function_decl))
832     d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
833   else if (is_tm_safe (current_function_decl))
834     d.func_flags = DIAG_TM_SAFE;
835   d.summary_flags = d.func_flags;
836
837   memset (&wi, 0, sizeof (wi));
838   wi.info = &d;
839
840   walk_gimple_seq (gimple_body (current_function_decl),
841                    diagnose_tm_1, diagnose_tm_1_op, &wi);
842
843   return 0;
844 }
845
846 namespace {
847
848 const pass_data pass_data_diagnose_tm_blocks =
849 {
850   GIMPLE_PASS, /* type */
851   "*diagnose_tm_blocks", /* name */
852   OPTGROUP_NONE, /* optinfo_flags */
853   true, /* has_gate */
854   true, /* has_execute */
855   TV_TRANS_MEM, /* tv_id */
856   PROP_gimple_any, /* properties_required */
857   0, /* properties_provided */
858   0, /* properties_destroyed */
859   0, /* todo_flags_start */
860   0, /* todo_flags_finish */
861 };
862
863 class pass_diagnose_tm_blocks : public gimple_opt_pass
864 {
865 public:
866   pass_diagnose_tm_blocks (gcc::context *ctxt)
867     : gimple_opt_pass (pass_data_diagnose_tm_blocks, ctxt)
868   {}
869
870   /* opt_pass methods: */
871   bool gate () { return gate_tm (); }
872   unsigned int execute () { return diagnose_tm_blocks (); }
873
874 }; // class pass_diagnose_tm_blocks
875
876 } // anon namespace
877
878 gimple_opt_pass *
879 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
880 {
881   return new pass_diagnose_tm_blocks (ctxt);
882 }
883 \f
884 /* Instead of instrumenting thread private memory, we save the
885    addresses in a log which we later use to save/restore the addresses
886    upon transaction start/restart.
887
888    The log is keyed by address, where each element contains individual
889    statements among different code paths that perform the store.
890
891    This log is later used to generate either plain save/restore of the
892    addresses upon transaction start/restart, or calls to the ITM_L*
893    logging functions.
894
895    So for something like:
896
897        struct large { int x[1000]; };
898        struct large lala = { 0 };
899        __transaction {
900          lala.x[i] = 123;
901          ...
902        }
903
904    We can either save/restore:
905
906        lala = { 0 };
907        trxn = _ITM_startTransaction ();
908        if (trxn & a_saveLiveVariables)
909          tmp_lala1 = lala.x[i];
910        else if (a & a_restoreLiveVariables)
911          lala.x[i] = tmp_lala1;
912
913    or use the logging functions:
914
915        lala = { 0 };
916        trxn = _ITM_startTransaction ();
917        _ITM_LU4 (&lala.x[i]);
918
919    Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
920    far up the dominator tree to shadow all of the writes to a given
921    location (thus reducing the total number of logging calls), but not
922    so high as to be called on a path that does not perform a
923    write.  */
924
925 /* One individual log entry.  We may have multiple statements for the
926    same location if neither dominate each other (on different
927    execution paths).  */
928 typedef struct tm_log_entry
929 {
930   /* Address to save.  */
931   tree addr;
932   /* Entry block for the transaction this address occurs in.  */
933   basic_block entry_block;
934   /* Dominating statements the store occurs in.  */
935   gimple_vec stmts;
936   /* Initially, while we are building the log, we place a nonzero
937      value here to mean that this address *will* be saved with a
938      save/restore sequence.  Later, when generating the save sequence
939      we place the SSA temp generated here.  */
940   tree save_var;
941 } *tm_log_entry_t;
942
943
944 /* Log entry hashtable helpers.  */
945
946 struct log_entry_hasher
947 {
948   typedef tm_log_entry value_type;
949   typedef tm_log_entry compare_type;
950   static inline hashval_t hash (const value_type *);
951   static inline bool equal (const value_type *, const compare_type *);
952   static inline void remove (value_type *);
953 };
954
955 /* Htab support.  Return hash value for a `tm_log_entry'.  */
956 inline hashval_t
957 log_entry_hasher::hash (const value_type *log)
958 {
959   return iterative_hash_expr (log->addr, 0);
960 }
961
962 /* Htab support.  Return true if two log entries are the same.  */
963 inline bool
964 log_entry_hasher::equal (const value_type *log1, const compare_type *log2)
965 {
966   /* FIXME:
967
968      rth: I suggest that we get rid of the component refs etc.
969      I.e. resolve the reference to base + offset.
970
971      We may need to actually finish a merge with mainline for this,
972      since we'd like to be presented with Richi's MEM_REF_EXPRs more
973      often than not.  But in the meantime your tm_log_entry could save
974      the results of get_inner_reference.
975
976      See: g++.dg/tm/pr46653.C
977   */
978
979   /* Special case plain equality because operand_equal_p() below will
980      return FALSE if the addresses are equal but they have
981      side-effects (e.g. a volatile address).  */
982   if (log1->addr == log2->addr)
983     return true;
984
985   return operand_equal_p (log1->addr, log2->addr, 0);
986 }
987
988 /* Htab support.  Free one tm_log_entry.  */
989 inline void
990 log_entry_hasher::remove (value_type *lp)
991 {
992   lp->stmts.release ();
993   free (lp);
994 }
995
996
997 /* The actual log.  */
998 static hash_table <log_entry_hasher> tm_log;
999
1000 /* Addresses to log with a save/restore sequence.  These should be in
1001    dominator order.  */
1002 static vec<tree> tm_log_save_addresses;
1003
1004 enum thread_memory_type
1005   {
1006     mem_non_local = 0,
1007     mem_thread_local,
1008     mem_transaction_local,
1009     mem_max
1010   };
1011
1012 typedef struct tm_new_mem_map
1013 {
1014   /* SSA_NAME being dereferenced.  */
1015   tree val;
1016   enum thread_memory_type local_new_memory;
1017 } tm_new_mem_map_t;
1018
1019 /* Hashtable helpers.  */
1020
1021 struct tm_mem_map_hasher : typed_free_remove <tm_new_mem_map_t>
1022 {
1023   typedef tm_new_mem_map_t value_type;
1024   typedef tm_new_mem_map_t compare_type;
1025   static inline hashval_t hash (const value_type *);
1026   static inline bool equal (const value_type *, const compare_type *);
1027 };
1028
1029 inline hashval_t
1030 tm_mem_map_hasher::hash (const value_type *v)
1031 {
1032   return (intptr_t)v->val >> 4;
1033 }
1034
1035 inline bool
1036 tm_mem_map_hasher::equal (const value_type *v, const compare_type *c)
1037 {
1038   return v->val == c->val;
1039 }
1040
1041 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1042    of memory (malloc, alloc, etc).  */
1043 static hash_table <tm_mem_map_hasher> tm_new_mem_hash;
1044
1045 /* Initialize logging data structures.  */
1046 static void
1047 tm_log_init (void)
1048 {
1049   tm_log.create (10);
1050   tm_new_mem_hash.create (5);
1051   tm_log_save_addresses.create (5);
1052 }
1053
1054 /* Free logging data structures.  */
1055 static void
1056 tm_log_delete (void)
1057 {
1058   tm_log.dispose ();
1059   tm_new_mem_hash.dispose ();
1060   tm_log_save_addresses.release ();
1061 }
1062
1063 /* Return true if MEM is a transaction invariant memory for the TM
1064    region starting at REGION_ENTRY_BLOCK.  */
1065 static bool
1066 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1067 {
1068   if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1069       && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1070     {
1071       basic_block def_bb;
1072
1073       def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1074       return def_bb != region_entry_block
1075         && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1076     }
1077
1078   mem = strip_invariant_refs (mem);
1079   return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1080 }
1081
1082 /* Given an address ADDR in STMT, find it in the memory log or add it,
1083    making sure to keep only the addresses highest in the dominator
1084    tree.
1085
1086    ENTRY_BLOCK is the entry_block for the transaction.
1087
1088    If we find the address in the log, make sure it's either the same
1089    address, or an equivalent one that dominates ADDR.
1090
1091    If we find the address, but neither ADDR dominates the found
1092    address, nor the found one dominates ADDR, we're on different
1093    execution paths.  Add it.
1094
1095    If known, ENTRY_BLOCK is the entry block for the region, otherwise
1096    NULL.  */
1097 static void
1098 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1099 {
1100   tm_log_entry **slot;
1101   struct tm_log_entry l, *lp;
1102
1103   l.addr = addr;
1104   slot = tm_log.find_slot (&l, INSERT);
1105   if (!*slot)
1106     {
1107       tree type = TREE_TYPE (addr);
1108
1109       lp = XNEW (struct tm_log_entry);
1110       lp->addr = addr;
1111       *slot = lp;
1112
1113       /* Small invariant addresses can be handled as save/restores.  */
1114       if (entry_block
1115           && transaction_invariant_address_p (lp->addr, entry_block)
1116           && TYPE_SIZE_UNIT (type) != NULL
1117           && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
1118           && ((HOST_WIDE_INT) tree_to_uhwi (TYPE_SIZE_UNIT (type))
1119               < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1120           /* We must be able to copy this type normally.  I.e., no
1121              special constructors and the like.  */
1122           && !TREE_ADDRESSABLE (type))
1123         {
1124           lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1125           lp->stmts.create (0);
1126           lp->entry_block = entry_block;
1127           /* Save addresses separately in dominator order so we don't
1128              get confused by overlapping addresses in the save/restore
1129              sequence.  */
1130           tm_log_save_addresses.safe_push (lp->addr);
1131         }
1132       else
1133         {
1134           /* Use the logging functions.  */
1135           lp->stmts.create (5);
1136           lp->stmts.quick_push (stmt);
1137           lp->save_var = NULL;
1138         }
1139     }
1140   else
1141     {
1142       size_t i;
1143       gimple oldstmt;
1144
1145       lp = *slot;
1146
1147       /* If we're generating a save/restore sequence, we don't care
1148          about statements.  */
1149       if (lp->save_var)
1150         return;
1151
1152       for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1153         {
1154           if (stmt == oldstmt)
1155             return;
1156           /* We already have a store to the same address, higher up the
1157              dominator tree.  Nothing to do.  */
1158           if (dominated_by_p (CDI_DOMINATORS,
1159                               gimple_bb (stmt), gimple_bb (oldstmt)))
1160             return;
1161           /* We should be processing blocks in dominator tree order.  */
1162           gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1163                                        gimple_bb (oldstmt), gimple_bb (stmt)));
1164         }
1165       /* Store is on a different code path.  */
1166       lp->stmts.safe_push (stmt);
1167     }
1168 }
1169
1170 /* Gimplify the address of a TARGET_MEM_REF.  Return the SSA_NAME
1171    result, insert the new statements before GSI.  */
1172
1173 static tree
1174 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1175 {
1176   if (TREE_CODE (x) == TARGET_MEM_REF)
1177     x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1178   else
1179     x = build_fold_addr_expr (x);
1180   return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1181 }
1182
1183 /* Instrument one address with the logging functions.
1184    ADDR is the address to save.
1185    STMT is the statement before which to place it.  */
1186 static void
1187 tm_log_emit_stmt (tree addr, gimple stmt)
1188 {
1189   tree type = TREE_TYPE (addr);
1190   tree size = TYPE_SIZE_UNIT (type);
1191   gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1192   gimple log;
1193   enum built_in_function code = BUILT_IN_TM_LOG;
1194
1195   if (type == float_type_node)
1196     code = BUILT_IN_TM_LOG_FLOAT;
1197   else if (type == double_type_node)
1198     code = BUILT_IN_TM_LOG_DOUBLE;
1199   else if (type == long_double_type_node)
1200     code = BUILT_IN_TM_LOG_LDOUBLE;
1201   else if (tree_fits_uhwi_p (size))
1202     {
1203       unsigned int n = tree_to_uhwi (size);
1204       switch (n)
1205         {
1206         case 1:
1207           code = BUILT_IN_TM_LOG_1;
1208           break;
1209         case 2:
1210           code = BUILT_IN_TM_LOG_2;
1211           break;
1212         case 4:
1213           code = BUILT_IN_TM_LOG_4;
1214           break;
1215         case 8:
1216           code = BUILT_IN_TM_LOG_8;
1217           break;
1218         default:
1219           code = BUILT_IN_TM_LOG;
1220           if (TREE_CODE (type) == VECTOR_TYPE)
1221             {
1222               if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1223                 code = BUILT_IN_TM_LOG_M64;
1224               else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1225                 code = BUILT_IN_TM_LOG_M128;
1226               else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1227                 code = BUILT_IN_TM_LOG_M256;
1228             }
1229           break;
1230         }
1231     }
1232
1233   addr = gimplify_addr (&gsi, addr);
1234   if (code == BUILT_IN_TM_LOG)
1235     log = gimple_build_call (builtin_decl_explicit (code), 2, addr,  size);
1236   else
1237     log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1238   gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1239 }
1240
1241 /* Go through the log and instrument address that must be instrumented
1242    with the logging functions.  Leave the save/restore addresses for
1243    later.  */
1244 static void
1245 tm_log_emit (void)
1246 {
1247   hash_table <log_entry_hasher>::iterator hi;
1248   struct tm_log_entry *lp;
1249
1250   FOR_EACH_HASH_TABLE_ELEMENT (tm_log, lp, tm_log_entry_t, hi)
1251     {
1252       size_t i;
1253       gimple stmt;
1254
1255       if (dump_file)
1256         {
1257           fprintf (dump_file, "TM thread private mem logging: ");
1258           print_generic_expr (dump_file, lp->addr, 0);
1259           fprintf (dump_file, "\n");
1260         }
1261
1262       if (lp->save_var)
1263         {
1264           if (dump_file)
1265             fprintf (dump_file, "DUMPING to variable\n");
1266           continue;
1267         }
1268       else
1269         {
1270           if (dump_file)
1271             fprintf (dump_file, "DUMPING with logging functions\n");
1272           for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1273             tm_log_emit_stmt (lp->addr, stmt);
1274         }
1275     }
1276 }
1277
1278 /* Emit the save sequence for the corresponding addresses in the log.
1279    ENTRY_BLOCK is the entry block for the transaction.
1280    BB is the basic block to insert the code in.  */
1281 static void
1282 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1283 {
1284   size_t i;
1285   gimple_stmt_iterator gsi = gsi_last_bb (bb);
1286   gimple stmt;
1287   struct tm_log_entry l, *lp;
1288
1289   for (i = 0; i < tm_log_save_addresses.length (); ++i)
1290     {
1291       l.addr = tm_log_save_addresses[i];
1292       lp = *(tm_log.find_slot (&l, NO_INSERT));
1293       gcc_assert (lp->save_var != NULL);
1294
1295       /* We only care about variables in the current transaction.  */
1296       if (lp->entry_block != entry_block)
1297         continue;
1298
1299       stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1300
1301       /* Make sure we can create an SSA_NAME for this type.  For
1302          instance, aggregates aren't allowed, in which case the system
1303          will create a VOP for us and everything will just work.  */
1304       if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1305         {
1306           lp->save_var = make_ssa_name (lp->save_var, stmt);
1307           gimple_assign_set_lhs (stmt, lp->save_var);
1308         }
1309
1310       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1311     }
1312 }
1313
1314 /* Emit the restore sequence for the corresponding addresses in the log.
1315    ENTRY_BLOCK is the entry block for the transaction.
1316    BB is the basic block to insert the code in.  */
1317 static void
1318 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1319 {
1320   int i;
1321   struct tm_log_entry l, *lp;
1322   gimple_stmt_iterator gsi;
1323   gimple stmt;
1324
1325   for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1326     {
1327       l.addr = tm_log_save_addresses[i];
1328       lp = *(tm_log.find_slot (&l, NO_INSERT));
1329       gcc_assert (lp->save_var != NULL);
1330
1331       /* We only care about variables in the current transaction.  */
1332       if (lp->entry_block != entry_block)
1333         continue;
1334
1335       /* Restores are in LIFO order from the saves in case we have
1336          overlaps.  */
1337       gsi = gsi_start_bb (bb);
1338
1339       stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1340       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1341     }
1342 }
1343
1344 \f
1345 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1346                                struct walk_stmt_info *);
1347 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1348                                   struct walk_stmt_info *);
1349
1350 /* Evaluate an address X being dereferenced and determine if it
1351    originally points to a non aliased new chunk of memory (malloc,
1352    alloca, etc).
1353
1354    Return MEM_THREAD_LOCAL if it points to a thread-local address.
1355    Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1356    Return MEM_NON_LOCAL otherwise.
1357
1358    ENTRY_BLOCK is the entry block to the transaction containing the
1359    dereference of X.  */
1360 static enum thread_memory_type
1361 thread_private_new_memory (basic_block entry_block, tree x)
1362 {
1363   gimple stmt = NULL;
1364   enum tree_code code;
1365   tm_new_mem_map_t **slot;
1366   tm_new_mem_map_t elt, *elt_p;
1367   tree val = x;
1368   enum thread_memory_type retval = mem_transaction_local;
1369
1370   if (!entry_block
1371       || TREE_CODE (x) != SSA_NAME
1372       /* Possible uninitialized use, or a function argument.  In
1373          either case, we don't care.  */
1374       || SSA_NAME_IS_DEFAULT_DEF (x))
1375     return mem_non_local;
1376
1377   /* Look in cache first.  */
1378   elt.val = x;
1379   slot = tm_new_mem_hash.find_slot (&elt, INSERT);
1380   elt_p = *slot;
1381   if (elt_p)
1382     return elt_p->local_new_memory;
1383
1384   /* Optimistically assume the memory is transaction local during
1385      processing.  This catches recursion into this variable.  */
1386   *slot = elt_p = XNEW (tm_new_mem_map_t);
1387   elt_p->val = val;
1388   elt_p->local_new_memory = mem_transaction_local;
1389
1390   /* Search DEF chain to find the original definition of this address.  */
1391   do
1392     {
1393       if (ptr_deref_may_alias_global_p (x))
1394         {
1395           /* Address escapes.  This is not thread-private.  */
1396           retval = mem_non_local;
1397           goto new_memory_ret;
1398         }
1399
1400       stmt = SSA_NAME_DEF_STMT (x);
1401
1402       /* If the malloc call is outside the transaction, this is
1403          thread-local.  */
1404       if (retval != mem_thread_local
1405           && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1406         retval = mem_thread_local;
1407
1408       if (is_gimple_assign (stmt))
1409         {
1410           code = gimple_assign_rhs_code (stmt);
1411           /* x = foo ==> foo */
1412           if (code == SSA_NAME)
1413             x = gimple_assign_rhs1 (stmt);
1414           /* x = foo + n ==> foo */
1415           else if (code == POINTER_PLUS_EXPR)
1416             x = gimple_assign_rhs1 (stmt);
1417           /* x = (cast*) foo ==> foo */
1418           else if (code == VIEW_CONVERT_EXPR || code == NOP_EXPR)
1419             x = gimple_assign_rhs1 (stmt);
1420           /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1421           else if (code == COND_EXPR)
1422             {
1423               tree op1 = gimple_assign_rhs2 (stmt);
1424               tree op2 = gimple_assign_rhs3 (stmt);
1425               enum thread_memory_type mem;
1426               retval = thread_private_new_memory (entry_block, op1);
1427               if (retval == mem_non_local)
1428                 goto new_memory_ret;
1429               mem = thread_private_new_memory (entry_block, op2);
1430               retval = MIN (retval, mem);
1431               goto new_memory_ret;
1432             }
1433           else
1434             {
1435               retval = mem_non_local;
1436               goto new_memory_ret;
1437             }
1438         }
1439       else
1440         {
1441           if (gimple_code (stmt) == GIMPLE_PHI)
1442             {
1443               unsigned int i;
1444               enum thread_memory_type mem;
1445               tree phi_result = gimple_phi_result (stmt);
1446
1447               /* If any of the ancestors are non-local, we are sure to
1448                  be non-local.  Otherwise we can avoid doing anything
1449                  and inherit what has already been generated.  */
1450               retval = mem_max;
1451               for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1452                 {
1453                   tree op = PHI_ARG_DEF (stmt, i);
1454
1455                   /* Exclude self-assignment.  */
1456                   if (phi_result == op)
1457                     continue;
1458
1459                   mem = thread_private_new_memory (entry_block, op);
1460                   if (mem == mem_non_local)
1461                     {
1462                       retval = mem;
1463                       goto new_memory_ret;
1464                     }
1465                   retval = MIN (retval, mem);
1466                 }
1467               goto new_memory_ret;
1468             }
1469           break;
1470         }
1471     }
1472   while (TREE_CODE (x) == SSA_NAME);
1473
1474   if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1475     /* Thread-local or transaction-local.  */
1476     ;
1477   else
1478     retval = mem_non_local;
1479
1480  new_memory_ret:
1481   elt_p->local_new_memory = retval;
1482   return retval;
1483 }
1484
1485 /* Determine whether X has to be instrumented using a read
1486    or write barrier.
1487
1488    ENTRY_BLOCK is the entry block for the region where stmt resides
1489    in.  NULL if unknown.
1490
1491    STMT is the statement in which X occurs in.  It is used for thread
1492    private memory instrumentation.  If no TPM instrumentation is
1493    desired, STMT should be null.  */
1494 static bool
1495 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1496 {
1497   tree orig = x;
1498   while (handled_component_p (x))
1499     x = TREE_OPERAND (x, 0);
1500
1501   switch (TREE_CODE (x))
1502     {
1503     case INDIRECT_REF:
1504     case MEM_REF:
1505       {
1506         enum thread_memory_type ret;
1507
1508         ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1509         if (ret == mem_non_local)
1510           return true;
1511         if (stmt && ret == mem_thread_local)
1512           /* ?? Should we pass `orig', or the INDIRECT_REF X.  ?? */
1513           tm_log_add (entry_block, orig, stmt);
1514
1515         /* Transaction-locals require nothing at all.  For malloc, a
1516            transaction restart frees the memory and we reallocate.
1517            For alloca, the stack pointer gets reset by the retry and
1518            we reallocate.  */
1519         return false;
1520       }
1521
1522     case TARGET_MEM_REF:
1523       if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1524         return true;
1525       x = TREE_OPERAND (TMR_BASE (x), 0);
1526       if (TREE_CODE (x) == PARM_DECL)
1527         return false;
1528       gcc_assert (TREE_CODE (x) == VAR_DECL);
1529       /* FALLTHRU */
1530
1531     case PARM_DECL:
1532     case RESULT_DECL:
1533     case VAR_DECL:
1534       if (DECL_BY_REFERENCE (x))
1535         {
1536           /* ??? This value is a pointer, but aggregate_value_p has been
1537              jigged to return true which confuses needs_to_live_in_memory.
1538              This ought to be cleaned up generically.
1539
1540              FIXME: Verify this still happens after the next mainline
1541              merge.  Testcase ie g++.dg/tm/pr47554.C.
1542           */
1543           return false;
1544         }
1545
1546       if (is_global_var (x))
1547         return !TREE_READONLY (x);
1548       if (/* FIXME: This condition should actually go below in the
1549              tm_log_add() call, however is_call_clobbered() depends on
1550              aliasing info which is not available during
1551              gimplification.  Since requires_barrier() gets called
1552              during lower_sequence_tm/gimplification, leave the call
1553              to needs_to_live_in_memory until we eliminate
1554              lower_sequence_tm altogether.  */
1555           needs_to_live_in_memory (x))
1556         return true;
1557       else
1558         {
1559           /* For local memory that doesn't escape (aka thread private
1560              memory), we can either save the value at the beginning of
1561              the transaction and restore on restart, or call a tm
1562              function to dynamically save and restore on restart
1563              (ITM_L*).  */
1564           if (stmt)
1565             tm_log_add (entry_block, orig, stmt);
1566           return false;
1567         }
1568
1569     default:
1570       return false;
1571     }
1572 }
1573
1574 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1575    a transaction region.  */
1576
1577 static void
1578 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1579 {
1580   gimple stmt = gsi_stmt (*gsi);
1581
1582   if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1583     *state |= GTMA_HAVE_LOAD;
1584   if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1585     *state |= GTMA_HAVE_STORE;
1586 }
1587
1588 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction.  */
1589
1590 static void
1591 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1592 {
1593   gimple stmt = gsi_stmt (*gsi);
1594   tree fn;
1595
1596   if (is_tm_pure_call (stmt))
1597     return;
1598
1599   /* Check if this call is a transaction abort.  */
1600   fn = gimple_call_fndecl (stmt);
1601   if (is_tm_abort (fn))
1602     *state |= GTMA_HAVE_ABORT;
1603
1604   /* Note that something may happen.  */
1605   *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1606 }
1607
1608 /* Lower a GIMPLE_TRANSACTION statement.  */
1609
1610 static void
1611 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1612 {
1613   gimple g, stmt = gsi_stmt (*gsi);
1614   unsigned int *outer_state = (unsigned int *) wi->info;
1615   unsigned int this_state = 0;
1616   struct walk_stmt_info this_wi;
1617
1618   /* First, lower the body.  The scanning that we do inside gives
1619      us some idea of what we're dealing with.  */
1620   memset (&this_wi, 0, sizeof (this_wi));
1621   this_wi.info = (void *) &this_state;
1622   walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1623                        lower_sequence_tm, NULL, &this_wi);
1624
1625   /* If there was absolutely nothing transaction related inside the
1626      transaction, we may elide it.  Likewise if this is a nested
1627      transaction and does not contain an abort.  */
1628   if (this_state == 0
1629       || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1630     {
1631       if (outer_state)
1632         *outer_state |= this_state;
1633
1634       gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1635                              GSI_SAME_STMT);
1636       gimple_transaction_set_body (stmt, NULL);
1637
1638       gsi_remove (gsi, true);
1639       wi->removed_stmt = true;
1640       return;
1641     }
1642
1643   /* Wrap the body of the transaction in a try-finally node so that
1644      the commit call is always properly called.  */
1645   g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1646   if (flag_exceptions)
1647     {
1648       tree ptr;
1649       gimple_seq n_seq, e_seq;
1650
1651       n_seq = gimple_seq_alloc_with_stmt (g);
1652       e_seq = NULL;
1653
1654       g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1655                              1, integer_zero_node);
1656       ptr = create_tmp_var (ptr_type_node, NULL);
1657       gimple_call_set_lhs (g, ptr);
1658       gimple_seq_add_stmt (&e_seq, g);
1659
1660       g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1661                              1, ptr);
1662       gimple_seq_add_stmt (&e_seq, g);
1663
1664       g = gimple_build_eh_else (n_seq, e_seq);
1665     }
1666
1667   g = gimple_build_try (gimple_transaction_body (stmt),
1668                         gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1669   gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1670
1671   gimple_transaction_set_body (stmt, NULL);
1672
1673   /* If the transaction calls abort or if this is an outer transaction,
1674      add an "over" label afterwards.  */
1675   if ((this_state & (GTMA_HAVE_ABORT))
1676       || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1677     {
1678       tree label = create_artificial_label (UNKNOWN_LOCATION);
1679       gimple_transaction_set_label (stmt, label);
1680       gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1681     }
1682
1683   /* Record the set of operations found for use later.  */
1684   this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1685   gimple_transaction_set_subcode (stmt, this_state);
1686 }
1687
1688 /* Iterate through the statements in the sequence, lowering them all
1689    as appropriate for being in a transaction.  */
1690
1691 static tree
1692 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1693                    struct walk_stmt_info *wi)
1694 {
1695   unsigned int *state = (unsigned int *) wi->info;
1696   gimple stmt = gsi_stmt (*gsi);
1697
1698   *handled_ops_p = true;
1699   switch (gimple_code (stmt))
1700     {
1701     case GIMPLE_ASSIGN:
1702       /* Only memory reads/writes need to be instrumented.  */
1703       if (gimple_assign_single_p (stmt))
1704         examine_assign_tm (state, gsi);
1705       break;
1706
1707     case GIMPLE_CALL:
1708       examine_call_tm (state, gsi);
1709       break;
1710
1711     case GIMPLE_ASM:
1712       *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1713       break;
1714
1715     case GIMPLE_TRANSACTION:
1716       lower_transaction (gsi, wi);
1717       break;
1718
1719     default:
1720       *handled_ops_p = !gimple_has_substatements (stmt);
1721       break;
1722     }
1723
1724   return NULL_TREE;
1725 }
1726
1727 /* Iterate through the statements in the sequence, lowering them all
1728    as appropriate for being outside of a transaction.  */
1729
1730 static tree
1731 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1732                       struct walk_stmt_info * wi)
1733 {
1734   gimple stmt = gsi_stmt (*gsi);
1735
1736   if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1737     {
1738       *handled_ops_p = true;
1739       lower_transaction (gsi, wi);
1740     }
1741   else
1742     *handled_ops_p = !gimple_has_substatements (stmt);
1743
1744   return NULL_TREE;
1745 }
1746
1747 /* Main entry point for flattening GIMPLE_TRANSACTION constructs.  After
1748    this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1749    been moved out, and all the data required for constructing a proper
1750    CFG has been recorded.  */
1751
1752 static unsigned int
1753 execute_lower_tm (void)
1754 {
1755   struct walk_stmt_info wi;
1756   gimple_seq body;
1757
1758   /* Transactional clones aren't created until a later pass.  */
1759   gcc_assert (!decl_is_tm_clone (current_function_decl));
1760
1761   body = gimple_body (current_function_decl);
1762   memset (&wi, 0, sizeof (wi));
1763   walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1764   gimple_set_body (current_function_decl, body);
1765
1766   return 0;
1767 }
1768
1769 namespace {
1770
1771 const pass_data pass_data_lower_tm =
1772 {
1773   GIMPLE_PASS, /* type */
1774   "tmlower", /* name */
1775   OPTGROUP_NONE, /* optinfo_flags */
1776   true, /* has_gate */
1777   true, /* has_execute */
1778   TV_TRANS_MEM, /* tv_id */
1779   PROP_gimple_lcf, /* properties_required */
1780   0, /* properties_provided */
1781   0, /* properties_destroyed */
1782   0, /* todo_flags_start */
1783   0, /* todo_flags_finish */
1784 };
1785
1786 class pass_lower_tm : public gimple_opt_pass
1787 {
1788 public:
1789   pass_lower_tm (gcc::context *ctxt)
1790     : gimple_opt_pass (pass_data_lower_tm, ctxt)
1791   {}
1792
1793   /* opt_pass methods: */
1794   bool gate () { return gate_tm (); }
1795   unsigned int execute () { return execute_lower_tm (); }
1796
1797 }; // class pass_lower_tm
1798
1799 } // anon namespace
1800
1801 gimple_opt_pass *
1802 make_pass_lower_tm (gcc::context *ctxt)
1803 {
1804   return new pass_lower_tm (ctxt);
1805 }
1806 \f
1807 /* Collect region information for each transaction.  */
1808
1809 struct tm_region
1810 {
1811   /* Link to the next unnested transaction.  */
1812   struct tm_region *next;
1813
1814   /* Link to the next inner transaction.  */
1815   struct tm_region *inner;
1816
1817   /* Link to the next outer transaction.  */
1818   struct tm_region *outer;
1819
1820   /* The GIMPLE_TRANSACTION statement beginning this transaction.
1821      After TM_MARK, this gets replaced by a call to
1822      BUILT_IN_TM_START.  */
1823   gimple transaction_stmt;
1824
1825   /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1826      BUILT_IN_TM_START, this field is true if the transaction is an
1827      outer transaction.  */
1828   bool original_transaction_was_outer;
1829
1830   /* Return value from BUILT_IN_TM_START.  */
1831   tree tm_state;
1832
1833   /* The entry block to this region.  This will always be the first
1834      block of the body of the transaction.  */
1835   basic_block entry_block;
1836
1837   /* The first block after an expanded call to _ITM_beginTransaction.  */
1838   basic_block restart_block;
1839
1840   /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1841      These blocks are still a part of the region (i.e., the border is
1842      inclusive). Note that this set is only complete for paths in the CFG
1843      starting at ENTRY_BLOCK, and that there is no exit block recorded for
1844      the edge to the "over" label.  */
1845   bitmap exit_blocks;
1846
1847   /* The set of all blocks that have an TM_IRREVOCABLE call.  */
1848   bitmap irr_blocks;
1849 };
1850
1851 typedef struct tm_region *tm_region_p;
1852
1853 /* True if there are pending edge statements to be committed for the
1854    current function being scanned in the tmmark pass.  */
1855 bool pending_edge_inserts_p;
1856
1857 static struct tm_region *all_tm_regions;
1858 static bitmap_obstack tm_obstack;
1859
1860
1861 /* A subroutine of tm_region_init.  Record the existence of the
1862    GIMPLE_TRANSACTION statement in a tree of tm_region elements.  */
1863
1864 static struct tm_region *
1865 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1866 {
1867   struct tm_region *region;
1868
1869   region = (struct tm_region *)
1870     obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1871
1872   if (outer)
1873     {
1874       region->next = outer->inner;
1875       outer->inner = region;
1876     }
1877   else
1878     {
1879       region->next = all_tm_regions;
1880       all_tm_regions = region;
1881     }
1882   region->inner = NULL;
1883   region->outer = outer;
1884
1885   region->transaction_stmt = stmt;
1886   region->original_transaction_was_outer = false;
1887   region->tm_state = NULL;
1888
1889   /* There are either one or two edges out of the block containing
1890      the GIMPLE_TRANSACTION, one to the actual region and one to the
1891      "over" label if the region contains an abort.  The former will
1892      always be the one marked FALLTHRU.  */
1893   region->entry_block = FALLTHRU_EDGE (bb)->dest;
1894
1895   region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1896   region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1897
1898   return region;
1899 }
1900
1901 /* A subroutine of tm_region_init.  Record all the exit and
1902    irrevocable blocks in BB into the region's exit_blocks and
1903    irr_blocks bitmaps.  Returns the new region being scanned.  */
1904
1905 static struct tm_region *
1906 tm_region_init_1 (struct tm_region *region, basic_block bb)
1907 {
1908   gimple_stmt_iterator gsi;
1909   gimple g;
1910
1911   if (!region
1912       || (!region->irr_blocks && !region->exit_blocks))
1913     return region;
1914
1915   /* Check to see if this is the end of a region by seeing if it
1916      contains a call to __builtin_tm_commit{,_eh}.  Note that the
1917      outermost region for DECL_IS_TM_CLONE need not collect this.  */
1918   for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1919     {
1920       g = gsi_stmt (gsi);
1921       if (gimple_code (g) == GIMPLE_CALL)
1922         {
1923           tree fn = gimple_call_fndecl (g);
1924           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1925             {
1926               if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1927                    || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1928                   && region->exit_blocks)
1929                 {
1930                   bitmap_set_bit (region->exit_blocks, bb->index);
1931                   region = region->outer;
1932                   break;
1933                 }
1934               if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1935                 bitmap_set_bit (region->irr_blocks, bb->index);
1936             }
1937         }
1938     }
1939   return region;
1940 }
1941
1942 /* Collect all of the transaction regions within the current function
1943    and record them in ALL_TM_REGIONS.  The REGION parameter may specify
1944    an "outermost" region for use by tm clones.  */
1945
1946 static void
1947 tm_region_init (struct tm_region *region)
1948 {
1949   gimple g;
1950   edge_iterator ei;
1951   edge e;
1952   basic_block bb;
1953   auto_vec<basic_block> queue;
1954   bitmap visited_blocks = BITMAP_ALLOC (NULL);
1955   struct tm_region *old_region;
1956   auto_vec<tm_region_p> bb_regions;
1957
1958   all_tm_regions = region;
1959   bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1960
1961   /* We could store this information in bb->aux, but we may get called
1962      through get_all_tm_blocks() from another pass that may be already
1963      using bb->aux.  */
1964   bb_regions.safe_grow_cleared (last_basic_block);
1965
1966   queue.safe_push (bb);
1967   bb_regions[bb->index] = region;
1968   do
1969     {
1970       bb = queue.pop ();
1971       region = bb_regions[bb->index];
1972       bb_regions[bb->index] = NULL;
1973
1974       /* Record exit and irrevocable blocks.  */
1975       region = tm_region_init_1 (region, bb);
1976
1977       /* Check for the last statement in the block beginning a new region.  */
1978       g = last_stmt (bb);
1979       old_region = region;
1980       if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1981         region = tm_region_init_0 (region, bb, g);
1982
1983       /* Process subsequent blocks.  */
1984       FOR_EACH_EDGE (e, ei, bb->succs)
1985         if (!bitmap_bit_p (visited_blocks, e->dest->index))
1986           {
1987             bitmap_set_bit (visited_blocks, e->dest->index);
1988             queue.safe_push (e->dest);
1989
1990             /* If the current block started a new region, make sure that only
1991                the entry block of the new region is associated with this region.
1992                Other successors are still part of the old region.  */
1993             if (old_region != region && e->dest != region->entry_block)
1994               bb_regions[e->dest->index] = old_region;
1995             else
1996               bb_regions[e->dest->index] = region;
1997           }
1998     }
1999   while (!queue.is_empty ());
2000   BITMAP_FREE (visited_blocks);
2001 }
2002
2003 /* The "gate" function for all transactional memory expansion and optimization
2004    passes.  We collect region information for each top-level transaction, and
2005    if we don't find any, we skip all of the TM passes.  Each region will have
2006    all of the exit blocks recorded, and the originating statement.  */
2007
2008 static bool
2009 gate_tm_init (void)
2010 {
2011   if (!flag_tm)
2012     return false;
2013
2014   calculate_dominance_info (CDI_DOMINATORS);
2015   bitmap_obstack_initialize (&tm_obstack);
2016
2017   /* If the function is a TM_CLONE, then the entire function is the region.  */
2018   if (decl_is_tm_clone (current_function_decl))
2019     {
2020       struct tm_region *region = (struct tm_region *)
2021         obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
2022       memset (region, 0, sizeof (*region));
2023       region->entry_block = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
2024       /* For a clone, the entire function is the region.  But even if
2025          we don't need to record any exit blocks, we may need to
2026          record irrevocable blocks.  */
2027       region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
2028
2029       tm_region_init (region);
2030     }
2031   else
2032     {
2033       tm_region_init (NULL);
2034
2035       /* If we didn't find any regions, cleanup and skip the whole tree
2036          of tm-related optimizations.  */
2037       if (all_tm_regions == NULL)
2038         {
2039           bitmap_obstack_release (&tm_obstack);
2040           return false;
2041         }
2042     }
2043
2044   return true;
2045 }
2046
2047 namespace {
2048
2049 const pass_data pass_data_tm_init =
2050 {
2051   GIMPLE_PASS, /* type */
2052   "*tminit", /* name */
2053   OPTGROUP_NONE, /* optinfo_flags */
2054   true, /* has_gate */
2055   false, /* has_execute */
2056   TV_TRANS_MEM, /* tv_id */
2057   ( PROP_ssa | PROP_cfg ), /* properties_required */
2058   0, /* properties_provided */
2059   0, /* properties_destroyed */
2060   0, /* todo_flags_start */
2061   0, /* todo_flags_finish */
2062 };
2063
2064 class pass_tm_init : public gimple_opt_pass
2065 {
2066 public:
2067   pass_tm_init (gcc::context *ctxt)
2068     : gimple_opt_pass (pass_data_tm_init, ctxt)
2069   {}
2070
2071   /* opt_pass methods: */
2072   bool gate () { return gate_tm_init (); }
2073
2074 }; // class pass_tm_init
2075
2076 } // anon namespace
2077
2078 gimple_opt_pass *
2079 make_pass_tm_init (gcc::context *ctxt)
2080 {
2081   return new pass_tm_init (ctxt);
2082 }
2083 \f
2084 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2085    represented by STATE.  */
2086
2087 static inline void
2088 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2089 {
2090   if (region && region->transaction_stmt)
2091     {
2092       flags |= gimple_transaction_subcode (region->transaction_stmt);
2093       gimple_transaction_set_subcode (region->transaction_stmt, flags);
2094     }
2095 }
2096
2097 /* Construct a memory load in a transactional context.  Return the
2098    gimple statement performing the load, or NULL if there is no
2099    TM_LOAD builtin of the appropriate size to do the load.
2100
2101    LOC is the location to use for the new statement(s).  */
2102
2103 static gimple
2104 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2105 {
2106   enum built_in_function code = END_BUILTINS;
2107   tree t, type = TREE_TYPE (rhs), decl;
2108   gimple gcall;
2109
2110   if (type == float_type_node)
2111     code = BUILT_IN_TM_LOAD_FLOAT;
2112   else if (type == double_type_node)
2113     code = BUILT_IN_TM_LOAD_DOUBLE;
2114   else if (type == long_double_type_node)
2115     code = BUILT_IN_TM_LOAD_LDOUBLE;
2116   else if (TYPE_SIZE_UNIT (type) != NULL
2117            && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2118     {
2119       switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2120         {
2121         case 1:
2122           code = BUILT_IN_TM_LOAD_1;
2123           break;
2124         case 2:
2125           code = BUILT_IN_TM_LOAD_2;
2126           break;
2127         case 4:
2128           code = BUILT_IN_TM_LOAD_4;
2129           break;
2130         case 8:
2131           code = BUILT_IN_TM_LOAD_8;
2132           break;
2133         }
2134     }
2135
2136   if (code == END_BUILTINS)
2137     {
2138       decl = targetm.vectorize.builtin_tm_load (type);
2139       if (!decl)
2140         return NULL;
2141     }
2142   else
2143     decl = builtin_decl_explicit (code);
2144
2145   t = gimplify_addr (gsi, rhs);
2146   gcall = gimple_build_call (decl, 1, t);
2147   gimple_set_location (gcall, loc);
2148
2149   t = TREE_TYPE (TREE_TYPE (decl));
2150   if (useless_type_conversion_p (type, t))
2151     {
2152       gimple_call_set_lhs (gcall, lhs);
2153       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2154     }
2155   else
2156     {
2157       gimple g;
2158       tree temp;
2159
2160       temp = create_tmp_reg (t, NULL);
2161       gimple_call_set_lhs (gcall, temp);
2162       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2163
2164       t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2165       g = gimple_build_assign (lhs, t);
2166       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2167     }
2168
2169   return gcall;
2170 }
2171
2172
2173 /* Similarly for storing TYPE in a transactional context.  */
2174
2175 static gimple
2176 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2177 {
2178   enum built_in_function code = END_BUILTINS;
2179   tree t, fn, type = TREE_TYPE (rhs), simple_type;
2180   gimple gcall;
2181
2182   if (type == float_type_node)
2183     code = BUILT_IN_TM_STORE_FLOAT;
2184   else if (type == double_type_node)
2185     code = BUILT_IN_TM_STORE_DOUBLE;
2186   else if (type == long_double_type_node)
2187     code = BUILT_IN_TM_STORE_LDOUBLE;
2188   else if (TYPE_SIZE_UNIT (type) != NULL
2189            && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2190     {
2191       switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2192         {
2193         case 1:
2194           code = BUILT_IN_TM_STORE_1;
2195           break;
2196         case 2:
2197           code = BUILT_IN_TM_STORE_2;
2198           break;
2199         case 4:
2200           code = BUILT_IN_TM_STORE_4;
2201           break;
2202         case 8:
2203           code = BUILT_IN_TM_STORE_8;
2204           break;
2205         }
2206     }
2207
2208   if (code == END_BUILTINS)
2209     {
2210       fn = targetm.vectorize.builtin_tm_store (type);
2211       if (!fn)
2212         return NULL;
2213     }
2214   else
2215     fn = builtin_decl_explicit (code);
2216
2217   simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2218
2219   if (TREE_CODE (rhs) == CONSTRUCTOR)
2220     {
2221       /* Handle the easy initialization to zero.  */
2222       if (!CONSTRUCTOR_ELTS (rhs))
2223         rhs = build_int_cst (simple_type, 0);
2224       else
2225         {
2226           /* ...otherwise punt to the caller and probably use
2227             BUILT_IN_TM_MEMMOVE, because we can't wrap a
2228             VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2229             valid gimple.  */
2230           return NULL;
2231         }
2232     }
2233   else if (!useless_type_conversion_p (simple_type, type))
2234     {
2235       gimple g;
2236       tree temp;
2237
2238       temp = create_tmp_reg (simple_type, NULL);
2239       t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2240       g = gimple_build_assign (temp, t);
2241       gimple_set_location (g, loc);
2242       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2243
2244       rhs = temp;
2245     }
2246
2247   t = gimplify_addr (gsi, lhs);
2248   gcall = gimple_build_call (fn, 2, t, rhs);
2249   gimple_set_location (gcall, loc);
2250   gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2251
2252   return gcall;
2253 }
2254
2255
2256 /* Expand an assignment statement into transactional builtins.  */
2257
2258 static void
2259 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2260 {
2261   gimple stmt = gsi_stmt (*gsi);
2262   location_t loc = gimple_location (stmt);
2263   tree lhs = gimple_assign_lhs (stmt);
2264   tree rhs = gimple_assign_rhs1 (stmt);
2265   bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2266   bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2267   gimple gcall = NULL;
2268
2269   if (!load_p && !store_p)
2270     {
2271       /* Add thread private addresses to log if applicable.  */
2272       requires_barrier (region->entry_block, lhs, stmt);
2273       gsi_next (gsi);
2274       return;
2275     }
2276
2277   // Remove original load/store statement.
2278   gsi_remove (gsi, true);
2279
2280   if (load_p && !store_p)
2281     {
2282       transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2283       gcall = build_tm_load (loc, lhs, rhs, gsi);
2284     }
2285   else if (store_p && !load_p)
2286     {
2287       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2288       gcall = build_tm_store (loc, lhs, rhs, gsi);
2289     }
2290   if (!gcall)
2291     {
2292       tree lhs_addr, rhs_addr, tmp;
2293
2294       if (load_p)
2295         transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2296       if (store_p)
2297         transaction_subcode_ior (region, GTMA_HAVE_STORE);
2298
2299       /* ??? Figure out if there's any possible overlap between the LHS
2300          and the RHS and if not, use MEMCPY.  */
2301
2302       if (load_p && is_gimple_reg (lhs))
2303         {
2304           tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2305           lhs_addr = build_fold_addr_expr (tmp);
2306         }
2307       else
2308         {
2309           tmp = NULL_TREE;
2310           lhs_addr = gimplify_addr (gsi, lhs);
2311         }
2312       rhs_addr = gimplify_addr (gsi, rhs);
2313       gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2314                                  3, lhs_addr, rhs_addr,
2315                                  TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2316       gimple_set_location (gcall, loc);
2317       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2318
2319       if (tmp)
2320         {
2321           gcall = gimple_build_assign (lhs, tmp);
2322           gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2323         }
2324     }
2325
2326   /* Now that we have the load/store in its instrumented form, add
2327      thread private addresses to the log if applicable.  */
2328   if (!store_p)
2329     requires_barrier (region->entry_block, lhs, gcall);
2330
2331   // The calls to build_tm_{store,load} above inserted the instrumented
2332   // call into the stream.
2333   // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2334 }
2335
2336
2337 /* Expand a call statement as appropriate for a transaction.  That is,
2338    either verify that the call does not affect the transaction, or
2339    redirect the call to a clone that handles transactions, or change
2340    the transaction state to IRREVOCABLE.  Return true if the call is
2341    one of the builtins that end a transaction.  */
2342
2343 static bool
2344 expand_call_tm (struct tm_region *region,
2345                 gimple_stmt_iterator *gsi)
2346 {
2347   gimple stmt = gsi_stmt (*gsi);
2348   tree lhs = gimple_call_lhs (stmt);
2349   tree fn_decl;
2350   struct cgraph_node *node;
2351   bool retval = false;
2352
2353   fn_decl = gimple_call_fndecl (stmt);
2354
2355   if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2356       || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2357     transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2358   if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2359     transaction_subcode_ior (region, GTMA_HAVE_STORE);
2360
2361   if (is_tm_pure_call (stmt))
2362     return false;
2363
2364   if (fn_decl)
2365     retval = is_tm_ending_fndecl (fn_decl);
2366   if (!retval)
2367     {
2368       /* Assume all non-const/pure calls write to memory, except
2369          transaction ending builtins.  */
2370       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2371     }
2372
2373   /* For indirect calls, we already generated a call into the runtime.  */
2374   if (!fn_decl)
2375     {
2376       tree fn = gimple_call_fn (stmt);
2377
2378       /* We are guaranteed never to go irrevocable on a safe or pure
2379          call, and the pure call was handled above.  */
2380       if (is_tm_safe (fn))
2381         return false;
2382       else
2383         transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2384
2385       return false;
2386     }
2387
2388   node = cgraph_get_node (fn_decl);
2389   /* All calls should have cgraph here.  */
2390   if (!node)
2391     {
2392       /* We can have a nodeless call here if some pass after IPA-tm
2393          added uninstrumented calls.  For example, loop distribution
2394          can transform certain loop constructs into __builtin_mem*
2395          calls.  In this case, see if we have a suitable TM
2396          replacement and fill in the gaps.  */
2397       gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2398       enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2399       gcc_assert (code == BUILT_IN_MEMCPY
2400                   || code == BUILT_IN_MEMMOVE
2401                   || code == BUILT_IN_MEMSET);
2402
2403       tree repl = find_tm_replacement_function (fn_decl);
2404       if (repl)
2405         {
2406           gimple_call_set_fndecl (stmt, repl);
2407           update_stmt (stmt);
2408           node = cgraph_create_node (repl);
2409           node->local.tm_may_enter_irr = false;
2410           return expand_call_tm (region, gsi);
2411         }
2412       gcc_unreachable ();
2413     }
2414   if (node->local.tm_may_enter_irr)
2415     transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2416
2417   if (is_tm_abort (fn_decl))
2418     {
2419       transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2420       return true;
2421     }
2422
2423   /* Instrument the store if needed.
2424
2425      If the assignment happens inside the function call (return slot
2426      optimization), there is no instrumentation to be done, since
2427      the callee should have done the right thing.  */
2428   if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2429       && !gimple_call_return_slot_opt_p (stmt))
2430     {
2431       tree tmp = create_tmp_reg (TREE_TYPE (lhs), NULL);
2432       location_t loc = gimple_location (stmt);
2433       edge fallthru_edge = NULL;
2434
2435       /* Remember if the call was going to throw.  */
2436       if (stmt_can_throw_internal (stmt))
2437         {
2438           edge_iterator ei;
2439           edge e;
2440           basic_block bb = gimple_bb (stmt);
2441
2442           FOR_EACH_EDGE (e, ei, bb->succs)
2443             if (e->flags & EDGE_FALLTHRU)
2444               {
2445                 fallthru_edge = e;
2446                 break;
2447               }
2448         }
2449
2450       gimple_call_set_lhs (stmt, tmp);
2451       update_stmt (stmt);
2452       stmt = gimple_build_assign (lhs, tmp);
2453       gimple_set_location (stmt, loc);
2454
2455       /* We cannot throw in the middle of a BB.  If the call was going
2456          to throw, place the instrumentation on the fallthru edge, so
2457          the call remains the last statement in the block.  */
2458       if (fallthru_edge)
2459         {
2460           gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2461           gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2462           expand_assign_tm (region, &fallthru_gsi);
2463           gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2464           pending_edge_inserts_p = true;
2465         }
2466       else
2467         {
2468           gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2469           expand_assign_tm (region, gsi);
2470         }
2471
2472       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2473     }
2474
2475   return retval;
2476 }
2477
2478
2479 /* Expand all statements in BB as appropriate for being inside
2480    a transaction.  */
2481
2482 static void
2483 expand_block_tm (struct tm_region *region, basic_block bb)
2484 {
2485   gimple_stmt_iterator gsi;
2486
2487   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2488     {
2489       gimple stmt = gsi_stmt (gsi);
2490       switch (gimple_code (stmt))
2491         {
2492         case GIMPLE_ASSIGN:
2493           /* Only memory reads/writes need to be instrumented.  */
2494           if (gimple_assign_single_p (stmt)
2495               && !gimple_clobber_p (stmt))
2496             {
2497               expand_assign_tm (region, &gsi);
2498               continue;
2499             }
2500           break;
2501
2502         case GIMPLE_CALL:
2503           if (expand_call_tm (region, &gsi))
2504             return;
2505           break;
2506
2507         case GIMPLE_ASM:
2508           gcc_unreachable ();
2509
2510         default:
2511           break;
2512         }
2513       if (!gsi_end_p (gsi))
2514         gsi_next (&gsi);
2515     }
2516 }
2517
2518 /* Return the list of basic-blocks in REGION.
2519
2520    STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2521    following a TM_IRREVOCABLE call.
2522
2523    INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2524    uninstrumented code path blocks in the list of basic blocks
2525    returned, false otherwise.  */
2526
2527 static vec<basic_block> 
2528 get_tm_region_blocks (basic_block entry_block,
2529                       bitmap exit_blocks,
2530                       bitmap irr_blocks,
2531                       bitmap all_region_blocks,
2532                       bool stop_at_irrevocable_p,
2533                       bool include_uninstrumented_p = true)
2534 {
2535   vec<basic_block> bbs = vNULL;
2536   unsigned i;
2537   edge e;
2538   edge_iterator ei;
2539   bitmap visited_blocks = BITMAP_ALLOC (NULL);
2540
2541   i = 0;
2542   bbs.safe_push (entry_block);
2543   bitmap_set_bit (visited_blocks, entry_block->index);
2544
2545   do
2546     {
2547       basic_block bb = bbs[i++];
2548
2549       if (exit_blocks &&
2550           bitmap_bit_p (exit_blocks, bb->index))
2551         continue;
2552
2553       if (stop_at_irrevocable_p
2554           && irr_blocks
2555           && bitmap_bit_p (irr_blocks, bb->index))
2556         continue;
2557
2558       FOR_EACH_EDGE (e, ei, bb->succs)
2559         if ((include_uninstrumented_p
2560              || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2561             && !bitmap_bit_p (visited_blocks, e->dest->index))
2562           {
2563             bitmap_set_bit (visited_blocks, e->dest->index);
2564             bbs.safe_push (e->dest);
2565           }
2566     }
2567   while (i < bbs.length ());
2568
2569   if (all_region_blocks)
2570     bitmap_ior_into (all_region_blocks, visited_blocks);
2571
2572   BITMAP_FREE (visited_blocks);
2573   return bbs;
2574 }
2575
2576 // Callback data for collect_bb2reg.
2577 struct bb2reg_stuff
2578 {
2579   vec<tm_region_p> *bb2reg;
2580   bool include_uninstrumented_p;
2581 };
2582
2583 // Callback for expand_regions, collect innermost region data for each bb.
2584 static void *
2585 collect_bb2reg (struct tm_region *region, void *data)
2586 {
2587   struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2588   vec<tm_region_p> *bb2reg = stuff->bb2reg;
2589   vec<basic_block> queue;
2590   unsigned int i;
2591   basic_block bb;
2592
2593   queue = get_tm_region_blocks (region->entry_block,
2594                                 region->exit_blocks,
2595                                 region->irr_blocks,
2596                                 NULL,
2597                                 /*stop_at_irr_p=*/true,
2598                                 stuff->include_uninstrumented_p);
2599
2600   // We expect expand_region to perform a post-order traversal of the region
2601   // tree.  Therefore the last region seen for any bb is the innermost.
2602   FOR_EACH_VEC_ELT (queue, i, bb)
2603     (*bb2reg)[bb->index] = region;
2604
2605   queue.release ();
2606   return NULL;
2607 }
2608
2609 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2610 // which a basic block belongs.  Note that we only consider the instrumented
2611 // code paths for the region; the uninstrumented code paths are ignored if
2612 // INCLUDE_UNINSTRUMENTED_P is false.
2613 //
2614 // ??? This data is very similar to the bb_regions array that is collected
2615 // during tm_region_init.  Or, rather, this data is similar to what could
2616 // be used within tm_region_init.  The actual computation in tm_region_init
2617 // begins and ends with bb_regions entirely full of NULL pointers, due to
2618 // the way in which pointers are swapped in and out of the array.
2619 //
2620 // ??? Our callers expect that blocks are not shared between transactions.
2621 // When the optimizers get too smart, and blocks are shared, then during
2622 // the tm_mark phase we'll add log entries to only one of the two transactions,
2623 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2624 // cycles.  The symptom being SSA defs that do not dominate their uses.
2625 // Note that the optimizers were locally correct with their transformation,
2626 // as we have no info within the program that suggests that the blocks cannot
2627 // be shared.
2628 //
2629 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2630 // only known instance of this block sharing.
2631
2632 static vec<tm_region_p>
2633 get_bb_regions_instrumented (bool traverse_clones,
2634                              bool include_uninstrumented_p)
2635 {
2636   unsigned n = last_basic_block;
2637   struct bb2reg_stuff stuff;
2638   vec<tm_region_p> ret;
2639
2640   ret.create (n);
2641   ret.safe_grow_cleared (n);
2642   stuff.bb2reg = &ret;
2643   stuff.include_uninstrumented_p = include_uninstrumented_p;
2644   expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2645
2646   return ret;
2647 }
2648
2649 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2650    transaction.  */
2651
2652 void
2653 compute_transaction_bits (void)
2654 {
2655   struct tm_region *region;
2656   vec<basic_block> queue;
2657   unsigned int i;
2658   basic_block bb;
2659
2660   /* ?? Perhaps we need to abstract gate_tm_init further, because we
2661      certainly don't need it to calculate CDI_DOMINATOR info.  */
2662   gate_tm_init ();
2663
2664   FOR_EACH_BB (bb)
2665     bb->flags &= ~BB_IN_TRANSACTION;
2666
2667   for (region = all_tm_regions; region; region = region->next)
2668     {
2669       queue = get_tm_region_blocks (region->entry_block,
2670                                     region->exit_blocks,
2671                                     region->irr_blocks,
2672                                     NULL,
2673                                     /*stop_at_irr_p=*/true);
2674       for (i = 0; queue.iterate (i, &bb); ++i)
2675         bb->flags |= BB_IN_TRANSACTION;
2676       queue.release ();
2677     }
2678
2679   if (all_tm_regions)
2680     bitmap_obstack_release (&tm_obstack);
2681 }
2682
2683 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2684    call to BUILT_IN_TM_START.  */
2685
2686 static void *
2687 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2688 {
2689   tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2690   basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2691   tree tm_state = region->tm_state;
2692   tree tm_state_type = TREE_TYPE (tm_state);
2693   edge abort_edge = NULL;
2694   edge inst_edge = NULL;
2695   edge uninst_edge = NULL;
2696   edge fallthru_edge = NULL;
2697
2698   // Identify the various successors of the transaction start.
2699   {
2700     edge_iterator i;
2701     edge e;
2702     FOR_EACH_EDGE (e, i, transaction_bb->succs)
2703       {
2704         if (e->flags & EDGE_TM_ABORT)
2705           abort_edge = e;
2706         else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2707           uninst_edge = e;
2708         else
2709           inst_edge = e;
2710         if (e->flags & EDGE_FALLTHRU)
2711           fallthru_edge = e;
2712       }
2713   }
2714
2715   /* ??? There are plenty of bits here we're not computing.  */
2716   {
2717     int subcode = gimple_transaction_subcode (region->transaction_stmt);
2718     int flags = 0;
2719     if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2720       flags |= PR_DOESGOIRREVOCABLE;
2721     if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2722       flags |= PR_HASNOIRREVOCABLE;
2723     /* If the transaction does not have an abort in lexical scope and is not
2724        marked as an outer transaction, then it will never abort.  */
2725     if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2726       flags |= PR_HASNOABORT;
2727     if ((subcode & GTMA_HAVE_STORE) == 0)
2728       flags |= PR_READONLY;
2729     if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2730       flags |= PR_INSTRUMENTEDCODE;
2731     if (uninst_edge)
2732       flags |= PR_UNINSTRUMENTEDCODE;
2733     if (subcode & GTMA_IS_OUTER)
2734       region->original_transaction_was_outer = true;
2735     tree t = build_int_cst (tm_state_type, flags);
2736     gimple call = gimple_build_call (tm_start, 1, t);
2737     gimple_call_set_lhs (call, tm_state);
2738     gimple_set_location (call, gimple_location (region->transaction_stmt));
2739
2740     // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2741     gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2742     gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2743     gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2744     gsi_remove (&gsi, true);
2745     region->transaction_stmt = call;
2746   }
2747
2748   // Generate log saves.
2749   if (!tm_log_save_addresses.is_empty ())
2750     tm_log_emit_saves (region->entry_block, transaction_bb);
2751
2752   // In the beginning, we've no tests to perform on transaction restart.
2753   // Note that after this point, transaction_bb becomes the "most recent
2754   // block containing tests for the transaction".
2755   region->restart_block = region->entry_block;
2756
2757   // Generate log restores.
2758   if (!tm_log_save_addresses.is_empty ())
2759     {
2760       basic_block test_bb = create_empty_bb (transaction_bb);
2761       basic_block code_bb = create_empty_bb (test_bb);
2762       basic_block join_bb = create_empty_bb (code_bb);
2763       if (current_loops && transaction_bb->loop_father)
2764         {
2765           add_bb_to_loop (test_bb, transaction_bb->loop_father);
2766           add_bb_to_loop (code_bb, transaction_bb->loop_father);
2767           add_bb_to_loop (join_bb, transaction_bb->loop_father);
2768         }
2769       if (region->restart_block == region->entry_block)
2770         region->restart_block = test_bb;
2771
2772       tree t1 = create_tmp_reg (tm_state_type, NULL);
2773       tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2774       gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2775                                                   tm_state, t2);
2776       gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2777       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2778
2779       t2 = build_int_cst (tm_state_type, 0);
2780       stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2781       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2782
2783       tm_log_emit_restores (region->entry_block, code_bb);
2784
2785       edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2786       edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2787       edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2788       redirect_edge_pred (fallthru_edge, join_bb);
2789
2790       join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2791       join_bb->count = test_bb->count = transaction_bb->count;
2792
2793       ei->probability = PROB_ALWAYS;
2794       et->probability = PROB_LIKELY;
2795       ef->probability = PROB_UNLIKELY;
2796       et->count = apply_probability (test_bb->count, et->probability);
2797       ef->count = apply_probability (test_bb->count, ef->probability);
2798
2799       code_bb->count = et->count;
2800       code_bb->frequency = EDGE_FREQUENCY (et);
2801
2802       transaction_bb = join_bb;
2803     }
2804
2805   // If we have an ABORT edge, create a test to perform the abort.
2806   if (abort_edge)
2807     {
2808       basic_block test_bb = create_empty_bb (transaction_bb);
2809       if (current_loops && transaction_bb->loop_father)
2810         add_bb_to_loop (test_bb, transaction_bb->loop_father);
2811       if (region->restart_block == region->entry_block)
2812         region->restart_block = test_bb;
2813
2814       tree t1 = create_tmp_reg (tm_state_type, NULL);
2815       tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2816       gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2817                                                   tm_state, t2);
2818       gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2819       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2820
2821       t2 = build_int_cst (tm_state_type, 0);
2822       stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2823       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2824
2825       edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2826       test_bb->frequency = transaction_bb->frequency;
2827       test_bb->count = transaction_bb->count;
2828       ei->probability = PROB_ALWAYS;
2829
2830       // Not abort edge.  If both are live, chose one at random as we'll
2831       // we'll be fixing that up below.
2832       redirect_edge_pred (fallthru_edge, test_bb);
2833       fallthru_edge->flags = EDGE_FALSE_VALUE;
2834       fallthru_edge->probability = PROB_VERY_LIKELY;
2835       fallthru_edge->count
2836         = apply_probability (test_bb->count, fallthru_edge->probability);
2837
2838       // Abort/over edge.
2839       redirect_edge_pred (abort_edge, test_bb);
2840       abort_edge->flags = EDGE_TRUE_VALUE;
2841       abort_edge->probability = PROB_VERY_UNLIKELY;
2842       abort_edge->count
2843         = apply_probability (test_bb->count, abort_edge->probability);
2844
2845       transaction_bb = test_bb;
2846     }
2847
2848   // If we have both instrumented and uninstrumented code paths, select one.
2849   if (inst_edge && uninst_edge)
2850     {
2851       basic_block test_bb = create_empty_bb (transaction_bb);
2852       if (current_loops && transaction_bb->loop_father)
2853         add_bb_to_loop (test_bb, transaction_bb->loop_father);
2854       if (region->restart_block == region->entry_block)
2855         region->restart_block = test_bb;
2856
2857       tree t1 = create_tmp_reg (tm_state_type, NULL);
2858       tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2859
2860       gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2861                                                   tm_state, t2);
2862       gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2863       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2864
2865       t2 = build_int_cst (tm_state_type, 0);
2866       stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2867       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2868
2869       // Create the edge into test_bb first, as we want to copy values
2870       // out of the fallthru edge.
2871       edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2872       e->probability = fallthru_edge->probability;
2873       test_bb->count = e->count = fallthru_edge->count;
2874       test_bb->frequency = EDGE_FREQUENCY (e);
2875
2876       // Now update the edges to the inst/uninist implementations.
2877       // For now assume that the paths are equally likely.  When using HTM,
2878       // we'll try the uninst path first and fallback to inst path if htm
2879       // buffers are exceeded.  Without HTM we start with the inst path and
2880       // use the uninst path when falling back to serial mode.
2881       redirect_edge_pred (inst_edge, test_bb);
2882       inst_edge->flags = EDGE_FALSE_VALUE;
2883       inst_edge->probability = REG_BR_PROB_BASE / 2;
2884       inst_edge->count
2885         = apply_probability (test_bb->count, inst_edge->probability);
2886
2887       redirect_edge_pred (uninst_edge, test_bb);
2888       uninst_edge->flags = EDGE_TRUE_VALUE;
2889       uninst_edge->probability = REG_BR_PROB_BASE / 2;
2890       uninst_edge->count
2891         = apply_probability (test_bb->count, uninst_edge->probability);
2892     }
2893
2894   // If we have no previous special cases, and we have PHIs at the beginning
2895   // of the atomic region, this means we have a loop at the beginning of the
2896   // atomic region that shares the first block.  This can cause problems with
2897   // the transaction restart abnormal edges to be added in the tm_edges pass.
2898   // Solve this by adding a new empty block to receive the abnormal edges.
2899   if (region->restart_block == region->entry_block
2900       && phi_nodes (region->entry_block))
2901     {
2902       basic_block empty_bb = create_empty_bb (transaction_bb);
2903       region->restart_block = empty_bb;
2904       if (current_loops && transaction_bb->loop_father)
2905         add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2906
2907       redirect_edge_pred (fallthru_edge, empty_bb);
2908       make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2909     }
2910
2911   return NULL;
2912 }
2913
2914 /* Generate the temporary to be used for the return value of
2915    BUILT_IN_TM_START.  */
2916
2917 static void *
2918 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2919 {
2920   tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2921   region->tm_state =
2922     create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2923
2924   // Reset the subcode, post optimizations.  We'll fill this in
2925   // again as we process blocks.
2926   if (region->exit_blocks)
2927     {
2928       unsigned int subcode
2929         = gimple_transaction_subcode (region->transaction_stmt);
2930
2931       if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2932         subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2933                     | GTMA_MAY_ENTER_IRREVOCABLE
2934                     | GTMA_HAS_NO_INSTRUMENTATION);
2935       else
2936         subcode &= GTMA_DECLARATION_MASK;
2937       gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2938     }
2939
2940   return NULL;
2941 }
2942
2943 // Propagate flags from inner transactions outwards.
2944 static void
2945 propagate_tm_flags_out (struct tm_region *region)
2946 {
2947   if (region == NULL)
2948     return;
2949   propagate_tm_flags_out (region->inner);
2950
2951   if (region->outer && region->outer->transaction_stmt)
2952     {
2953       unsigned s = gimple_transaction_subcode (region->transaction_stmt);
2954       s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2955             | GTMA_MAY_ENTER_IRREVOCABLE);
2956       s |= gimple_transaction_subcode (region->outer->transaction_stmt);
2957       gimple_transaction_set_subcode (region->outer->transaction_stmt, s);
2958     }
2959
2960   propagate_tm_flags_out (region->next);
2961 }
2962
2963 /* Entry point to the MARK phase of TM expansion.  Here we replace
2964    transactional memory statements with calls to builtins, and function
2965    calls with their transactional clones (if available).  But we don't
2966    yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges.  */
2967
2968 static unsigned int
2969 execute_tm_mark (void)
2970 {
2971   pending_edge_inserts_p = false;
2972
2973   expand_regions (all_tm_regions, generate_tm_state, NULL,
2974                   /*traverse_clones=*/true);
2975
2976   tm_log_init ();
2977
2978   vec<tm_region_p> bb_regions
2979     = get_bb_regions_instrumented (/*traverse_clones=*/true,
2980                                    /*include_uninstrumented_p=*/false);
2981   struct tm_region *r;
2982   unsigned i;
2983
2984   // Expand memory operations into calls into the runtime.
2985   // This collects log entries as well.
2986   FOR_EACH_VEC_ELT (bb_regions, i, r)
2987     {
2988       if (r != NULL)
2989         {
2990           if (r->transaction_stmt)
2991             {
2992               unsigned sub = gimple_transaction_subcode (r->transaction_stmt);
2993
2994               /* If we're sure to go irrevocable, there won't be
2995                  anything to expand, since the run-time will go
2996                  irrevocable right away.  */
2997               if (sub & GTMA_DOES_GO_IRREVOCABLE
2998                   && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2999                 continue;
3000             }
3001           expand_block_tm (r, BASIC_BLOCK (i));
3002         }
3003     }
3004
3005   bb_regions.release ();
3006
3007   // Propagate flags from inner transactions outwards.
3008   propagate_tm_flags_out (all_tm_regions);
3009
3010   // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
3011   expand_regions (all_tm_regions, expand_transaction, NULL,
3012                   /*traverse_clones=*/false);
3013
3014   tm_log_emit ();
3015   tm_log_delete ();
3016
3017   if (pending_edge_inserts_p)
3018     gsi_commit_edge_inserts ();
3019   free_dominance_info (CDI_DOMINATORS);
3020   return 0;
3021 }
3022
3023 namespace {
3024
3025 const pass_data pass_data_tm_mark =
3026 {
3027   GIMPLE_PASS, /* type */
3028   "tmmark", /* name */
3029   OPTGROUP_NONE, /* optinfo_flags */
3030   false, /* has_gate */
3031   true, /* has_execute */
3032   TV_TRANS_MEM, /* tv_id */
3033   ( PROP_ssa | PROP_cfg ), /* properties_required */
3034   0, /* properties_provided */
3035   0, /* properties_destroyed */
3036   0, /* todo_flags_start */
3037   ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3038 };
3039
3040 class pass_tm_mark : public gimple_opt_pass
3041 {
3042 public:
3043   pass_tm_mark (gcc::context *ctxt)
3044     : gimple_opt_pass (pass_data_tm_mark, ctxt)
3045   {}
3046
3047   /* opt_pass methods: */
3048   unsigned int execute () { return execute_tm_mark (); }
3049
3050 }; // class pass_tm_mark
3051
3052 } // anon namespace
3053
3054 gimple_opt_pass *
3055 make_pass_tm_mark (gcc::context *ctxt)
3056 {
3057   return new pass_tm_mark (ctxt);
3058 }
3059 \f
3060
3061 /* Create an abnormal edge from STMT at iter, splitting the block
3062    as necessary.  Adjust *PNEXT as needed for the split block.  */
3063
3064 static inline void
3065 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3066                        gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3067 {
3068   basic_block bb = gimple_bb (stmt);
3069   if (!gsi_one_before_end_p (iter))
3070     {
3071       edge e = split_block (bb, stmt);
3072       *pnext = gsi_start_bb (e->dest);
3073     }
3074   make_edge (bb, dest_bb, EDGE_ABNORMAL);
3075
3076   // Record the need for the edge for the benefit of the rtl passes.
3077   if (cfun->gimple_df->tm_restart == NULL)
3078     cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
3079                                                    struct_ptr_eq, ggc_free);
3080
3081   struct tm_restart_node dummy;
3082   dummy.stmt = stmt;
3083   dummy.label_or_list = gimple_block_label (dest_bb);
3084
3085   void **slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
3086   struct tm_restart_node *n = (struct tm_restart_node *) *slot;
3087   if (n == NULL)
3088     {
3089       n = ggc_alloc_tm_restart_node ();
3090       *n = dummy;
3091     }
3092   else
3093     {
3094       tree old = n->label_or_list;
3095       if (TREE_CODE (old) == LABEL_DECL)
3096         old = tree_cons (NULL, old, NULL);
3097       n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3098     }
3099 }
3100
3101 /* Split block BB as necessary for every builtin function we added, and
3102    wire up the abnormal back edges implied by the transaction restart.  */
3103
3104 static void
3105 expand_block_edges (struct tm_region *const region, basic_block bb)
3106 {
3107   gimple_stmt_iterator gsi, next_gsi;
3108
3109   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3110     {
3111       gimple stmt = gsi_stmt (gsi);
3112
3113       next_gsi = gsi;
3114       gsi_next (&next_gsi);
3115
3116       // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3117       if (gimple_code (stmt) != GIMPLE_CALL
3118           || (gimple_call_flags (stmt) & ECF_TM_BUILTIN) == 0)
3119         continue;
3120
3121       if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_TM_ABORT)
3122         {
3123           // If we have a ``_transaction_cancel [[outer]]'', there is only
3124           // one abnormal edge: to the transaction marked OUTER.
3125           // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3126           // constant argument, which we can examine here.  Users invoking
3127           // TM_ABORT directly get what they deserve.
3128           tree arg = gimple_call_arg (stmt, 0);
3129           if (TREE_CODE (arg) == INTEGER_CST
3130               && (TREE_INT_CST_LOW (arg) & AR_OUTERABORT) != 0
3131               && !decl_is_tm_clone (current_function_decl))
3132             {
3133               // Find the GTMA_IS_OUTER transaction.
3134               for (struct tm_region *o = region; o; o = o->outer)
3135                 if (o->original_transaction_was_outer)
3136                   {
3137                     split_bb_make_tm_edge (stmt, o->restart_block,
3138                                            gsi, &next_gsi);
3139                     break;
3140                   }
3141
3142               // Otherwise, the front-end should have semantically checked
3143               // outer aborts, but in either case the target region is not
3144               // within this function.
3145               continue;
3146             }
3147
3148           // Non-outer, TM aborts have an abnormal edge to the inner-most
3149           // transaction, the one being aborted;
3150           split_bb_make_tm_edge (stmt, region->restart_block, gsi, &next_gsi);
3151         }
3152
3153       // All TM builtins have an abnormal edge to the outer-most transaction.
3154       // We never restart inner transactions.  For tm clones, we know a-priori
3155       // that the outer-most transaction is outside the function.
3156       if (decl_is_tm_clone (current_function_decl))
3157         continue;
3158
3159       if (cfun->gimple_df->tm_restart == NULL)
3160         cfun->gimple_df->tm_restart
3161           = htab_create_ggc (31, struct_ptr_hash, struct_ptr_eq, ggc_free);
3162
3163       // All TM builtins have an abnormal edge to the outer-most transaction.
3164       // We never restart inner transactions.
3165       for (struct tm_region *o = region; o; o = o->outer)
3166         if (!o->outer)
3167           {
3168             split_bb_make_tm_edge (stmt, o->restart_block, gsi, &next_gsi);
3169             break;
3170           }
3171
3172       // Delete any tail-call annotation that may have been added.
3173       // The tail-call pass may have mis-identified the commit as being
3174       // a candidate because we had not yet added this restart edge.
3175       gimple_call_set_tail (stmt, false);
3176     }
3177 }
3178
3179 /* Entry point to the final expansion of transactional nodes. */
3180
3181 static unsigned int
3182 execute_tm_edges (void)
3183 {
3184   vec<tm_region_p> bb_regions
3185     = get_bb_regions_instrumented (/*traverse_clones=*/false,
3186                                    /*include_uninstrumented_p=*/true);
3187   struct tm_region *r;
3188   unsigned i;
3189
3190   FOR_EACH_VEC_ELT (bb_regions, i, r)
3191     if (r != NULL)
3192       expand_block_edges (r, BASIC_BLOCK (i));
3193
3194   bb_regions.release ();
3195
3196   /* We've got to release the dominance info now, to indicate that it
3197      must be rebuilt completely.  Otherwise we'll crash trying to update
3198      the SSA web in the TODO section following this pass.  */
3199   free_dominance_info (CDI_DOMINATORS);
3200   bitmap_obstack_release (&tm_obstack);
3201   all_tm_regions = NULL;
3202
3203   return 0;
3204 }
3205
3206 namespace {
3207
3208 const pass_data pass_data_tm_edges =
3209 {
3210   GIMPLE_PASS, /* type */
3211   "tmedge", /* name */
3212   OPTGROUP_NONE, /* optinfo_flags */
3213   false, /* has_gate */
3214   true, /* has_execute */
3215   TV_TRANS_MEM, /* tv_id */
3216   ( PROP_ssa | PROP_cfg ), /* properties_required */
3217   0, /* properties_provided */
3218   0, /* properties_destroyed */
3219   0, /* todo_flags_start */
3220   ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3221 };
3222
3223 class pass_tm_edges : public gimple_opt_pass
3224 {
3225 public:
3226   pass_tm_edges (gcc::context *ctxt)
3227     : gimple_opt_pass (pass_data_tm_edges, ctxt)
3228   {}
3229
3230   /* opt_pass methods: */
3231   unsigned int execute () { return execute_tm_edges (); }
3232
3233 }; // class pass_tm_edges
3234
3235 } // anon namespace
3236
3237 gimple_opt_pass *
3238 make_pass_tm_edges (gcc::context *ctxt)
3239 {
3240   return new pass_tm_edges (ctxt);
3241 }
3242 \f
3243 /* Helper function for expand_regions.  Expand REGION and recurse to
3244    the inner region.  Call CALLBACK on each region.  CALLBACK returns
3245    NULL to continue the traversal, otherwise a non-null value which
3246    this function will return as well.  TRAVERSE_CLONES is true if we
3247    should traverse transactional clones.  */
3248
3249 static void *
3250 expand_regions_1 (struct tm_region *region,
3251                   void *(*callback)(struct tm_region *, void *),
3252                   void *data,
3253                   bool traverse_clones)
3254 {
3255   void *retval = NULL;
3256   if (region->exit_blocks
3257       || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3258     {
3259       retval = callback (region, data);
3260       if (retval)
3261         return retval;
3262     }
3263   if (region->inner)
3264     {
3265       retval = expand_regions (region->inner, callback, data, traverse_clones);
3266       if (retval)
3267         return retval;
3268     }
3269   return retval;
3270 }
3271
3272 /* Traverse the regions enclosed and including REGION.  Execute
3273    CALLBACK for each region, passing DATA.  CALLBACK returns NULL to
3274    continue the traversal, otherwise a non-null value which this
3275    function will return as well.  TRAVERSE_CLONES is true if we should
3276    traverse transactional clones.  */
3277
3278 static void *
3279 expand_regions (struct tm_region *region,
3280                 void *(*callback)(struct tm_region *, void *),
3281                 void *data,
3282                 bool traverse_clones)
3283 {
3284   void *retval = NULL;
3285   while (region)
3286     {
3287       retval = expand_regions_1 (region, callback, data, traverse_clones);
3288       if (retval)
3289         return retval;
3290       region = region->next;
3291     }
3292   return retval;
3293 }
3294
3295 \f
3296 /* A unique TM memory operation.  */
3297 typedef struct tm_memop
3298 {
3299   /* Unique ID that all memory operations to the same location have.  */
3300   unsigned int value_id;
3301   /* Address of load/store.  */
3302   tree addr;
3303 } *tm_memop_t;
3304
3305 /* TM memory operation hashtable helpers.  */
3306
3307 struct tm_memop_hasher : typed_free_remove <tm_memop>
3308 {
3309   typedef tm_memop value_type;
3310   typedef tm_memop compare_type;
3311   static inline hashval_t hash (const value_type *);
3312   static inline bool equal (const value_type *, const compare_type *);
3313 };
3314
3315 /* Htab support.  Return a hash value for a `tm_memop'.  */
3316 inline hashval_t
3317 tm_memop_hasher::hash (const value_type *mem)
3318 {
3319   tree addr = mem->addr;
3320   /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3321      actually done with operand_equal_p (see tm_memop_eq).  */
3322   if (TREE_CODE (addr) == ADDR_EXPR)
3323     addr = TREE_OPERAND (addr, 0);
3324   return iterative_hash_expr (addr, 0);
3325 }
3326
3327 /* Htab support.  Return true if two tm_memop's are the same.  */
3328 inline bool
3329 tm_memop_hasher::equal (const value_type *mem1, const compare_type *mem2)
3330 {
3331   return operand_equal_p (mem1->addr, mem2->addr, 0);
3332 }
3333
3334 /* Sets for solving data flow equations in the memory optimization pass.  */
3335 struct tm_memopt_bitmaps
3336 {
3337   /* Stores available to this BB upon entry.  Basically, stores that
3338      dominate this BB.  */
3339   bitmap store_avail_in;
3340   /* Stores available at the end of this BB.  */
3341   bitmap store_avail_out;
3342   bitmap store_antic_in;
3343   bitmap store_antic_out;
3344   /* Reads available to this BB upon entry.  Basically, reads that
3345      dominate this BB.  */
3346   bitmap read_avail_in;
3347   /* Reads available at the end of this BB.  */
3348   bitmap read_avail_out;
3349   /* Reads performed in this BB.  */
3350   bitmap read_local;
3351   /* Writes performed in this BB.  */
3352   bitmap store_local;
3353
3354   /* Temporary storage for pass.  */
3355   /* Is the current BB in the worklist?  */
3356   bool avail_in_worklist_p;
3357   /* Have we visited this BB?  */
3358   bool visited_p;
3359 };
3360
3361 static bitmap_obstack tm_memopt_obstack;
3362
3363 /* Unique counter for TM loads and stores. Loads and stores of the
3364    same address get the same ID.  */
3365 static unsigned int tm_memopt_value_id;
3366 static hash_table <tm_memop_hasher> tm_memopt_value_numbers;
3367
3368 #define STORE_AVAIL_IN(BB) \
3369   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3370 #define STORE_AVAIL_OUT(BB) \
3371   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3372 #define STORE_ANTIC_IN(BB) \
3373   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3374 #define STORE_ANTIC_OUT(BB) \
3375   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3376 #define READ_AVAIL_IN(BB) \
3377   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3378 #define READ_AVAIL_OUT(BB) \
3379   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3380 #define READ_LOCAL(BB) \
3381   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3382 #define STORE_LOCAL(BB) \
3383   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3384 #define AVAIL_IN_WORKLIST_P(BB) \
3385   ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3386 #define BB_VISITED_P(BB) \
3387   ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3388
3389 /* Given a TM load/store in STMT, return the value number for the address
3390    it accesses.  */
3391
3392 static unsigned int
3393 tm_memopt_value_number (gimple stmt, enum insert_option op)
3394 {
3395   struct tm_memop tmpmem, *mem;
3396   tm_memop **slot;
3397
3398   gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3399   tmpmem.addr = gimple_call_arg (stmt, 0);
3400   slot = tm_memopt_value_numbers.find_slot (&tmpmem, op);
3401   if (*slot)
3402     mem = *slot;
3403   else if (op == INSERT)
3404     {
3405       mem = XNEW (struct tm_memop);
3406       *slot = mem;
3407       mem->value_id = tm_memopt_value_id++;
3408       mem->addr = tmpmem.addr;
3409     }
3410   else
3411     gcc_unreachable ();
3412   return mem->value_id;
3413 }
3414
3415 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL.  */
3416
3417 static void
3418 tm_memopt_accumulate_memops (basic_block bb)
3419 {
3420   gimple_stmt_iterator gsi;
3421
3422   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3423     {
3424       gimple stmt = gsi_stmt (gsi);
3425       bitmap bits;
3426       unsigned int loc;
3427
3428       if (is_tm_store (stmt))
3429         bits = STORE_LOCAL (bb);
3430       else if (is_tm_load (stmt))
3431         bits = READ_LOCAL (bb);
3432       else
3433         continue;
3434
3435       loc = tm_memopt_value_number (stmt, INSERT);
3436       bitmap_set_bit (bits, loc);
3437       if (dump_file)
3438         {
3439           fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3440                    is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3441                    gimple_bb (stmt)->index);
3442           print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3443           fprintf (dump_file, "\n");
3444         }
3445     }
3446 }
3447
3448 /* Prettily dump one of the memopt sets.  BITS is the bitmap to dump.  */
3449
3450 static void
3451 dump_tm_memopt_set (const char *set_name, bitmap bits)
3452 {
3453   unsigned i;
3454   bitmap_iterator bi;
3455   const char *comma = "";
3456
3457   fprintf (dump_file, "TM memopt: %s: [", set_name);
3458   EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3459     {
3460       hash_table <tm_memop_hasher>::iterator hi;
3461       struct tm_memop *mem = NULL;
3462
3463       /* Yeah, yeah, yeah.  Whatever.  This is just for debugging.  */
3464       FOR_EACH_HASH_TABLE_ELEMENT (tm_memopt_value_numbers, mem, tm_memop_t, hi)
3465         if (mem->value_id == i)
3466           break;
3467       gcc_assert (mem->value_id == i);
3468       fprintf (dump_file, "%s", comma);
3469       comma = ", ";
3470       print_generic_expr (dump_file, mem->addr, 0);
3471     }
3472   fprintf (dump_file, "]\n");
3473 }
3474
3475 /* Prettily dump all of the memopt sets in BLOCKS.  */
3476
3477 static void
3478 dump_tm_memopt_sets (vec<basic_block> blocks)
3479 {
3480   size_t i;
3481   basic_block bb;
3482
3483   for (i = 0; blocks.iterate (i, &bb); ++i)
3484     {
3485       fprintf (dump_file, "------------BB %d---------\n", bb->index);
3486       dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3487       dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3488       dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3489       dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3490       dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3491       dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3492     }
3493 }
3494
3495 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB.  */
3496
3497 static void
3498 tm_memopt_compute_avin (basic_block bb)
3499 {
3500   edge e;
3501   unsigned ix;
3502
3503   /* Seed with the AVOUT of any predecessor.  */
3504   for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3505     {
3506       e = EDGE_PRED (bb, ix);
3507       /* Make sure we have already visited this BB, and is thus
3508          initialized.
3509
3510           If e->src->aux is NULL, this predecessor is actually on an
3511           enclosing transaction.  We only care about the current
3512           transaction, so ignore it.  */
3513       if (e->src->aux && BB_VISITED_P (e->src))
3514         {
3515           bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3516           bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3517           break;
3518         }
3519     }
3520
3521   for (; ix < EDGE_COUNT (bb->preds); ix++)
3522     {
3523       e = EDGE_PRED (bb, ix);
3524       if (e->src->aux && BB_VISITED_P (e->src))
3525         {
3526           bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3527           bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3528         }
3529     }
3530
3531   BB_VISITED_P (bb) = true;
3532 }
3533
3534 /* Compute the STORE_ANTIC_IN for the basic block BB.  */
3535
3536 static void
3537 tm_memopt_compute_antin (basic_block bb)
3538 {
3539   edge e;
3540   unsigned ix;
3541
3542   /* Seed with the ANTIC_OUT of any successor.  */
3543   for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3544     {
3545       e = EDGE_SUCC (bb, ix);
3546       /* Make sure we have already visited this BB, and is thus
3547          initialized.  */
3548       if (BB_VISITED_P (e->dest))
3549         {
3550           bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3551           break;
3552         }
3553     }
3554
3555   for (; ix < EDGE_COUNT (bb->succs); ix++)
3556     {
3557       e = EDGE_SUCC (bb, ix);
3558       if (BB_VISITED_P  (e->dest))
3559         bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3560     }
3561
3562   BB_VISITED_P (bb) = true;
3563 }
3564
3565 /* Compute the AVAIL sets for every basic block in BLOCKS.
3566
3567    We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3568
3569      AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3570      AVAIL_IN[bb]  = intersect (AVAIL_OUT[predecessors])
3571
3572    This is basically what we do in lcm's compute_available(), but here
3573    we calculate two sets of sets (one for STOREs and one for READs),
3574    and we work on a region instead of the entire CFG.
3575
3576    REGION is the TM region.
3577    BLOCKS are the basic blocks in the region.  */
3578
3579 static void
3580 tm_memopt_compute_available (struct tm_region *region,
3581                              vec<basic_block> blocks)
3582 {
3583   edge e;
3584   basic_block *worklist, *qin, *qout, *qend, bb;
3585   unsigned int qlen, i;
3586   edge_iterator ei;
3587   bool changed;
3588
3589   /* Allocate a worklist array/queue.  Entries are only added to the
3590      list if they were not already on the list.  So the size is
3591      bounded by the number of basic blocks in the region.  */
3592   qlen = blocks.length () - 1;
3593   qin = qout = worklist =
3594     XNEWVEC (basic_block, qlen);
3595
3596   /* Put every block in the region on the worklist.  */
3597   for (i = 0; blocks.iterate (i, &bb); ++i)
3598     {
3599       /* Seed AVAIL_OUT with the LOCAL set.  */
3600       bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3601       bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3602
3603       AVAIL_IN_WORKLIST_P (bb) = true;
3604       /* No need to insert the entry block, since it has an AVIN of
3605          null, and an AVOUT that has already been seeded in.  */
3606       if (bb != region->entry_block)
3607         *qin++ = bb;
3608     }
3609
3610   /* The entry block has been initialized with the local sets.  */
3611   BB_VISITED_P (region->entry_block) = true;
3612
3613   qin = worklist;
3614   qend = &worklist[qlen];
3615
3616   /* Iterate until the worklist is empty.  */
3617   while (qlen)
3618     {
3619       /* Take the first entry off the worklist.  */
3620       bb = *qout++;
3621       qlen--;
3622
3623       if (qout >= qend)
3624         qout = worklist;
3625
3626       /* This block can be added to the worklist again if necessary.  */
3627       AVAIL_IN_WORKLIST_P (bb) = false;
3628       tm_memopt_compute_avin (bb);
3629
3630       /* Note: We do not add the LOCAL sets here because we already
3631          seeded the AVAIL_OUT sets with them.  */
3632       changed  = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3633       changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3634       if (changed
3635           && (region->exit_blocks == NULL
3636               || !bitmap_bit_p (region->exit_blocks, bb->index)))
3637         /* If the out state of this block changed, then we need to add
3638            its successors to the worklist if they are not already in.  */
3639         FOR_EACH_EDGE (e, ei, bb->succs)
3640           if (!AVAIL_IN_WORKLIST_P (e->dest)
3641               && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
3642             {
3643               *qin++ = e->dest;
3644               AVAIL_IN_WORKLIST_P (e->dest) = true;
3645               qlen++;
3646
3647               if (qin >= qend)
3648                 qin = worklist;
3649             }
3650     }
3651
3652   free (worklist);
3653
3654   if (dump_file)
3655     dump_tm_memopt_sets (blocks);
3656 }
3657
3658 /* Compute ANTIC sets for every basic block in BLOCKS.
3659
3660    We compute STORE_ANTIC_OUT as follows:
3661
3662         STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3663         STORE_ANTIC_IN[bb]  = intersect(STORE_ANTIC_OUT[successors])
3664
3665    REGION is the TM region.
3666    BLOCKS are the basic blocks in the region.  */
3667
3668 static void
3669 tm_memopt_compute_antic (struct tm_region *region,
3670                          vec<basic_block> blocks)
3671 {
3672   edge e;
3673   basic_block *worklist, *qin, *qout, *qend, bb;
3674   unsigned int qlen;
3675   int i;
3676   edge_iterator ei;
3677
3678   /* Allocate a worklist array/queue.  Entries are only added to the
3679      list if they were not already on the list.  So the size is
3680      bounded by the number of basic blocks in the region.  */
3681   qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3682
3683   for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3684     {
3685       bb = blocks[i];
3686
3687       /* Seed ANTIC_OUT with the LOCAL set.  */
3688       bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3689
3690       /* Put every block in the region on the worklist.  */
3691       AVAIL_IN_WORKLIST_P (bb) = true;
3692       /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3693          and their ANTIC_OUT has already been seeded in.  */
3694       if (region->exit_blocks
3695           && !bitmap_bit_p (region->exit_blocks, bb->index))
3696         {
3697           qlen++;
3698           *qin++ = bb;
3699         }
3700     }
3701
3702   /* The exit blocks have been initialized with the local sets.  */
3703   if (region->exit_blocks)
3704     {
3705       unsigned int i;
3706       bitmap_iterator bi;
3707       EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3708         BB_VISITED_P (BASIC_BLOCK (i)) = true;
3709     }
3710
3711   qin = worklist;
3712   qend = &worklist[qlen];
3713
3714   /* Iterate until the worklist is empty.  */
3715   while (qlen)
3716     {
3717       /* Take the first entry off the worklist.  */
3718       bb = *qout++;
3719       qlen--;
3720
3721       if (qout >= qend)
3722         qout = worklist;
3723
3724       /* This block can be added to the worklist again if necessary.  */
3725       AVAIL_IN_WORKLIST_P (bb) = false;
3726       tm_memopt_compute_antin (bb);
3727
3728       /* Note: We do not add the LOCAL sets here because we already
3729          seeded the ANTIC_OUT sets with them.  */
3730       if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3731           && bb != region->entry_block)
3732         /* If the out state of this block changed, then we need to add
3733            its predecessors to the worklist if they are not already in.  */
3734         FOR_EACH_EDGE (e, ei, bb->preds)
3735           if (!AVAIL_IN_WORKLIST_P (e->src))
3736             {
3737               *qin++ = e->src;
3738               AVAIL_IN_WORKLIST_P (e->src) = true;
3739               qlen++;
3740
3741               if (qin >= qend)
3742                 qin = worklist;
3743             }
3744     }
3745
3746   free (worklist);
3747
3748   if (dump_file)
3749     dump_tm_memopt_sets (blocks);
3750 }
3751
3752 /* Offsets of load variants from TM_LOAD.  For example,
3753    BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3754    See gtm-builtins.def.  */
3755 #define TRANSFORM_RAR 1
3756 #define TRANSFORM_RAW 2
3757 #define TRANSFORM_RFW 3
3758 /* Offsets of store variants from TM_STORE.  */
3759 #define TRANSFORM_WAR 1
3760 #define TRANSFORM_WAW 2
3761
3762 /* Inform about a load/store optimization.  */
3763
3764 static void
3765 dump_tm_memopt_transform (gimple stmt)
3766 {
3767   if (dump_file)
3768     {
3769       fprintf (dump_file, "TM memopt: transforming: ");
3770       print_gimple_stmt (dump_file, stmt, 0, 0);
3771       fprintf (dump_file, "\n");
3772     }
3773 }
3774
3775 /* Perform a read/write optimization.  Replaces the TM builtin in STMT
3776    by a builtin that is OFFSET entries down in the builtins table in
3777    gtm-builtins.def.  */
3778
3779 static void
3780 tm_memopt_transform_stmt (unsigned int offset,
3781                           gimple stmt,
3782                           gimple_stmt_iterator *gsi)
3783 {
3784   tree fn = gimple_call_fn (stmt);
3785   gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3786   TREE_OPERAND (fn, 0)
3787     = builtin_decl_explicit ((enum built_in_function)
3788                              (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3789                               + offset));
3790   gimple_call_set_fn (stmt, fn);
3791   gsi_replace (gsi, stmt, true);
3792   dump_tm_memopt_transform (stmt);
3793 }
3794
3795 /* Perform the actual TM memory optimization transformations in the
3796    basic blocks in BLOCKS.  */
3797
3798 static void
3799 tm_memopt_transform_blocks (vec<basic_block> blocks)
3800 {
3801   size_t i;
3802   basic_block bb;
3803   gimple_stmt_iterator gsi;
3804
3805   for (i = 0; blocks.iterate (i, &bb); ++i)
3806     {
3807       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3808         {
3809           gimple stmt = gsi_stmt (gsi);
3810           bitmap read_avail = READ_AVAIL_IN (bb);
3811           bitmap store_avail = STORE_AVAIL_IN (bb);
3812           bitmap store_antic = STORE_ANTIC_OUT (bb);
3813           unsigned int loc;
3814
3815           if (is_tm_simple_load (stmt))
3816             {
3817               loc = tm_memopt_value_number (stmt, NO_INSERT);
3818               if (store_avail && bitmap_bit_p (store_avail, loc))
3819                 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3820               else if (store_antic && bitmap_bit_p (store_antic, loc))
3821                 {
3822                   tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3823                   bitmap_set_bit (store_avail, loc);
3824                 }
3825               else if (read_avail && bitmap_bit_p (read_avail, loc))
3826                 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3827               else
3828                 bitmap_set_bit (read_avail, loc);
3829             }
3830           else if (is_tm_simple_store (stmt))
3831             {
3832               loc = tm_memopt_value_number (stmt, NO_INSERT);
3833               if (store_avail && bitmap_bit_p (store_avail, loc))
3834                 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3835               else
3836                 {
3837                   if (read_avail && bitmap_bit_p (read_avail, loc))
3838                     tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3839                   bitmap_set_bit (store_avail, loc);
3840                 }
3841             }
3842         }
3843     }
3844 }
3845
3846 /* Return a new set of bitmaps for a BB.  */
3847
3848 static struct tm_memopt_bitmaps *
3849 tm_memopt_init_sets (void)
3850 {
3851   struct tm_memopt_bitmaps *b
3852     = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3853   b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3854   b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3855   b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3856   b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3857   b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3858   b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3859   b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3860   b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3861   b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3862   return b;
3863 }
3864
3865 /* Free sets computed for each BB.  */
3866
3867 static void
3868 tm_memopt_free_sets (vec<basic_block> blocks)
3869 {
3870   size_t i;
3871   basic_block bb;
3872
3873   for (i = 0; blocks.iterate (i, &bb); ++i)
3874     bb->aux = NULL;
3875 }
3876
3877 /* Clear the visited bit for every basic block in BLOCKS.  */
3878
3879 static void
3880 tm_memopt_clear_visited (vec<basic_block> blocks)
3881 {
3882   size_t i;
3883   basic_block bb;
3884
3885   for (i = 0; blocks.iterate (i, &bb); ++i)
3886     BB_VISITED_P (bb) = false;
3887 }
3888
3889 /* Replace TM load/stores with hints for the runtime.  We handle
3890    things like read-after-write, write-after-read, read-after-read,
3891    read-for-write, etc.  */
3892
3893 static unsigned int
3894 execute_tm_memopt (void)
3895 {
3896   struct tm_region *region;
3897   vec<basic_block> bbs;
3898
3899   tm_memopt_value_id = 0;
3900   tm_memopt_value_numbers.create (10);
3901
3902   for (region = all_tm_regions; region; region = region->next)
3903     {
3904       /* All the TM stores/loads in the current region.  */
3905       size_t i;
3906       basic_block bb;
3907
3908       bitmap_obstack_initialize (&tm_memopt_obstack);
3909
3910       /* Save all BBs for the current region.  */
3911       bbs = get_tm_region_blocks (region->entry_block,
3912                                   region->exit_blocks,
3913                                   region->irr_blocks,
3914                                   NULL,
3915                                   false);
3916
3917       /* Collect all the memory operations.  */
3918       for (i = 0; bbs.iterate (i, &bb); ++i)
3919         {
3920           bb->aux = tm_memopt_init_sets ();
3921           tm_memopt_accumulate_memops (bb);
3922         }
3923
3924       /* Solve data flow equations and transform each block accordingly.  */
3925       tm_memopt_clear_visited (bbs);
3926       tm_memopt_compute_available (region, bbs);
3927       tm_memopt_clear_visited (bbs);
3928       tm_memopt_compute_antic (region, bbs);
3929       tm_memopt_transform_blocks (bbs);
3930
3931       tm_memopt_free_sets (bbs);
3932       bbs.release ();
3933       bitmap_obstack_release (&tm_memopt_obstack);
3934       tm_memopt_value_numbers.empty ();
3935     }
3936
3937   tm_memopt_value_numbers.dispose ();
3938   return 0;
3939 }
3940
3941 static bool
3942 gate_tm_memopt (void)
3943 {
3944   return flag_tm && optimize > 0;
3945 }
3946
3947 namespace {
3948
3949 const pass_data pass_data_tm_memopt =
3950 {
3951   GIMPLE_PASS, /* type */
3952   "tmmemopt", /* name */
3953   OPTGROUP_NONE, /* optinfo_flags */
3954   true, /* has_gate */
3955   true, /* has_execute */
3956   TV_TRANS_MEM, /* tv_id */
3957   ( PROP_ssa | PROP_cfg ), /* properties_required */
3958   0, /* properties_provided */
3959   0, /* properties_destroyed */
3960   0, /* todo_flags_start */
3961   0, /* todo_flags_finish */
3962 };
3963
3964 class pass_tm_memopt : public gimple_opt_pass
3965 {
3966 public:
3967   pass_tm_memopt (gcc::context *ctxt)
3968     : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3969   {}
3970
3971   /* opt_pass methods: */
3972   bool gate () { return gate_tm_memopt (); }
3973   unsigned int execute () { return execute_tm_memopt (); }
3974
3975 }; // class pass_tm_memopt
3976
3977 } // anon namespace
3978
3979 gimple_opt_pass *
3980 make_pass_tm_memopt (gcc::context *ctxt)
3981 {
3982   return new pass_tm_memopt (ctxt);
3983 }
3984
3985 \f
3986 /* Interprocedual analysis for the creation of transactional clones.
3987    The aim of this pass is to find which functions are referenced in
3988    a non-irrevocable transaction context, and for those over which
3989    we have control (or user directive), create a version of the
3990    function which uses only the transactional interface to reference
3991    protected memories.  This analysis proceeds in several steps:
3992
3993      (1) Collect the set of all possible transactional clones:
3994
3995         (a) For all local public functions marked tm_callable, push
3996             it onto the tm_callee queue.
3997
3998         (b) For all local functions, scan for calls in transaction blocks.
3999             Push the caller and callee onto the tm_caller and tm_callee
4000             queues.  Count the number of callers for each callee.
4001
4002         (c) For each local function on the callee list, assume we will
4003             create a transactional clone.  Push *all* calls onto the
4004             callee queues; count the number of clone callers separately
4005             to the number of original callers.
4006
4007      (2) Propagate irrevocable status up the dominator tree:
4008
4009         (a) Any external function on the callee list that is not marked
4010             tm_callable is irrevocable.  Push all callers of such onto
4011             a worklist.
4012
4013         (b) For each function on the worklist, mark each block that
4014             contains an irrevocable call.  Use the AND operator to
4015             propagate that mark up the dominator tree.
4016
4017         (c) If we reach the entry block for a possible transactional
4018             clone, then the transactional clone is irrevocable, and
4019             we should not create the clone after all.  Push all
4020             callers onto the worklist.
4021
4022         (d) Place tm_irrevocable calls at the beginning of the relevant
4023             blocks.  Special case here is the entry block for the entire
4024             transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
4025             the library to begin the region in serial mode.  Decrement
4026             the call count for all callees in the irrevocable region.
4027
4028      (3) Create the transactional clones:
4029
4030         Any tm_callee that still has a non-zero call count is cloned.
4031 */
4032
4033 /* This structure is stored in the AUX field of each cgraph_node.  */
4034 struct tm_ipa_cg_data
4035 {
4036   /* The clone of the function that got created.  */
4037   struct cgraph_node *clone;
4038
4039   /* The tm regions in the normal function.  */
4040   struct tm_region *all_tm_regions;
4041
4042   /* The blocks of the normal/clone functions that contain irrevocable
4043      calls, or blocks that are post-dominated by irrevocable calls.  */
4044   bitmap irrevocable_blocks_normal;
4045   bitmap irrevocable_blocks_clone;
4046
4047   /* The blocks of the normal function that are involved in transactions.  */
4048   bitmap transaction_blocks_normal;
4049
4050   /* The number of callers to the transactional clone of this function
4051      from normal and transactional clones respectively.  */
4052   unsigned tm_callers_normal;
4053   unsigned tm_callers_clone;
4054
4055   /* True if all calls to this function's transactional clone
4056      are irrevocable.  Also automatically true if the function
4057      has no transactional clone.  */
4058   bool is_irrevocable;
4059
4060   /* Flags indicating the presence of this function in various queues.  */
4061   bool in_callee_queue;
4062   bool in_worklist;
4063
4064   /* Flags indicating the kind of scan desired while in the worklist.  */
4065   bool want_irr_scan_normal;
4066 };
4067
4068 typedef vec<cgraph_node_ptr> cgraph_node_queue;
4069
4070 /* Return the ipa data associated with NODE, allocating zeroed memory
4071    if necessary.  TRAVERSE_ALIASES is true if we must traverse aliases
4072    and set *NODE accordingly.  */
4073
4074 static struct tm_ipa_cg_data *
4075 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4076 {
4077   struct tm_ipa_cg_data *d;
4078
4079   if (traverse_aliases && (*node)->alias)
4080     *node = cgraph_alias_target (*node);
4081
4082   d = (struct tm_ipa_cg_data *) (*node)->aux;
4083
4084   if (d == NULL)
4085     {
4086       d = (struct tm_ipa_cg_data *)
4087         obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4088       (*node)->aux = (void *) d;
4089       memset (d, 0, sizeof (*d));
4090     }
4091
4092   return d;
4093 }
4094
4095 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4096    it is already present.  */
4097
4098 static void
4099 maybe_push_queue (struct cgraph_node *node,
4100                   cgraph_node_queue *queue_p, bool *in_queue_p)
4101 {
4102   if (!*in_queue_p)
4103     {
4104       *in_queue_p = true;
4105       queue_p->safe_push (node);
4106     }
4107 }
4108
4109 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4110    code path.  QUEUE are the basic blocks inside the transaction
4111    represented in REGION.
4112
4113    Later in split_code_paths() we will add the conditional to choose
4114    between the two alternatives.  */
4115
4116 static void
4117 ipa_uninstrument_transaction (struct tm_region *region,
4118                               vec<basic_block> queue)
4119 {
4120   gimple transaction = region->transaction_stmt;
4121   basic_block transaction_bb = gimple_bb (transaction);
4122   int n = queue.length ();
4123   basic_block *new_bbs = XNEWVEC (basic_block, n);
4124
4125   copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4126             true);
4127   edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4128   add_phi_args_after_copy (new_bbs, n, e);
4129
4130   // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4131   //   a) EDGE_FALLTHRU into the transaction
4132   //   b) EDGE_TM_ABORT out of the transaction
4133   //   c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4134
4135   free (new_bbs);
4136 }
4137
4138 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4139    Queue all callees within block BB.  */
4140
4141 static void
4142 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4143                          basic_block bb, bool for_clone)
4144 {
4145   gimple_stmt_iterator gsi;
4146
4147   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4148     {
4149       gimple stmt = gsi_stmt (gsi);
4150       if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4151         {
4152           tree fndecl = gimple_call_fndecl (stmt);
4153           if (fndecl)
4154             {
4155               struct tm_ipa_cg_data *d;
4156               unsigned *pcallers;
4157               struct cgraph_node *node;
4158
4159               if (is_tm_ending_fndecl (fndecl))
4160                 continue;
4161               if (find_tm_replacement_function (fndecl))
4162                 continue;
4163
4164               node = cgraph_get_node (fndecl);
4165               gcc_assert (node != NULL);
4166               d = get_cg_data (&node, true);
4167
4168               pcallers = (for_clone ? &d->tm_callers_clone
4169                           : &d->tm_callers_normal);
4170               *pcallers += 1;
4171
4172               maybe_push_queue (node, callees_p, &d->in_callee_queue);
4173             }
4174         }
4175     }
4176 }
4177
4178 /* Scan all calls in NODE that are within a transaction region,
4179    and push the resulting nodes into the callee queue.  */
4180
4181 static void
4182 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4183                                cgraph_node_queue *callees_p)
4184 {
4185   struct tm_region *r;
4186
4187   d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4188   d->all_tm_regions = all_tm_regions;
4189
4190   for (r = all_tm_regions; r; r = r->next)
4191     {
4192       vec<basic_block> bbs;
4193       basic_block bb;
4194       unsigned i;
4195
4196       bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4197                                   d->transaction_blocks_normal, false);
4198
4199       // Generate the uninstrumented code path for this transaction.
4200       ipa_uninstrument_transaction (r, bbs);
4201
4202       FOR_EACH_VEC_ELT (bbs, i, bb)
4203         ipa_tm_scan_calls_block (callees_p, bb, false);
4204
4205       bbs.release ();
4206     }
4207
4208   // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4209   // copying them, rather than forcing us to do this externally.
4210   rebuild_cgraph_edges ();
4211
4212   // ??? In ipa_uninstrument_transaction we don't try to update dominators
4213   // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4214   // Instead, just release dominators here so update_ssa recomputes them.
4215   free_dominance_info (CDI_DOMINATORS);
4216
4217   // When building the uninstrumented code path, copy_bbs will have invoked
4218   // create_new_def_for starting an "ssa update context".  There is only one
4219   // instance of this context, so resolve ssa updates before moving on to
4220   // the next function.
4221   update_ssa (TODO_update_ssa);
4222 }
4223
4224 /* Scan all calls in NODE as if this is the transactional clone,
4225    and push the destinations into the callee queue.  */
4226
4227 static void
4228 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4229                          cgraph_node_queue *callees_p)
4230 {
4231   struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
4232   basic_block bb;
4233
4234   FOR_EACH_BB_FN (bb, fn)
4235     ipa_tm_scan_calls_block (callees_p, bb, true);
4236 }
4237
4238 /* The function NODE has been detected to be irrevocable.  Push all
4239    of its callers onto WORKLIST for the purpose of re-scanning them.  */
4240
4241 static void
4242 ipa_tm_note_irrevocable (struct cgraph_node *node,
4243                          cgraph_node_queue *worklist_p)
4244 {
4245   struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4246   struct cgraph_edge *e;
4247
4248   d->is_irrevocable = true;
4249
4250   for (e = node->callers; e ; e = e->next_caller)
4251     {
4252       basic_block bb;
4253       struct cgraph_node *caller;
4254
4255       /* Don't examine recursive calls.  */
4256       if (e->caller == node)
4257         continue;
4258       /* Even if we think we can go irrevocable, believe the user
4259          above all.  */
4260       if (is_tm_safe_or_pure (e->caller->decl))
4261         continue;
4262
4263       caller = e->caller;
4264       d = get_cg_data (&caller, true);
4265
4266       /* Check if the callee is in a transactional region.  If so,
4267          schedule the function for normal re-scan as well.  */
4268       bb = gimple_bb (e->call_stmt);
4269       gcc_assert (bb != NULL);
4270       if (d->transaction_blocks_normal
4271           && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4272         d->want_irr_scan_normal = true;
4273
4274       maybe_push_queue (caller, worklist_p, &d->in_worklist);
4275     }
4276 }
4277
4278 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4279    within the block is irrevocable.  */
4280
4281 static bool
4282 ipa_tm_scan_irr_block (basic_block bb)
4283 {
4284   gimple_stmt_iterator gsi;
4285   tree fn;
4286
4287   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4288     {
4289       gimple stmt = gsi_stmt (gsi);
4290       switch (gimple_code (stmt))
4291         {
4292         case GIMPLE_ASSIGN:
4293           if (gimple_assign_single_p (stmt))
4294             {
4295               tree lhs = gimple_assign_lhs (stmt);
4296               tree rhs = gimple_assign_rhs1 (stmt);
4297               if (volatile_var_p (lhs) || volatile_var_p (rhs))
4298                 return true;
4299             }
4300           break;
4301
4302         case GIMPLE_CALL:
4303           {
4304             tree lhs = gimple_call_lhs (stmt);
4305             if (lhs && volatile_var_p (lhs))
4306               return true;
4307
4308             if (is_tm_pure_call (stmt))
4309               break;
4310
4311             fn = gimple_call_fn (stmt);
4312
4313             /* Functions with the attribute are by definition irrevocable.  */
4314             if (is_tm_irrevocable (fn))
4315               return true;
4316
4317             /* For direct function calls, go ahead and check for replacement
4318                functions, or transitive irrevocable functions.  For indirect
4319                functions, we'll ask the runtime.  */
4320             if (TREE_CODE (fn) == ADDR_EXPR)
4321               {
4322                 struct tm_ipa_cg_data *d;
4323                 struct cgraph_node *node;
4324
4325                 fn = TREE_OPERAND (fn, 0);
4326                 if (is_tm_ending_fndecl (fn))
4327                   break;
4328                 if (find_tm_replacement_function (fn))
4329                   break;
4330
4331                 node = cgraph_get_node (fn);
4332                 d = get_cg_data (&node, true);
4333
4334                 /* Return true if irrevocable, but above all, believe
4335                    the user.  */
4336                 if (d->is_irrevocable
4337                     && !is_tm_safe_or_pure (fn))
4338                   return true;
4339               }
4340             break;
4341           }
4342
4343         case GIMPLE_ASM:
4344           /* ??? The Approved Method of indicating that an inline
4345              assembly statement is not relevant to the transaction
4346              is to wrap it in a __tm_waiver block.  This is not
4347              yet implemented, so we can't check for it.  */
4348           if (is_tm_safe (current_function_decl))
4349             {
4350               tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4351               SET_EXPR_LOCATION (t, gimple_location (stmt));
4352               error ("%Kasm not allowed in %<transaction_safe%> function", t);
4353             }
4354           return true;
4355
4356         default:
4357           break;
4358         }
4359     }
4360
4361   return false;
4362 }
4363
4364 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4365    for new irrevocable blocks, marking them in NEW_IRR.  Don't bother
4366    scanning past OLD_IRR or EXIT_BLOCKS.  */
4367
4368 static bool
4369 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4370                         bitmap old_irr, bitmap exit_blocks)
4371 {
4372   bool any_new_irr = false;
4373   edge e;
4374   edge_iterator ei;
4375   bitmap visited_blocks = BITMAP_ALLOC (NULL);
4376
4377   do
4378     {
4379       basic_block bb = pqueue->pop ();
4380
4381       /* Don't re-scan blocks we know already are irrevocable.  */
4382       if (old_irr && bitmap_bit_p (old_irr, bb->index))
4383         continue;
4384
4385       if (ipa_tm_scan_irr_block (bb))
4386         {
4387           bitmap_set_bit (new_irr, bb->index);
4388           any_new_irr = true;
4389         }
4390       else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4391         {
4392           FOR_EACH_EDGE (e, ei, bb->succs)
4393             if (!bitmap_bit_p (visited_blocks, e->dest->index))
4394               {
4395                 bitmap_set_bit (visited_blocks, e->dest->index);
4396                 pqueue->safe_push (e->dest);
4397               }
4398         }
4399     }
4400   while (!pqueue->is_empty ());
4401
4402   BITMAP_FREE (visited_blocks);
4403
4404   return any_new_irr;
4405 }
4406
4407 /* Propagate the irrevocable property both up and down the dominator tree.
4408    BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4409    TM regions; OLD_IRR are the results of a previous scan of the dominator
4410    tree which has been fully propagated; NEW_IRR is the set of new blocks
4411    which are gaining the irrevocable property during the current scan.  */
4412
4413 static void
4414 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4415                       bitmap old_irr, bitmap exit_blocks)
4416 {
4417   vec<basic_block> bbs;
4418   bitmap all_region_blocks;
4419
4420   /* If this block is in the old set, no need to rescan.  */
4421   if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4422     return;
4423
4424   all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4425   bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4426                               all_region_blocks, false);
4427   do
4428     {
4429       basic_block bb = bbs.pop ();
4430       bool this_irr = bitmap_bit_p (new_irr, bb->index);
4431       bool all_son_irr = false;
4432       edge_iterator ei;
4433       edge e;
4434
4435       /* Propagate up.  If my children are, I am too, but we must have
4436          at least one child that is.  */
4437       if (!this_irr)
4438         {
4439           FOR_EACH_EDGE (e, ei, bb->succs)
4440             {
4441               if (!bitmap_bit_p (new_irr, e->dest->index))
4442                 {
4443                   all_son_irr = false;
4444                   break;
4445                 }
4446               else
4447                 all_son_irr = true;
4448             }
4449           if (all_son_irr)
4450             {
4451               /* Add block to new_irr if it hasn't already been processed. */
4452               if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4453                 {
4454                   bitmap_set_bit (new_irr, bb->index);
4455                   this_irr = true;
4456                 }
4457             }
4458         }
4459
4460       /* Propagate down to everyone we immediately dominate.  */
4461       if (this_irr)
4462         {
4463           basic_block son;
4464           for (son = first_dom_son (CDI_DOMINATORS, bb);
4465                son;
4466                son = next_dom_son (CDI_DOMINATORS, son))
4467             {
4468               /* Make sure block is actually in a TM region, and it
4469                  isn't already in old_irr.  */
4470               if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4471                   && bitmap_bit_p (all_region_blocks, son->index))
4472                 bitmap_set_bit (new_irr, son->index);
4473             }
4474         }
4475     }
4476   while (!bbs.is_empty ());
4477
4478   BITMAP_FREE (all_region_blocks);
4479   bbs.release ();
4480 }
4481
4482 static void
4483 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4484 {
4485   gimple_stmt_iterator gsi;
4486
4487   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4488     {
4489       gimple stmt = gsi_stmt (gsi);
4490       if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4491         {
4492           tree fndecl = gimple_call_fndecl (stmt);
4493           if (fndecl)
4494             {
4495               struct tm_ipa_cg_data *d;
4496               unsigned *pcallers;
4497               struct cgraph_node *tnode;
4498
4499               if (is_tm_ending_fndecl (fndecl))
4500                 continue;
4501               if (find_tm_replacement_function (fndecl))
4502                 continue;
4503
4504               tnode = cgraph_get_node (fndecl);
4505               d = get_cg_data (&tnode, true);
4506
4507               pcallers = (for_clone ? &d->tm_callers_clone
4508                           : &d->tm_callers_normal);
4509
4510               gcc_assert (*pcallers > 0);
4511               *pcallers -= 1;
4512             }
4513         }
4514     }
4515 }
4516
4517 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4518    as well as other irrevocable actions such as inline assembly.  Mark all
4519    such blocks as irrevocable and decrement the number of calls to
4520    transactional clones.  Return true if, for the transactional clone, the
4521    entire function is irrevocable.  */
4522
4523 static bool
4524 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4525 {
4526   struct tm_ipa_cg_data *d;
4527   bitmap new_irr, old_irr;
4528   bool ret = false;
4529
4530   /* Builtin operators (operator new, and such).  */
4531   if (DECL_STRUCT_FUNCTION (node->decl) == NULL
4532       || DECL_STRUCT_FUNCTION (node->decl)->cfg == NULL)
4533     return false;
4534
4535   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4536   calculate_dominance_info (CDI_DOMINATORS);
4537
4538   d = get_cg_data (&node, true);
4539   stack_vec<basic_block, 10> queue;
4540   new_irr = BITMAP_ALLOC (&tm_obstack);
4541
4542   /* Scan each tm region, propagating irrevocable status through the tree.  */
4543   if (for_clone)
4544     {
4545       old_irr = d->irrevocable_blocks_clone;
4546       queue.quick_push (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
4547       if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4548         {
4549           ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
4550                                 new_irr,
4551                                 old_irr, NULL);
4552           ret = bitmap_bit_p (new_irr,
4553                               single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun))->index);
4554         }
4555     }
4556   else
4557     {
4558       struct tm_region *region;
4559
4560       old_irr = d->irrevocable_blocks_normal;
4561       for (region = d->all_tm_regions; region; region = region->next)
4562         {
4563           queue.quick_push (region->entry_block);
4564           if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4565                                       region->exit_blocks))
4566             ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4567                                   region->exit_blocks);
4568         }
4569     }
4570
4571   /* If we found any new irrevocable blocks, reduce the call count for
4572      transactional clones within the irrevocable blocks.  Save the new
4573      set of irrevocable blocks for next time.  */
4574   if (!bitmap_empty_p (new_irr))
4575     {
4576       bitmap_iterator bmi;
4577       unsigned i;
4578
4579       EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4580         ipa_tm_decrement_clone_counts (BASIC_BLOCK (i), for_clone);
4581
4582       if (old_irr)
4583         {
4584           bitmap_ior_into (old_irr, new_irr);
4585           BITMAP_FREE (new_irr);
4586         }
4587       else if (for_clone)
4588         d->irrevocable_blocks_clone = new_irr;
4589       else
4590         d->irrevocable_blocks_normal = new_irr;
4591
4592       if (dump_file && new_irr)
4593         {
4594           const char *dname;
4595           bitmap_iterator bmi;
4596           unsigned i;
4597
4598           dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4599           EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4600             fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4601         }
4602     }
4603   else
4604     BITMAP_FREE (new_irr);
4605
4606   pop_cfun ();
4607
4608   return ret;
4609 }
4610
4611 /* Return true if, for the transactional clone of NODE, any call
4612    may enter irrevocable mode.  */
4613
4614 static bool
4615 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4616 {
4617   struct tm_ipa_cg_data *d;
4618   tree decl;
4619   unsigned flags;
4620
4621   d = get_cg_data (&node, true);
4622   decl = node->decl;
4623   flags = flags_from_decl_or_type (decl);
4624
4625   /* Handle some TM builtins.  Ordinarily these aren't actually generated
4626      at this point, but handling these functions when written in by the
4627      user makes it easier to build unit tests.  */
4628   if (flags & ECF_TM_BUILTIN)
4629     return false;
4630
4631   /* Filter out all functions that are marked.  */
4632   if (flags & ECF_TM_PURE)
4633     return false;
4634   if (is_tm_safe (decl))
4635     return false;
4636   if (is_tm_irrevocable (decl))
4637     return true;
4638   if (is_tm_callable (decl))
4639     return true;
4640   if (find_tm_replacement_function (decl))
4641     return true;
4642
4643   /* If we aren't seeing the final version of the function we don't
4644      know what it will contain at runtime.  */
4645   if (cgraph_function_body_availability (node) < AVAIL_AVAILABLE)
4646     return true;
4647
4648   /* If the function must go irrevocable, then of course true.  */
4649   if (d->is_irrevocable)
4650     return true;
4651
4652   /* If there are any blocks marked irrevocable, then the function
4653      as a whole may enter irrevocable.  */
4654   if (d->irrevocable_blocks_clone)
4655     return true;
4656
4657   /* We may have previously marked this function as tm_may_enter_irr;
4658      see pass_diagnose_tm_blocks.  */
4659   if (node->local.tm_may_enter_irr)
4660     return true;
4661
4662   /* Recurse on the main body for aliases.  In general, this will
4663      result in one of the bits above being set so that we will not
4664      have to recurse next time.  */
4665   if (node->alias)
4666     return ipa_tm_mayenterirr_function (cgraph_get_node (node->thunk.alias));
4667
4668   /* What remains is unmarked local functions without items that force
4669      the function to go irrevocable.  */
4670   return false;
4671 }
4672
4673 /* Diagnose calls from transaction_safe functions to unmarked
4674    functions that are determined to not be safe.  */
4675
4676 static void
4677 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4678 {
4679   struct cgraph_edge *e;
4680
4681   for (e = node->callees; e ; e = e->next_callee)
4682     if (!is_tm_callable (e->callee->decl)
4683         && e->callee->local.tm_may_enter_irr)
4684       error_at (gimple_location (e->call_stmt),
4685                 "unsafe function call %qD within "
4686                 "%<transaction_safe%> function", e->callee->decl);
4687 }
4688
4689 /* Diagnose call from atomic transactions to unmarked functions
4690    that are determined to not be safe.  */
4691
4692 static void
4693 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4694                            struct tm_region *all_tm_regions)
4695 {
4696   struct tm_region *r;
4697
4698   for (r = all_tm_regions; r ; r = r->next)
4699     if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4700       {
4701         /* Atomic transactions can be nested inside relaxed.  */
4702         if (r->inner)
4703           ipa_tm_diagnose_transaction (node, r->inner);
4704       }
4705     else
4706       {
4707         vec<basic_block> bbs;
4708         gimple_stmt_iterator gsi;
4709         basic_block bb;
4710         size_t i;
4711
4712         bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4713                                     r->irr_blocks, NULL, false);
4714
4715         for (i = 0; bbs.iterate (i, &bb); ++i)
4716           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4717             {
4718               gimple stmt = gsi_stmt (gsi);
4719               tree fndecl;
4720
4721               if (gimple_code (stmt) == GIMPLE_ASM)
4722                 {
4723                   error_at (gimple_location (stmt),
4724                             "asm not allowed in atomic transaction");
4725                   continue;
4726                 }
4727
4728               if (!is_gimple_call (stmt))
4729                 continue;
4730               fndecl = gimple_call_fndecl (stmt);
4731
4732               /* Indirect function calls have been diagnosed already.  */
4733               if (!fndecl)
4734                 continue;
4735
4736               /* Stop at the end of the transaction.  */
4737               if (is_tm_ending_fndecl (fndecl))
4738                 {
4739                   if (bitmap_bit_p (r->exit_blocks, bb->index))
4740                     break;
4741                   continue;
4742                 }
4743
4744               /* Marked functions have been diagnosed already.  */
4745               if (is_tm_pure_call (stmt))
4746                 continue;
4747               if (is_tm_callable (fndecl))
4748                 continue;
4749
4750               if (cgraph_local_info (fndecl)->tm_may_enter_irr)
4751                 error_at (gimple_location (stmt),
4752                           "unsafe function call %qD within "
4753                           "atomic transaction", fndecl);
4754             }
4755
4756         bbs.release ();
4757       }
4758 }
4759
4760 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4761    OLD_DECL.  The returned value is a freshly malloced pointer that
4762    should be freed by the caller.  */
4763
4764 static tree
4765 tm_mangle (tree old_asm_id)
4766 {
4767   const char *old_asm_name;
4768   char *tm_name;
4769   void *alloc = NULL;
4770   struct demangle_component *dc;
4771   tree new_asm_id;
4772
4773   /* Determine if the symbol is already a valid C++ mangled name.  Do this
4774      even for C, which might be interfacing with C++ code via appropriately
4775      ugly identifiers.  */
4776   /* ??? We could probably do just as well checking for "_Z" and be done.  */
4777   old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4778   dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4779
4780   if (dc == NULL)
4781     {
4782       char length[8];
4783
4784     do_unencoded:
4785       sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4786       tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4787     }
4788   else
4789     {
4790       old_asm_name += 2;        /* Skip _Z */
4791
4792       switch (dc->type)
4793         {
4794         case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4795         case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4796           /* Don't play silly games, you!  */
4797           goto do_unencoded;
4798
4799         case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4800           /* I'd really like to know if we can ever be passed one of
4801              these from the C++ front end.  The Logical Thing would
4802              seem that hidden-alias should be outer-most, so that we
4803              get hidden-alias of a transaction-clone and not vice-versa.  */
4804           old_asm_name += 2;
4805           break;
4806
4807         default:
4808           break;
4809         }
4810
4811       tm_name = concat ("_ZGTt", old_asm_name, NULL);
4812     }
4813   free (alloc);
4814
4815   new_asm_id = get_identifier (tm_name);
4816   free (tm_name);
4817
4818   return new_asm_id;
4819 }
4820
4821 static inline void
4822 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4823 {
4824   cgraph_mark_force_output_node (node);
4825   node->analyzed = true;
4826 }
4827
4828 static inline void
4829 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4830 {
4831   node->forced_by_abi = true;
4832   node->analyzed = true;
4833 }
4834
4835 /* Callback data for ipa_tm_create_version_alias.  */
4836 struct create_version_alias_info
4837 {
4838   struct cgraph_node *old_node;
4839   tree new_decl;
4840 };
4841
4842 /* A subroutine of ipa_tm_create_version, called via
4843    cgraph_for_node_and_aliases.  Create new tm clones for each of
4844    the existing aliases.  */
4845 static bool
4846 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4847 {
4848   struct create_version_alias_info *info
4849     = (struct create_version_alias_info *)data;
4850   tree old_decl, new_decl, tm_name;
4851   struct cgraph_node *new_node;
4852
4853   if (!node->cpp_implicit_alias)
4854     return false;
4855
4856   old_decl = node->decl;
4857   tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4858   new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4859                          TREE_CODE (old_decl), tm_name,
4860                          TREE_TYPE (old_decl));
4861
4862   SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4863   SET_DECL_RTL (new_decl, NULL);
4864
4865   /* Based loosely on C++'s make_alias_for().  */
4866   TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4867   DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4868   DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4869   TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4870   DECL_EXTERNAL (new_decl) = 0;
4871   DECL_ARTIFICIAL (new_decl) = 1;
4872   TREE_ADDRESSABLE (new_decl) = 1;
4873   TREE_USED (new_decl) = 1;
4874   TREE_SYMBOL_REFERENCED (tm_name) = 1;
4875
4876   /* Perform the same remapping to the comdat group.  */
4877   if (DECL_ONE_ONLY (new_decl))
4878     DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4879
4880   new_node = cgraph_same_body_alias (NULL, new_decl, info->new_decl);
4881   new_node->tm_clone = true;
4882   new_node->externally_visible = info->old_node->externally_visible;
4883   /* ?? Do not traverse aliases here.  */
4884   get_cg_data (&node, false)->clone = new_node;
4885
4886   record_tm_clone_pair (old_decl, new_decl);
4887
4888   if (info->old_node->force_output
4889       || ipa_ref_list_first_referring (&info->old_node->ref_list))
4890     ipa_tm_mark_force_output_node (new_node);
4891   if (info->old_node->forced_by_abi)
4892     ipa_tm_mark_forced_by_abi_node (new_node);
4893   return false;
4894 }
4895
4896 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4897    appropriate for the transactional clone.  */
4898
4899 static void
4900 ipa_tm_create_version (struct cgraph_node *old_node)
4901 {
4902   tree new_decl, old_decl, tm_name;
4903   struct cgraph_node *new_node;
4904
4905   old_decl = old_node->decl;
4906   new_decl = copy_node (old_decl);
4907
4908   /* DECL_ASSEMBLER_NAME needs to be set before we call
4909      cgraph_copy_node_for_versioning below, because cgraph_node will
4910      fill the assembler_name_hash.  */
4911   tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4912   SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4913   SET_DECL_RTL (new_decl, NULL);
4914   TREE_SYMBOL_REFERENCED (tm_name) = 1;
4915
4916   /* Perform the same remapping to the comdat group.  */
4917   if (DECL_ONE_ONLY (new_decl))
4918     DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4919
4920   new_node = cgraph_copy_node_for_versioning (old_node, new_decl, vNULL, NULL);
4921   new_node->local.local = false;
4922   new_node->externally_visible = old_node->externally_visible;
4923   new_node->lowered = true;
4924   new_node->tm_clone = 1;
4925   get_cg_data (&old_node, true)->clone = new_node;
4926
4927   if (cgraph_function_body_availability (old_node) >= AVAIL_OVERWRITABLE)
4928     {
4929       /* Remap extern inline to static inline.  */
4930       /* ??? Is it worth trying to use make_decl_one_only?  */
4931       if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4932         {
4933           DECL_EXTERNAL (new_decl) = 0;
4934           TREE_PUBLIC (new_decl) = 0;
4935           DECL_WEAK (new_decl) = 0;
4936         }
4937
4938       tree_function_versioning (old_decl, new_decl,
4939                                 NULL, false, NULL,
4940                                 false, NULL, NULL);
4941     }
4942
4943   record_tm_clone_pair (old_decl, new_decl);
4944
4945   cgraph_call_function_insertion_hooks (new_node);
4946   if (old_node->force_output
4947       || ipa_ref_list_first_referring (&old_node->ref_list))
4948     ipa_tm_mark_force_output_node (new_node);
4949   if (old_node->forced_by_abi)
4950     ipa_tm_mark_forced_by_abi_node (new_node);
4951
4952   /* Do the same thing, but for any aliases of the original node.  */
4953   {
4954     struct create_version_alias_info data;
4955     data.old_node = old_node;
4956     data.new_decl = new_decl;
4957     cgraph_for_node_and_aliases (old_node, ipa_tm_create_version_alias,
4958                                  &data, true);
4959   }
4960 }
4961
4962 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB.  */
4963
4964 static void
4965 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4966                         basic_block bb)
4967 {
4968   gimple_stmt_iterator gsi;
4969   gimple g;
4970
4971   transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4972
4973   g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4974                          1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4975
4976   split_block_after_labels (bb);
4977   gsi = gsi_after_labels (bb);
4978   gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4979
4980   cgraph_create_edge (node,
4981                cgraph_get_create_node
4982                   (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4983                       g, 0,
4984                       compute_call_stmt_bb_frequency (node->decl,
4985                                                       gimple_bb (g)));
4986 }
4987
4988 /* Construct a call to TM_GETTMCLONE and insert it before GSI.  */
4989
4990 static bool
4991 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4992                                struct tm_region *region,
4993                                gimple_stmt_iterator *gsi, gimple stmt)
4994 {
4995   tree gettm_fn, ret, old_fn, callfn;
4996   gimple g, g2;
4997   bool safe;
4998
4999   old_fn = gimple_call_fn (stmt);
5000
5001   if (TREE_CODE (old_fn) == ADDR_EXPR)
5002     {
5003       tree fndecl = TREE_OPERAND (old_fn, 0);
5004       tree clone = get_tm_clone_pair (fndecl);
5005
5006       /* By transforming the call into a TM_GETTMCLONE, we are
5007          technically taking the address of the original function and
5008          its clone.  Explain this so inlining will know this function
5009          is needed.  */
5010       cgraph_mark_address_taken_node (cgraph_get_node (fndecl));
5011       if (clone)
5012         cgraph_mark_address_taken_node (cgraph_get_node (clone));
5013     }
5014
5015   safe = is_tm_safe (TREE_TYPE (old_fn));
5016   gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
5017                                     : BUILT_IN_TM_GETTMCLONE_IRR);
5018   ret = create_tmp_var (ptr_type_node, NULL);
5019
5020   if (!safe)
5021     transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
5022
5023   /* Discard OBJ_TYPE_REF, since we weren't able to fold it.  */
5024   if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
5025     old_fn = OBJ_TYPE_REF_EXPR (old_fn);
5026
5027   g = gimple_build_call (gettm_fn, 1, old_fn);
5028   ret = make_ssa_name (ret, g);
5029   gimple_call_set_lhs (g, ret);
5030
5031   gsi_insert_before (gsi, g, GSI_SAME_STMT);
5032
5033   cgraph_create_edge (node, cgraph_get_create_node (gettm_fn), g, 0,
5034                       compute_call_stmt_bb_frequency (node->decl,
5035                                                       gimple_bb (g)));
5036
5037   /* Cast return value from tm_gettmclone* into appropriate function
5038      pointer.  */
5039   callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
5040   g2 = gimple_build_assign (callfn,
5041                             fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5042   callfn = make_ssa_name (callfn, g2);
5043   gimple_assign_set_lhs (g2, callfn);
5044   gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5045
5046   /* ??? This is a hack to preserve the NOTHROW bit on the call,
5047      which we would have derived from the decl.  Failure to save
5048      this bit means we might have to split the basic block.  */
5049   if (gimple_call_nothrow_p (stmt))
5050     gimple_call_set_nothrow (stmt, true);
5051
5052   gimple_call_set_fn (stmt, callfn);
5053
5054   /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5055      for a call statement.  Fix it.  */
5056   {
5057     tree lhs = gimple_call_lhs (stmt);
5058     tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5059     if (lhs
5060         && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5061     {
5062       tree temp;
5063
5064       temp = create_tmp_reg (rettype, 0);
5065       gimple_call_set_lhs (stmt, temp);
5066
5067       g2 = gimple_build_assign (lhs,
5068                                 fold_build1 (VIEW_CONVERT_EXPR,
5069                                              TREE_TYPE (lhs), temp));
5070       gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5071     }
5072   }
5073
5074   update_stmt (stmt);
5075
5076   return true;
5077 }
5078
5079 /* Helper function for ipa_tm_transform_calls*.  Given a call
5080    statement in GSI which resides inside transaction REGION, redirect
5081    the call to either its wrapper function, or its clone.  */
5082
5083 static void
5084 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5085                                  struct tm_region *region,
5086                                  gimple_stmt_iterator *gsi,
5087                                  bool *need_ssa_rename_p)
5088 {
5089   gimple stmt = gsi_stmt (*gsi);
5090   struct cgraph_node *new_node;
5091   struct cgraph_edge *e = cgraph_edge (node, stmt);
5092   tree fndecl = gimple_call_fndecl (stmt);
5093
5094   /* For indirect calls, pass the address through the runtime.  */
5095   if (fndecl == NULL)
5096     {
5097       *need_ssa_rename_p |=
5098         ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5099       return;
5100     }
5101
5102   /* Handle some TM builtins.  Ordinarily these aren't actually generated
5103      at this point, but handling these functions when written in by the
5104      user makes it easier to build unit tests.  */
5105   if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5106     return;
5107
5108   /* Fixup recursive calls inside clones.  */
5109   /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5110      for recursion but not update the call statements themselves?  */
5111   if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5112     {
5113       gimple_call_set_fndecl (stmt, current_function_decl);
5114       return;
5115     }
5116
5117   /* If there is a replacement, use it.  */
5118   fndecl = find_tm_replacement_function (fndecl);
5119   if (fndecl)
5120     {
5121       new_node = cgraph_get_create_node (fndecl);
5122
5123       /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5124
5125          We can't do this earlier in record_tm_replacement because
5126          cgraph_remove_unreachable_nodes is called before we inject
5127          references to the node.  Further, we can't do this in some
5128          nice central place in ipa_tm_execute because we don't have
5129          the exact list of wrapper functions that would be used.
5130          Marking more wrappers than necessary results in the creation
5131          of unnecessary cgraph_nodes, which can cause some of the
5132          other IPA passes to crash.
5133
5134          We do need to mark these nodes so that we get the proper
5135          result in expand_call_tm.  */
5136       /* ??? This seems broken.  How is it that we're marking the
5137          CALLEE as may_enter_irr?  Surely we should be marking the
5138          CALLER.  Also note that find_tm_replacement_function also
5139          contains mappings into the TM runtime, e.g. memcpy.  These
5140          we know won't go irrevocable.  */
5141       new_node->local.tm_may_enter_irr = 1;
5142     }
5143   else
5144     {
5145       struct tm_ipa_cg_data *d;
5146       struct cgraph_node *tnode = e->callee;
5147
5148       d = get_cg_data (&tnode, true);
5149       new_node = d->clone;
5150
5151       /* As we've already skipped pure calls and appropriate builtins,
5152          and we've already marked irrevocable blocks, if we can't come
5153          up with a static replacement, then ask the runtime.  */
5154       if (new_node == NULL)
5155         {
5156           *need_ssa_rename_p |=
5157             ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5158           return;
5159         }
5160
5161       fndecl = new_node->decl;
5162     }
5163
5164   cgraph_redirect_edge_callee (e, new_node);
5165   gimple_call_set_fndecl (stmt, fndecl);
5166 }
5167
5168 /* Helper function for ipa_tm_transform_calls.  For a given BB,
5169    install calls to tm_irrevocable when IRR_BLOCKS are reached,
5170    redirect other calls to the generated transactional clone.  */
5171
5172 static bool
5173 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5174                           basic_block bb, bitmap irr_blocks)
5175 {
5176   gimple_stmt_iterator gsi;
5177   bool need_ssa_rename = false;
5178
5179   if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5180     {
5181       ipa_tm_insert_irr_call (node, region, bb);
5182       return true;
5183     }
5184
5185   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5186     {
5187       gimple stmt = gsi_stmt (gsi);
5188
5189       if (!is_gimple_call (stmt))
5190         continue;
5191       if (is_tm_pure_call (stmt))
5192         continue;
5193
5194       /* Redirect edges to the appropriate replacement or clone.  */
5195       ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5196     }
5197
5198   return need_ssa_rename;
5199 }
5200
5201 /* Walk the CFG for REGION, beginning at BB.  Install calls to
5202    tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5203    the generated transactional clone.  */
5204
5205 static bool
5206 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5207                         basic_block bb, bitmap irr_blocks)
5208 {
5209   bool need_ssa_rename = false;
5210   edge e;
5211   edge_iterator ei;
5212   auto_vec<basic_block> queue;
5213   bitmap visited_blocks = BITMAP_ALLOC (NULL);
5214
5215   queue.safe_push (bb);
5216   do
5217     {
5218       bb = queue.pop ();
5219
5220       need_ssa_rename |=
5221         ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5222
5223       if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5224         continue;
5225
5226       if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5227         continue;
5228
5229       FOR_EACH_EDGE (e, ei, bb->succs)
5230         if (!bitmap_bit_p (visited_blocks, e->dest->index))
5231           {
5232             bitmap_set_bit (visited_blocks, e->dest->index);
5233             queue.safe_push (e->dest);
5234           }
5235     }
5236   while (!queue.is_empty ());
5237
5238   BITMAP_FREE (visited_blocks);
5239
5240   return need_ssa_rename;
5241 }
5242
5243 /* Transform the calls within the TM regions within NODE.  */
5244
5245 static void
5246 ipa_tm_transform_transaction (struct cgraph_node *node)
5247 {
5248   struct tm_ipa_cg_data *d;
5249   struct tm_region *region;
5250   bool need_ssa_rename = false;
5251
5252   d = get_cg_data (&node, true);
5253
5254   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5255   calculate_dominance_info (CDI_DOMINATORS);
5256
5257   for (region = d->all_tm_regions; region; region = region->next)
5258     {
5259       /* If we're sure to go irrevocable, don't transform anything.  */
5260       if (d->irrevocable_blocks_normal
5261           && bitmap_bit_p (d->irrevocable_blocks_normal,
5262                            region->entry_block->index))
5263         {
5264           transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5265                                            | GTMA_MAY_ENTER_IRREVOCABLE
5266                                            | GTMA_HAS_NO_INSTRUMENTATION);
5267           continue;
5268         }
5269
5270       need_ssa_rename |=
5271         ipa_tm_transform_calls (node, region, region->entry_block,
5272                                 d->irrevocable_blocks_normal);
5273     }
5274
5275   if (need_ssa_rename)
5276     update_ssa (TODO_update_ssa_only_virtuals);
5277
5278   pop_cfun ();
5279 }
5280
5281 /* Transform the calls within the transactional clone of NODE.  */
5282
5283 static void
5284 ipa_tm_transform_clone (struct cgraph_node *node)
5285 {
5286   struct tm_ipa_cg_data *d;
5287   bool need_ssa_rename;
5288
5289   d = get_cg_data (&node, true);
5290
5291   /* If this function makes no calls and has no irrevocable blocks,
5292      then there's nothing to do.  */
5293   /* ??? Remove non-aborting top-level transactions.  */
5294   if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5295     return;
5296
5297   push_cfun (DECL_STRUCT_FUNCTION (d->clone->decl));
5298   calculate_dominance_info (CDI_DOMINATORS);
5299
5300   need_ssa_rename =
5301     ipa_tm_transform_calls (d->clone, NULL,
5302                             single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
5303                             d->irrevocable_blocks_clone);
5304
5305   if (need_ssa_rename)
5306     update_ssa (TODO_update_ssa_only_virtuals);
5307
5308   pop_cfun ();
5309 }
5310
5311 /* Main entry point for the transactional memory IPA pass.  */
5312
5313 static unsigned int
5314 ipa_tm_execute (void)
5315 {
5316   cgraph_node_queue tm_callees = cgraph_node_queue ();
5317   /* List of functions that will go irrevocable.  */
5318   cgraph_node_queue irr_worklist = cgraph_node_queue ();
5319
5320   struct cgraph_node *node;
5321   struct tm_ipa_cg_data *d;
5322   enum availability a;
5323   unsigned int i;
5324
5325 #ifdef ENABLE_CHECKING
5326   verify_cgraph ();
5327 #endif
5328
5329   bitmap_obstack_initialize (&tm_obstack);
5330   initialize_original_copy_tables ();
5331
5332   /* For all local functions marked tm_callable, queue them.  */
5333   FOR_EACH_DEFINED_FUNCTION (node)
5334     if (is_tm_callable (node->decl)
5335         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5336       {
5337         d = get_cg_data (&node, true);
5338         maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5339       }
5340
5341   /* For all local reachable functions...  */
5342   FOR_EACH_DEFINED_FUNCTION (node)
5343     if (node->lowered
5344         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5345       {
5346         /* ... marked tm_pure, record that fact for the runtime by
5347            indicating that the pure function is its own tm_callable.
5348            No need to do this if the function's address can't be taken.  */
5349         if (is_tm_pure (node->decl))
5350           {
5351             if (!node->local.local)
5352               record_tm_clone_pair (node->decl, node->decl);
5353             continue;
5354           }
5355
5356         push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5357         calculate_dominance_info (CDI_DOMINATORS);
5358
5359         tm_region_init (NULL);
5360         if (all_tm_regions)
5361           {
5362             d = get_cg_data (&node, true);
5363
5364             /* Scan for calls that are in each transaction, and
5365                generate the uninstrumented code path.  */
5366             ipa_tm_scan_calls_transaction (d, &tm_callees);
5367
5368             /* Put it in the worklist so we can scan the function
5369                later (ipa_tm_scan_irr_function) and mark the
5370                irrevocable blocks.  */
5371             maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5372             d->want_irr_scan_normal = true;
5373           }
5374
5375         pop_cfun ();
5376       }
5377
5378   /* For every local function on the callee list, scan as if we will be
5379      creating a transactional clone, queueing all new functions we find
5380      along the way.  */
5381   for (i = 0; i < tm_callees.length (); ++i)
5382     {
5383       node = tm_callees[i];
5384       a = cgraph_function_body_availability (node);
5385       d = get_cg_data (&node, true);
5386
5387       /* Put it in the worklist so we can scan the function later
5388          (ipa_tm_scan_irr_function) and mark the irrevocable
5389          blocks.  */
5390       maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5391
5392       /* Some callees cannot be arbitrarily cloned.  These will always be
5393          irrevocable.  Mark these now, so that we need not scan them.  */
5394       if (is_tm_irrevocable (node->decl))
5395         ipa_tm_note_irrevocable (node, &irr_worklist);
5396       else if (a <= AVAIL_NOT_AVAILABLE
5397                && !is_tm_safe_or_pure (node->decl))
5398         ipa_tm_note_irrevocable (node, &irr_worklist);
5399       else if (a >= AVAIL_OVERWRITABLE)
5400         {
5401           if (!tree_versionable_function_p (node->decl))
5402             ipa_tm_note_irrevocable (node, &irr_worklist);
5403           else if (!d->is_irrevocable)
5404             {
5405               /* If this is an alias, make sure its base is queued as well.
5406                  we need not scan the callees now, as the base will do.  */
5407               if (node->alias)
5408                 {
5409                   node = cgraph_get_node (node->thunk.alias);
5410                   d = get_cg_data (&node, true);
5411                   maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5412                   continue;
5413                 }
5414
5415               /* Add all nodes called by this function into
5416                  tm_callees as well.  */
5417               ipa_tm_scan_calls_clone (node, &tm_callees);
5418             }
5419         }
5420     }
5421
5422   /* Iterate scans until no more work to be done.  Prefer not to use
5423      vec::pop because the worklist tends to follow a breadth-first
5424      search of the callgraph, which should allow convergance with a
5425      minimum number of scans.  But we also don't want the worklist
5426      array to grow without bound, so we shift the array up periodically.  */
5427   for (i = 0; i < irr_worklist.length (); ++i)
5428     {
5429       if (i > 256 && i == irr_worklist.length () / 8)
5430         {
5431           irr_worklist.block_remove (0, i);
5432           i = 0;
5433         }
5434
5435       node = irr_worklist[i];
5436       d = get_cg_data (&node, true);
5437       d->in_worklist = false;
5438
5439       if (d->want_irr_scan_normal)
5440         {
5441           d->want_irr_scan_normal = false;
5442           ipa_tm_scan_irr_function (node, false);
5443         }
5444       if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5445         ipa_tm_note_irrevocable (node, &irr_worklist);
5446     }
5447
5448   /* For every function on the callee list, collect the tm_may_enter_irr
5449      bit on the node.  */
5450   irr_worklist.truncate (0);
5451   for (i = 0; i < tm_callees.length (); ++i)
5452     {
5453       node = tm_callees[i];
5454       if (ipa_tm_mayenterirr_function (node))
5455         {
5456           d = get_cg_data (&node, true);
5457           gcc_assert (d->in_worklist == false);
5458           maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5459         }
5460     }
5461
5462   /* Propagate the tm_may_enter_irr bit to callers until stable.  */
5463   for (i = 0; i < irr_worklist.length (); ++i)
5464     {
5465       struct cgraph_node *caller;
5466       struct cgraph_edge *e;
5467       struct ipa_ref *ref;
5468       unsigned j;
5469
5470       if (i > 256 && i == irr_worklist.length () / 8)
5471         {
5472           irr_worklist.block_remove (0, i);
5473           i = 0;
5474         }
5475
5476       node = irr_worklist[i];
5477       d = get_cg_data (&node, true);
5478       d->in_worklist = false;
5479       node->local.tm_may_enter_irr = true;
5480
5481       /* Propagate back to normal callers.  */
5482       for (e = node->callers; e ; e = e->next_caller)
5483         {
5484           caller = e->caller;
5485           if (!is_tm_safe_or_pure (caller->decl)
5486               && !caller->local.tm_may_enter_irr)
5487             {
5488               d = get_cg_data (&caller, true);
5489               maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5490             }
5491         }
5492
5493       /* Propagate back to referring aliases as well.  */
5494       for (j = 0; ipa_ref_list_referring_iterate (&node->ref_list, j, ref); j++)
5495         {
5496           caller = cgraph (ref->referring);
5497           if (ref->use == IPA_REF_ALIAS
5498               && !caller->local.tm_may_enter_irr)
5499             {
5500               /* ?? Do not traverse aliases here.  */
5501               d = get_cg_data (&caller, false);
5502               maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5503             }
5504         }
5505     }
5506
5507   /* Now validate all tm_safe functions, and all atomic regions in
5508      other functions.  */
5509   FOR_EACH_DEFINED_FUNCTION (node)
5510     if (node->lowered
5511         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5512       {
5513         d = get_cg_data (&node, true);
5514         if (is_tm_safe (node->decl))
5515           ipa_tm_diagnose_tm_safe (node);
5516         else if (d->all_tm_regions)
5517           ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5518       }
5519
5520   /* Create clones.  Do those that are not irrevocable and have a
5521      positive call count.  Do those publicly visible functions that
5522      the user directed us to clone.  */
5523   for (i = 0; i < tm_callees.length (); ++i)
5524     {
5525       bool doit = false;
5526
5527       node = tm_callees[i];
5528       if (node->cpp_implicit_alias)
5529         continue;
5530
5531       a = cgraph_function_body_availability (node);
5532       d = get_cg_data (&node, true);
5533
5534       if (a <= AVAIL_NOT_AVAILABLE)
5535         doit = is_tm_callable (node->decl);
5536       else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
5537         doit = true;
5538       else if (!d->is_irrevocable
5539                && d->tm_callers_normal + d->tm_callers_clone > 0)
5540         doit = true;
5541
5542       if (doit)
5543         ipa_tm_create_version (node);
5544     }
5545
5546   /* Redirect calls to the new clones, and insert irrevocable marks.  */
5547   for (i = 0; i < tm_callees.length (); ++i)
5548     {
5549       node = tm_callees[i];
5550       if (node->analyzed)
5551         {
5552           d = get_cg_data (&node, true);
5553           if (d->clone)
5554             ipa_tm_transform_clone (node);
5555         }
5556     }
5557   FOR_EACH_DEFINED_FUNCTION (node)
5558     if (node->lowered
5559         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5560       {
5561         d = get_cg_data (&node, true);
5562         if (d->all_tm_regions)
5563           ipa_tm_transform_transaction (node);
5564       }
5565
5566   /* Free and clear all data structures.  */
5567   tm_callees.release ();
5568   irr_worklist.release ();
5569   bitmap_obstack_release (&tm_obstack);
5570   free_original_copy_tables ();
5571
5572   FOR_EACH_FUNCTION (node)
5573     node->aux = NULL;
5574
5575 #ifdef ENABLE_CHECKING
5576   verify_cgraph ();
5577 #endif
5578
5579   return 0;
5580 }
5581
5582 namespace {
5583
5584 const pass_data pass_data_ipa_tm =
5585 {
5586   SIMPLE_IPA_PASS, /* type */
5587   "tmipa", /* name */
5588   OPTGROUP_NONE, /* optinfo_flags */
5589   true, /* has_gate */
5590   true, /* has_execute */
5591   TV_TRANS_MEM, /* tv_id */
5592   ( PROP_ssa | PROP_cfg ), /* properties_required */
5593   0, /* properties_provided */
5594   0, /* properties_destroyed */
5595   0, /* todo_flags_start */
5596   0, /* todo_flags_finish */
5597 };
5598
5599 class pass_ipa_tm : public simple_ipa_opt_pass
5600 {
5601 public:
5602   pass_ipa_tm (gcc::context *ctxt)
5603     : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5604   {}
5605
5606   /* opt_pass methods: */
5607   bool gate () { return gate_tm (); }
5608   unsigned int execute () { return ipa_tm_execute (); }
5609
5610 }; // class pass_ipa_tm
5611
5612 } // anon namespace
5613
5614 simple_ipa_opt_pass *
5615 make_pass_ipa_tm (gcc::context *ctxt)
5616 {
5617   return new pass_ipa_tm (ctxt);
5618 }
5619
5620 #include "gt-trans-mem.h"