Simplify convert_modes, ignoring invalid old modes for CONST_INTs.
[official-gcc.git] / gcc / trans-mem.c
blob3371c7ea26edb885eb0ecacb6d2110b9ac64cb46
1 /* Passes for transactional memory support.
2 Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hash-table.h"
24 #include "tree.h"
25 #include "gimple.h"
26 #include "tree-ssa.h"
27 #include "tree-pass.h"
28 #include "tree-inline.h"
29 #include "diagnostic-core.h"
30 #include "demangle.h"
31 #include "output.h"
32 #include "trans-mem.h"
33 #include "params.h"
34 #include "target.h"
35 #include "langhooks.h"
36 #include "gimple-pretty-print.h"
37 #include "cfgloop.h"
38 #include "tree-ssa-address.h"
41 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
42 #define PROB_VERY_LIKELY (PROB_ALWAYS - PROB_VERY_UNLIKELY)
43 #define PROB_UNLIKELY (REG_BR_PROB_BASE / 5 - 1)
44 #define PROB_LIKELY (PROB_ALWAYS - PROB_VERY_LIKELY)
45 #define PROB_ALWAYS (REG_BR_PROB_BASE)
47 #define A_RUNINSTRUMENTEDCODE 0x0001
48 #define A_RUNUNINSTRUMENTEDCODE 0x0002
49 #define A_SAVELIVEVARIABLES 0x0004
50 #define A_RESTORELIVEVARIABLES 0x0008
51 #define A_ABORTTRANSACTION 0x0010
53 #define AR_USERABORT 0x0001
54 #define AR_USERRETRY 0x0002
55 #define AR_TMCONFLICT 0x0004
56 #define AR_EXCEPTIONBLOCKABORT 0x0008
57 #define AR_OUTERABORT 0x0010
59 #define MODE_SERIALIRREVOCABLE 0x0000
62 /* The representation of a transaction changes several times during the
63 lowering process. In the beginning, in the front-end we have the
64 GENERIC tree TRANSACTION_EXPR. For example,
66 __transaction {
67 local++;
68 if (++global == 10)
69 __tm_abort;
72 During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
73 trivially replaced with a GIMPLE_TRANSACTION node.
75 During pass_lower_tm, we examine the body of transactions looking
76 for aborts. Transactions that do not contain an abort may be
77 merged into an outer transaction. We also add a TRY-FINALLY node
78 to arrange for the transaction to be committed on any exit.
80 [??? Think about how this arrangement affects throw-with-commit
81 and throw-with-abort operations. In this case we want the TRY to
82 handle gotos, but not to catch any exceptions because the transaction
83 will already be closed.]
85 GIMPLE_TRANSACTION [label=NULL] {
86 try {
87 local = local + 1;
88 t0 = global;
89 t1 = t0 + 1;
90 global = t1;
91 if (t1 == 10)
92 __builtin___tm_abort ();
93 } finally {
94 __builtin___tm_commit ();
98 During pass_lower_eh, we create EH regions for the transactions,
99 intermixed with the regular EH stuff. This gives us a nice persistent
100 mapping (all the way through rtl) from transactional memory operation
101 back to the transaction, which allows us to get the abnormal edges
102 correct to model transaction aborts and restarts:
104 GIMPLE_TRANSACTION [label=over]
105 local = local + 1;
106 t0 = global;
107 t1 = t0 + 1;
108 global = t1;
109 if (t1 == 10)
110 __builtin___tm_abort ();
111 __builtin___tm_commit ();
112 over:
114 This is the end of all_lowering_passes, and so is what is present
115 during the IPA passes, and through all of the optimization passes.
117 During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
118 functions and mark functions for cloning.
120 At the end of gimple optimization, before exiting SSA form,
121 pass_tm_edges replaces statements that perform transactional
122 memory operations with the appropriate TM builtins, and swap
123 out function calls with their transactional clones. At this
124 point we introduce the abnormal transaction restart edges and
125 complete lowering of the GIMPLE_TRANSACTION node.
127 x = __builtin___tm_start (MAY_ABORT);
128 eh_label:
129 if (x & abort_transaction)
130 goto over;
131 local = local + 1;
132 t0 = __builtin___tm_load (global);
133 t1 = t0 + 1;
134 __builtin___tm_store (&global, t1);
135 if (t1 == 10)
136 __builtin___tm_abort ();
137 __builtin___tm_commit ();
138 over:
141 static void *expand_regions (struct tm_region *,
142 void *(*callback)(struct tm_region *, void *),
143 void *, bool);
146 /* Return the attributes we want to examine for X, or NULL if it's not
147 something we examine. We look at function types, but allow pointers
148 to function types and function decls and peek through. */
150 static tree
151 get_attrs_for (const_tree x)
153 switch (TREE_CODE (x))
155 case FUNCTION_DECL:
156 return TYPE_ATTRIBUTES (TREE_TYPE (x));
157 break;
159 default:
160 if (TYPE_P (x))
161 return NULL;
162 x = TREE_TYPE (x);
163 if (TREE_CODE (x) != POINTER_TYPE)
164 return NULL;
165 /* FALLTHRU */
167 case POINTER_TYPE:
168 x = TREE_TYPE (x);
169 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
170 return NULL;
171 /* FALLTHRU */
173 case FUNCTION_TYPE:
174 case METHOD_TYPE:
175 return TYPE_ATTRIBUTES (x);
179 /* Return true if X has been marked TM_PURE. */
181 bool
182 is_tm_pure (const_tree x)
184 unsigned flags;
186 switch (TREE_CODE (x))
188 case FUNCTION_DECL:
189 case FUNCTION_TYPE:
190 case METHOD_TYPE:
191 break;
193 default:
194 if (TYPE_P (x))
195 return false;
196 x = TREE_TYPE (x);
197 if (TREE_CODE (x) != POINTER_TYPE)
198 return false;
199 /* FALLTHRU */
201 case POINTER_TYPE:
202 x = TREE_TYPE (x);
203 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
204 return false;
205 break;
208 flags = flags_from_decl_or_type (x);
209 return (flags & ECF_TM_PURE) != 0;
212 /* Return true if X has been marked TM_IRREVOCABLE. */
214 static bool
215 is_tm_irrevocable (tree x)
217 tree attrs = get_attrs_for (x);
219 if (attrs && lookup_attribute ("transaction_unsafe", attrs))
220 return true;
222 /* A call to the irrevocable builtin is by definition,
223 irrevocable. */
224 if (TREE_CODE (x) == ADDR_EXPR)
225 x = TREE_OPERAND (x, 0);
226 if (TREE_CODE (x) == FUNCTION_DECL
227 && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
228 && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
229 return true;
231 return false;
234 /* Return true if X has been marked TM_SAFE. */
236 bool
237 is_tm_safe (const_tree x)
239 if (flag_tm)
241 tree attrs = get_attrs_for (x);
242 if (attrs)
244 if (lookup_attribute ("transaction_safe", attrs))
245 return true;
246 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
247 return true;
250 return false;
253 /* Return true if CALL is const, or tm_pure. */
255 static bool
256 is_tm_pure_call (gimple call)
258 tree fn = gimple_call_fn (call);
260 if (TREE_CODE (fn) == ADDR_EXPR)
262 fn = TREE_OPERAND (fn, 0);
263 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
265 else
266 fn = TREE_TYPE (fn);
268 return is_tm_pure (fn);
271 /* Return true if X has been marked TM_CALLABLE. */
273 static bool
274 is_tm_callable (tree x)
276 tree attrs = get_attrs_for (x);
277 if (attrs)
279 if (lookup_attribute ("transaction_callable", attrs))
280 return true;
281 if (lookup_attribute ("transaction_safe", attrs))
282 return true;
283 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
284 return true;
286 return false;
289 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER. */
291 bool
292 is_tm_may_cancel_outer (tree x)
294 tree attrs = get_attrs_for (x);
295 if (attrs)
296 return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
297 return false;
300 /* Return true for built in functions that "end" a transaction. */
302 bool
303 is_tm_ending_fndecl (tree fndecl)
305 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
306 switch (DECL_FUNCTION_CODE (fndecl))
308 case BUILT_IN_TM_COMMIT:
309 case BUILT_IN_TM_COMMIT_EH:
310 case BUILT_IN_TM_ABORT:
311 case BUILT_IN_TM_IRREVOCABLE:
312 return true;
313 default:
314 break;
317 return false;
320 /* Return true if STMT is a TM load. */
322 static bool
323 is_tm_load (gimple stmt)
325 tree fndecl;
327 if (gimple_code (stmt) != GIMPLE_CALL)
328 return false;
330 fndecl = gimple_call_fndecl (stmt);
331 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
332 && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
335 /* Same as above, but for simple TM loads, that is, not the
336 after-write, after-read, etc optimized variants. */
338 static bool
339 is_tm_simple_load (gimple stmt)
341 tree fndecl;
343 if (gimple_code (stmt) != GIMPLE_CALL)
344 return false;
346 fndecl = gimple_call_fndecl (stmt);
347 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
349 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
350 return (fcode == BUILT_IN_TM_LOAD_1
351 || fcode == BUILT_IN_TM_LOAD_2
352 || fcode == BUILT_IN_TM_LOAD_4
353 || fcode == BUILT_IN_TM_LOAD_8
354 || fcode == BUILT_IN_TM_LOAD_FLOAT
355 || fcode == BUILT_IN_TM_LOAD_DOUBLE
356 || fcode == BUILT_IN_TM_LOAD_LDOUBLE
357 || fcode == BUILT_IN_TM_LOAD_M64
358 || fcode == BUILT_IN_TM_LOAD_M128
359 || fcode == BUILT_IN_TM_LOAD_M256);
361 return false;
364 /* Return true if STMT is a TM store. */
366 static bool
367 is_tm_store (gimple stmt)
369 tree fndecl;
371 if (gimple_code (stmt) != GIMPLE_CALL)
372 return false;
374 fndecl = gimple_call_fndecl (stmt);
375 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
376 && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
379 /* Same as above, but for simple TM stores, that is, not the
380 after-write, after-read, etc optimized variants. */
382 static bool
383 is_tm_simple_store (gimple stmt)
385 tree fndecl;
387 if (gimple_code (stmt) != GIMPLE_CALL)
388 return false;
390 fndecl = gimple_call_fndecl (stmt);
391 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
393 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
394 return (fcode == BUILT_IN_TM_STORE_1
395 || fcode == BUILT_IN_TM_STORE_2
396 || fcode == BUILT_IN_TM_STORE_4
397 || fcode == BUILT_IN_TM_STORE_8
398 || fcode == BUILT_IN_TM_STORE_FLOAT
399 || fcode == BUILT_IN_TM_STORE_DOUBLE
400 || fcode == BUILT_IN_TM_STORE_LDOUBLE
401 || fcode == BUILT_IN_TM_STORE_M64
402 || fcode == BUILT_IN_TM_STORE_M128
403 || fcode == BUILT_IN_TM_STORE_M256);
405 return false;
408 /* Return true if FNDECL is BUILT_IN_TM_ABORT. */
410 static bool
411 is_tm_abort (tree fndecl)
413 return (fndecl
414 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
415 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
418 /* Build a GENERIC tree for a user abort. This is called by front ends
419 while transforming the __tm_abort statement. */
421 tree
422 build_tm_abort_call (location_t loc, bool is_outer)
424 return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
425 build_int_cst (integer_type_node,
426 AR_USERABORT
427 | (is_outer ? AR_OUTERABORT : 0)));
430 /* Common gateing function for several of the TM passes. */
432 static bool
433 gate_tm (void)
435 return flag_tm;
438 /* Map for aribtrary function replacement under TM, as created
439 by the tm_wrap attribute. */
441 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
442 htab_t tm_wrap_map;
444 void
445 record_tm_replacement (tree from, tree to)
447 struct tree_map **slot, *h;
449 /* Do not inline wrapper functions that will get replaced in the TM
450 pass.
452 Suppose you have foo() that will get replaced into tmfoo(). Make
453 sure the inliner doesn't try to outsmart us and inline foo()
454 before we get a chance to do the TM replacement. */
455 DECL_UNINLINABLE (from) = 1;
457 if (tm_wrap_map == NULL)
458 tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
460 h = ggc_alloc_tree_map ();
461 h->hash = htab_hash_pointer (from);
462 h->base.from = from;
463 h->to = to;
465 slot = (struct tree_map **)
466 htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
467 *slot = h;
470 /* Return a TM-aware replacement function for DECL. */
472 static tree
473 find_tm_replacement_function (tree fndecl)
475 if (tm_wrap_map)
477 struct tree_map *h, in;
479 in.base.from = fndecl;
480 in.hash = htab_hash_pointer (fndecl);
481 h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
482 if (h)
483 return h->to;
486 /* ??? We may well want TM versions of most of the common <string.h>
487 functions. For now, we've already these two defined. */
488 /* Adjust expand_call_tm() attributes as necessary for the cases
489 handled here: */
490 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
491 switch (DECL_FUNCTION_CODE (fndecl))
493 case BUILT_IN_MEMCPY:
494 return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
495 case BUILT_IN_MEMMOVE:
496 return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
497 case BUILT_IN_MEMSET:
498 return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
499 default:
500 return NULL;
503 return NULL;
506 /* When appropriate, record TM replacement for memory allocation functions.
508 FROM is the FNDECL to wrap. */
509 void
510 tm_malloc_replacement (tree from)
512 const char *str;
513 tree to;
515 if (TREE_CODE (from) != FUNCTION_DECL)
516 return;
518 /* If we have a previous replacement, the user must be explicitly
519 wrapping malloc/calloc/free. They better know what they're
520 doing... */
521 if (find_tm_replacement_function (from))
522 return;
524 str = IDENTIFIER_POINTER (DECL_NAME (from));
526 if (!strcmp (str, "malloc"))
527 to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
528 else if (!strcmp (str, "calloc"))
529 to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
530 else if (!strcmp (str, "free"))
531 to = builtin_decl_explicit (BUILT_IN_TM_FREE);
532 else
533 return;
535 TREE_NOTHROW (to) = 0;
537 record_tm_replacement (from, to);
540 /* Diagnostics for tm_safe functions/regions. Called by the front end
541 once we've lowered the function to high-gimple. */
543 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
544 Process exactly one statement. WI->INFO is set to non-null when in
545 the context of a tm_safe function, and null for a __transaction block. */
547 #define DIAG_TM_OUTER 1
548 #define DIAG_TM_SAFE 2
549 #define DIAG_TM_RELAXED 4
551 struct diagnose_tm
553 unsigned int summary_flags : 8;
554 unsigned int block_flags : 8;
555 unsigned int func_flags : 8;
556 unsigned int saw_volatile : 1;
557 gimple stmt;
560 /* Return true if T is a volatile variable of some kind. */
562 static bool
563 volatile_var_p (tree t)
565 return (SSA_VAR_P (t)
566 && TREE_THIS_VOLATILE (TREE_TYPE (t)));
569 /* Tree callback function for diagnose_tm pass. */
571 static tree
572 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
573 void *data)
575 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
576 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
578 if (volatile_var_p (*tp)
579 && d->block_flags & DIAG_TM_SAFE
580 && !d->saw_volatile)
582 d->saw_volatile = 1;
583 error_at (gimple_location (d->stmt),
584 "invalid volatile use of %qD inside transaction",
585 *tp);
588 return NULL_TREE;
591 static tree
592 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
593 struct walk_stmt_info *wi)
595 gimple stmt = gsi_stmt (*gsi);
596 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
598 /* Save stmt for use in leaf analysis. */
599 d->stmt = stmt;
601 switch (gimple_code (stmt))
603 case GIMPLE_CALL:
605 tree fn = gimple_call_fn (stmt);
607 if ((d->summary_flags & DIAG_TM_OUTER) == 0
608 && is_tm_may_cancel_outer (fn))
609 error_at (gimple_location (stmt),
610 "%<transaction_may_cancel_outer%> function call not within"
611 " outer transaction or %<transaction_may_cancel_outer%>");
613 if (d->summary_flags & DIAG_TM_SAFE)
615 bool is_safe, direct_call_p;
616 tree replacement;
618 if (TREE_CODE (fn) == ADDR_EXPR
619 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
621 direct_call_p = true;
622 replacement = TREE_OPERAND (fn, 0);
623 replacement = find_tm_replacement_function (replacement);
624 if (replacement)
625 fn = replacement;
627 else
629 direct_call_p = false;
630 replacement = NULL_TREE;
633 if (is_tm_safe_or_pure (fn))
634 is_safe = true;
635 else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
637 /* A function explicitly marked transaction_callable as
638 opposed to transaction_safe is being defined to be
639 unsafe as part of its ABI, regardless of its contents. */
640 is_safe = false;
642 else if (direct_call_p)
644 if (flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
645 is_safe = true;
646 else if (replacement)
648 /* ??? At present we've been considering replacements
649 merely transaction_callable, and therefore might
650 enter irrevocable. The tm_wrap attribute has not
651 yet made it into the new language spec. */
652 is_safe = false;
654 else
656 /* ??? Diagnostics for unmarked direct calls moved into
657 the IPA pass. Section 3.2 of the spec details how
658 functions not marked should be considered "implicitly
659 safe" based on having examined the function body. */
660 is_safe = true;
663 else
665 /* An unmarked indirect call. Consider it unsafe even
666 though optimization may yet figure out how to inline. */
667 is_safe = false;
670 if (!is_safe)
672 if (TREE_CODE (fn) == ADDR_EXPR)
673 fn = TREE_OPERAND (fn, 0);
674 if (d->block_flags & DIAG_TM_SAFE)
676 if (direct_call_p)
677 error_at (gimple_location (stmt),
678 "unsafe function call %qD within "
679 "atomic transaction", fn);
680 else
682 if (!DECL_P (fn) || DECL_NAME (fn))
683 error_at (gimple_location (stmt),
684 "unsafe function call %qE within "
685 "atomic transaction", fn);
686 else
687 error_at (gimple_location (stmt),
688 "unsafe indirect function call within "
689 "atomic transaction");
692 else
694 if (direct_call_p)
695 error_at (gimple_location (stmt),
696 "unsafe function call %qD within "
697 "%<transaction_safe%> function", fn);
698 else
700 if (!DECL_P (fn) || DECL_NAME (fn))
701 error_at (gimple_location (stmt),
702 "unsafe function call %qE within "
703 "%<transaction_safe%> function", fn);
704 else
705 error_at (gimple_location (stmt),
706 "unsafe indirect function call within "
707 "%<transaction_safe%> function");
713 break;
715 case GIMPLE_ASM:
716 /* ??? We ought to come up with a way to add attributes to
717 asm statements, and then add "transaction_safe" to it.
718 Either that or get the language spec to resurrect __tm_waiver. */
719 if (d->block_flags & DIAG_TM_SAFE)
720 error_at (gimple_location (stmt),
721 "asm not allowed in atomic transaction");
722 else if (d->func_flags & DIAG_TM_SAFE)
723 error_at (gimple_location (stmt),
724 "asm not allowed in %<transaction_safe%> function");
725 break;
727 case GIMPLE_TRANSACTION:
729 unsigned char inner_flags = DIAG_TM_SAFE;
731 if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
733 if (d->block_flags & DIAG_TM_SAFE)
734 error_at (gimple_location (stmt),
735 "relaxed transaction in atomic transaction");
736 else if (d->func_flags & DIAG_TM_SAFE)
737 error_at (gimple_location (stmt),
738 "relaxed transaction in %<transaction_safe%> function");
739 inner_flags = DIAG_TM_RELAXED;
741 else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
743 if (d->block_flags)
744 error_at (gimple_location (stmt),
745 "outer transaction in transaction");
746 else if (d->func_flags & DIAG_TM_OUTER)
747 error_at (gimple_location (stmt),
748 "outer transaction in "
749 "%<transaction_may_cancel_outer%> function");
750 else if (d->func_flags & DIAG_TM_SAFE)
751 error_at (gimple_location (stmt),
752 "outer transaction in %<transaction_safe%> function");
753 inner_flags |= DIAG_TM_OUTER;
756 *handled_ops_p = true;
757 if (gimple_transaction_body (stmt))
759 struct walk_stmt_info wi_inner;
760 struct diagnose_tm d_inner;
762 memset (&d_inner, 0, sizeof (d_inner));
763 d_inner.func_flags = d->func_flags;
764 d_inner.block_flags = d->block_flags | inner_flags;
765 d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
767 memset (&wi_inner, 0, sizeof (wi_inner));
768 wi_inner.info = &d_inner;
770 walk_gimple_seq (gimple_transaction_body (stmt),
771 diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
774 break;
776 default:
777 break;
780 return NULL_TREE;
783 static unsigned int
784 diagnose_tm_blocks (void)
786 struct walk_stmt_info wi;
787 struct diagnose_tm d;
789 memset (&d, 0, sizeof (d));
790 if (is_tm_may_cancel_outer (current_function_decl))
791 d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
792 else if (is_tm_safe (current_function_decl))
793 d.func_flags = DIAG_TM_SAFE;
794 d.summary_flags = d.func_flags;
796 memset (&wi, 0, sizeof (wi));
797 wi.info = &d;
799 walk_gimple_seq (gimple_body (current_function_decl),
800 diagnose_tm_1, diagnose_tm_1_op, &wi);
802 return 0;
805 namespace {
807 const pass_data pass_data_diagnose_tm_blocks =
809 GIMPLE_PASS, /* type */
810 "*diagnose_tm_blocks", /* name */
811 OPTGROUP_NONE, /* optinfo_flags */
812 true, /* has_gate */
813 true, /* has_execute */
814 TV_TRANS_MEM, /* tv_id */
815 PROP_gimple_any, /* properties_required */
816 0, /* properties_provided */
817 0, /* properties_destroyed */
818 0, /* todo_flags_start */
819 0, /* todo_flags_finish */
822 class pass_diagnose_tm_blocks : public gimple_opt_pass
824 public:
825 pass_diagnose_tm_blocks (gcc::context *ctxt)
826 : gimple_opt_pass (pass_data_diagnose_tm_blocks, ctxt)
829 /* opt_pass methods: */
830 bool gate () { return gate_tm (); }
831 unsigned int execute () { return diagnose_tm_blocks (); }
833 }; // class pass_diagnose_tm_blocks
835 } // anon namespace
837 gimple_opt_pass *
838 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
840 return new pass_diagnose_tm_blocks (ctxt);
843 /* Instead of instrumenting thread private memory, we save the
844 addresses in a log which we later use to save/restore the addresses
845 upon transaction start/restart.
847 The log is keyed by address, where each element contains individual
848 statements among different code paths that perform the store.
850 This log is later used to generate either plain save/restore of the
851 addresses upon transaction start/restart, or calls to the ITM_L*
852 logging functions.
854 So for something like:
856 struct large { int x[1000]; };
857 struct large lala = { 0 };
858 __transaction {
859 lala.x[i] = 123;
863 We can either save/restore:
865 lala = { 0 };
866 trxn = _ITM_startTransaction ();
867 if (trxn & a_saveLiveVariables)
868 tmp_lala1 = lala.x[i];
869 else if (a & a_restoreLiveVariables)
870 lala.x[i] = tmp_lala1;
872 or use the logging functions:
874 lala = { 0 };
875 trxn = _ITM_startTransaction ();
876 _ITM_LU4 (&lala.x[i]);
878 Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
879 far up the dominator tree to shadow all of the writes to a given
880 location (thus reducing the total number of logging calls), but not
881 so high as to be called on a path that does not perform a
882 write. */
884 /* One individual log entry. We may have multiple statements for the
885 same location if neither dominate each other (on different
886 execution paths). */
887 typedef struct tm_log_entry
889 /* Address to save. */
890 tree addr;
891 /* Entry block for the transaction this address occurs in. */
892 basic_block entry_block;
893 /* Dominating statements the store occurs in. */
894 gimple_vec stmts;
895 /* Initially, while we are building the log, we place a nonzero
896 value here to mean that this address *will* be saved with a
897 save/restore sequence. Later, when generating the save sequence
898 we place the SSA temp generated here. */
899 tree save_var;
900 } *tm_log_entry_t;
903 /* Log entry hashtable helpers. */
905 struct log_entry_hasher
907 typedef tm_log_entry value_type;
908 typedef tm_log_entry compare_type;
909 static inline hashval_t hash (const value_type *);
910 static inline bool equal (const value_type *, const compare_type *);
911 static inline void remove (value_type *);
914 /* Htab support. Return hash value for a `tm_log_entry'. */
915 inline hashval_t
916 log_entry_hasher::hash (const value_type *log)
918 return iterative_hash_expr (log->addr, 0);
921 /* Htab support. Return true if two log entries are the same. */
922 inline bool
923 log_entry_hasher::equal (const value_type *log1, const compare_type *log2)
925 /* FIXME:
927 rth: I suggest that we get rid of the component refs etc.
928 I.e. resolve the reference to base + offset.
930 We may need to actually finish a merge with mainline for this,
931 since we'd like to be presented with Richi's MEM_REF_EXPRs more
932 often than not. But in the meantime your tm_log_entry could save
933 the results of get_inner_reference.
935 See: g++.dg/tm/pr46653.C
938 /* Special case plain equality because operand_equal_p() below will
939 return FALSE if the addresses are equal but they have
940 side-effects (e.g. a volatile address). */
941 if (log1->addr == log2->addr)
942 return true;
944 return operand_equal_p (log1->addr, log2->addr, 0);
947 /* Htab support. Free one tm_log_entry. */
948 inline void
949 log_entry_hasher::remove (value_type *lp)
951 lp->stmts.release ();
952 free (lp);
956 /* The actual log. */
957 static hash_table <log_entry_hasher> tm_log;
959 /* Addresses to log with a save/restore sequence. These should be in
960 dominator order. */
961 static vec<tree> tm_log_save_addresses;
963 enum thread_memory_type
965 mem_non_local = 0,
966 mem_thread_local,
967 mem_transaction_local,
968 mem_max
971 typedef struct tm_new_mem_map
973 /* SSA_NAME being dereferenced. */
974 tree val;
975 enum thread_memory_type local_new_memory;
976 } tm_new_mem_map_t;
978 /* Hashtable helpers. */
980 struct tm_mem_map_hasher : typed_free_remove <tm_new_mem_map_t>
982 typedef tm_new_mem_map_t value_type;
983 typedef tm_new_mem_map_t compare_type;
984 static inline hashval_t hash (const value_type *);
985 static inline bool equal (const value_type *, const compare_type *);
988 inline hashval_t
989 tm_mem_map_hasher::hash (const value_type *v)
991 return (intptr_t)v->val >> 4;
994 inline bool
995 tm_mem_map_hasher::equal (const value_type *v, const compare_type *c)
997 return v->val == c->val;
1000 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1001 of memory (malloc, alloc, etc). */
1002 static hash_table <tm_mem_map_hasher> tm_new_mem_hash;
1004 /* Initialize logging data structures. */
1005 static void
1006 tm_log_init (void)
1008 tm_log.create (10);
1009 tm_new_mem_hash.create (5);
1010 tm_log_save_addresses.create (5);
1013 /* Free logging data structures. */
1014 static void
1015 tm_log_delete (void)
1017 tm_log.dispose ();
1018 tm_new_mem_hash.dispose ();
1019 tm_log_save_addresses.release ();
1022 /* Return true if MEM is a transaction invariant memory for the TM
1023 region starting at REGION_ENTRY_BLOCK. */
1024 static bool
1025 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1027 if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1028 && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1030 basic_block def_bb;
1032 def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1033 return def_bb != region_entry_block
1034 && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1037 mem = strip_invariant_refs (mem);
1038 return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1041 /* Given an address ADDR in STMT, find it in the memory log or add it,
1042 making sure to keep only the addresses highest in the dominator
1043 tree.
1045 ENTRY_BLOCK is the entry_block for the transaction.
1047 If we find the address in the log, make sure it's either the same
1048 address, or an equivalent one that dominates ADDR.
1050 If we find the address, but neither ADDR dominates the found
1051 address, nor the found one dominates ADDR, we're on different
1052 execution paths. Add it.
1054 If known, ENTRY_BLOCK is the entry block for the region, otherwise
1055 NULL. */
1056 static void
1057 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1059 tm_log_entry **slot;
1060 struct tm_log_entry l, *lp;
1062 l.addr = addr;
1063 slot = tm_log.find_slot (&l, INSERT);
1064 if (!*slot)
1066 tree type = TREE_TYPE (addr);
1068 lp = XNEW (struct tm_log_entry);
1069 lp->addr = addr;
1070 *slot = lp;
1072 /* Small invariant addresses can be handled as save/restores. */
1073 if (entry_block
1074 && transaction_invariant_address_p (lp->addr, entry_block)
1075 && TYPE_SIZE_UNIT (type) != NULL
1076 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
1077 && ((HOST_WIDE_INT)(tree_to_uhwi (TYPE_SIZE_UNIT (type)))
1078 < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1079 /* We must be able to copy this type normally. I.e., no
1080 special constructors and the like. */
1081 && !TREE_ADDRESSABLE (type))
1083 lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1084 lp->stmts.create (0);
1085 lp->entry_block = entry_block;
1086 /* Save addresses separately in dominator order so we don't
1087 get confused by overlapping addresses in the save/restore
1088 sequence. */
1089 tm_log_save_addresses.safe_push (lp->addr);
1091 else
1093 /* Use the logging functions. */
1094 lp->stmts.create (5);
1095 lp->stmts.quick_push (stmt);
1096 lp->save_var = NULL;
1099 else
1101 size_t i;
1102 gimple oldstmt;
1104 lp = *slot;
1106 /* If we're generating a save/restore sequence, we don't care
1107 about statements. */
1108 if (lp->save_var)
1109 return;
1111 for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1113 if (stmt == oldstmt)
1114 return;
1115 /* We already have a store to the same address, higher up the
1116 dominator tree. Nothing to do. */
1117 if (dominated_by_p (CDI_DOMINATORS,
1118 gimple_bb (stmt), gimple_bb (oldstmt)))
1119 return;
1120 /* We should be processing blocks in dominator tree order. */
1121 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1122 gimple_bb (oldstmt), gimple_bb (stmt)));
1124 /* Store is on a different code path. */
1125 lp->stmts.safe_push (stmt);
1129 /* Gimplify the address of a TARGET_MEM_REF. Return the SSA_NAME
1130 result, insert the new statements before GSI. */
1132 static tree
1133 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1135 if (TREE_CODE (x) == TARGET_MEM_REF)
1136 x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1137 else
1138 x = build_fold_addr_expr (x);
1139 return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1142 /* Instrument one address with the logging functions.
1143 ADDR is the address to save.
1144 STMT is the statement before which to place it. */
1145 static void
1146 tm_log_emit_stmt (tree addr, gimple stmt)
1148 tree type = TREE_TYPE (addr);
1149 tree size = TYPE_SIZE_UNIT (type);
1150 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1151 gimple log;
1152 enum built_in_function code = BUILT_IN_TM_LOG;
1154 if (type == float_type_node)
1155 code = BUILT_IN_TM_LOG_FLOAT;
1156 else if (type == double_type_node)
1157 code = BUILT_IN_TM_LOG_DOUBLE;
1158 else if (type == long_double_type_node)
1159 code = BUILT_IN_TM_LOG_LDOUBLE;
1160 else if (tree_fits_uhwi_p (size))
1162 unsigned int n = tree_to_uhwi (size);
1163 switch (n)
1165 case 1:
1166 code = BUILT_IN_TM_LOG_1;
1167 break;
1168 case 2:
1169 code = BUILT_IN_TM_LOG_2;
1170 break;
1171 case 4:
1172 code = BUILT_IN_TM_LOG_4;
1173 break;
1174 case 8:
1175 code = BUILT_IN_TM_LOG_8;
1176 break;
1177 default:
1178 code = BUILT_IN_TM_LOG;
1179 if (TREE_CODE (type) == VECTOR_TYPE)
1181 if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1182 code = BUILT_IN_TM_LOG_M64;
1183 else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1184 code = BUILT_IN_TM_LOG_M128;
1185 else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1186 code = BUILT_IN_TM_LOG_M256;
1188 break;
1192 addr = gimplify_addr (&gsi, addr);
1193 if (code == BUILT_IN_TM_LOG)
1194 log = gimple_build_call (builtin_decl_explicit (code), 2, addr, size);
1195 else
1196 log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1197 gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1200 /* Go through the log and instrument address that must be instrumented
1201 with the logging functions. Leave the save/restore addresses for
1202 later. */
1203 static void
1204 tm_log_emit (void)
1206 hash_table <log_entry_hasher>::iterator hi;
1207 struct tm_log_entry *lp;
1209 FOR_EACH_HASH_TABLE_ELEMENT (tm_log, lp, tm_log_entry_t, hi)
1211 size_t i;
1212 gimple stmt;
1214 if (dump_file)
1216 fprintf (dump_file, "TM thread private mem logging: ");
1217 print_generic_expr (dump_file, lp->addr, 0);
1218 fprintf (dump_file, "\n");
1221 if (lp->save_var)
1223 if (dump_file)
1224 fprintf (dump_file, "DUMPING to variable\n");
1225 continue;
1227 else
1229 if (dump_file)
1230 fprintf (dump_file, "DUMPING with logging functions\n");
1231 for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1232 tm_log_emit_stmt (lp->addr, stmt);
1237 /* Emit the save sequence for the corresponding addresses in the log.
1238 ENTRY_BLOCK is the entry block for the transaction.
1239 BB is the basic block to insert the code in. */
1240 static void
1241 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1243 size_t i;
1244 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1245 gimple stmt;
1246 struct tm_log_entry l, *lp;
1248 for (i = 0; i < tm_log_save_addresses.length (); ++i)
1250 l.addr = tm_log_save_addresses[i];
1251 lp = *(tm_log.find_slot (&l, NO_INSERT));
1252 gcc_assert (lp->save_var != NULL);
1254 /* We only care about variables in the current transaction. */
1255 if (lp->entry_block != entry_block)
1256 continue;
1258 stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1260 /* Make sure we can create an SSA_NAME for this type. For
1261 instance, aggregates aren't allowed, in which case the system
1262 will create a VOP for us and everything will just work. */
1263 if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1265 lp->save_var = make_ssa_name (lp->save_var, stmt);
1266 gimple_assign_set_lhs (stmt, lp->save_var);
1269 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1273 /* Emit the restore sequence for the corresponding addresses in the log.
1274 ENTRY_BLOCK is the entry block for the transaction.
1275 BB is the basic block to insert the code in. */
1276 static void
1277 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1279 int i;
1280 struct tm_log_entry l, *lp;
1281 gimple_stmt_iterator gsi;
1282 gimple stmt;
1284 for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1286 l.addr = tm_log_save_addresses[i];
1287 lp = *(tm_log.find_slot (&l, NO_INSERT));
1288 gcc_assert (lp->save_var != NULL);
1290 /* We only care about variables in the current transaction. */
1291 if (lp->entry_block != entry_block)
1292 continue;
1294 /* Restores are in LIFO order from the saves in case we have
1295 overlaps. */
1296 gsi = gsi_start_bb (bb);
1298 stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1299 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1304 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1305 struct walk_stmt_info *);
1306 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1307 struct walk_stmt_info *);
1309 /* Evaluate an address X being dereferenced and determine if it
1310 originally points to a non aliased new chunk of memory (malloc,
1311 alloca, etc).
1313 Return MEM_THREAD_LOCAL if it points to a thread-local address.
1314 Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1315 Return MEM_NON_LOCAL otherwise.
1317 ENTRY_BLOCK is the entry block to the transaction containing the
1318 dereference of X. */
1319 static enum thread_memory_type
1320 thread_private_new_memory (basic_block entry_block, tree x)
1322 gimple stmt = NULL;
1323 enum tree_code code;
1324 tm_new_mem_map_t **slot;
1325 tm_new_mem_map_t elt, *elt_p;
1326 tree val = x;
1327 enum thread_memory_type retval = mem_transaction_local;
1329 if (!entry_block
1330 || TREE_CODE (x) != SSA_NAME
1331 /* Possible uninitialized use, or a function argument. In
1332 either case, we don't care. */
1333 || SSA_NAME_IS_DEFAULT_DEF (x))
1334 return mem_non_local;
1336 /* Look in cache first. */
1337 elt.val = x;
1338 slot = tm_new_mem_hash.find_slot (&elt, INSERT);
1339 elt_p = *slot;
1340 if (elt_p)
1341 return elt_p->local_new_memory;
1343 /* Optimistically assume the memory is transaction local during
1344 processing. This catches recursion into this variable. */
1345 *slot = elt_p = XNEW (tm_new_mem_map_t);
1346 elt_p->val = val;
1347 elt_p->local_new_memory = mem_transaction_local;
1349 /* Search DEF chain to find the original definition of this address. */
1352 if (ptr_deref_may_alias_global_p (x))
1354 /* Address escapes. This is not thread-private. */
1355 retval = mem_non_local;
1356 goto new_memory_ret;
1359 stmt = SSA_NAME_DEF_STMT (x);
1361 /* If the malloc call is outside the transaction, this is
1362 thread-local. */
1363 if (retval != mem_thread_local
1364 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1365 retval = mem_thread_local;
1367 if (is_gimple_assign (stmt))
1369 code = gimple_assign_rhs_code (stmt);
1370 /* x = foo ==> foo */
1371 if (code == SSA_NAME)
1372 x = gimple_assign_rhs1 (stmt);
1373 /* x = foo + n ==> foo */
1374 else if (code == POINTER_PLUS_EXPR)
1375 x = gimple_assign_rhs1 (stmt);
1376 /* x = (cast*) foo ==> foo */
1377 else if (code == VIEW_CONVERT_EXPR || code == NOP_EXPR)
1378 x = gimple_assign_rhs1 (stmt);
1379 /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1380 else if (code == COND_EXPR)
1382 tree op1 = gimple_assign_rhs2 (stmt);
1383 tree op2 = gimple_assign_rhs3 (stmt);
1384 enum thread_memory_type mem;
1385 retval = thread_private_new_memory (entry_block, op1);
1386 if (retval == mem_non_local)
1387 goto new_memory_ret;
1388 mem = thread_private_new_memory (entry_block, op2);
1389 retval = MIN (retval, mem);
1390 goto new_memory_ret;
1392 else
1394 retval = mem_non_local;
1395 goto new_memory_ret;
1398 else
1400 if (gimple_code (stmt) == GIMPLE_PHI)
1402 unsigned int i;
1403 enum thread_memory_type mem;
1404 tree phi_result = gimple_phi_result (stmt);
1406 /* If any of the ancestors are non-local, we are sure to
1407 be non-local. Otherwise we can avoid doing anything
1408 and inherit what has already been generated. */
1409 retval = mem_max;
1410 for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1412 tree op = PHI_ARG_DEF (stmt, i);
1414 /* Exclude self-assignment. */
1415 if (phi_result == op)
1416 continue;
1418 mem = thread_private_new_memory (entry_block, op);
1419 if (mem == mem_non_local)
1421 retval = mem;
1422 goto new_memory_ret;
1424 retval = MIN (retval, mem);
1426 goto new_memory_ret;
1428 break;
1431 while (TREE_CODE (x) == SSA_NAME);
1433 if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1434 /* Thread-local or transaction-local. */
1436 else
1437 retval = mem_non_local;
1439 new_memory_ret:
1440 elt_p->local_new_memory = retval;
1441 return retval;
1444 /* Determine whether X has to be instrumented using a read
1445 or write barrier.
1447 ENTRY_BLOCK is the entry block for the region where stmt resides
1448 in. NULL if unknown.
1450 STMT is the statement in which X occurs in. It is used for thread
1451 private memory instrumentation. If no TPM instrumentation is
1452 desired, STMT should be null. */
1453 static bool
1454 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1456 tree orig = x;
1457 while (handled_component_p (x))
1458 x = TREE_OPERAND (x, 0);
1460 switch (TREE_CODE (x))
1462 case INDIRECT_REF:
1463 case MEM_REF:
1465 enum thread_memory_type ret;
1467 ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1468 if (ret == mem_non_local)
1469 return true;
1470 if (stmt && ret == mem_thread_local)
1471 /* ?? Should we pass `orig', or the INDIRECT_REF X. ?? */
1472 tm_log_add (entry_block, orig, stmt);
1474 /* Transaction-locals require nothing at all. For malloc, a
1475 transaction restart frees the memory and we reallocate.
1476 For alloca, the stack pointer gets reset by the retry and
1477 we reallocate. */
1478 return false;
1481 case TARGET_MEM_REF:
1482 if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1483 return true;
1484 x = TREE_OPERAND (TMR_BASE (x), 0);
1485 if (TREE_CODE (x) == PARM_DECL)
1486 return false;
1487 gcc_assert (TREE_CODE (x) == VAR_DECL);
1488 /* FALLTHRU */
1490 case PARM_DECL:
1491 case RESULT_DECL:
1492 case VAR_DECL:
1493 if (DECL_BY_REFERENCE (x))
1495 /* ??? This value is a pointer, but aggregate_value_p has been
1496 jigged to return true which confuses needs_to_live_in_memory.
1497 This ought to be cleaned up generically.
1499 FIXME: Verify this still happens after the next mainline
1500 merge. Testcase ie g++.dg/tm/pr47554.C.
1502 return false;
1505 if (is_global_var (x))
1506 return !TREE_READONLY (x);
1507 if (/* FIXME: This condition should actually go below in the
1508 tm_log_add() call, however is_call_clobbered() depends on
1509 aliasing info which is not available during
1510 gimplification. Since requires_barrier() gets called
1511 during lower_sequence_tm/gimplification, leave the call
1512 to needs_to_live_in_memory until we eliminate
1513 lower_sequence_tm altogether. */
1514 needs_to_live_in_memory (x))
1515 return true;
1516 else
1518 /* For local memory that doesn't escape (aka thread private
1519 memory), we can either save the value at the beginning of
1520 the transaction and restore on restart, or call a tm
1521 function to dynamically save and restore on restart
1522 (ITM_L*). */
1523 if (stmt)
1524 tm_log_add (entry_block, orig, stmt);
1525 return false;
1528 default:
1529 return false;
1533 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1534 a transaction region. */
1536 static void
1537 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1539 gimple stmt = gsi_stmt (*gsi);
1541 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1542 *state |= GTMA_HAVE_LOAD;
1543 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1544 *state |= GTMA_HAVE_STORE;
1547 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction. */
1549 static void
1550 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1552 gimple stmt = gsi_stmt (*gsi);
1553 tree fn;
1555 if (is_tm_pure_call (stmt))
1556 return;
1558 /* Check if this call is a transaction abort. */
1559 fn = gimple_call_fndecl (stmt);
1560 if (is_tm_abort (fn))
1561 *state |= GTMA_HAVE_ABORT;
1563 /* Note that something may happen. */
1564 *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1567 /* Lower a GIMPLE_TRANSACTION statement. */
1569 static void
1570 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1572 gimple g, stmt = gsi_stmt (*gsi);
1573 unsigned int *outer_state = (unsigned int *) wi->info;
1574 unsigned int this_state = 0;
1575 struct walk_stmt_info this_wi;
1577 /* First, lower the body. The scanning that we do inside gives
1578 us some idea of what we're dealing with. */
1579 memset (&this_wi, 0, sizeof (this_wi));
1580 this_wi.info = (void *) &this_state;
1581 walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1582 lower_sequence_tm, NULL, &this_wi);
1584 /* If there was absolutely nothing transaction related inside the
1585 transaction, we may elide it. Likewise if this is a nested
1586 transaction and does not contain an abort. */
1587 if (this_state == 0
1588 || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1590 if (outer_state)
1591 *outer_state |= this_state;
1593 gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1594 GSI_SAME_STMT);
1595 gimple_transaction_set_body (stmt, NULL);
1597 gsi_remove (gsi, true);
1598 wi->removed_stmt = true;
1599 return;
1602 /* Wrap the body of the transaction in a try-finally node so that
1603 the commit call is always properly called. */
1604 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1605 if (flag_exceptions)
1607 tree ptr;
1608 gimple_seq n_seq, e_seq;
1610 n_seq = gimple_seq_alloc_with_stmt (g);
1611 e_seq = NULL;
1613 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1614 1, integer_zero_node);
1615 ptr = create_tmp_var (ptr_type_node, NULL);
1616 gimple_call_set_lhs (g, ptr);
1617 gimple_seq_add_stmt (&e_seq, g);
1619 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1620 1, ptr);
1621 gimple_seq_add_stmt (&e_seq, g);
1623 g = gimple_build_eh_else (n_seq, e_seq);
1626 g = gimple_build_try (gimple_transaction_body (stmt),
1627 gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1628 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1630 gimple_transaction_set_body (stmt, NULL);
1632 /* If the transaction calls abort or if this is an outer transaction,
1633 add an "over" label afterwards. */
1634 if ((this_state & (GTMA_HAVE_ABORT))
1635 || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1637 tree label = create_artificial_label (UNKNOWN_LOCATION);
1638 gimple_transaction_set_label (stmt, label);
1639 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1642 /* Record the set of operations found for use later. */
1643 this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1644 gimple_transaction_set_subcode (stmt, this_state);
1647 /* Iterate through the statements in the sequence, lowering them all
1648 as appropriate for being in a transaction. */
1650 static tree
1651 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1652 struct walk_stmt_info *wi)
1654 unsigned int *state = (unsigned int *) wi->info;
1655 gimple stmt = gsi_stmt (*gsi);
1657 *handled_ops_p = true;
1658 switch (gimple_code (stmt))
1660 case GIMPLE_ASSIGN:
1661 /* Only memory reads/writes need to be instrumented. */
1662 if (gimple_assign_single_p (stmt))
1663 examine_assign_tm (state, gsi);
1664 break;
1666 case GIMPLE_CALL:
1667 examine_call_tm (state, gsi);
1668 break;
1670 case GIMPLE_ASM:
1671 *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1672 break;
1674 case GIMPLE_TRANSACTION:
1675 lower_transaction (gsi, wi);
1676 break;
1678 default:
1679 *handled_ops_p = !gimple_has_substatements (stmt);
1680 break;
1683 return NULL_TREE;
1686 /* Iterate through the statements in the sequence, lowering them all
1687 as appropriate for being outside of a transaction. */
1689 static tree
1690 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1691 struct walk_stmt_info * wi)
1693 gimple stmt = gsi_stmt (*gsi);
1695 if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1697 *handled_ops_p = true;
1698 lower_transaction (gsi, wi);
1700 else
1701 *handled_ops_p = !gimple_has_substatements (stmt);
1703 return NULL_TREE;
1706 /* Main entry point for flattening GIMPLE_TRANSACTION constructs. After
1707 this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1708 been moved out, and all the data required for constructing a proper
1709 CFG has been recorded. */
1711 static unsigned int
1712 execute_lower_tm (void)
1714 struct walk_stmt_info wi;
1715 gimple_seq body;
1717 /* Transactional clones aren't created until a later pass. */
1718 gcc_assert (!decl_is_tm_clone (current_function_decl));
1720 body = gimple_body (current_function_decl);
1721 memset (&wi, 0, sizeof (wi));
1722 walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1723 gimple_set_body (current_function_decl, body);
1725 return 0;
1728 namespace {
1730 const pass_data pass_data_lower_tm =
1732 GIMPLE_PASS, /* type */
1733 "tmlower", /* name */
1734 OPTGROUP_NONE, /* optinfo_flags */
1735 true, /* has_gate */
1736 true, /* has_execute */
1737 TV_TRANS_MEM, /* tv_id */
1738 PROP_gimple_lcf, /* properties_required */
1739 0, /* properties_provided */
1740 0, /* properties_destroyed */
1741 0, /* todo_flags_start */
1742 0, /* todo_flags_finish */
1745 class pass_lower_tm : public gimple_opt_pass
1747 public:
1748 pass_lower_tm (gcc::context *ctxt)
1749 : gimple_opt_pass (pass_data_lower_tm, ctxt)
1752 /* opt_pass methods: */
1753 bool gate () { return gate_tm (); }
1754 unsigned int execute () { return execute_lower_tm (); }
1756 }; // class pass_lower_tm
1758 } // anon namespace
1760 gimple_opt_pass *
1761 make_pass_lower_tm (gcc::context *ctxt)
1763 return new pass_lower_tm (ctxt);
1766 /* Collect region information for each transaction. */
1768 struct tm_region
1770 /* Link to the next unnested transaction. */
1771 struct tm_region *next;
1773 /* Link to the next inner transaction. */
1774 struct tm_region *inner;
1776 /* Link to the next outer transaction. */
1777 struct tm_region *outer;
1779 /* The GIMPLE_TRANSACTION statement beginning this transaction.
1780 After TM_MARK, this gets replaced by a call to
1781 BUILT_IN_TM_START. */
1782 gimple transaction_stmt;
1784 /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1785 BUILT_IN_TM_START, this field is true if the transaction is an
1786 outer transaction. */
1787 bool original_transaction_was_outer;
1789 /* Return value from BUILT_IN_TM_START. */
1790 tree tm_state;
1792 /* The entry block to this region. This will always be the first
1793 block of the body of the transaction. */
1794 basic_block entry_block;
1796 /* The first block after an expanded call to _ITM_beginTransaction. */
1797 basic_block restart_block;
1799 /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1800 These blocks are still a part of the region (i.e., the border is
1801 inclusive). Note that this set is only complete for paths in the CFG
1802 starting at ENTRY_BLOCK, and that there is no exit block recorded for
1803 the edge to the "over" label. */
1804 bitmap exit_blocks;
1806 /* The set of all blocks that have an TM_IRREVOCABLE call. */
1807 bitmap irr_blocks;
1810 typedef struct tm_region *tm_region_p;
1812 /* True if there are pending edge statements to be committed for the
1813 current function being scanned in the tmmark pass. */
1814 bool pending_edge_inserts_p;
1816 static struct tm_region *all_tm_regions;
1817 static bitmap_obstack tm_obstack;
1820 /* A subroutine of tm_region_init. Record the existence of the
1821 GIMPLE_TRANSACTION statement in a tree of tm_region elements. */
1823 static struct tm_region *
1824 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1826 struct tm_region *region;
1828 region = (struct tm_region *)
1829 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1831 if (outer)
1833 region->next = outer->inner;
1834 outer->inner = region;
1836 else
1838 region->next = all_tm_regions;
1839 all_tm_regions = region;
1841 region->inner = NULL;
1842 region->outer = outer;
1844 region->transaction_stmt = stmt;
1845 region->original_transaction_was_outer = false;
1846 region->tm_state = NULL;
1848 /* There are either one or two edges out of the block containing
1849 the GIMPLE_TRANSACTION, one to the actual region and one to the
1850 "over" label if the region contains an abort. The former will
1851 always be the one marked FALLTHRU. */
1852 region->entry_block = FALLTHRU_EDGE (bb)->dest;
1854 region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1855 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1857 return region;
1860 /* A subroutine of tm_region_init. Record all the exit and
1861 irrevocable blocks in BB into the region's exit_blocks and
1862 irr_blocks bitmaps. Returns the new region being scanned. */
1864 static struct tm_region *
1865 tm_region_init_1 (struct tm_region *region, basic_block bb)
1867 gimple_stmt_iterator gsi;
1868 gimple g;
1870 if (!region
1871 || (!region->irr_blocks && !region->exit_blocks))
1872 return region;
1874 /* Check to see if this is the end of a region by seeing if it
1875 contains a call to __builtin_tm_commit{,_eh}. Note that the
1876 outermost region for DECL_IS_TM_CLONE need not collect this. */
1877 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1879 g = gsi_stmt (gsi);
1880 if (gimple_code (g) == GIMPLE_CALL)
1882 tree fn = gimple_call_fndecl (g);
1883 if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1885 if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1886 || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1887 && region->exit_blocks)
1889 bitmap_set_bit (region->exit_blocks, bb->index);
1890 region = region->outer;
1891 break;
1893 if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1894 bitmap_set_bit (region->irr_blocks, bb->index);
1898 return region;
1901 /* Collect all of the transaction regions within the current function
1902 and record them in ALL_TM_REGIONS. The REGION parameter may specify
1903 an "outermost" region for use by tm clones. */
1905 static void
1906 tm_region_init (struct tm_region *region)
1908 gimple g;
1909 edge_iterator ei;
1910 edge e;
1911 basic_block bb;
1912 vec<basic_block> queue = vNULL;
1913 bitmap visited_blocks = BITMAP_ALLOC (NULL);
1914 struct tm_region *old_region;
1915 vec<tm_region_p> bb_regions = vNULL;
1917 all_tm_regions = region;
1918 bb = single_succ (ENTRY_BLOCK_PTR);
1920 /* We could store this information in bb->aux, but we may get called
1921 through get_all_tm_blocks() from another pass that may be already
1922 using bb->aux. */
1923 bb_regions.safe_grow_cleared (last_basic_block);
1925 queue.safe_push (bb);
1926 bb_regions[bb->index] = region;
1929 bb = queue.pop ();
1930 region = bb_regions[bb->index];
1931 bb_regions[bb->index] = NULL;
1933 /* Record exit and irrevocable blocks. */
1934 region = tm_region_init_1 (region, bb);
1936 /* Check for the last statement in the block beginning a new region. */
1937 g = last_stmt (bb);
1938 old_region = region;
1939 if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1940 region = tm_region_init_0 (region, bb, g);
1942 /* Process subsequent blocks. */
1943 FOR_EACH_EDGE (e, ei, bb->succs)
1944 if (!bitmap_bit_p (visited_blocks, e->dest->index))
1946 bitmap_set_bit (visited_blocks, e->dest->index);
1947 queue.safe_push (e->dest);
1949 /* If the current block started a new region, make sure that only
1950 the entry block of the new region is associated with this region.
1951 Other successors are still part of the old region. */
1952 if (old_region != region && e->dest != region->entry_block)
1953 bb_regions[e->dest->index] = old_region;
1954 else
1955 bb_regions[e->dest->index] = region;
1958 while (!queue.is_empty ());
1959 queue.release ();
1960 BITMAP_FREE (visited_blocks);
1961 bb_regions.release ();
1964 /* The "gate" function for all transactional memory expansion and optimization
1965 passes. We collect region information for each top-level transaction, and
1966 if we don't find any, we skip all of the TM passes. Each region will have
1967 all of the exit blocks recorded, and the originating statement. */
1969 static bool
1970 gate_tm_init (void)
1972 if (!flag_tm)
1973 return false;
1975 calculate_dominance_info (CDI_DOMINATORS);
1976 bitmap_obstack_initialize (&tm_obstack);
1978 /* If the function is a TM_CLONE, then the entire function is the region. */
1979 if (decl_is_tm_clone (current_function_decl))
1981 struct tm_region *region = (struct tm_region *)
1982 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1983 memset (region, 0, sizeof (*region));
1984 region->entry_block = single_succ (ENTRY_BLOCK_PTR);
1985 /* For a clone, the entire function is the region. But even if
1986 we don't need to record any exit blocks, we may need to
1987 record irrevocable blocks. */
1988 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1990 tm_region_init (region);
1992 else
1994 tm_region_init (NULL);
1996 /* If we didn't find any regions, cleanup and skip the whole tree
1997 of tm-related optimizations. */
1998 if (all_tm_regions == NULL)
2000 bitmap_obstack_release (&tm_obstack);
2001 return false;
2005 return true;
2008 namespace {
2010 const pass_data pass_data_tm_init =
2012 GIMPLE_PASS, /* type */
2013 "*tminit", /* name */
2014 OPTGROUP_NONE, /* optinfo_flags */
2015 true, /* has_gate */
2016 false, /* has_execute */
2017 TV_TRANS_MEM, /* tv_id */
2018 ( PROP_ssa | PROP_cfg ), /* properties_required */
2019 0, /* properties_provided */
2020 0, /* properties_destroyed */
2021 0, /* todo_flags_start */
2022 0, /* todo_flags_finish */
2025 class pass_tm_init : public gimple_opt_pass
2027 public:
2028 pass_tm_init (gcc::context *ctxt)
2029 : gimple_opt_pass (pass_data_tm_init, ctxt)
2032 /* opt_pass methods: */
2033 bool gate () { return gate_tm_init (); }
2035 }; // class pass_tm_init
2037 } // anon namespace
2039 gimple_opt_pass *
2040 make_pass_tm_init (gcc::context *ctxt)
2042 return new pass_tm_init (ctxt);
2045 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2046 represented by STATE. */
2048 static inline void
2049 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2051 if (region && region->transaction_stmt)
2053 flags |= gimple_transaction_subcode (region->transaction_stmt);
2054 gimple_transaction_set_subcode (region->transaction_stmt, flags);
2058 /* Construct a memory load in a transactional context. Return the
2059 gimple statement performing the load, or NULL if there is no
2060 TM_LOAD builtin of the appropriate size to do the load.
2062 LOC is the location to use for the new statement(s). */
2064 static gimple
2065 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2067 enum built_in_function code = END_BUILTINS;
2068 tree t, type = TREE_TYPE (rhs), decl;
2069 gimple gcall;
2071 if (type == float_type_node)
2072 code = BUILT_IN_TM_LOAD_FLOAT;
2073 else if (type == double_type_node)
2074 code = BUILT_IN_TM_LOAD_DOUBLE;
2075 else if (type == long_double_type_node)
2076 code = BUILT_IN_TM_LOAD_LDOUBLE;
2077 else if (TYPE_SIZE_UNIT (type) != NULL
2078 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2080 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2082 case 1:
2083 code = BUILT_IN_TM_LOAD_1;
2084 break;
2085 case 2:
2086 code = BUILT_IN_TM_LOAD_2;
2087 break;
2088 case 4:
2089 code = BUILT_IN_TM_LOAD_4;
2090 break;
2091 case 8:
2092 code = BUILT_IN_TM_LOAD_8;
2093 break;
2097 if (code == END_BUILTINS)
2099 decl = targetm.vectorize.builtin_tm_load (type);
2100 if (!decl)
2101 return NULL;
2103 else
2104 decl = builtin_decl_explicit (code);
2106 t = gimplify_addr (gsi, rhs);
2107 gcall = gimple_build_call (decl, 1, t);
2108 gimple_set_location (gcall, loc);
2110 t = TREE_TYPE (TREE_TYPE (decl));
2111 if (useless_type_conversion_p (type, t))
2113 gimple_call_set_lhs (gcall, lhs);
2114 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2116 else
2118 gimple g;
2119 tree temp;
2121 temp = create_tmp_reg (t, NULL);
2122 gimple_call_set_lhs (gcall, temp);
2123 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2125 t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2126 g = gimple_build_assign (lhs, t);
2127 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2130 return gcall;
2134 /* Similarly for storing TYPE in a transactional context. */
2136 static gimple
2137 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2139 enum built_in_function code = END_BUILTINS;
2140 tree t, fn, type = TREE_TYPE (rhs), simple_type;
2141 gimple gcall;
2143 if (type == float_type_node)
2144 code = BUILT_IN_TM_STORE_FLOAT;
2145 else if (type == double_type_node)
2146 code = BUILT_IN_TM_STORE_DOUBLE;
2147 else if (type == long_double_type_node)
2148 code = BUILT_IN_TM_STORE_LDOUBLE;
2149 else if (TYPE_SIZE_UNIT (type) != NULL
2150 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2152 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2154 case 1:
2155 code = BUILT_IN_TM_STORE_1;
2156 break;
2157 case 2:
2158 code = BUILT_IN_TM_STORE_2;
2159 break;
2160 case 4:
2161 code = BUILT_IN_TM_STORE_4;
2162 break;
2163 case 8:
2164 code = BUILT_IN_TM_STORE_8;
2165 break;
2169 if (code == END_BUILTINS)
2171 fn = targetm.vectorize.builtin_tm_store (type);
2172 if (!fn)
2173 return NULL;
2175 else
2176 fn = builtin_decl_explicit (code);
2178 simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2180 if (TREE_CODE (rhs) == CONSTRUCTOR)
2182 /* Handle the easy initialization to zero. */
2183 if (!CONSTRUCTOR_ELTS (rhs))
2184 rhs = build_int_cst (simple_type, 0);
2185 else
2187 /* ...otherwise punt to the caller and probably use
2188 BUILT_IN_TM_MEMMOVE, because we can't wrap a
2189 VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2190 valid gimple. */
2191 return NULL;
2194 else if (!useless_type_conversion_p (simple_type, type))
2196 gimple g;
2197 tree temp;
2199 temp = create_tmp_reg (simple_type, NULL);
2200 t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2201 g = gimple_build_assign (temp, t);
2202 gimple_set_location (g, loc);
2203 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2205 rhs = temp;
2208 t = gimplify_addr (gsi, lhs);
2209 gcall = gimple_build_call (fn, 2, t, rhs);
2210 gimple_set_location (gcall, loc);
2211 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2213 return gcall;
2217 /* Expand an assignment statement into transactional builtins. */
2219 static void
2220 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2222 gimple stmt = gsi_stmt (*gsi);
2223 location_t loc = gimple_location (stmt);
2224 tree lhs = gimple_assign_lhs (stmt);
2225 tree rhs = gimple_assign_rhs1 (stmt);
2226 bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2227 bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2228 gimple gcall = NULL;
2230 if (!load_p && !store_p)
2232 /* Add thread private addresses to log if applicable. */
2233 requires_barrier (region->entry_block, lhs, stmt);
2234 gsi_next (gsi);
2235 return;
2238 // Remove original load/store statement.
2239 gsi_remove (gsi, true);
2241 if (load_p && !store_p)
2243 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2244 gcall = build_tm_load (loc, lhs, rhs, gsi);
2246 else if (store_p && !load_p)
2248 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2249 gcall = build_tm_store (loc, lhs, rhs, gsi);
2251 if (!gcall)
2253 tree lhs_addr, rhs_addr, tmp;
2255 if (load_p)
2256 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2257 if (store_p)
2258 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2260 /* ??? Figure out if there's any possible overlap between the LHS
2261 and the RHS and if not, use MEMCPY. */
2263 if (load_p && is_gimple_reg (lhs))
2265 tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2266 lhs_addr = build_fold_addr_expr (tmp);
2268 else
2270 tmp = NULL_TREE;
2271 lhs_addr = gimplify_addr (gsi, lhs);
2273 rhs_addr = gimplify_addr (gsi, rhs);
2274 gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2275 3, lhs_addr, rhs_addr,
2276 TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2277 gimple_set_location (gcall, loc);
2278 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2280 if (tmp)
2282 gcall = gimple_build_assign (lhs, tmp);
2283 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2287 /* Now that we have the load/store in its instrumented form, add
2288 thread private addresses to the log if applicable. */
2289 if (!store_p)
2290 requires_barrier (region->entry_block, lhs, gcall);
2292 // The calls to build_tm_{store,load} above inserted the instrumented
2293 // call into the stream.
2294 // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2298 /* Expand a call statement as appropriate for a transaction. That is,
2299 either verify that the call does not affect the transaction, or
2300 redirect the call to a clone that handles transactions, or change
2301 the transaction state to IRREVOCABLE. Return true if the call is
2302 one of the builtins that end a transaction. */
2304 static bool
2305 expand_call_tm (struct tm_region *region,
2306 gimple_stmt_iterator *gsi)
2308 gimple stmt = gsi_stmt (*gsi);
2309 tree lhs = gimple_call_lhs (stmt);
2310 tree fn_decl;
2311 struct cgraph_node *node;
2312 bool retval = false;
2314 fn_decl = gimple_call_fndecl (stmt);
2316 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2317 || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2318 transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2319 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2320 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2322 if (is_tm_pure_call (stmt))
2323 return false;
2325 if (fn_decl)
2326 retval = is_tm_ending_fndecl (fn_decl);
2327 if (!retval)
2329 /* Assume all non-const/pure calls write to memory, except
2330 transaction ending builtins. */
2331 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2334 /* For indirect calls, we already generated a call into the runtime. */
2335 if (!fn_decl)
2337 tree fn = gimple_call_fn (stmt);
2339 /* We are guaranteed never to go irrevocable on a safe or pure
2340 call, and the pure call was handled above. */
2341 if (is_tm_safe (fn))
2342 return false;
2343 else
2344 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2346 return false;
2349 node = cgraph_get_node (fn_decl);
2350 /* All calls should have cgraph here. */
2351 if (!node)
2353 /* We can have a nodeless call here if some pass after IPA-tm
2354 added uninstrumented calls. For example, loop distribution
2355 can transform certain loop constructs into __builtin_mem*
2356 calls. In this case, see if we have a suitable TM
2357 replacement and fill in the gaps. */
2358 gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2359 enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2360 gcc_assert (code == BUILT_IN_MEMCPY
2361 || code == BUILT_IN_MEMMOVE
2362 || code == BUILT_IN_MEMSET);
2364 tree repl = find_tm_replacement_function (fn_decl);
2365 if (repl)
2367 gimple_call_set_fndecl (stmt, repl);
2368 update_stmt (stmt);
2369 node = cgraph_create_node (repl);
2370 node->local.tm_may_enter_irr = false;
2371 return expand_call_tm (region, gsi);
2373 gcc_unreachable ();
2375 if (node->local.tm_may_enter_irr)
2376 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2378 if (is_tm_abort (fn_decl))
2380 transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2381 return true;
2384 /* Instrument the store if needed.
2386 If the assignment happens inside the function call (return slot
2387 optimization), there is no instrumentation to be done, since
2388 the callee should have done the right thing. */
2389 if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2390 && !gimple_call_return_slot_opt_p (stmt))
2392 tree tmp = create_tmp_reg (TREE_TYPE (lhs), NULL);
2393 location_t loc = gimple_location (stmt);
2394 edge fallthru_edge = NULL;
2396 /* Remember if the call was going to throw. */
2397 if (stmt_can_throw_internal (stmt))
2399 edge_iterator ei;
2400 edge e;
2401 basic_block bb = gimple_bb (stmt);
2403 FOR_EACH_EDGE (e, ei, bb->succs)
2404 if (e->flags & EDGE_FALLTHRU)
2406 fallthru_edge = e;
2407 break;
2411 gimple_call_set_lhs (stmt, tmp);
2412 update_stmt (stmt);
2413 stmt = gimple_build_assign (lhs, tmp);
2414 gimple_set_location (stmt, loc);
2416 /* We cannot throw in the middle of a BB. If the call was going
2417 to throw, place the instrumentation on the fallthru edge, so
2418 the call remains the last statement in the block. */
2419 if (fallthru_edge)
2421 gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2422 gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2423 expand_assign_tm (region, &fallthru_gsi);
2424 gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2425 pending_edge_inserts_p = true;
2427 else
2429 gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2430 expand_assign_tm (region, gsi);
2433 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2436 return retval;
2440 /* Expand all statements in BB as appropriate for being inside
2441 a transaction. */
2443 static void
2444 expand_block_tm (struct tm_region *region, basic_block bb)
2446 gimple_stmt_iterator gsi;
2448 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2450 gimple stmt = gsi_stmt (gsi);
2451 switch (gimple_code (stmt))
2453 case GIMPLE_ASSIGN:
2454 /* Only memory reads/writes need to be instrumented. */
2455 if (gimple_assign_single_p (stmt)
2456 && !gimple_clobber_p (stmt))
2458 expand_assign_tm (region, &gsi);
2459 continue;
2461 break;
2463 case GIMPLE_CALL:
2464 if (expand_call_tm (region, &gsi))
2465 return;
2466 break;
2468 case GIMPLE_ASM:
2469 gcc_unreachable ();
2471 default:
2472 break;
2474 if (!gsi_end_p (gsi))
2475 gsi_next (&gsi);
2479 /* Return the list of basic-blocks in REGION.
2481 STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2482 following a TM_IRREVOCABLE call.
2484 INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2485 uninstrumented code path blocks in the list of basic blocks
2486 returned, false otherwise. */
2488 static vec<basic_block>
2489 get_tm_region_blocks (basic_block entry_block,
2490 bitmap exit_blocks,
2491 bitmap irr_blocks,
2492 bitmap all_region_blocks,
2493 bool stop_at_irrevocable_p,
2494 bool include_uninstrumented_p = true)
2496 vec<basic_block> bbs = vNULL;
2497 unsigned i;
2498 edge e;
2499 edge_iterator ei;
2500 bitmap visited_blocks = BITMAP_ALLOC (NULL);
2502 i = 0;
2503 bbs.safe_push (entry_block);
2504 bitmap_set_bit (visited_blocks, entry_block->index);
2508 basic_block bb = bbs[i++];
2510 if (exit_blocks &&
2511 bitmap_bit_p (exit_blocks, bb->index))
2512 continue;
2514 if (stop_at_irrevocable_p
2515 && irr_blocks
2516 && bitmap_bit_p (irr_blocks, bb->index))
2517 continue;
2519 FOR_EACH_EDGE (e, ei, bb->succs)
2520 if ((include_uninstrumented_p
2521 || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2522 && !bitmap_bit_p (visited_blocks, e->dest->index))
2524 bitmap_set_bit (visited_blocks, e->dest->index);
2525 bbs.safe_push (e->dest);
2528 while (i < bbs.length ());
2530 if (all_region_blocks)
2531 bitmap_ior_into (all_region_blocks, visited_blocks);
2533 BITMAP_FREE (visited_blocks);
2534 return bbs;
2537 // Callback data for collect_bb2reg.
2538 struct bb2reg_stuff
2540 vec<tm_region_p> *bb2reg;
2541 bool include_uninstrumented_p;
2544 // Callback for expand_regions, collect innermost region data for each bb.
2545 static void *
2546 collect_bb2reg (struct tm_region *region, void *data)
2548 struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2549 vec<tm_region_p> *bb2reg = stuff->bb2reg;
2550 vec<basic_block> queue;
2551 unsigned int i;
2552 basic_block bb;
2554 queue = get_tm_region_blocks (region->entry_block,
2555 region->exit_blocks,
2556 region->irr_blocks,
2557 NULL,
2558 /*stop_at_irr_p=*/true,
2559 stuff->include_uninstrumented_p);
2561 // We expect expand_region to perform a post-order traversal of the region
2562 // tree. Therefore the last region seen for any bb is the innermost.
2563 FOR_EACH_VEC_ELT (queue, i, bb)
2564 (*bb2reg)[bb->index] = region;
2566 queue.release ();
2567 return NULL;
2570 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2571 // which a basic block belongs. Note that we only consider the instrumented
2572 // code paths for the region; the uninstrumented code paths are ignored if
2573 // INCLUDE_UNINSTRUMENTED_P is false.
2575 // ??? This data is very similar to the bb_regions array that is collected
2576 // during tm_region_init. Or, rather, this data is similar to what could
2577 // be used within tm_region_init. The actual computation in tm_region_init
2578 // begins and ends with bb_regions entirely full of NULL pointers, due to
2579 // the way in which pointers are swapped in and out of the array.
2581 // ??? Our callers expect that blocks are not shared between transactions.
2582 // When the optimizers get too smart, and blocks are shared, then during
2583 // the tm_mark phase we'll add log entries to only one of the two transactions,
2584 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2585 // cycles. The symptom being SSA defs that do not dominate their uses.
2586 // Note that the optimizers were locally correct with their transformation,
2587 // as we have no info within the program that suggests that the blocks cannot
2588 // be shared.
2590 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2591 // only known instance of this block sharing.
2593 static vec<tm_region_p>
2594 get_bb_regions_instrumented (bool traverse_clones,
2595 bool include_uninstrumented_p)
2597 unsigned n = last_basic_block;
2598 struct bb2reg_stuff stuff;
2599 vec<tm_region_p> ret;
2601 ret.create (n);
2602 ret.safe_grow_cleared (n);
2603 stuff.bb2reg = &ret;
2604 stuff.include_uninstrumented_p = include_uninstrumented_p;
2605 expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2607 return ret;
2610 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2611 transaction. */
2613 void
2614 compute_transaction_bits (void)
2616 struct tm_region *region;
2617 vec<basic_block> queue;
2618 unsigned int i;
2619 basic_block bb;
2621 /* ?? Perhaps we need to abstract gate_tm_init further, because we
2622 certainly don't need it to calculate CDI_DOMINATOR info. */
2623 gate_tm_init ();
2625 FOR_EACH_BB (bb)
2626 bb->flags &= ~BB_IN_TRANSACTION;
2628 for (region = all_tm_regions; region; region = region->next)
2630 queue = get_tm_region_blocks (region->entry_block,
2631 region->exit_blocks,
2632 region->irr_blocks,
2633 NULL,
2634 /*stop_at_irr_p=*/true);
2635 for (i = 0; queue.iterate (i, &bb); ++i)
2636 bb->flags |= BB_IN_TRANSACTION;
2637 queue.release ();
2640 if (all_tm_regions)
2641 bitmap_obstack_release (&tm_obstack);
2644 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2645 call to BUILT_IN_TM_START. */
2647 static void *
2648 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2650 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2651 basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2652 tree tm_state = region->tm_state;
2653 tree tm_state_type = TREE_TYPE (tm_state);
2654 edge abort_edge = NULL;
2655 edge inst_edge = NULL;
2656 edge uninst_edge = NULL;
2657 edge fallthru_edge = NULL;
2659 // Identify the various successors of the transaction start.
2661 edge_iterator i;
2662 edge e;
2663 FOR_EACH_EDGE (e, i, transaction_bb->succs)
2665 if (e->flags & EDGE_TM_ABORT)
2666 abort_edge = e;
2667 else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2668 uninst_edge = e;
2669 else
2670 inst_edge = e;
2671 if (e->flags & EDGE_FALLTHRU)
2672 fallthru_edge = e;
2676 /* ??? There are plenty of bits here we're not computing. */
2678 int subcode = gimple_transaction_subcode (region->transaction_stmt);
2679 int flags = 0;
2680 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2681 flags |= PR_DOESGOIRREVOCABLE;
2682 if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2683 flags |= PR_HASNOIRREVOCABLE;
2684 /* If the transaction does not have an abort in lexical scope and is not
2685 marked as an outer transaction, then it will never abort. */
2686 if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2687 flags |= PR_HASNOABORT;
2688 if ((subcode & GTMA_HAVE_STORE) == 0)
2689 flags |= PR_READONLY;
2690 if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2691 flags |= PR_INSTRUMENTEDCODE;
2692 if (uninst_edge)
2693 flags |= PR_UNINSTRUMENTEDCODE;
2694 if (subcode & GTMA_IS_OUTER)
2695 region->original_transaction_was_outer = true;
2696 tree t = build_int_cst (tm_state_type, flags);
2697 gimple call = gimple_build_call (tm_start, 1, t);
2698 gimple_call_set_lhs (call, tm_state);
2699 gimple_set_location (call, gimple_location (region->transaction_stmt));
2701 // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2702 gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2703 gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2704 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2705 gsi_remove (&gsi, true);
2706 region->transaction_stmt = call;
2709 // Generate log saves.
2710 if (!tm_log_save_addresses.is_empty ())
2711 tm_log_emit_saves (region->entry_block, transaction_bb);
2713 // In the beginning, we've no tests to perform on transaction restart.
2714 // Note that after this point, transaction_bb becomes the "most recent
2715 // block containing tests for the transaction".
2716 region->restart_block = region->entry_block;
2718 // Generate log restores.
2719 if (!tm_log_save_addresses.is_empty ())
2721 basic_block test_bb = create_empty_bb (transaction_bb);
2722 basic_block code_bb = create_empty_bb (test_bb);
2723 basic_block join_bb = create_empty_bb (code_bb);
2724 if (current_loops && transaction_bb->loop_father)
2726 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2727 add_bb_to_loop (code_bb, transaction_bb->loop_father);
2728 add_bb_to_loop (join_bb, transaction_bb->loop_father);
2730 if (region->restart_block == region->entry_block)
2731 region->restart_block = test_bb;
2733 tree t1 = create_tmp_reg (tm_state_type, NULL);
2734 tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2735 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2736 tm_state, t2);
2737 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2738 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2740 t2 = build_int_cst (tm_state_type, 0);
2741 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2742 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2744 tm_log_emit_restores (region->entry_block, code_bb);
2746 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2747 edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2748 edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2749 redirect_edge_pred (fallthru_edge, join_bb);
2751 join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2752 join_bb->count = test_bb->count = transaction_bb->count;
2754 ei->probability = PROB_ALWAYS;
2755 et->probability = PROB_LIKELY;
2756 ef->probability = PROB_UNLIKELY;
2757 et->count = apply_probability (test_bb->count, et->probability);
2758 ef->count = apply_probability (test_bb->count, ef->probability);
2760 code_bb->count = et->count;
2761 code_bb->frequency = EDGE_FREQUENCY (et);
2763 transaction_bb = join_bb;
2766 // If we have an ABORT edge, create a test to perform the abort.
2767 if (abort_edge)
2769 basic_block test_bb = create_empty_bb (transaction_bb);
2770 if (current_loops && transaction_bb->loop_father)
2771 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2772 if (region->restart_block == region->entry_block)
2773 region->restart_block = test_bb;
2775 tree t1 = create_tmp_reg (tm_state_type, NULL);
2776 tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2777 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2778 tm_state, t2);
2779 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2780 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2782 t2 = build_int_cst (tm_state_type, 0);
2783 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2784 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2786 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2787 test_bb->frequency = transaction_bb->frequency;
2788 test_bb->count = transaction_bb->count;
2789 ei->probability = PROB_ALWAYS;
2791 // Not abort edge. If both are live, chose one at random as we'll
2792 // we'll be fixing that up below.
2793 redirect_edge_pred (fallthru_edge, test_bb);
2794 fallthru_edge->flags = EDGE_FALSE_VALUE;
2795 fallthru_edge->probability = PROB_VERY_LIKELY;
2796 fallthru_edge->count
2797 = apply_probability (test_bb->count, fallthru_edge->probability);
2799 // Abort/over edge.
2800 redirect_edge_pred (abort_edge, test_bb);
2801 abort_edge->flags = EDGE_TRUE_VALUE;
2802 abort_edge->probability = PROB_VERY_UNLIKELY;
2803 abort_edge->count
2804 = apply_probability (test_bb->count, abort_edge->probability);
2806 transaction_bb = test_bb;
2809 // If we have both instrumented and uninstrumented code paths, select one.
2810 if (inst_edge && uninst_edge)
2812 basic_block test_bb = create_empty_bb (transaction_bb);
2813 if (current_loops && transaction_bb->loop_father)
2814 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2815 if (region->restart_block == region->entry_block)
2816 region->restart_block = test_bb;
2818 tree t1 = create_tmp_reg (tm_state_type, NULL);
2819 tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2821 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2822 tm_state, t2);
2823 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2824 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2826 t2 = build_int_cst (tm_state_type, 0);
2827 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2828 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2830 // Create the edge into test_bb first, as we want to copy values
2831 // out of the fallthru edge.
2832 edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2833 e->probability = fallthru_edge->probability;
2834 test_bb->count = e->count = fallthru_edge->count;
2835 test_bb->frequency = EDGE_FREQUENCY (e);
2837 // Now update the edges to the inst/uninist implementations.
2838 // For now assume that the paths are equally likely. When using HTM,
2839 // we'll try the uninst path first and fallback to inst path if htm
2840 // buffers are exceeded. Without HTM we start with the inst path and
2841 // use the uninst path when falling back to serial mode.
2842 redirect_edge_pred (inst_edge, test_bb);
2843 inst_edge->flags = EDGE_FALSE_VALUE;
2844 inst_edge->probability = REG_BR_PROB_BASE / 2;
2845 inst_edge->count
2846 = apply_probability (test_bb->count, inst_edge->probability);
2848 redirect_edge_pred (uninst_edge, test_bb);
2849 uninst_edge->flags = EDGE_TRUE_VALUE;
2850 uninst_edge->probability = REG_BR_PROB_BASE / 2;
2851 uninst_edge->count
2852 = apply_probability (test_bb->count, uninst_edge->probability);
2855 // If we have no previous special cases, and we have PHIs at the beginning
2856 // of the atomic region, this means we have a loop at the beginning of the
2857 // atomic region that shares the first block. This can cause problems with
2858 // the transaction restart abnormal edges to be added in the tm_edges pass.
2859 // Solve this by adding a new empty block to receive the abnormal edges.
2860 if (region->restart_block == region->entry_block
2861 && phi_nodes (region->entry_block))
2863 basic_block empty_bb = create_empty_bb (transaction_bb);
2864 region->restart_block = empty_bb;
2865 if (current_loops && transaction_bb->loop_father)
2866 add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2868 redirect_edge_pred (fallthru_edge, empty_bb);
2869 make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2872 return NULL;
2875 /* Generate the temporary to be used for the return value of
2876 BUILT_IN_TM_START. */
2878 static void *
2879 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2881 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2882 region->tm_state =
2883 create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2885 // Reset the subcode, post optimizations. We'll fill this in
2886 // again as we process blocks.
2887 if (region->exit_blocks)
2889 unsigned int subcode
2890 = gimple_transaction_subcode (region->transaction_stmt);
2892 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2893 subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2894 | GTMA_MAY_ENTER_IRREVOCABLE
2895 | GTMA_HAS_NO_INSTRUMENTATION);
2896 else
2897 subcode &= GTMA_DECLARATION_MASK;
2898 gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2901 return NULL;
2904 // Propagate flags from inner transactions outwards.
2905 static void
2906 propagate_tm_flags_out (struct tm_region *region)
2908 if (region == NULL)
2909 return;
2910 propagate_tm_flags_out (region->inner);
2912 if (region->outer && region->outer->transaction_stmt)
2914 unsigned s = gimple_transaction_subcode (region->transaction_stmt);
2915 s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2916 | GTMA_MAY_ENTER_IRREVOCABLE);
2917 s |= gimple_transaction_subcode (region->outer->transaction_stmt);
2918 gimple_transaction_set_subcode (region->outer->transaction_stmt, s);
2921 propagate_tm_flags_out (region->next);
2924 /* Entry point to the MARK phase of TM expansion. Here we replace
2925 transactional memory statements with calls to builtins, and function
2926 calls with their transactional clones (if available). But we don't
2927 yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges. */
2929 static unsigned int
2930 execute_tm_mark (void)
2932 pending_edge_inserts_p = false;
2934 expand_regions (all_tm_regions, generate_tm_state, NULL,
2935 /*traverse_clones=*/true);
2937 tm_log_init ();
2939 vec<tm_region_p> bb_regions
2940 = get_bb_regions_instrumented (/*traverse_clones=*/true,
2941 /*include_uninstrumented_p=*/false);
2942 struct tm_region *r;
2943 unsigned i;
2945 // Expand memory operations into calls into the runtime.
2946 // This collects log entries as well.
2947 FOR_EACH_VEC_ELT (bb_regions, i, r)
2949 if (r != NULL)
2951 if (r->transaction_stmt)
2953 unsigned sub = gimple_transaction_subcode (r->transaction_stmt);
2955 /* If we're sure to go irrevocable, there won't be
2956 anything to expand, since the run-time will go
2957 irrevocable right away. */
2958 if (sub & GTMA_DOES_GO_IRREVOCABLE
2959 && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2960 continue;
2962 expand_block_tm (r, BASIC_BLOCK (i));
2966 bb_regions.release ();
2968 // Propagate flags from inner transactions outwards.
2969 propagate_tm_flags_out (all_tm_regions);
2971 // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
2972 expand_regions (all_tm_regions, expand_transaction, NULL,
2973 /*traverse_clones=*/false);
2975 tm_log_emit ();
2976 tm_log_delete ();
2978 if (pending_edge_inserts_p)
2979 gsi_commit_edge_inserts ();
2980 free_dominance_info (CDI_DOMINATORS);
2981 return 0;
2984 namespace {
2986 const pass_data pass_data_tm_mark =
2988 GIMPLE_PASS, /* type */
2989 "tmmark", /* name */
2990 OPTGROUP_NONE, /* optinfo_flags */
2991 false, /* has_gate */
2992 true, /* has_execute */
2993 TV_TRANS_MEM, /* tv_id */
2994 ( PROP_ssa | PROP_cfg ), /* properties_required */
2995 0, /* properties_provided */
2996 0, /* properties_destroyed */
2997 0, /* todo_flags_start */
2998 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3001 class pass_tm_mark : public gimple_opt_pass
3003 public:
3004 pass_tm_mark (gcc::context *ctxt)
3005 : gimple_opt_pass (pass_data_tm_mark, ctxt)
3008 /* opt_pass methods: */
3009 unsigned int execute () { return execute_tm_mark (); }
3011 }; // class pass_tm_mark
3013 } // anon namespace
3015 gimple_opt_pass *
3016 make_pass_tm_mark (gcc::context *ctxt)
3018 return new pass_tm_mark (ctxt);
3022 /* Create an abnormal edge from STMT at iter, splitting the block
3023 as necessary. Adjust *PNEXT as needed for the split block. */
3025 static inline void
3026 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3027 gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3029 basic_block bb = gimple_bb (stmt);
3030 if (!gsi_one_before_end_p (iter))
3032 edge e = split_block (bb, stmt);
3033 *pnext = gsi_start_bb (e->dest);
3035 make_edge (bb, dest_bb, EDGE_ABNORMAL);
3037 // Record the need for the edge for the benefit of the rtl passes.
3038 if (cfun->gimple_df->tm_restart == NULL)
3039 cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
3040 struct_ptr_eq, ggc_free);
3042 struct tm_restart_node dummy;
3043 dummy.stmt = stmt;
3044 dummy.label_or_list = gimple_block_label (dest_bb);
3046 void **slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
3047 struct tm_restart_node *n = (struct tm_restart_node *) *slot;
3048 if (n == NULL)
3050 n = ggc_alloc_tm_restart_node ();
3051 *n = dummy;
3053 else
3055 tree old = n->label_or_list;
3056 if (TREE_CODE (old) == LABEL_DECL)
3057 old = tree_cons (NULL, old, NULL);
3058 n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3062 /* Split block BB as necessary for every builtin function we added, and
3063 wire up the abnormal back edges implied by the transaction restart. */
3065 static void
3066 expand_block_edges (struct tm_region *const region, basic_block bb)
3068 gimple_stmt_iterator gsi, next_gsi;
3070 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3072 gimple stmt = gsi_stmt (gsi);
3074 next_gsi = gsi;
3075 gsi_next (&next_gsi);
3077 // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3078 if (gimple_code (stmt) != GIMPLE_CALL
3079 || (gimple_call_flags (stmt) & ECF_TM_BUILTIN) == 0)
3080 continue;
3082 if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_TM_ABORT)
3084 // If we have a ``_transaction_cancel [[outer]]'', there is only
3085 // one abnormal edge: to the transaction marked OUTER.
3086 // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3087 // constant argument, which we can examine here. Users invoking
3088 // TM_ABORT directly get what they deserve.
3089 tree arg = gimple_call_arg (stmt, 0);
3090 if (TREE_CODE (arg) == INTEGER_CST
3091 && (tree_to_hwi (arg) & AR_OUTERABORT) != 0
3092 && !decl_is_tm_clone (current_function_decl))
3094 // Find the GTMA_IS_OUTER transaction.
3095 for (struct tm_region *o = region; o; o = o->outer)
3096 if (o->original_transaction_was_outer)
3098 split_bb_make_tm_edge (stmt, o->restart_block,
3099 gsi, &next_gsi);
3100 break;
3103 // Otherwise, the front-end should have semantically checked
3104 // outer aborts, but in either case the target region is not
3105 // within this function.
3106 continue;
3109 // Non-outer, TM aborts have an abnormal edge to the inner-most
3110 // transaction, the one being aborted;
3111 split_bb_make_tm_edge (stmt, region->restart_block, gsi, &next_gsi);
3114 // All TM builtins have an abnormal edge to the outer-most transaction.
3115 // We never restart inner transactions. For tm clones, we know a-priori
3116 // that the outer-most transaction is outside the function.
3117 if (decl_is_tm_clone (current_function_decl))
3118 continue;
3120 if (cfun->gimple_df->tm_restart == NULL)
3121 cfun->gimple_df->tm_restart
3122 = htab_create_ggc (31, struct_ptr_hash, struct_ptr_eq, ggc_free);
3124 // All TM builtins have an abnormal edge to the outer-most transaction.
3125 // We never restart inner transactions.
3126 for (struct tm_region *o = region; o; o = o->outer)
3127 if (!o->outer)
3129 split_bb_make_tm_edge (stmt, o->restart_block, gsi, &next_gsi);
3130 break;
3133 // Delete any tail-call annotation that may have been added.
3134 // The tail-call pass may have mis-identified the commit as being
3135 // a candidate because we had not yet added this restart edge.
3136 gimple_call_set_tail (stmt, false);
3140 /* Entry point to the final expansion of transactional nodes. */
3142 static unsigned int
3143 execute_tm_edges (void)
3145 vec<tm_region_p> bb_regions
3146 = get_bb_regions_instrumented (/*traverse_clones=*/false,
3147 /*include_uninstrumented_p=*/true);
3148 struct tm_region *r;
3149 unsigned i;
3151 FOR_EACH_VEC_ELT (bb_regions, i, r)
3152 if (r != NULL)
3153 expand_block_edges (r, BASIC_BLOCK (i));
3155 bb_regions.release ();
3157 /* We've got to release the dominance info now, to indicate that it
3158 must be rebuilt completely. Otherwise we'll crash trying to update
3159 the SSA web in the TODO section following this pass. */
3160 free_dominance_info (CDI_DOMINATORS);
3161 bitmap_obstack_release (&tm_obstack);
3162 all_tm_regions = NULL;
3164 return 0;
3167 namespace {
3169 const pass_data pass_data_tm_edges =
3171 GIMPLE_PASS, /* type */
3172 "tmedge", /* name */
3173 OPTGROUP_NONE, /* optinfo_flags */
3174 false, /* has_gate */
3175 true, /* has_execute */
3176 TV_TRANS_MEM, /* tv_id */
3177 ( PROP_ssa | PROP_cfg ), /* properties_required */
3178 0, /* properties_provided */
3179 0, /* properties_destroyed */
3180 0, /* todo_flags_start */
3181 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3184 class pass_tm_edges : public gimple_opt_pass
3186 public:
3187 pass_tm_edges (gcc::context *ctxt)
3188 : gimple_opt_pass (pass_data_tm_edges, ctxt)
3191 /* opt_pass methods: */
3192 unsigned int execute () { return execute_tm_edges (); }
3194 }; // class pass_tm_edges
3196 } // anon namespace
3198 gimple_opt_pass *
3199 make_pass_tm_edges (gcc::context *ctxt)
3201 return new pass_tm_edges (ctxt);
3204 /* Helper function for expand_regions. Expand REGION and recurse to
3205 the inner region. Call CALLBACK on each region. CALLBACK returns
3206 NULL to continue the traversal, otherwise a non-null value which
3207 this function will return as well. TRAVERSE_CLONES is true if we
3208 should traverse transactional clones. */
3210 static void *
3211 expand_regions_1 (struct tm_region *region,
3212 void *(*callback)(struct tm_region *, void *),
3213 void *data,
3214 bool traverse_clones)
3216 void *retval = NULL;
3217 if (region->exit_blocks
3218 || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3220 retval = callback (region, data);
3221 if (retval)
3222 return retval;
3224 if (region->inner)
3226 retval = expand_regions (region->inner, callback, data, traverse_clones);
3227 if (retval)
3228 return retval;
3230 return retval;
3233 /* Traverse the regions enclosed and including REGION. Execute
3234 CALLBACK for each region, passing DATA. CALLBACK returns NULL to
3235 continue the traversal, otherwise a non-null value which this
3236 function will return as well. TRAVERSE_CLONES is true if we should
3237 traverse transactional clones. */
3239 static void *
3240 expand_regions (struct tm_region *region,
3241 void *(*callback)(struct tm_region *, void *),
3242 void *data,
3243 bool traverse_clones)
3245 void *retval = NULL;
3246 while (region)
3248 retval = expand_regions_1 (region, callback, data, traverse_clones);
3249 if (retval)
3250 return retval;
3251 region = region->next;
3253 return retval;
3257 /* A unique TM memory operation. */
3258 typedef struct tm_memop
3260 /* Unique ID that all memory operations to the same location have. */
3261 unsigned int value_id;
3262 /* Address of load/store. */
3263 tree addr;
3264 } *tm_memop_t;
3266 /* TM memory operation hashtable helpers. */
3268 struct tm_memop_hasher : typed_free_remove <tm_memop>
3270 typedef tm_memop value_type;
3271 typedef tm_memop compare_type;
3272 static inline hashval_t hash (const value_type *);
3273 static inline bool equal (const value_type *, const compare_type *);
3276 /* Htab support. Return a hash value for a `tm_memop'. */
3277 inline hashval_t
3278 tm_memop_hasher::hash (const value_type *mem)
3280 tree addr = mem->addr;
3281 /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3282 actually done with operand_equal_p (see tm_memop_eq). */
3283 if (TREE_CODE (addr) == ADDR_EXPR)
3284 addr = TREE_OPERAND (addr, 0);
3285 return iterative_hash_expr (addr, 0);
3288 /* Htab support. Return true if two tm_memop's are the same. */
3289 inline bool
3290 tm_memop_hasher::equal (const value_type *mem1, const compare_type *mem2)
3292 return operand_equal_p (mem1->addr, mem2->addr, 0);
3295 /* Sets for solving data flow equations in the memory optimization pass. */
3296 struct tm_memopt_bitmaps
3298 /* Stores available to this BB upon entry. Basically, stores that
3299 dominate this BB. */
3300 bitmap store_avail_in;
3301 /* Stores available at the end of this BB. */
3302 bitmap store_avail_out;
3303 bitmap store_antic_in;
3304 bitmap store_antic_out;
3305 /* Reads available to this BB upon entry. Basically, reads that
3306 dominate this BB. */
3307 bitmap read_avail_in;
3308 /* Reads available at the end of this BB. */
3309 bitmap read_avail_out;
3310 /* Reads performed in this BB. */
3311 bitmap read_local;
3312 /* Writes performed in this BB. */
3313 bitmap store_local;
3315 /* Temporary storage for pass. */
3316 /* Is the current BB in the worklist? */
3317 bool avail_in_worklist_p;
3318 /* Have we visited this BB? */
3319 bool visited_p;
3322 static bitmap_obstack tm_memopt_obstack;
3324 /* Unique counter for TM loads and stores. Loads and stores of the
3325 same address get the same ID. */
3326 static unsigned int tm_memopt_value_id;
3327 static hash_table <tm_memop_hasher> tm_memopt_value_numbers;
3329 #define STORE_AVAIL_IN(BB) \
3330 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3331 #define STORE_AVAIL_OUT(BB) \
3332 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3333 #define STORE_ANTIC_IN(BB) \
3334 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3335 #define STORE_ANTIC_OUT(BB) \
3336 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3337 #define READ_AVAIL_IN(BB) \
3338 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3339 #define READ_AVAIL_OUT(BB) \
3340 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3341 #define READ_LOCAL(BB) \
3342 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3343 #define STORE_LOCAL(BB) \
3344 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3345 #define AVAIL_IN_WORKLIST_P(BB) \
3346 ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3347 #define BB_VISITED_P(BB) \
3348 ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3350 /* Given a TM load/store in STMT, return the value number for the address
3351 it accesses. */
3353 static unsigned int
3354 tm_memopt_value_number (gimple stmt, enum insert_option op)
3356 struct tm_memop tmpmem, *mem;
3357 tm_memop **slot;
3359 gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3360 tmpmem.addr = gimple_call_arg (stmt, 0);
3361 slot = tm_memopt_value_numbers.find_slot (&tmpmem, op);
3362 if (*slot)
3363 mem = *slot;
3364 else if (op == INSERT)
3366 mem = XNEW (struct tm_memop);
3367 *slot = mem;
3368 mem->value_id = tm_memopt_value_id++;
3369 mem->addr = tmpmem.addr;
3371 else
3372 gcc_unreachable ();
3373 return mem->value_id;
3376 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL. */
3378 static void
3379 tm_memopt_accumulate_memops (basic_block bb)
3381 gimple_stmt_iterator gsi;
3383 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3385 gimple stmt = gsi_stmt (gsi);
3386 bitmap bits;
3387 unsigned int loc;
3389 if (is_tm_store (stmt))
3390 bits = STORE_LOCAL (bb);
3391 else if (is_tm_load (stmt))
3392 bits = READ_LOCAL (bb);
3393 else
3394 continue;
3396 loc = tm_memopt_value_number (stmt, INSERT);
3397 bitmap_set_bit (bits, loc);
3398 if (dump_file)
3400 fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3401 is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3402 gimple_bb (stmt)->index);
3403 print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3404 fprintf (dump_file, "\n");
3409 /* Prettily dump one of the memopt sets. BITS is the bitmap to dump. */
3411 static void
3412 dump_tm_memopt_set (const char *set_name, bitmap bits)
3414 unsigned i;
3415 bitmap_iterator bi;
3416 const char *comma = "";
3418 fprintf (dump_file, "TM memopt: %s: [", set_name);
3419 EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3421 hash_table <tm_memop_hasher>::iterator hi;
3422 struct tm_memop *mem = NULL;
3424 /* Yeah, yeah, yeah. Whatever. This is just for debugging. */
3425 FOR_EACH_HASH_TABLE_ELEMENT (tm_memopt_value_numbers, mem, tm_memop_t, hi)
3426 if (mem->value_id == i)
3427 break;
3428 gcc_assert (mem->value_id == i);
3429 fprintf (dump_file, "%s", comma);
3430 comma = ", ";
3431 print_generic_expr (dump_file, mem->addr, 0);
3433 fprintf (dump_file, "]\n");
3436 /* Prettily dump all of the memopt sets in BLOCKS. */
3438 static void
3439 dump_tm_memopt_sets (vec<basic_block> blocks)
3441 size_t i;
3442 basic_block bb;
3444 for (i = 0; blocks.iterate (i, &bb); ++i)
3446 fprintf (dump_file, "------------BB %d---------\n", bb->index);
3447 dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3448 dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3449 dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3450 dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3451 dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3452 dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3456 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB. */
3458 static void
3459 tm_memopt_compute_avin (basic_block bb)
3461 edge e;
3462 unsigned ix;
3464 /* Seed with the AVOUT of any predecessor. */
3465 for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3467 e = EDGE_PRED (bb, ix);
3468 /* Make sure we have already visited this BB, and is thus
3469 initialized.
3471 If e->src->aux is NULL, this predecessor is actually on an
3472 enclosing transaction. We only care about the current
3473 transaction, so ignore it. */
3474 if (e->src->aux && BB_VISITED_P (e->src))
3476 bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3477 bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3478 break;
3482 for (; ix < EDGE_COUNT (bb->preds); ix++)
3484 e = EDGE_PRED (bb, ix);
3485 if (e->src->aux && BB_VISITED_P (e->src))
3487 bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3488 bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3492 BB_VISITED_P (bb) = true;
3495 /* Compute the STORE_ANTIC_IN for the basic block BB. */
3497 static void
3498 tm_memopt_compute_antin (basic_block bb)
3500 edge e;
3501 unsigned ix;
3503 /* Seed with the ANTIC_OUT of any successor. */
3504 for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3506 e = EDGE_SUCC (bb, ix);
3507 /* Make sure we have already visited this BB, and is thus
3508 initialized. */
3509 if (BB_VISITED_P (e->dest))
3511 bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3512 break;
3516 for (; ix < EDGE_COUNT (bb->succs); ix++)
3518 e = EDGE_SUCC (bb, ix);
3519 if (BB_VISITED_P (e->dest))
3520 bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3523 BB_VISITED_P (bb) = true;
3526 /* Compute the AVAIL sets for every basic block in BLOCKS.
3528 We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3530 AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3531 AVAIL_IN[bb] = intersect (AVAIL_OUT[predecessors])
3533 This is basically what we do in lcm's compute_available(), but here
3534 we calculate two sets of sets (one for STOREs and one for READs),
3535 and we work on a region instead of the entire CFG.
3537 REGION is the TM region.
3538 BLOCKS are the basic blocks in the region. */
3540 static void
3541 tm_memopt_compute_available (struct tm_region *region,
3542 vec<basic_block> blocks)
3544 edge e;
3545 basic_block *worklist, *qin, *qout, *qend, bb;
3546 unsigned int qlen, i;
3547 edge_iterator ei;
3548 bool changed;
3550 /* Allocate a worklist array/queue. Entries are only added to the
3551 list if they were not already on the list. So the size is
3552 bounded by the number of basic blocks in the region. */
3553 qlen = blocks.length () - 1;
3554 qin = qout = worklist =
3555 XNEWVEC (basic_block, qlen);
3557 /* Put every block in the region on the worklist. */
3558 for (i = 0; blocks.iterate (i, &bb); ++i)
3560 /* Seed AVAIL_OUT with the LOCAL set. */
3561 bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3562 bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3564 AVAIL_IN_WORKLIST_P (bb) = true;
3565 /* No need to insert the entry block, since it has an AVIN of
3566 null, and an AVOUT that has already been seeded in. */
3567 if (bb != region->entry_block)
3568 *qin++ = bb;
3571 /* The entry block has been initialized with the local sets. */
3572 BB_VISITED_P (region->entry_block) = true;
3574 qin = worklist;
3575 qend = &worklist[qlen];
3577 /* Iterate until the worklist is empty. */
3578 while (qlen)
3580 /* Take the first entry off the worklist. */
3581 bb = *qout++;
3582 qlen--;
3584 if (qout >= qend)
3585 qout = worklist;
3587 /* This block can be added to the worklist again if necessary. */
3588 AVAIL_IN_WORKLIST_P (bb) = false;
3589 tm_memopt_compute_avin (bb);
3591 /* Note: We do not add the LOCAL sets here because we already
3592 seeded the AVAIL_OUT sets with them. */
3593 changed = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3594 changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3595 if (changed
3596 && (region->exit_blocks == NULL
3597 || !bitmap_bit_p (region->exit_blocks, bb->index)))
3598 /* If the out state of this block changed, then we need to add
3599 its successors to the worklist if they are not already in. */
3600 FOR_EACH_EDGE (e, ei, bb->succs)
3601 if (!AVAIL_IN_WORKLIST_P (e->dest) && e->dest != EXIT_BLOCK_PTR)
3603 *qin++ = e->dest;
3604 AVAIL_IN_WORKLIST_P (e->dest) = true;
3605 qlen++;
3607 if (qin >= qend)
3608 qin = worklist;
3612 free (worklist);
3614 if (dump_file)
3615 dump_tm_memopt_sets (blocks);
3618 /* Compute ANTIC sets for every basic block in BLOCKS.
3620 We compute STORE_ANTIC_OUT as follows:
3622 STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3623 STORE_ANTIC_IN[bb] = intersect(STORE_ANTIC_OUT[successors])
3625 REGION is the TM region.
3626 BLOCKS are the basic blocks in the region. */
3628 static void
3629 tm_memopt_compute_antic (struct tm_region *region,
3630 vec<basic_block> blocks)
3632 edge e;
3633 basic_block *worklist, *qin, *qout, *qend, bb;
3634 unsigned int qlen;
3635 int i;
3636 edge_iterator ei;
3638 /* Allocate a worklist array/queue. Entries are only added to the
3639 list if they were not already on the list. So the size is
3640 bounded by the number of basic blocks in the region. */
3641 qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3643 for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3645 bb = blocks[i];
3647 /* Seed ANTIC_OUT with the LOCAL set. */
3648 bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3650 /* Put every block in the region on the worklist. */
3651 AVAIL_IN_WORKLIST_P (bb) = true;
3652 /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3653 and their ANTIC_OUT has already been seeded in. */
3654 if (region->exit_blocks
3655 && !bitmap_bit_p (region->exit_blocks, bb->index))
3657 qlen++;
3658 *qin++ = bb;
3662 /* The exit blocks have been initialized with the local sets. */
3663 if (region->exit_blocks)
3665 unsigned int i;
3666 bitmap_iterator bi;
3667 EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3668 BB_VISITED_P (BASIC_BLOCK (i)) = true;
3671 qin = worklist;
3672 qend = &worklist[qlen];
3674 /* Iterate until the worklist is empty. */
3675 while (qlen)
3677 /* Take the first entry off the worklist. */
3678 bb = *qout++;
3679 qlen--;
3681 if (qout >= qend)
3682 qout = worklist;
3684 /* This block can be added to the worklist again if necessary. */
3685 AVAIL_IN_WORKLIST_P (bb) = false;
3686 tm_memopt_compute_antin (bb);
3688 /* Note: We do not add the LOCAL sets here because we already
3689 seeded the ANTIC_OUT sets with them. */
3690 if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3691 && bb != region->entry_block)
3692 /* If the out state of this block changed, then we need to add
3693 its predecessors to the worklist if they are not already in. */
3694 FOR_EACH_EDGE (e, ei, bb->preds)
3695 if (!AVAIL_IN_WORKLIST_P (e->src))
3697 *qin++ = e->src;
3698 AVAIL_IN_WORKLIST_P (e->src) = true;
3699 qlen++;
3701 if (qin >= qend)
3702 qin = worklist;
3706 free (worklist);
3708 if (dump_file)
3709 dump_tm_memopt_sets (blocks);
3712 /* Offsets of load variants from TM_LOAD. For example,
3713 BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3714 See gtm-builtins.def. */
3715 #define TRANSFORM_RAR 1
3716 #define TRANSFORM_RAW 2
3717 #define TRANSFORM_RFW 3
3718 /* Offsets of store variants from TM_STORE. */
3719 #define TRANSFORM_WAR 1
3720 #define TRANSFORM_WAW 2
3722 /* Inform about a load/store optimization. */
3724 static void
3725 dump_tm_memopt_transform (gimple stmt)
3727 if (dump_file)
3729 fprintf (dump_file, "TM memopt: transforming: ");
3730 print_gimple_stmt (dump_file, stmt, 0, 0);
3731 fprintf (dump_file, "\n");
3735 /* Perform a read/write optimization. Replaces the TM builtin in STMT
3736 by a builtin that is OFFSET entries down in the builtins table in
3737 gtm-builtins.def. */
3739 static void
3740 tm_memopt_transform_stmt (unsigned int offset,
3741 gimple stmt,
3742 gimple_stmt_iterator *gsi)
3744 tree fn = gimple_call_fn (stmt);
3745 gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3746 TREE_OPERAND (fn, 0)
3747 = builtin_decl_explicit ((enum built_in_function)
3748 (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3749 + offset));
3750 gimple_call_set_fn (stmt, fn);
3751 gsi_replace (gsi, stmt, true);
3752 dump_tm_memopt_transform (stmt);
3755 /* Perform the actual TM memory optimization transformations in the
3756 basic blocks in BLOCKS. */
3758 static void
3759 tm_memopt_transform_blocks (vec<basic_block> blocks)
3761 size_t i;
3762 basic_block bb;
3763 gimple_stmt_iterator gsi;
3765 for (i = 0; blocks.iterate (i, &bb); ++i)
3767 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3769 gimple stmt = gsi_stmt (gsi);
3770 bitmap read_avail = READ_AVAIL_IN (bb);
3771 bitmap store_avail = STORE_AVAIL_IN (bb);
3772 bitmap store_antic = STORE_ANTIC_OUT (bb);
3773 unsigned int loc;
3775 if (is_tm_simple_load (stmt))
3777 loc = tm_memopt_value_number (stmt, NO_INSERT);
3778 if (store_avail && bitmap_bit_p (store_avail, loc))
3779 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3780 else if (store_antic && bitmap_bit_p (store_antic, loc))
3782 tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3783 bitmap_set_bit (store_avail, loc);
3785 else if (read_avail && bitmap_bit_p (read_avail, loc))
3786 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3787 else
3788 bitmap_set_bit (read_avail, loc);
3790 else if (is_tm_simple_store (stmt))
3792 loc = tm_memopt_value_number (stmt, NO_INSERT);
3793 if (store_avail && bitmap_bit_p (store_avail, loc))
3794 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3795 else
3797 if (read_avail && bitmap_bit_p (read_avail, loc))
3798 tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3799 bitmap_set_bit (store_avail, loc);
3806 /* Return a new set of bitmaps for a BB. */
3808 static struct tm_memopt_bitmaps *
3809 tm_memopt_init_sets (void)
3811 struct tm_memopt_bitmaps *b
3812 = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3813 b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3814 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3815 b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3816 b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3817 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3818 b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3819 b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3820 b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3821 b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3822 return b;
3825 /* Free sets computed for each BB. */
3827 static void
3828 tm_memopt_free_sets (vec<basic_block> blocks)
3830 size_t i;
3831 basic_block bb;
3833 for (i = 0; blocks.iterate (i, &bb); ++i)
3834 bb->aux = NULL;
3837 /* Clear the visited bit for every basic block in BLOCKS. */
3839 static void
3840 tm_memopt_clear_visited (vec<basic_block> blocks)
3842 size_t i;
3843 basic_block bb;
3845 for (i = 0; blocks.iterate (i, &bb); ++i)
3846 BB_VISITED_P (bb) = false;
3849 /* Replace TM load/stores with hints for the runtime. We handle
3850 things like read-after-write, write-after-read, read-after-read,
3851 read-for-write, etc. */
3853 static unsigned int
3854 execute_tm_memopt (void)
3856 struct tm_region *region;
3857 vec<basic_block> bbs;
3859 tm_memopt_value_id = 0;
3860 tm_memopt_value_numbers.create (10);
3862 for (region = all_tm_regions; region; region = region->next)
3864 /* All the TM stores/loads in the current region. */
3865 size_t i;
3866 basic_block bb;
3868 bitmap_obstack_initialize (&tm_memopt_obstack);
3870 /* Save all BBs for the current region. */
3871 bbs = get_tm_region_blocks (region->entry_block,
3872 region->exit_blocks,
3873 region->irr_blocks,
3874 NULL,
3875 false);
3877 /* Collect all the memory operations. */
3878 for (i = 0; bbs.iterate (i, &bb); ++i)
3880 bb->aux = tm_memopt_init_sets ();
3881 tm_memopt_accumulate_memops (bb);
3884 /* Solve data flow equations and transform each block accordingly. */
3885 tm_memopt_clear_visited (bbs);
3886 tm_memopt_compute_available (region, bbs);
3887 tm_memopt_clear_visited (bbs);
3888 tm_memopt_compute_antic (region, bbs);
3889 tm_memopt_transform_blocks (bbs);
3891 tm_memopt_free_sets (bbs);
3892 bbs.release ();
3893 bitmap_obstack_release (&tm_memopt_obstack);
3894 tm_memopt_value_numbers.empty ();
3897 tm_memopt_value_numbers.dispose ();
3898 return 0;
3901 static bool
3902 gate_tm_memopt (void)
3904 return flag_tm && optimize > 0;
3907 namespace {
3909 const pass_data pass_data_tm_memopt =
3911 GIMPLE_PASS, /* type */
3912 "tmmemopt", /* name */
3913 OPTGROUP_NONE, /* optinfo_flags */
3914 true, /* has_gate */
3915 true, /* has_execute */
3916 TV_TRANS_MEM, /* tv_id */
3917 ( PROP_ssa | PROP_cfg ), /* properties_required */
3918 0, /* properties_provided */
3919 0, /* properties_destroyed */
3920 0, /* todo_flags_start */
3921 0, /* todo_flags_finish */
3924 class pass_tm_memopt : public gimple_opt_pass
3926 public:
3927 pass_tm_memopt (gcc::context *ctxt)
3928 : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3931 /* opt_pass methods: */
3932 bool gate () { return gate_tm_memopt (); }
3933 unsigned int execute () { return execute_tm_memopt (); }
3935 }; // class pass_tm_memopt
3937 } // anon namespace
3939 gimple_opt_pass *
3940 make_pass_tm_memopt (gcc::context *ctxt)
3942 return new pass_tm_memopt (ctxt);
3946 /* Interprocedual analysis for the creation of transactional clones.
3947 The aim of this pass is to find which functions are referenced in
3948 a non-irrevocable transaction context, and for those over which
3949 we have control (or user directive), create a version of the
3950 function which uses only the transactional interface to reference
3951 protected memories. This analysis proceeds in several steps:
3953 (1) Collect the set of all possible transactional clones:
3955 (a) For all local public functions marked tm_callable, push
3956 it onto the tm_callee queue.
3958 (b) For all local functions, scan for calls in transaction blocks.
3959 Push the caller and callee onto the tm_caller and tm_callee
3960 queues. Count the number of callers for each callee.
3962 (c) For each local function on the callee list, assume we will
3963 create a transactional clone. Push *all* calls onto the
3964 callee queues; count the number of clone callers separately
3965 to the number of original callers.
3967 (2) Propagate irrevocable status up the dominator tree:
3969 (a) Any external function on the callee list that is not marked
3970 tm_callable is irrevocable. Push all callers of such onto
3971 a worklist.
3973 (b) For each function on the worklist, mark each block that
3974 contains an irrevocable call. Use the AND operator to
3975 propagate that mark up the dominator tree.
3977 (c) If we reach the entry block for a possible transactional
3978 clone, then the transactional clone is irrevocable, and
3979 we should not create the clone after all. Push all
3980 callers onto the worklist.
3982 (d) Place tm_irrevocable calls at the beginning of the relevant
3983 blocks. Special case here is the entry block for the entire
3984 transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
3985 the library to begin the region in serial mode. Decrement
3986 the call count for all callees in the irrevocable region.
3988 (3) Create the transactional clones:
3990 Any tm_callee that still has a non-zero call count is cloned.
3993 /* This structure is stored in the AUX field of each cgraph_node. */
3994 struct tm_ipa_cg_data
3996 /* The clone of the function that got created. */
3997 struct cgraph_node *clone;
3999 /* The tm regions in the normal function. */
4000 struct tm_region *all_tm_regions;
4002 /* The blocks of the normal/clone functions that contain irrevocable
4003 calls, or blocks that are post-dominated by irrevocable calls. */
4004 bitmap irrevocable_blocks_normal;
4005 bitmap irrevocable_blocks_clone;
4007 /* The blocks of the normal function that are involved in transactions. */
4008 bitmap transaction_blocks_normal;
4010 /* The number of callers to the transactional clone of this function
4011 from normal and transactional clones respectively. */
4012 unsigned tm_callers_normal;
4013 unsigned tm_callers_clone;
4015 /* True if all calls to this function's transactional clone
4016 are irrevocable. Also automatically true if the function
4017 has no transactional clone. */
4018 bool is_irrevocable;
4020 /* Flags indicating the presence of this function in various queues. */
4021 bool in_callee_queue;
4022 bool in_worklist;
4024 /* Flags indicating the kind of scan desired while in the worklist. */
4025 bool want_irr_scan_normal;
4028 typedef vec<cgraph_node_ptr> cgraph_node_queue;
4030 /* Return the ipa data associated with NODE, allocating zeroed memory
4031 if necessary. TRAVERSE_ALIASES is true if we must traverse aliases
4032 and set *NODE accordingly. */
4034 static struct tm_ipa_cg_data *
4035 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4037 struct tm_ipa_cg_data *d;
4039 if (traverse_aliases && (*node)->symbol.alias)
4040 *node = cgraph_alias_target (*node);
4042 d = (struct tm_ipa_cg_data *) (*node)->symbol.aux;
4044 if (d == NULL)
4046 d = (struct tm_ipa_cg_data *)
4047 obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4048 (*node)->symbol.aux = (void *) d;
4049 memset (d, 0, sizeof (*d));
4052 return d;
4055 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4056 it is already present. */
4058 static void
4059 maybe_push_queue (struct cgraph_node *node,
4060 cgraph_node_queue *queue_p, bool *in_queue_p)
4062 if (!*in_queue_p)
4064 *in_queue_p = true;
4065 queue_p->safe_push (node);
4069 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4070 code path. QUEUE are the basic blocks inside the transaction
4071 represented in REGION.
4073 Later in split_code_paths() we will add the conditional to choose
4074 between the two alternatives. */
4076 static void
4077 ipa_uninstrument_transaction (struct tm_region *region,
4078 vec<basic_block> queue)
4080 gimple transaction = region->transaction_stmt;
4081 basic_block transaction_bb = gimple_bb (transaction);
4082 int n = queue.length ();
4083 basic_block *new_bbs = XNEWVEC (basic_block, n);
4085 copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4086 true);
4087 edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4088 add_phi_args_after_copy (new_bbs, n, e);
4090 // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4091 // a) EDGE_FALLTHRU into the transaction
4092 // b) EDGE_TM_ABORT out of the transaction
4093 // c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4095 free (new_bbs);
4098 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4099 Queue all callees within block BB. */
4101 static void
4102 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4103 basic_block bb, bool for_clone)
4105 gimple_stmt_iterator gsi;
4107 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4109 gimple stmt = gsi_stmt (gsi);
4110 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4112 tree fndecl = gimple_call_fndecl (stmt);
4113 if (fndecl)
4115 struct tm_ipa_cg_data *d;
4116 unsigned *pcallers;
4117 struct cgraph_node *node;
4119 if (is_tm_ending_fndecl (fndecl))
4120 continue;
4121 if (find_tm_replacement_function (fndecl))
4122 continue;
4124 node = cgraph_get_node (fndecl);
4125 gcc_assert (node != NULL);
4126 d = get_cg_data (&node, true);
4128 pcallers = (for_clone ? &d->tm_callers_clone
4129 : &d->tm_callers_normal);
4130 *pcallers += 1;
4132 maybe_push_queue (node, callees_p, &d->in_callee_queue);
4138 /* Scan all calls in NODE that are within a transaction region,
4139 and push the resulting nodes into the callee queue. */
4141 static void
4142 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4143 cgraph_node_queue *callees_p)
4145 struct tm_region *r;
4147 d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4148 d->all_tm_regions = all_tm_regions;
4150 for (r = all_tm_regions; r; r = r->next)
4152 vec<basic_block> bbs;
4153 basic_block bb;
4154 unsigned i;
4156 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4157 d->transaction_blocks_normal, false);
4159 // Generate the uninstrumented code path for this transaction.
4160 ipa_uninstrument_transaction (r, bbs);
4162 FOR_EACH_VEC_ELT (bbs, i, bb)
4163 ipa_tm_scan_calls_block (callees_p, bb, false);
4165 bbs.release ();
4168 // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4169 // copying them, rather than forcing us to do this externally.
4170 rebuild_cgraph_edges ();
4172 // ??? In ipa_uninstrument_transaction we don't try to update dominators
4173 // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4174 // Instead, just release dominators here so update_ssa recomputes them.
4175 free_dominance_info (CDI_DOMINATORS);
4177 // When building the uninstrumented code path, copy_bbs will have invoked
4178 // create_new_def_for starting an "ssa update context". There is only one
4179 // instance of this context, so resolve ssa updates before moving on to
4180 // the next function.
4181 update_ssa (TODO_update_ssa);
4184 /* Scan all calls in NODE as if this is the transactional clone,
4185 and push the destinations into the callee queue. */
4187 static void
4188 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4189 cgraph_node_queue *callees_p)
4191 struct function *fn = DECL_STRUCT_FUNCTION (node->symbol.decl);
4192 basic_block bb;
4194 FOR_EACH_BB_FN (bb, fn)
4195 ipa_tm_scan_calls_block (callees_p, bb, true);
4198 /* The function NODE has been detected to be irrevocable. Push all
4199 of its callers onto WORKLIST for the purpose of re-scanning them. */
4201 static void
4202 ipa_tm_note_irrevocable (struct cgraph_node *node,
4203 cgraph_node_queue *worklist_p)
4205 struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4206 struct cgraph_edge *e;
4208 d->is_irrevocable = true;
4210 for (e = node->callers; e ; e = e->next_caller)
4212 basic_block bb;
4213 struct cgraph_node *caller;
4215 /* Don't examine recursive calls. */
4216 if (e->caller == node)
4217 continue;
4218 /* Even if we think we can go irrevocable, believe the user
4219 above all. */
4220 if (is_tm_safe_or_pure (e->caller->symbol.decl))
4221 continue;
4223 caller = e->caller;
4224 d = get_cg_data (&caller, true);
4226 /* Check if the callee is in a transactional region. If so,
4227 schedule the function for normal re-scan as well. */
4228 bb = gimple_bb (e->call_stmt);
4229 gcc_assert (bb != NULL);
4230 if (d->transaction_blocks_normal
4231 && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4232 d->want_irr_scan_normal = true;
4234 maybe_push_queue (caller, worklist_p, &d->in_worklist);
4238 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4239 within the block is irrevocable. */
4241 static bool
4242 ipa_tm_scan_irr_block (basic_block bb)
4244 gimple_stmt_iterator gsi;
4245 tree fn;
4247 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4249 gimple stmt = gsi_stmt (gsi);
4250 switch (gimple_code (stmt))
4252 case GIMPLE_ASSIGN:
4253 if (gimple_assign_single_p (stmt))
4255 tree lhs = gimple_assign_lhs (stmt);
4256 tree rhs = gimple_assign_rhs1 (stmt);
4257 if (volatile_var_p (lhs) || volatile_var_p (rhs))
4258 return true;
4260 break;
4262 case GIMPLE_CALL:
4264 tree lhs = gimple_call_lhs (stmt);
4265 if (lhs && volatile_var_p (lhs))
4266 return true;
4268 if (is_tm_pure_call (stmt))
4269 break;
4271 fn = gimple_call_fn (stmt);
4273 /* Functions with the attribute are by definition irrevocable. */
4274 if (is_tm_irrevocable (fn))
4275 return true;
4277 /* For direct function calls, go ahead and check for replacement
4278 functions, or transitive irrevocable functions. For indirect
4279 functions, we'll ask the runtime. */
4280 if (TREE_CODE (fn) == ADDR_EXPR)
4282 struct tm_ipa_cg_data *d;
4283 struct cgraph_node *node;
4285 fn = TREE_OPERAND (fn, 0);
4286 if (is_tm_ending_fndecl (fn))
4287 break;
4288 if (find_tm_replacement_function (fn))
4289 break;
4291 node = cgraph_get_node (fn);
4292 d = get_cg_data (&node, true);
4294 /* Return true if irrevocable, but above all, believe
4295 the user. */
4296 if (d->is_irrevocable
4297 && !is_tm_safe_or_pure (fn))
4298 return true;
4300 break;
4303 case GIMPLE_ASM:
4304 /* ??? The Approved Method of indicating that an inline
4305 assembly statement is not relevant to the transaction
4306 is to wrap it in a __tm_waiver block. This is not
4307 yet implemented, so we can't check for it. */
4308 if (is_tm_safe (current_function_decl))
4310 tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4311 SET_EXPR_LOCATION (t, gimple_location (stmt));
4312 error ("%Kasm not allowed in %<transaction_safe%> function", t);
4314 return true;
4316 default:
4317 break;
4321 return false;
4324 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4325 for new irrevocable blocks, marking them in NEW_IRR. Don't bother
4326 scanning past OLD_IRR or EXIT_BLOCKS. */
4328 static bool
4329 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4330 bitmap old_irr, bitmap exit_blocks)
4332 bool any_new_irr = false;
4333 edge e;
4334 edge_iterator ei;
4335 bitmap visited_blocks = BITMAP_ALLOC (NULL);
4339 basic_block bb = pqueue->pop ();
4341 /* Don't re-scan blocks we know already are irrevocable. */
4342 if (old_irr && bitmap_bit_p (old_irr, bb->index))
4343 continue;
4345 if (ipa_tm_scan_irr_block (bb))
4347 bitmap_set_bit (new_irr, bb->index);
4348 any_new_irr = true;
4350 else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4352 FOR_EACH_EDGE (e, ei, bb->succs)
4353 if (!bitmap_bit_p (visited_blocks, e->dest->index))
4355 bitmap_set_bit (visited_blocks, e->dest->index);
4356 pqueue->safe_push (e->dest);
4360 while (!pqueue->is_empty ());
4362 BITMAP_FREE (visited_blocks);
4364 return any_new_irr;
4367 /* Propagate the irrevocable property both up and down the dominator tree.
4368 BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4369 TM regions; OLD_IRR are the results of a previous scan of the dominator
4370 tree which has been fully propagated; NEW_IRR is the set of new blocks
4371 which are gaining the irrevocable property during the current scan. */
4373 static void
4374 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4375 bitmap old_irr, bitmap exit_blocks)
4377 vec<basic_block> bbs;
4378 bitmap all_region_blocks;
4380 /* If this block is in the old set, no need to rescan. */
4381 if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4382 return;
4384 all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4385 bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4386 all_region_blocks, false);
4389 basic_block bb = bbs.pop ();
4390 bool this_irr = bitmap_bit_p (new_irr, bb->index);
4391 bool all_son_irr = false;
4392 edge_iterator ei;
4393 edge e;
4395 /* Propagate up. If my children are, I am too, but we must have
4396 at least one child that is. */
4397 if (!this_irr)
4399 FOR_EACH_EDGE (e, ei, bb->succs)
4401 if (!bitmap_bit_p (new_irr, e->dest->index))
4403 all_son_irr = false;
4404 break;
4406 else
4407 all_son_irr = true;
4409 if (all_son_irr)
4411 /* Add block to new_irr if it hasn't already been processed. */
4412 if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4414 bitmap_set_bit (new_irr, bb->index);
4415 this_irr = true;
4420 /* Propagate down to everyone we immediately dominate. */
4421 if (this_irr)
4423 basic_block son;
4424 for (son = first_dom_son (CDI_DOMINATORS, bb);
4425 son;
4426 son = next_dom_son (CDI_DOMINATORS, son))
4428 /* Make sure block is actually in a TM region, and it
4429 isn't already in old_irr. */
4430 if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4431 && bitmap_bit_p (all_region_blocks, son->index))
4432 bitmap_set_bit (new_irr, son->index);
4436 while (!bbs.is_empty ());
4438 BITMAP_FREE (all_region_blocks);
4439 bbs.release ();
4442 static void
4443 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4445 gimple_stmt_iterator gsi;
4447 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4449 gimple stmt = gsi_stmt (gsi);
4450 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4452 tree fndecl = gimple_call_fndecl (stmt);
4453 if (fndecl)
4455 struct tm_ipa_cg_data *d;
4456 unsigned *pcallers;
4457 struct cgraph_node *tnode;
4459 if (is_tm_ending_fndecl (fndecl))
4460 continue;
4461 if (find_tm_replacement_function (fndecl))
4462 continue;
4464 tnode = cgraph_get_node (fndecl);
4465 d = get_cg_data (&tnode, true);
4467 pcallers = (for_clone ? &d->tm_callers_clone
4468 : &d->tm_callers_normal);
4470 gcc_assert (*pcallers > 0);
4471 *pcallers -= 1;
4477 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4478 as well as other irrevocable actions such as inline assembly. Mark all
4479 such blocks as irrevocable and decrement the number of calls to
4480 transactional clones. Return true if, for the transactional clone, the
4481 entire function is irrevocable. */
4483 static bool
4484 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4486 struct tm_ipa_cg_data *d;
4487 bitmap new_irr, old_irr;
4488 vec<basic_block> queue;
4489 bool ret = false;
4491 /* Builtin operators (operator new, and such). */
4492 if (DECL_STRUCT_FUNCTION (node->symbol.decl) == NULL
4493 || DECL_STRUCT_FUNCTION (node->symbol.decl)->cfg == NULL)
4494 return false;
4496 push_cfun (DECL_STRUCT_FUNCTION (node->symbol.decl));
4497 calculate_dominance_info (CDI_DOMINATORS);
4499 d = get_cg_data (&node, true);
4500 queue.create (10);
4501 new_irr = BITMAP_ALLOC (&tm_obstack);
4503 /* Scan each tm region, propagating irrevocable status through the tree. */
4504 if (for_clone)
4506 old_irr = d->irrevocable_blocks_clone;
4507 queue.quick_push (single_succ (ENTRY_BLOCK_PTR));
4508 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4510 ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR), new_irr,
4511 old_irr, NULL);
4512 ret = bitmap_bit_p (new_irr, single_succ (ENTRY_BLOCK_PTR)->index);
4515 else
4517 struct tm_region *region;
4519 old_irr = d->irrevocable_blocks_normal;
4520 for (region = d->all_tm_regions; region; region = region->next)
4522 queue.quick_push (region->entry_block);
4523 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4524 region->exit_blocks))
4525 ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4526 region->exit_blocks);
4530 /* If we found any new irrevocable blocks, reduce the call count for
4531 transactional clones within the irrevocable blocks. Save the new
4532 set of irrevocable blocks for next time. */
4533 if (!bitmap_empty_p (new_irr))
4535 bitmap_iterator bmi;
4536 unsigned i;
4538 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4539 ipa_tm_decrement_clone_counts (BASIC_BLOCK (i), for_clone);
4541 if (old_irr)
4543 bitmap_ior_into (old_irr, new_irr);
4544 BITMAP_FREE (new_irr);
4546 else if (for_clone)
4547 d->irrevocable_blocks_clone = new_irr;
4548 else
4549 d->irrevocable_blocks_normal = new_irr;
4551 if (dump_file && new_irr)
4553 const char *dname;
4554 bitmap_iterator bmi;
4555 unsigned i;
4557 dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4558 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4559 fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4562 else
4563 BITMAP_FREE (new_irr);
4565 queue.release ();
4566 pop_cfun ();
4568 return ret;
4571 /* Return true if, for the transactional clone of NODE, any call
4572 may enter irrevocable mode. */
4574 static bool
4575 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4577 struct tm_ipa_cg_data *d;
4578 tree decl;
4579 unsigned flags;
4581 d = get_cg_data (&node, true);
4582 decl = node->symbol.decl;
4583 flags = flags_from_decl_or_type (decl);
4585 /* Handle some TM builtins. Ordinarily these aren't actually generated
4586 at this point, but handling these functions when written in by the
4587 user makes it easier to build unit tests. */
4588 if (flags & ECF_TM_BUILTIN)
4589 return false;
4591 /* Filter out all functions that are marked. */
4592 if (flags & ECF_TM_PURE)
4593 return false;
4594 if (is_tm_safe (decl))
4595 return false;
4596 if (is_tm_irrevocable (decl))
4597 return true;
4598 if (is_tm_callable (decl))
4599 return true;
4600 if (find_tm_replacement_function (decl))
4601 return true;
4603 /* If we aren't seeing the final version of the function we don't
4604 know what it will contain at runtime. */
4605 if (cgraph_function_body_availability (node) < AVAIL_AVAILABLE)
4606 return true;
4608 /* If the function must go irrevocable, then of course true. */
4609 if (d->is_irrevocable)
4610 return true;
4612 /* If there are any blocks marked irrevocable, then the function
4613 as a whole may enter irrevocable. */
4614 if (d->irrevocable_blocks_clone)
4615 return true;
4617 /* We may have previously marked this function as tm_may_enter_irr;
4618 see pass_diagnose_tm_blocks. */
4619 if (node->local.tm_may_enter_irr)
4620 return true;
4622 /* Recurse on the main body for aliases. In general, this will
4623 result in one of the bits above being set so that we will not
4624 have to recurse next time. */
4625 if (node->symbol.alias)
4626 return ipa_tm_mayenterirr_function (cgraph_get_node (node->thunk.alias));
4628 /* What remains is unmarked local functions without items that force
4629 the function to go irrevocable. */
4630 return false;
4633 /* Diagnose calls from transaction_safe functions to unmarked
4634 functions that are determined to not be safe. */
4636 static void
4637 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4639 struct cgraph_edge *e;
4641 for (e = node->callees; e ; e = e->next_callee)
4642 if (!is_tm_callable (e->callee->symbol.decl)
4643 && e->callee->local.tm_may_enter_irr)
4644 error_at (gimple_location (e->call_stmt),
4645 "unsafe function call %qD within "
4646 "%<transaction_safe%> function", e->callee->symbol.decl);
4649 /* Diagnose call from atomic transactions to unmarked functions
4650 that are determined to not be safe. */
4652 static void
4653 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4654 struct tm_region *all_tm_regions)
4656 struct tm_region *r;
4658 for (r = all_tm_regions; r ; r = r->next)
4659 if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4661 /* Atomic transactions can be nested inside relaxed. */
4662 if (r->inner)
4663 ipa_tm_diagnose_transaction (node, r->inner);
4665 else
4667 vec<basic_block> bbs;
4668 gimple_stmt_iterator gsi;
4669 basic_block bb;
4670 size_t i;
4672 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4673 r->irr_blocks, NULL, false);
4675 for (i = 0; bbs.iterate (i, &bb); ++i)
4676 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4678 gimple stmt = gsi_stmt (gsi);
4679 tree fndecl;
4681 if (gimple_code (stmt) == GIMPLE_ASM)
4683 error_at (gimple_location (stmt),
4684 "asm not allowed in atomic transaction");
4685 continue;
4688 if (!is_gimple_call (stmt))
4689 continue;
4690 fndecl = gimple_call_fndecl (stmt);
4692 /* Indirect function calls have been diagnosed already. */
4693 if (!fndecl)
4694 continue;
4696 /* Stop at the end of the transaction. */
4697 if (is_tm_ending_fndecl (fndecl))
4699 if (bitmap_bit_p (r->exit_blocks, bb->index))
4700 break;
4701 continue;
4704 /* Marked functions have been diagnosed already. */
4705 if (is_tm_pure_call (stmt))
4706 continue;
4707 if (is_tm_callable (fndecl))
4708 continue;
4710 if (cgraph_local_info (fndecl)->tm_may_enter_irr)
4711 error_at (gimple_location (stmt),
4712 "unsafe function call %qD within "
4713 "atomic transaction", fndecl);
4716 bbs.release ();
4720 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4721 OLD_DECL. The returned value is a freshly malloced pointer that
4722 should be freed by the caller. */
4724 static tree
4725 tm_mangle (tree old_asm_id)
4727 const char *old_asm_name;
4728 char *tm_name;
4729 void *alloc = NULL;
4730 struct demangle_component *dc;
4731 tree new_asm_id;
4733 /* Determine if the symbol is already a valid C++ mangled name. Do this
4734 even for C, which might be interfacing with C++ code via appropriately
4735 ugly identifiers. */
4736 /* ??? We could probably do just as well checking for "_Z" and be done. */
4737 old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4738 dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4740 if (dc == NULL)
4742 char length[8];
4744 do_unencoded:
4745 sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4746 tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4748 else
4750 old_asm_name += 2; /* Skip _Z */
4752 switch (dc->type)
4754 case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4755 case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4756 /* Don't play silly games, you! */
4757 goto do_unencoded;
4759 case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4760 /* I'd really like to know if we can ever be passed one of
4761 these from the C++ front end. The Logical Thing would
4762 seem that hidden-alias should be outer-most, so that we
4763 get hidden-alias of a transaction-clone and not vice-versa. */
4764 old_asm_name += 2;
4765 break;
4767 default:
4768 break;
4771 tm_name = concat ("_ZGTt", old_asm_name, NULL);
4773 free (alloc);
4775 new_asm_id = get_identifier (tm_name);
4776 free (tm_name);
4778 return new_asm_id;
4781 static inline void
4782 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4784 cgraph_mark_force_output_node (node);
4785 node->symbol.analyzed = true;
4788 static inline void
4789 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4791 node->symbol.forced_by_abi = true;
4792 node->symbol.analyzed = true;
4795 /* Callback data for ipa_tm_create_version_alias. */
4796 struct create_version_alias_info
4798 struct cgraph_node *old_node;
4799 tree new_decl;
4802 /* A subroutine of ipa_tm_create_version, called via
4803 cgraph_for_node_and_aliases. Create new tm clones for each of
4804 the existing aliases. */
4805 static bool
4806 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4808 struct create_version_alias_info *info
4809 = (struct create_version_alias_info *)data;
4810 tree old_decl, new_decl, tm_name;
4811 struct cgraph_node *new_node;
4813 if (!node->symbol.cpp_implicit_alias)
4814 return false;
4816 old_decl = node->symbol.decl;
4817 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4818 new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4819 TREE_CODE (old_decl), tm_name,
4820 TREE_TYPE (old_decl));
4822 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4823 SET_DECL_RTL (new_decl, NULL);
4825 /* Based loosely on C++'s make_alias_for(). */
4826 TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4827 DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4828 DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4829 TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4830 DECL_EXTERNAL (new_decl) = 0;
4831 DECL_ARTIFICIAL (new_decl) = 1;
4832 TREE_ADDRESSABLE (new_decl) = 1;
4833 TREE_USED (new_decl) = 1;
4834 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4836 /* Perform the same remapping to the comdat group. */
4837 if (DECL_ONE_ONLY (new_decl))
4838 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4840 new_node = cgraph_same_body_alias (NULL, new_decl, info->new_decl);
4841 new_node->tm_clone = true;
4842 new_node->symbol.externally_visible = info->old_node->symbol.externally_visible;
4843 /* ?? Do not traverse aliases here. */
4844 get_cg_data (&node, false)->clone = new_node;
4846 record_tm_clone_pair (old_decl, new_decl);
4848 if (info->old_node->symbol.force_output
4849 || ipa_ref_list_first_referring (&info->old_node->symbol.ref_list))
4850 ipa_tm_mark_force_output_node (new_node);
4851 if (info->old_node->symbol.forced_by_abi)
4852 ipa_tm_mark_forced_by_abi_node (new_node);
4853 return false;
4856 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4857 appropriate for the transactional clone. */
4859 static void
4860 ipa_tm_create_version (struct cgraph_node *old_node)
4862 tree new_decl, old_decl, tm_name;
4863 struct cgraph_node *new_node;
4865 old_decl = old_node->symbol.decl;
4866 new_decl = copy_node (old_decl);
4868 /* DECL_ASSEMBLER_NAME needs to be set before we call
4869 cgraph_copy_node_for_versioning below, because cgraph_node will
4870 fill the assembler_name_hash. */
4871 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4872 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4873 SET_DECL_RTL (new_decl, NULL);
4874 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4876 /* Perform the same remapping to the comdat group. */
4877 if (DECL_ONE_ONLY (new_decl))
4878 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4880 new_node = cgraph_copy_node_for_versioning (old_node, new_decl, vNULL, NULL);
4881 new_node->local.local = false;
4882 new_node->symbol.externally_visible = old_node->symbol.externally_visible;
4883 new_node->lowered = true;
4884 new_node->tm_clone = 1;
4885 get_cg_data (&old_node, true)->clone = new_node;
4887 if (cgraph_function_body_availability (old_node) >= AVAIL_OVERWRITABLE)
4889 /* Remap extern inline to static inline. */
4890 /* ??? Is it worth trying to use make_decl_one_only? */
4891 if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4893 DECL_EXTERNAL (new_decl) = 0;
4894 TREE_PUBLIC (new_decl) = 0;
4895 DECL_WEAK (new_decl) = 0;
4898 tree_function_versioning (old_decl, new_decl,
4899 NULL, false, NULL,
4900 false, NULL, NULL);
4903 record_tm_clone_pair (old_decl, new_decl);
4905 cgraph_call_function_insertion_hooks (new_node);
4906 if (old_node->symbol.force_output
4907 || ipa_ref_list_first_referring (&old_node->symbol.ref_list))
4908 ipa_tm_mark_force_output_node (new_node);
4909 if (old_node->symbol.forced_by_abi)
4910 ipa_tm_mark_forced_by_abi_node (new_node);
4912 /* Do the same thing, but for any aliases of the original node. */
4914 struct create_version_alias_info data;
4915 data.old_node = old_node;
4916 data.new_decl = new_decl;
4917 cgraph_for_node_and_aliases (old_node, ipa_tm_create_version_alias,
4918 &data, true);
4922 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB. */
4924 static void
4925 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4926 basic_block bb)
4928 gimple_stmt_iterator gsi;
4929 gimple g;
4931 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4933 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4934 1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4936 split_block_after_labels (bb);
4937 gsi = gsi_after_labels (bb);
4938 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4940 cgraph_create_edge (node,
4941 cgraph_get_create_node
4942 (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4943 g, 0,
4944 compute_call_stmt_bb_frequency (node->symbol.decl,
4945 gimple_bb (g)));
4948 /* Construct a call to TM_GETTMCLONE and insert it before GSI. */
4950 static bool
4951 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4952 struct tm_region *region,
4953 gimple_stmt_iterator *gsi, gimple stmt)
4955 tree gettm_fn, ret, old_fn, callfn;
4956 gimple g, g2;
4957 bool safe;
4959 old_fn = gimple_call_fn (stmt);
4961 if (TREE_CODE (old_fn) == ADDR_EXPR)
4963 tree fndecl = TREE_OPERAND (old_fn, 0);
4964 tree clone = get_tm_clone_pair (fndecl);
4966 /* By transforming the call into a TM_GETTMCLONE, we are
4967 technically taking the address of the original function and
4968 its clone. Explain this so inlining will know this function
4969 is needed. */
4970 cgraph_mark_address_taken_node (cgraph_get_node (fndecl));
4971 if (clone)
4972 cgraph_mark_address_taken_node (cgraph_get_node (clone));
4975 safe = is_tm_safe (TREE_TYPE (old_fn));
4976 gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
4977 : BUILT_IN_TM_GETTMCLONE_IRR);
4978 ret = create_tmp_var (ptr_type_node, NULL);
4980 if (!safe)
4981 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4983 /* Discard OBJ_TYPE_REF, since we weren't able to fold it. */
4984 if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
4985 old_fn = OBJ_TYPE_REF_EXPR (old_fn);
4987 g = gimple_build_call (gettm_fn, 1, old_fn);
4988 ret = make_ssa_name (ret, g);
4989 gimple_call_set_lhs (g, ret);
4991 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4993 cgraph_create_edge (node, cgraph_get_create_node (gettm_fn), g, 0,
4994 compute_call_stmt_bb_frequency (node->symbol.decl,
4995 gimple_bb (g)));
4997 /* Cast return value from tm_gettmclone* into appropriate function
4998 pointer. */
4999 callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
5000 g2 = gimple_build_assign (callfn,
5001 fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5002 callfn = make_ssa_name (callfn, g2);
5003 gimple_assign_set_lhs (g2, callfn);
5004 gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5006 /* ??? This is a hack to preserve the NOTHROW bit on the call,
5007 which we would have derived from the decl. Failure to save
5008 this bit means we might have to split the basic block. */
5009 if (gimple_call_nothrow_p (stmt))
5010 gimple_call_set_nothrow (stmt, true);
5012 gimple_call_set_fn (stmt, callfn);
5014 /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5015 for a call statement. Fix it. */
5017 tree lhs = gimple_call_lhs (stmt);
5018 tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5019 if (lhs
5020 && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5022 tree temp;
5024 temp = create_tmp_reg (rettype, 0);
5025 gimple_call_set_lhs (stmt, temp);
5027 g2 = gimple_build_assign (lhs,
5028 fold_build1 (VIEW_CONVERT_EXPR,
5029 TREE_TYPE (lhs), temp));
5030 gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5034 update_stmt (stmt);
5036 return true;
5039 /* Helper function for ipa_tm_transform_calls*. Given a call
5040 statement in GSI which resides inside transaction REGION, redirect
5041 the call to either its wrapper function, or its clone. */
5043 static void
5044 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5045 struct tm_region *region,
5046 gimple_stmt_iterator *gsi,
5047 bool *need_ssa_rename_p)
5049 gimple stmt = gsi_stmt (*gsi);
5050 struct cgraph_node *new_node;
5051 struct cgraph_edge *e = cgraph_edge (node, stmt);
5052 tree fndecl = gimple_call_fndecl (stmt);
5054 /* For indirect calls, pass the address through the runtime. */
5055 if (fndecl == NULL)
5057 *need_ssa_rename_p |=
5058 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5059 return;
5062 /* Handle some TM builtins. Ordinarily these aren't actually generated
5063 at this point, but handling these functions when written in by the
5064 user makes it easier to build unit tests. */
5065 if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5066 return;
5068 /* Fixup recursive calls inside clones. */
5069 /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5070 for recursion but not update the call statements themselves? */
5071 if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5073 gimple_call_set_fndecl (stmt, current_function_decl);
5074 return;
5077 /* If there is a replacement, use it. */
5078 fndecl = find_tm_replacement_function (fndecl);
5079 if (fndecl)
5081 new_node = cgraph_get_create_node (fndecl);
5083 /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5085 We can't do this earlier in record_tm_replacement because
5086 cgraph_remove_unreachable_nodes is called before we inject
5087 references to the node. Further, we can't do this in some
5088 nice central place in ipa_tm_execute because we don't have
5089 the exact list of wrapper functions that would be used.
5090 Marking more wrappers than necessary results in the creation
5091 of unnecessary cgraph_nodes, which can cause some of the
5092 other IPA passes to crash.
5094 We do need to mark these nodes so that we get the proper
5095 result in expand_call_tm. */
5096 /* ??? This seems broken. How is it that we're marking the
5097 CALLEE as may_enter_irr? Surely we should be marking the
5098 CALLER. Also note that find_tm_replacement_function also
5099 contains mappings into the TM runtime, e.g. memcpy. These
5100 we know won't go irrevocable. */
5101 new_node->local.tm_may_enter_irr = 1;
5103 else
5105 struct tm_ipa_cg_data *d;
5106 struct cgraph_node *tnode = e->callee;
5108 d = get_cg_data (&tnode, true);
5109 new_node = d->clone;
5111 /* As we've already skipped pure calls and appropriate builtins,
5112 and we've already marked irrevocable blocks, if we can't come
5113 up with a static replacement, then ask the runtime. */
5114 if (new_node == NULL)
5116 *need_ssa_rename_p |=
5117 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5118 return;
5121 fndecl = new_node->symbol.decl;
5124 cgraph_redirect_edge_callee (e, new_node);
5125 gimple_call_set_fndecl (stmt, fndecl);
5128 /* Helper function for ipa_tm_transform_calls. For a given BB,
5129 install calls to tm_irrevocable when IRR_BLOCKS are reached,
5130 redirect other calls to the generated transactional clone. */
5132 static bool
5133 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5134 basic_block bb, bitmap irr_blocks)
5136 gimple_stmt_iterator gsi;
5137 bool need_ssa_rename = false;
5139 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5141 ipa_tm_insert_irr_call (node, region, bb);
5142 return true;
5145 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5147 gimple stmt = gsi_stmt (gsi);
5149 if (!is_gimple_call (stmt))
5150 continue;
5151 if (is_tm_pure_call (stmt))
5152 continue;
5154 /* Redirect edges to the appropriate replacement or clone. */
5155 ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5158 return need_ssa_rename;
5161 /* Walk the CFG for REGION, beginning at BB. Install calls to
5162 tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5163 the generated transactional clone. */
5165 static bool
5166 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5167 basic_block bb, bitmap irr_blocks)
5169 bool need_ssa_rename = false;
5170 edge e;
5171 edge_iterator ei;
5172 vec<basic_block> queue = vNULL;
5173 bitmap visited_blocks = BITMAP_ALLOC (NULL);
5175 queue.safe_push (bb);
5178 bb = queue.pop ();
5180 need_ssa_rename |=
5181 ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5183 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5184 continue;
5186 if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5187 continue;
5189 FOR_EACH_EDGE (e, ei, bb->succs)
5190 if (!bitmap_bit_p (visited_blocks, e->dest->index))
5192 bitmap_set_bit (visited_blocks, e->dest->index);
5193 queue.safe_push (e->dest);
5196 while (!queue.is_empty ());
5198 queue.release ();
5199 BITMAP_FREE (visited_blocks);
5201 return need_ssa_rename;
5204 /* Transform the calls within the TM regions within NODE. */
5206 static void
5207 ipa_tm_transform_transaction (struct cgraph_node *node)
5209 struct tm_ipa_cg_data *d;
5210 struct tm_region *region;
5211 bool need_ssa_rename = false;
5213 d = get_cg_data (&node, true);
5215 push_cfun (DECL_STRUCT_FUNCTION (node->symbol.decl));
5216 calculate_dominance_info (CDI_DOMINATORS);
5218 for (region = d->all_tm_regions; region; region = region->next)
5220 /* If we're sure to go irrevocable, don't transform anything. */
5221 if (d->irrevocable_blocks_normal
5222 && bitmap_bit_p (d->irrevocable_blocks_normal,
5223 region->entry_block->index))
5225 transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5226 | GTMA_MAY_ENTER_IRREVOCABLE
5227 | GTMA_HAS_NO_INSTRUMENTATION);
5228 continue;
5231 need_ssa_rename |=
5232 ipa_tm_transform_calls (node, region, region->entry_block,
5233 d->irrevocable_blocks_normal);
5236 if (need_ssa_rename)
5237 update_ssa (TODO_update_ssa_only_virtuals);
5239 pop_cfun ();
5242 /* Transform the calls within the transactional clone of NODE. */
5244 static void
5245 ipa_tm_transform_clone (struct cgraph_node *node)
5247 struct tm_ipa_cg_data *d;
5248 bool need_ssa_rename;
5250 d = get_cg_data (&node, true);
5252 /* If this function makes no calls and has no irrevocable blocks,
5253 then there's nothing to do. */
5254 /* ??? Remove non-aborting top-level transactions. */
5255 if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5256 return;
5258 push_cfun (DECL_STRUCT_FUNCTION (d->clone->symbol.decl));
5259 calculate_dominance_info (CDI_DOMINATORS);
5261 need_ssa_rename =
5262 ipa_tm_transform_calls (d->clone, NULL, single_succ (ENTRY_BLOCK_PTR),
5263 d->irrevocable_blocks_clone);
5265 if (need_ssa_rename)
5266 update_ssa (TODO_update_ssa_only_virtuals);
5268 pop_cfun ();
5271 /* Main entry point for the transactional memory IPA pass. */
5273 static unsigned int
5274 ipa_tm_execute (void)
5276 cgraph_node_queue tm_callees = cgraph_node_queue ();
5277 /* List of functions that will go irrevocable. */
5278 cgraph_node_queue irr_worklist = cgraph_node_queue ();
5280 struct cgraph_node *node;
5281 struct tm_ipa_cg_data *d;
5282 enum availability a;
5283 unsigned int i;
5285 #ifdef ENABLE_CHECKING
5286 verify_cgraph ();
5287 #endif
5289 bitmap_obstack_initialize (&tm_obstack);
5290 initialize_original_copy_tables ();
5292 /* For all local functions marked tm_callable, queue them. */
5293 FOR_EACH_DEFINED_FUNCTION (node)
5294 if (is_tm_callable (node->symbol.decl)
5295 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5297 d = get_cg_data (&node, true);
5298 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5301 /* For all local reachable functions... */
5302 FOR_EACH_DEFINED_FUNCTION (node)
5303 if (node->lowered
5304 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5306 /* ... marked tm_pure, record that fact for the runtime by
5307 indicating that the pure function is its own tm_callable.
5308 No need to do this if the function's address can't be taken. */
5309 if (is_tm_pure (node->symbol.decl))
5311 if (!node->local.local)
5312 record_tm_clone_pair (node->symbol.decl, node->symbol.decl);
5313 continue;
5316 push_cfun (DECL_STRUCT_FUNCTION (node->symbol.decl));
5317 calculate_dominance_info (CDI_DOMINATORS);
5319 tm_region_init (NULL);
5320 if (all_tm_regions)
5322 d = get_cg_data (&node, true);
5324 /* Scan for calls that are in each transaction, and
5325 generate the uninstrumented code path. */
5326 ipa_tm_scan_calls_transaction (d, &tm_callees);
5328 /* Put it in the worklist so we can scan the function
5329 later (ipa_tm_scan_irr_function) and mark the
5330 irrevocable blocks. */
5331 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5332 d->want_irr_scan_normal = true;
5335 pop_cfun ();
5338 /* For every local function on the callee list, scan as if we will be
5339 creating a transactional clone, queueing all new functions we find
5340 along the way. */
5341 for (i = 0; i < tm_callees.length (); ++i)
5343 node = tm_callees[i];
5344 a = cgraph_function_body_availability (node);
5345 d = get_cg_data (&node, true);
5347 /* Put it in the worklist so we can scan the function later
5348 (ipa_tm_scan_irr_function) and mark the irrevocable
5349 blocks. */
5350 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5352 /* Some callees cannot be arbitrarily cloned. These will always be
5353 irrevocable. Mark these now, so that we need not scan them. */
5354 if (is_tm_irrevocable (node->symbol.decl))
5355 ipa_tm_note_irrevocable (node, &irr_worklist);
5356 else if (a <= AVAIL_NOT_AVAILABLE
5357 && !is_tm_safe_or_pure (node->symbol.decl))
5358 ipa_tm_note_irrevocable (node, &irr_worklist);
5359 else if (a >= AVAIL_OVERWRITABLE)
5361 if (!tree_versionable_function_p (node->symbol.decl))
5362 ipa_tm_note_irrevocable (node, &irr_worklist);
5363 else if (!d->is_irrevocable)
5365 /* If this is an alias, make sure its base is queued as well.
5366 we need not scan the callees now, as the base will do. */
5367 if (node->symbol.alias)
5369 node = cgraph_get_node (node->thunk.alias);
5370 d = get_cg_data (&node, true);
5371 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5372 continue;
5375 /* Add all nodes called by this function into
5376 tm_callees as well. */
5377 ipa_tm_scan_calls_clone (node, &tm_callees);
5382 /* Iterate scans until no more work to be done. Prefer not to use
5383 vec::pop because the worklist tends to follow a breadth-first
5384 search of the callgraph, which should allow convergance with a
5385 minimum number of scans. But we also don't want the worklist
5386 array to grow without bound, so we shift the array up periodically. */
5387 for (i = 0; i < irr_worklist.length (); ++i)
5389 if (i > 256 && i == irr_worklist.length () / 8)
5391 irr_worklist.block_remove (0, i);
5392 i = 0;
5395 node = irr_worklist[i];
5396 d = get_cg_data (&node, true);
5397 d->in_worklist = false;
5399 if (d->want_irr_scan_normal)
5401 d->want_irr_scan_normal = false;
5402 ipa_tm_scan_irr_function (node, false);
5404 if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5405 ipa_tm_note_irrevocable (node, &irr_worklist);
5408 /* For every function on the callee list, collect the tm_may_enter_irr
5409 bit on the node. */
5410 irr_worklist.truncate (0);
5411 for (i = 0; i < tm_callees.length (); ++i)
5413 node = tm_callees[i];
5414 if (ipa_tm_mayenterirr_function (node))
5416 d = get_cg_data (&node, true);
5417 gcc_assert (d->in_worklist == false);
5418 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5422 /* Propagate the tm_may_enter_irr bit to callers until stable. */
5423 for (i = 0; i < irr_worklist.length (); ++i)
5425 struct cgraph_node *caller;
5426 struct cgraph_edge *e;
5427 struct ipa_ref *ref;
5428 unsigned j;
5430 if (i > 256 && i == irr_worklist.length () / 8)
5432 irr_worklist.block_remove (0, i);
5433 i = 0;
5436 node = irr_worklist[i];
5437 d = get_cg_data (&node, true);
5438 d->in_worklist = false;
5439 node->local.tm_may_enter_irr = true;
5441 /* Propagate back to normal callers. */
5442 for (e = node->callers; e ; e = e->next_caller)
5444 caller = e->caller;
5445 if (!is_tm_safe_or_pure (caller->symbol.decl)
5446 && !caller->local.tm_may_enter_irr)
5448 d = get_cg_data (&caller, true);
5449 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5453 /* Propagate back to referring aliases as well. */
5454 for (j = 0; ipa_ref_list_referring_iterate (&node->symbol.ref_list, j, ref); j++)
5456 caller = cgraph (ref->referring);
5457 if (ref->use == IPA_REF_ALIAS
5458 && !caller->local.tm_may_enter_irr)
5460 /* ?? Do not traverse aliases here. */
5461 d = get_cg_data (&caller, false);
5462 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5467 /* Now validate all tm_safe functions, and all atomic regions in
5468 other functions. */
5469 FOR_EACH_DEFINED_FUNCTION (node)
5470 if (node->lowered
5471 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5473 d = get_cg_data (&node, true);
5474 if (is_tm_safe (node->symbol.decl))
5475 ipa_tm_diagnose_tm_safe (node);
5476 else if (d->all_tm_regions)
5477 ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5480 /* Create clones. Do those that are not irrevocable and have a
5481 positive call count. Do those publicly visible functions that
5482 the user directed us to clone. */
5483 for (i = 0; i < tm_callees.length (); ++i)
5485 bool doit = false;
5487 node = tm_callees[i];
5488 if (node->symbol.cpp_implicit_alias)
5489 continue;
5491 a = cgraph_function_body_availability (node);
5492 d = get_cg_data (&node, true);
5494 if (a <= AVAIL_NOT_AVAILABLE)
5495 doit = is_tm_callable (node->symbol.decl);
5496 else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->symbol.decl))
5497 doit = true;
5498 else if (!d->is_irrevocable
5499 && d->tm_callers_normal + d->tm_callers_clone > 0)
5500 doit = true;
5502 if (doit)
5503 ipa_tm_create_version (node);
5506 /* Redirect calls to the new clones, and insert irrevocable marks. */
5507 for (i = 0; i < tm_callees.length (); ++i)
5509 node = tm_callees[i];
5510 if (node->symbol.analyzed)
5512 d = get_cg_data (&node, true);
5513 if (d->clone)
5514 ipa_tm_transform_clone (node);
5517 FOR_EACH_DEFINED_FUNCTION (node)
5518 if (node->lowered
5519 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5521 d = get_cg_data (&node, true);
5522 if (d->all_tm_regions)
5523 ipa_tm_transform_transaction (node);
5526 /* Free and clear all data structures. */
5527 tm_callees.release ();
5528 irr_worklist.release ();
5529 bitmap_obstack_release (&tm_obstack);
5530 free_original_copy_tables ();
5532 FOR_EACH_FUNCTION (node)
5533 node->symbol.aux = NULL;
5535 #ifdef ENABLE_CHECKING
5536 verify_cgraph ();
5537 #endif
5539 return 0;
5542 namespace {
5544 const pass_data pass_data_ipa_tm =
5546 SIMPLE_IPA_PASS, /* type */
5547 "tmipa", /* name */
5548 OPTGROUP_NONE, /* optinfo_flags */
5549 true, /* has_gate */
5550 true, /* has_execute */
5551 TV_TRANS_MEM, /* tv_id */
5552 ( PROP_ssa | PROP_cfg ), /* properties_required */
5553 0, /* properties_provided */
5554 0, /* properties_destroyed */
5555 0, /* todo_flags_start */
5556 0, /* todo_flags_finish */
5559 class pass_ipa_tm : public simple_ipa_opt_pass
5561 public:
5562 pass_ipa_tm (gcc::context *ctxt)
5563 : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5566 /* opt_pass methods: */
5567 bool gate () { return gate_tm (); }
5568 unsigned int execute () { return ipa_tm_execute (); }
5570 }; // class pass_ipa_tm
5572 } // anon namespace
5574 simple_ipa_opt_pass *
5575 make_pass_ipa_tm (gcc::context *ctxt)
5577 return new pass_ipa_tm (ctxt);
5580 #include "gt-trans-mem.h"