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